text:
Q: 'mappedBy reference an unknown target entity property' when properties with the same name exist in both parent and child entities I'm on Spring Boot v1.5.3 and when I use Hibernate inheritance, AnnotationException: mappedBy reference an unknown target entity property occurs when there are properties with the same name in both parent and child entities.
For example:
Apple => RedApple
      => GreenApple
      => etc.
Tree  => RedAppleTree
      => GreenAppleTree
      => etc.

// Tree.java

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@EqualsAndHashCode(exclude = {"apples"})
@DiscriminatorColumn(name = "colour")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class Tree {
    @Id
    @GeneratedValue
    private Long id;
}

// RedAppleTree.java

@Entity
@Table(name = "tree")
@DiscriminatorValue("RED")
public class RedAppleTree extends Tree {
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "tree")
    private List<RedApple> apples;
}

// Apple.java

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@DiscriminatorColumn(name = "colour")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class Apple {
    @Id
    @GeneratedValue
    private Long id;

    @Enumerated(EnumType.STRING)
    @Column(insertable = false, updatable = false)
    private Colour colour;

    @JoinColumn(insertable = false, updatable = false)
    @ManyToOne
    private Tree tree;
}

// RedApple.java

@Entity
@Table(name = "apple")
@DiscriminatorValue("RED")
public class RedApple extends Apple {
    @JoinColumn(insertable = false, updatable = false)
    @ManyToOne
    private RedAppleTree tree;
}

// Colour.java

public enum Colour {
    RED,
    GREEN,
}

Apple.tree and RedApple.tree exist at the same time. In parent Apple the type is Tree; in child RedApple it's RedAppleTree.
Now when the project runs, I get:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.example.demo.dao.RedApple.tree in com.example.demo.dao.RedAppleTree.apples
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean (AbstractAutowireCapableBeanFactory.java:1628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject (AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean (AbstractApplicationContext.java:1081)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:856)
    at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:542)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh (EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:737)
    at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:314)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1162)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1151)
    at com.example.demo.DemoApplication.main (DemoApplication.java:13)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:834)
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.example.demo.dao.RedApple.tree in com.example.demo.dao.RedAppleTree.apples
    at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass (CollectionBinder.java:769)
    at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass (CollectionBinder.java:719)
    at org.hibernate.cfg.CollectionSecondPass.doSecondPass (CollectionSecondPass.java:54)
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses (InFlightMetadataCollectorImpl.java:1655)
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses (InFlightMetadataCollectorImpl.java:1623)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete (MetadataBuildingProcess.java:278)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata (EntityManagerFactoryBuilderImpl.java:847)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build (EntityManagerFactoryBuilderImpl.java:874)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory (SpringHibernateJpaPersistenceProvider.java:60)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory (LocalContainerEntityManagerFactoryBean.java:353)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory (AbstractEntityManagerFactoryBean.java:370)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet (AbstractEntityManagerFactoryBean.java:359)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods (AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean (AbstractAutowireCapableBeanFactory.java:1624)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject (AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean (AbstractApplicationContext.java:1081)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:856)
    at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:542)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh (EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:737)
    at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:314)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1162)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1151)
    at com.example.demo.DemoApplication.main (DemoApplication.java:13)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:834)

Now I can rename one of the properties to work around this problem but in the actual project I'm working on it'd lead to more changes.
Is it possible to keep the property name untouched?

A: It is a problem to duplicate your "tree" property in both your superclass and your subclass. I believe that this example here will do what you want.
Tree.java
@Entity
@Table(name = "tree")
@DiscriminatorColumn(name = "colour")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class Tree<APPLE extends Apple> {

    @Id
    @GeneratedValue
    private Long id;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "tree", targetEntity = Apple.class)
    private Set<APPLE> apples = Sets.newHashSet();

    //... getters & setters
}

Apple.java
@Table(name = "apple")
@Entity
@DiscriminatorColumn(name = "colour")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class Apple<TREE extends Tree> {

    @Id
    @GeneratedValue
    private Long id;

    @JoinColumn(name = "tree_id")
    @ManyToOne(targetEntity = Tree.class)
    private TREE tree;

}

RedAppleTree.java
@Entity
@Table(name = "tree")
@DiscriminatorColumn(name = "colour")
@DiscriminatorValue("RED")
public class RedAppleTree extends Tree<RedApple> {
}

RedApple.java
@Entity
@Table(name = "apple")
@DiscriminatorColumn(name = "colour")
@DiscriminatorValue("RED")
public class RedApple extends Apple<RedAppleTree> {
}

This creates the following DB tables
create table tree (
   colour varchar(31) not null,
    id bigint generated by default as identity (start with 1),
    primary key (id)
);
create table apple (
   colour varchar(31) not null,
    id bigint generated by default as identity (start with 1),
    tree_id bigint,
    primary key (id)
)

Then, when I run the following code
@Test
public void test() {

    RedAppleTree tree = new RedAppleTree();
    session.persist(tree);

    GreenAppleTree greenTree = new GreenAppleTree();
    session.persist(greenTree);

    RedApple apple = new RedApple();
    apple.setTree(tree);
    session.persist(apple);

    tree.getApples().add(apple);
    session.flush();
    session.clear();

    tree = session.get(RedAppleTree.class, tree.getId());

    System.err.println(session.createCriteria(RedAppleTree.class).list());
}

This results in the following SQL (ran with hibernate-sql-logging enabled)
Hibernate:
insert
into
    tree
    (id, version, colour)
values
    (default, ?, 'RED')
Hibernate:
insert
into
    tree
    (id, version, colour)
values
    (default, ?, 'GREEN')
Hibernate:
insert
into
    apple
    (id, version, tree_id, colour)
values
    (default, ?, ?, 'RED')
Hibernate:
select
    redappletr0_.id as id2_409_0_,
    redappletr0_.version as version3_409_0_
from
    tree redappletr0_
where
    redappletr0_.id=?
    and redappletr0_.colour='RED'
Hibernate:
select
    this_.id as id2_409_0_,
    this_.version as version3_409_0_
from
    tree this_
where
    this_.colour='RED'

I believe that this ought to solve your basic problem.

A: The truth is that I have never encountered a similar problem, the logical thing, and a good practice would be to change the name of the property to differentiate which entity each one refers to, the compiler will tell you where to change it.
You could try indicating the child class in the relation as follows:
mappedBy = "tree", targetEntity = RedAppleTree.class

But I reiterate, the best option would be to change the name of the property, even if it involves more work.


text:
Q: Can webapplication be notified that the web container (ex. Tomcat) is reloading, unloading or shutting down I have a Wicket Web Application running in Tomcat. The application uses Spring (via org.springframework.web.context.ContextLoaderListener) to initialise the application. This is all well and good for start up, but what I would also like is to receive some sort of notification that the Context is being destroyed so that I can shutdown spawned threads. Is there a way of receiving such a notification? I've included excerpts from my application to aid your understanding of my question.
web.xml extract
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:com/mysite/web/spring/applicationContext.xml</param-value>
</context-param>

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

Spring applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
    "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
    <bean id="MyWebService" class="com.mysite.web.MyWebApp">
    </bean>
</beans>

MyWebApp.java extract
public class MyWebApp extends org.apache.wicket.protocol.http.WebApplication {
    private MyWebServiceServiceAPI webservice =
       MyWebServiceAppImpl.getMyWebService();

    public MyWebServiceWebApp() {
    }

    @Override
    public void init() {
        super.init();
        webservice.start();
    }
}

MyWebServiceAppImpl.java extract
    public class MyWebServiceAppImpl  extends ServiceImpl
        implements MyWebServiceServiceAPI  {
        // The ServiceImpl implements the Callable<T> interface

    private static MyWebServiceServiceAPI instance;
    private List<Future<ServiceImpl>> results =
        new ArrayList<Future<ServiceImpl>>();
    private ExecutorService pool = Executors.newCachedThreadPool();

    private MyWebServiceAppImpl() {
        super(.....);
    }

    public synchronized static MyWebServiceServiceAPI getMyWebService() {
        if (instance == null) {
            instance = new MyWebServiceAppImpl();
            instance.start();
        }
        return instance;
    }

@Override
public synchronized void start() {

    if (!started()) {
        pool.submit(this);
        super.start();
    }
}

A: Yes, you can implement your own ContextListener.
package myapp;

public class MyContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent arg0) {
        //called when context is started
    }

    public void contextDestroyed(ServletContextEvent arg0) {
      //called context destroyed
    }
}

You need to add that listener to your web.xml
 <listener>
    <listener-class>myapp.MyContextListener</listener-class>
 </listener>

redpajama_set_name: RedPajamaStackExchange


text:
Q: read in .txt file , transform into pandas dataframe, but spaces seperating value vary in number of spaces This script reads in a txt file and creates a df, but the 'sep' argument I want to handle values that may be seperated by 1 space or more, so when I run the script above I get many columns with NaN.
code:
df = pd.read_csv(data_file,header = None, sep=' ')

example txt file
blah blahh    bl
blah3 blahhe      ble

I want there to just be 3 columns so i get
Col_a  col_b   col_c
blah   blahh    bl
blah3  blahhe   ble

A: You can use regex as the delimiter:
pd.read_csv(data_file, header=None, delimiter=r"\s+", names='Col_a Col_b Col_c'.split(' '))

Or you can use delim_whitespace=True argument, it's faster than regex:
pd.read_csv(data_file, header=None, delim_whitespace=True, names='Col_a Col_b Col_c'.split(' '))

Reference: How to read file with space separated values in pandas


text:
Q: Frequency shift without affecting signal length Non-physicist here.
From what I've learned in university and what common sense says, a shift in frequency of a signal results in a change in its length in time. For example, if a sinusoid signal of frequency $f$ and length $t$ is transferred to frequency domain, it's $f$ divided by $2$, then converted back to time domain, the length of the signal would be $2t$.
Correct me if I'm wrong! But this is quite intuitive. If you make a signal slower, it would take more time to finish and vice versa.
This is a reason why I've been told it's impossible to change frequency of a streaming signal and output it with the same speed. For example, it would be impossible to take a man's speech and change it to sound like a woman without making it faster.
Now I've had various observations:

*

*In Coursera, you can increase the speed of course lectures and the sound is also of course sped up. However, there is no rise in the pitch of the voice of the speaker. In fact, the speaker sounds very similar to the normal speed. How is it possible to change in speed of the signal didn't affect its frequency?

*My amplifier has a dial for shifting the pitch. So, while playing, you can here the output with a different pitch. Again, how is this possible? If the amplifier is rising the pitch, shouldn't its output be faster than its input? (i.e. a contradiction!) I'm suspecting some trick though, as the output sounds rather "artificial".

It seems that it is somewhat possible to change the frequency of a signal without affecting its length. One (theoretical) way I can think of would be to understand the current "notes" playing (i.e. the different frequencies making the signal) in very small intervals, change the note and replay them for the duration of that interval.
My question is, first if my understanding is at all correct. Either way, is there a mathematical way for changing the pitch of a signal without affecting its length in time? If not, how can they be doing it in practice?

A: You are correct that it's impossible to change the frequency of every component of a waveform while (a) preserving all the phase relationships between the frequencies and (b) preserving the length of the waveform.  However, while it's mathematically impossible to do this precisely, it is possible to do things that sound quite a lot like it to the human ear. The most basic algorithms for this are fairly simple, but doing it well is pretty difficult, and the algorithms are being improved all the time. It is referred to as "pitch shifting" if the goal is to change the pitch but not the time, and "time stretching" if you want to change the time while keeping the pitch.
The reason this is possible is that the ear distinguishes rhythm and pitch as quite distinct things. A sequence of clicks will sound like a sequence of clicks until its frequency passses about 20-30 Hz, at which point it transitions into a buzzing sound that's perceived as having a pitch. Because of this, as DumpsterDoofus said, you can chop the sound up into little segments of short duration, change the pitch of each one individually, and then stitch them back together again, repeating things or leaving gaps where necessary.
By itself this doesn't sound so good, because you get a click at the end of each segment, where the waveforms don't line up. It can be improved a lot by overlapping "windows" of sound, which each have a fade-in and fade-out applied. That way you don't hear the clicks that the ends of the segments, but you do tend to hear phase-cancellation effects where thr windows are added back together again. For this reason this technique requires quite a bit of tuning to get it to sound good on any given input sound.
There are also Fourier-domain techniques, as Brandon Enright said. These also usually use overlapping windows; I guess the advantage of using the Fourier domain is that you have more control over the phase relationships. (I don't know very much about these techniques.)
A fairly recent development is the "pitch synchronous overlap-add" (PSOLA) algorithm. This uses overlapping windows as well, but it synchronises the length of the windows to the pitch of the input sound. This makes it much harder for the ear to perceive the individual windows. I call it "the algorithm that ruined music", because it's responsible for that nasty "autotune" effect that's been overused on the vocals of every pop record for the last ten years or so. However, it does also have peaceful applications, and the pitch dial on your amplifier probably uses some version of it.
You can find more details about these algorithms on Wikipedia.


text:
Q: ios: UITableVIewCell expand not working as expected My TableView cell has a button. On click, I want to expand the cell. For expanding I'm changing the height of the cell on button click and reload the row. But when one row is expanded and then I try to expand another row, the behaviour is not as expected. The previously expanded row closes instead of clicked row.
Also, sometimes I've to click the button twice to expand.
public class ProgramMeasurementDetailsTableViewSource : UITableViewSource
{

    List<ProgramMeasurementDetail> mList;

    string HeaderIdentfier = "programMeasurementDetailsHeader";
    string CellIdentifier = "programMeasurementDetailsCell";
    int TAG_CHECKBOX = 61;
    int TAG_LABEL_VITAL_NAME = 62;
    int TAG_LABEL_GOAL = 63;
    int TAG_BUTTON_EDIT = 64;
    int TAG_VIEW_HEADER_COLUMN_SEPARATOR = 66;
    int TAG_VIEW_ROW_COLUMN_SEPARATOR = 65;
    List<bool> expandStatusList = new List<bool>();
    UITableView tableView;

    public ProgramMeasurementDetailsTableViewSource(List<ProgramMeasurementDetail> mList, UITableView tableView)
    {
        this.tableView = tableView;
        this.mList = mList;
        for (int i = 0; i < mList.Count; i++)
            expandStatusList.Add(false);
    }

    public override nint NumberOfSections(UITableView tableView)
    {
        return 1;
    }

    public override nint RowsInSection(UITableView tableview, nint section)
    {
        return mList.Count;
    }

    public override nfloat GetHeightForHeader(UITableView tableView, nint section)
    {
        return 32;
    }

    public override nfloat GetHeightForRow(UITableView tableView, Foundation.NSIndexPath indexPath)
    {
        if (expandStatusList[indexPath.Row])
            return 70;
        else
            return 32;
    }

    public override UITableViewCell GetCell(UITableView tableView, Foundation.NSIndexPath indexPath)
    {
        UITableViewCell cell = tableView.DequeueReusableCell(CellIdentifier);
        if (cell == null)
        {
            cell = new UITableViewCell(UITableViewCellStyle.Default, CellIdentifier);
        }
        CheckBox checkBox = (CheckBox)cell.ViewWithTag(TAG_CHECKBOX);
        UILabel vitalNameLabel = (UILabel)cell.ViewWithTag(TAG_LABEL_VITAL_NAME);
        UILabel goalLabel = (UILabel)cell.ViewWithTag(TAG_LABEL_GOAL);
        UIButton editGoalButton = (UIButton)cell.ViewWithTag(TAG_BUTTON_EDIT);
        editGoalButton.TouchUpInside += (object sender, EventArgs e) =>
         {
             expandStatusList[indexPath.Row] = !expandStatusList[indexPath.Row];
             tableView.ReloadRows(new Foundation.NSIndexPath[] { indexPath }, UITableViewRowAnimation.Automatic);

         };

        .....
        return cell;
    }
}

I tried moving the button click event handling inside the if (cell == null), then but button click/expand is not working at all. I put breakpoint and it seems that part never gets executed.
I've the cell layout designed in storyboard.
I've struggling with this problem for quite sometime now. Any help is appreciated.

A: Does the bug you see happen when you scroll the list up and down? This is happening because you are wiring up the TouchUpInside event handler in the GetCell method and then it never get unhooked when the cell is reused, so you end up with multiple cells wired to the same handler or even multiple handlers!
In general, you don't want to do these types on things in the GetCell method, it should only be used to DequeueReusableCell or create a new one. Everything else should be done within a custom cell.
Looking at your code example, it doesn't look like you are using a custom cell, so what you could do is this:
1.) In GetCell set the tag of the button as the row of the IndexPath
editGoalButton.Tag = indexPath.Row;

2.) In ProgramMeasurementDetailsTableViewSource Create a separate method for your event handler:
private void ToggleRow(object sender, EventArgs e)
{
    var btn = sender as UIButton;
    expandStatusList[btn.Tag] = !expandStatusList[btn.Tag];
    tableView.ReloadRows(new Foundation.NSIndexPath[] { NSIndexPath.FromRowSection(btn.Tag, 0) }, UITableViewRowAnimation.Automatic);
}

3.) In GetCell Unhook before you rehook the TouchUpInside handler:
editGoalButton.TouchUpInside -= ToggleRow;
editGoalButton.TouchUpInside += ToggleRow;

While this will make sure that the button is only hooked up once, it really isn't the right way to handle a situation like this. You should be using a custom cell and doing all the wiring in the cell and then the unhook and clean up in the PrepareForReuse override in UITableViewCell. I would highly recommend going though this Xamarin tutorial
If you do go through it...notice how consolidated the GetCell method is.
--UPDATE--
In your CustomCell class:
private EventHandler _tapAction;
public void Setup(EventHandler tapAction, int row, ....)
{
     //keep a reference to the action, so we can unhook it later
     _tapAction = tapAction;
     editGoalButton.Tag = row;
     ....
     editGoalButton.TouchUpInside += _tapAction;
}

public override void PrepareForReuse()
{
     ....
     editGoalButton.TouchUpInside -= _tapAction;
     _tapAction = null;
}

And you would just pass through the ToggleRow method as the Action parameter when you call Setup in GetCell.


text:
Q: Two separate angularJS apps on the same file system My routes will look something like this:
/create-company/index.html#/part-one
/dashboard/index.html#/view1
/auth/

Now the create-company app is used initially and from then on the branch dashboard app is used.
Currently I use the seed project to make app, config, logs, scripts & test folders in my home directory for one app.
To add the second app, Should I create two folders app1 & app2 which each contain their own app, config, logs, scripts & test folders?
Then I can point /dashboard/ to /app1/app and point /create-company/ to /app2/app
Or would it be better to stick with a single angularJS app at /app/ and to point both /create-company/ and /dashboard/ to the same /app/ folder?

A: Although there may be use-cases where having multiple, completely separated apps is helpful and/or appropriate, from your description the two 'apps' you describe would appear to be different sub-sections of one larger app.
Consider in your usage, would there be any overlapping components, such as shared directives, templates, or services? If so, it would be best to avoid duplication.
In addition, there is no restriction on loading the same app on two different pages, with different markup - controllers etc, which would lead to completely different functionality.
For example the following is perfectly fine on different pages:


text:
Q: Implementing Kernel in C and Shell in C# Is it possible to implement MVC architecture's control in one language and view in other language.
What I'm looking for is a pattern to have a "kernel" in C and the "shell" in C#.
Or like "server" in C and "client" in C# (but in the same machine).
Only approach I come up with is to use pipes or sockets to communicate between the two processes.
Is there a better approach ? (I'm sure there is but What is it ? )
Eidt : I found a number of approaches here in MSDN.but wonder what would be the ideal.

A: Shared memory might be a solution: MSDN - Creating Named Shared Memory
But beware that dealing with shared memory is a LOT trickier than dealing with "higher level" constructs like sockets.
Cheers. Keith.


text:
Q: How do I use a Launchpad recipe for patching and building an original package? I have a patch against vim which applies to packaged version. I would like to automate this, so that when new ubuntu is released, the newer unpatched vim gets patched & built using a recipe. I read documentation on recipes, though I am not sure how to apply a patch.
Should I create branch with modified source and have the recipe merge it? How does that handle when patched branch gets out-of-date with the distro package in newer release? (The patch will very likely still apply; but will the branches be able to merge as well?)

A: Yes, you should indeed create a new branch derived from the vim Bazaar branch on Launchpad (lp:ubuntu/vim), and commit your patch to that branch.
As long as there are no conflicts when merging, the recipe will merge the two branches when one of them changes, and rebuild. This means that if there is a new revision in the ubuntu branch, it will happily rebuild.
The recipe would look something like this:
# bzr-builder format 0.3 deb-version {debupstream}+myfix{revno:myfix}
lp:ubuntu/oneiric/vim
merge myfix lp:~YOURNAME/ubuntu/oneiric/vim/myfix

The guide for this is here


text:
Q: I want to be able to enable browser caching on my Godaddy Cpanel Apache Hosting Server and have the following code. but this code does not work ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/png A2592000
ExpiresByType image/x-icon A2592000
ExpiresByType text/css A86400
ExpiresByType text/javascript A86400
ExpiresByType application/x-shockwave-flash A2592000

A: To enable browser caching you need to edit your HTTP headers to set expiry dates on certain types of files.
In this code we will set our caching parameters to tell the browser what types of files to cache.
please try following code.
 ## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
## EXPIRES CACHING ##


text:
Q: NullPointerException after updating JSF to 2.1, Richfaces to 4.3.7 When updating

*

*jsf from 1.2 to 2.1

*richfaces from 3.3.3 to 4.3.7.Final

following this link
I got stuck with some strange exception
java.lang.NullPointerException
com.ocpsoft.pretty.faces.application.PrettyNavigationHandler.processFacesNavigation(PrettyNavigationHandler.java:58)
com.ocpsoft.pretty.faces.application.PrettyNavigationHandler.handleNavigation(PrettyNavigationHandler.java:44)
com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:130)
javax.faces.component.UICommand.broadcast(UICommand.java:315)
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
ua.com.winforce.online.site.http.filter.LocaleFilter.doFilter(LocaleFilter.java:65)

which appears after submitting simple form on login.jspx page
<h:form>

    <h:outputText value="#{localeController.locale.registr.email}" escape="false"/>
    <h:inputText id="rLogin"  value="#{playerRegistration.login}" />

    <h:outputText value="#{localeController.locale.registr.password}" escape="false"/>
    <h:inputSecret value="#{playerRegistration.password}"/>

    <h:commandButton value="#{localeController.locale.mainMsg.registration}" action="#{playerRegistration.doRegistration}" />

LocaleFilter works as usual.
After updating I left .jspx page format.
I think that something wrong in configuration but can't find the reason.
main pom.xml:
<properties>
    <targetJdk>1.6</targetJdk>
    <spring.version>4.0.5.RELEASE</spring.version>
    <spring.security.version>3.2.4.RELEASE</spring.security.version>
    <hibernate.version>4.2.16.Final</hibernate.version>
    <richfaces.version>4.3.7.Final</richfaces.version>
</properties>

<dependencyManagement>
    <dependencies>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.7</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <type>jar</type>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <type>jar</type>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <dependency>
      <groupId>org.richfaces</groupId>
      <artifactId>richfaces-bom</artifactId>
      <version>${richfaces.version}</version>
      <scope>import</scope>
      <type>pom</type>
    </dependency>

    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
      <groupId>com.sun.faces</groupId>
      <artifactId>jsf-api</artifactId>
    </dependency>
    <dependency>
      <groupId>com.sun.faces</groupId>
      <artifactId>jsf-impl</artifactId>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>wsdl4j</groupId>
        <artifactId>wsdl4j</artifactId>
        <version>1.6.1</version>
    </dependency>
    <dependency>
        <groupId>org.richfaces.core</groupId>
        <artifactId>richfaces-core-impl</artifactId>
      </dependency>
      <dependency>
        <groupId>org.richfaces.ui</groupId>
        <artifactId>richfaces-components-ui</artifactId>
      </dependency>
</dependencies>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     version="3.0">
<mime-mapping>
    <extension>jspx</extension>
    <mime-type>application/xml</mime-type>
</mime-mapping>

<context-param>
    <param-name>javax.faces.application.CONFIG_FILES</param-name>
    <param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>

<context-param>
    <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
    <param-value>.jspx</param-value>
</context-param>
<context-param>
    <param-name>javax.faces.FACELETS_SUFFIX</param-name>
    <param-value>.jspx</param-value>
</context-param>
<context-param>
    <param-name>javax.faces.FACELETS_VIEW_MAPPINGS</param-name>
    <param-value>*.jspx</param-value>
</context-param>

<context-param>
    <param-name>com.sun.faces.validateXml</param-name>
    <param-value>false</param-value>
</context-param>

<context-param>
    <param-name>facelets.DEVELOPMENT</param-name>
    <param-value>false</param-value>
</context-param>

<context-param>
        <param-name>com.sun.faces.enableRestoreView11Compatibility</param-name>
        <param-value>false</param-value>
</context-param>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/applicationContext-site-dao.xml
        /WEB-INF/applicationContext-site-security.xml
    </param-value>
</context-param>

<context-param>
    <param-name>com.sun.faces.sendPoweredByHeader</param-name>
    <param-value>false</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
    <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.html</url-pattern>
</servlet-mapping>

faces-config.xml header:
<faces-config version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
<locale-config>
        <default-locale>ru</default-locale>
        <supported-locale>ru</supported-locale>
        <supported-locale>en</supported-locale>
    </locale-config>

Here are libs, used in project:

*

*org/graylog2/gelfj/0.9.1-SNAPSHOT/gelfj-0.9.1-SNAPSHOT.jar

*com/googlecode/json-simple/json-simple/1.1/json-simple-1.1.jar

*commons-pool/commons-pool/1.5.2/commons-pool-1.5.2.jar

*jcraft/jcraft/1/jcraft-1.jar

*jazzlib/jazzlib/1.07/jazzlib-1.07.jar

*net/sf/json-lib/json-lib/2.2.3/json-lib-2.2.3-jdk15.jar

*net/sf/ezmorph/ezmorph/1.0.6/ezmorph-1.0.6.jar

*javax/mail/mail/1.4.1/mail-1.4.1.jar

*javax/activation/activation/1.1/activation-1.1.jar

*license4j-runtime/license4j-runtime/3.1/license4j-runtime-3.1.jar

*jdbcappender/jdbcappender/2.1.01/jdbcappender-2.1.01.jar

*log4j/log4j/1.2.14/log4j-1.2.14.jar

*org/slf4j/slf4j-log4j12/1.7.7/slf4j-log4j12-1.7.7.jar

*commons-lang/commons-lang/2.4/commons-lang-2.4.jar

*commons-io/commons-io/1.4/commons-io-1.4.jar

*commons-collections/commons-collections/3.2/commons-collections-3.2.jar

*commons-dbcp/commons-dbcp/1.2.1/commons-dbcp-1.2.1.jar

*xml-apis/xml-apis/1.0.b2/xml-apis-1.0.b2.jar

*xerces/xercesImpl/2.9.1/xercesImpl-2.9.1.jar

*commons-discovery/commons-discovery/0.4/commons-discovery-0.4.jar

*commons-logging/commons-logging/1.0.4/commons-logging-1.0.4.jar

*javax/servlet/jstl/1.2/jstl-1.2.jar

*com/sun/facelets/jsf-facelets/1.1.15/jsf-facelets-1.1.15.jar

*aspectj/aspectjrt/1.5.3/aspectjrt-1.5.3.jar

*aspectj/aspectjweaver/1.5.3/aspectjweaver-1.5.3.jar

*jfree/jcommon/1.0.12/jcommon-1.0.12.jar

*org/springframework/spring-web/4.0.5.RELEASE/spring-web-4.0.5.RELEASE.jar

*org/springframework/spring-aop/4.0.5.RELEASE/spring-aop-4.0.5.RELEASE.jar

*org/springframework/spring-jdbc/4.0.5.RELEASE/spring-jdbc-4.0.5.RELEASE.jar

*org/springframework/spring-tx/4.0.5.RELEASE/spring-tx-4.0.5.RELEASE.jar

*org/springframework/spring-orm/4.0.5.RELEASE/spring-orm-4.0.5.RELEASE.jar

*org/springframework/spring-support/2.0.8/spring-support-2.0.8.jar

*aopalliance/aopalliance/1.0/aopalliance-1.0.jar

*org/springframework/security/spring-security-core/3.2.4.RELEASE/spring-security-core-3.2.4.RELEASE.jar

*org/springframework/spring-expression/3.2.8.RELEASE/spring-expression-3.2.8.RELEASE.jar

*org/springframework/security/spring-security-config/3.2.4.RELEASE/spring-security-config-3.2.4.RELEASE.jar

*org/springframework/security/spring-security-taglibs/3.2.4.RELEASE/spring-security-taglibs-3.2.4.RELEASE.jar

*org/springframework/security/spring-security-acl/3.2.4.RELEASE/spring-security-acl-3.2.4.RELEASE.jar

*org/springframework/security/spring-security-web/3.2.4.RELEASE/spring-security-web-3.2.4.RELEASE.jar

*commons-httpclient/commons-httpclient/3.1/commons-httpclient-3.1.jar

*commons-validator/commons-validator/1.2.0/commons-validator-1.2.0.jar

*commons-beanutils/commons-beanutils/1.7.0/commons-beanutils-1.7.0.jar

*commons-digester/commons-digester/1.6/commons-digester-1.6.jar

*oro/oro/2.0.8/oro-2.0.8.jar

*commons-net/commons-net/3.3/commons-net-3.3.jar

*javassist/javassist/3.10.0.GA/javassist-3.10.0.GA.jar

*postgresql/postgresql/8.3-603.jdbc4/postgresql-8.3-603.jdbc4.jar

*quartz/quartz/1.5.2/quartz-1.5.2.jar

*org/freemarker/freemarker/2.3.9/freemarker-2.3.9.jar

*avalon-framework/avalon-framework/4.1.3/avalon-framework-4.1.3.jar

*com/sun/xml/messaging/saaj/saaj-impl/1.3.1/saaj-impl-1.3.1.jar

*javax/xml/soap/saaj-api/1.3/saaj-api-1.3.jar

*com/octo/captcha/jcaptcha-all/1.0-RC6/jcaptcha-all-1.0-RC6.jar

*javax/annotation/jsr250-api/1.0/jsr250-api-1.0.jar

*commons-codec/commons-codec/1.4/commons-codec-1.4.jar

*org/springframework/spring-core/4.0.5.RELEASE/spring-core-4.0.5.RELEASE.jar

*com/ocpsoft/prettyfaces-jsf12/3.3.3/prettyfaces-jsf12-3.3.3.jar

*org/richfaces/core/richfaces-core-impl/4.3.7.Final/richfaces-core-impl-4.3.7.Final.jar

*org/richfaces/core/richfaces-core-api/4.3.7.Final/richfaces-core-api-4.3.7.Final.jar

*net/sourceforge/cssparser/cssparser/0.9.5/cssparser-0.9.5.jar

*org/w3c/css/sac/1.3/sac-1.3.jar

*com/google/guava/guava/13.0.1/guava-13.0.1.jar

*org/richfaces/ui/richfaces-components-ui/4.3.7.Final/richfaces-components-ui-4.3.7.Final.jar

*org/richfaces/ui/richfaces-components-api/4.3.7.Final/richfaces-components-api-4.3.7.Final.jar

*com/sun/faces/jsf-impl/2.1.3/jsf-impl-2.1.3.jar

*com/sun/faces/jsf-api/2.1.3/jsf-api-2.1.3.jar

*commons-configuration/commons-configuration/1.10/commons-configuration-1.10.jar

*org/hibernate/hibernate-core/4.2.16.Final/hibernate-core-4.2.16.Final.jar

*antlr/antlr/2.7.7/antlr-2.7.7.jar

*org/jboss/logging/jboss-logging/3.1.0.GA/jboss-logging-3.1.0.GA.jar

*dom4j/dom4j/1.6.1/dom4j-1.6.1.jar

*org/javassist/javassist/3.18.1-GA/javassist-3.18.1-GA.jar

*org/jboss/spec/javax/transaction/jboss-transaction-api_1.1_spec/1.0.1.Final/jboss-transaction-api_1.1_spec-1.0.1.Final.jar

*org/hibernate/javax/persistence/hibernate-jpa-2.0-api/1.0.1.Final/hibernate-jpa-2.0-api-1.0.1.Final.jar

*org/hibernate/common/hibernate-commons-annotations/4.0.2.Final/hibernate-commons-annotations-4.0.2.Final.jar

*javax/jms/jms-api/1.1-rev-1/jms-api-1.1-rev-1.jar

*org/apache/xbean/xbean-spring/4.1/xbean-spring-4.1.jar

*org/apache/activemq/activemq-all/5.12.1/activemq-all-5.12.1.jar

*org/springframework/spring-jms/4.0.5.RELEASE/spring-jms-4.0.5.RELEASE.jar

*joda-time/joda-time/2.7/joda-time-2.7.jar

*org/springframework/spring-context-support/4.0.5.RELEASE/spring-context-support-4.0.5.RELEASE.jar

*org/springframework/spring-beans/4.0.5.RELEASE/spring-beans-4.0.5.RELEASE.jar

*org/springframework/spring-context/4.0.5.RELEASE/spring-context-4.0.5.RELEASE.jar

*net/sf/ehcache/ehcache/2.10.0/ehcache-2.10.0.jar

*org/slf4j/slf4j-api/1.7.7/slf4j-api-1.7.7.jar

*javax/servlet/javax.servlet-api/3.0.1/javax.servlet-api-3.0.1.jar

*wsdl4j/wsdl4j/1.6.1/wsdl4j-1.6.1.jar

I am ready to add any extra information to find a reason of this situation. I hope someone can help me to find out how to solve this problem, because Google doesn't know about this issue. Any help will be useful.

A: Change prettyfaces to JSF 2 compatible version (for example prettyfaces-jsf2-3.3.3.jar)

prettyfaces-jsf12... is for JSF 1.2, prettyfaces-jsf2... is for JSF 2.x (from OCPSoft doc)

, check if it proper defined in your project. Plus you can add following filter in web.xml:
<filter>
    <filter-name>Pretty Filter</filter-name>
    <filter-class>com.ocpsoft.pretty.PrettyFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>Pretty Filter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>

A: the problem was in the following dependency
com/ocpsoft/prettyfaces-jsf12/3.3.3/prettyfaces-jsf12-3.3.3.jar

when I replaced it with
com/ocpsoft/prettyfaces-jsf2/3.3.3/prettyfaces-jsf2-3.3.3.jar

for the second version of JSF, the problem has gone


text:
Q: How do i show recent posts first in Django blog? I'm new Django, and i've been following a tutorial on creating a blog.
I've created a blog, that displays the posts. But, it displays the posts in the order: oldest posts first, and newest posts last.
This is the code in "models.py":
from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=32)
    date = models.DateTimeField(auto_now_add=True)
    text = models.TextField()

How can i display the new posts first and the old posts last?

A: from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=32)
    date = models.DateTimeField(auto_now_add=True)
    text = models.TextField()

    class Meta:
        ordering = ['-date',]

https://docs.djangoproject.com/en/dev/topics/db/models/#meta-options
or do it with when you create the queryset
Blog.objects.all().order_by('-date')

https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by

A: *

*This is how to work for me, not a new solution, only more detailed.

*in my views.py
def blog(request):
    post_list = Post.objects.all().order_by('-timestamp')

    context = {
        'post_list': post_list,
    }
    return render(request, 'blog/blog.html', context)

*

*Thank you.


text:
Q: Groupby transformation Here I have films grouped by year, but I need to have a year value filled for each film respectively.
Could you please suggest how can I do that?
cast.groupby(['year','name']).size()

year  name
1894  Blanche Bayliss         1
      Chauncey Depew          1
      William Courtenay       1
1900  Orrie Perry             1
      Reg Perry               1
1905  Armand Dranem           1
1906  Battling Nelson         1
      E.J. Tait               1
      Elizabeth Tait          1
      Frank (VI) Mills        1
      Frank Tait              1
      Helfrid Lambert         1
      Jack (II) Ennis         1
      Joe Gans                1
      John (III) Forde        1
      John Tait               1
      Knut Lambert            1
      Mr. Marshall            1
      Mr. McKenzie            1
      Norman (II) Campbell    1
      Sam Crewes              1
      Tollie Zellman          1
      Will Coyne              1
1907  Arthur Guest            1

Thanks!

A: Also try this.
cast.groupby(['year','name']).size().reset_index()


text:
Q: keystone projet not getting updated while code changes I'm new to keystone.js, but not new in the node and js framework world.
I installed keystone with the generator, I can run it with gulp or node keystone , in both cases the site is available on 3000, but updating js files in /routes or /models won't change anything until I re-run gulp or node... is that normal ?
I also ensured that I was in development mode with set NODE_ENV='development'

A: This has nothing to do with KeystoneJS.
By default neither gulp or node monitor for code changes.
If you want to monitor for code changes from within your gulp setup have a look at gulp-watch.
Otherwise, you can just use nodemon like so: nodemon keystone.js


text:
Q: Retrieve only specific columns of spreadsheet with zend gdata from gdocs I am working with relatively large spreadsheets from gdocs and access them via the zend library. I only need certain columns at any given time so in order to save memory it would be helpful to use the list-based feed to only retrieve these certain columns and not the whole spreadsheet. The basic query I am using is according to the zend documentation
$query = new Zend_Gdata_Spreadsheets_ListQuery();
$query->setSpreadsheetKey($spreadsheetKey);
$query->setWorksheetId($worksheetId);
$listFeed = $spreadsheetService->getListFeed($query);

I have the opportunity to send a structured query via $query->setSpreadsheetQuery('name=someName'); but as far as I can see this only works for limiting the number of rows returned and not the number of columns. Is there a way to somehow use this to get specific columns? Alternatively it would be helpful to get only certain, previously specified rows of the spreadsheet so as to retrieve only blocks of the spreadsheet and thin out one block at the time. Either way, I need to avoid having the whole spreadsheet in the memory at any given time.
Thanks for any help.

A: I managed to work around this problem using a cell-based feed. Basically what I did was to first get the column number for a specific column header like so
$query = new Zend_Gdata_Spreadsheets_CellQuery();
$query->setSpreadsheetKey($spreadsheetkey);
$query->setWorksheetId($wworksheetkey);
$query->setMinRow(1);
$query->setMaxRow(1);
$headerFeed = $spreadsheetService->getCellFeed($query);

foreach($headerFeed as $cellEntry){
    if(strcasecmp($cellEntry->cell->getText(), $column) ==  0){
        $colNr = $cellEntry->cell->getColumn();
        break;
    }
}

which will give me the column number for the $column column. I would then proceed to get a specific range of rows for the given column number so that I can read in the whole column block by block without ever having the whole spreadsheet(or column) in memory. This can be done as
$query->setMinCol($colNr);
$query->setMaxCol($colNr);
$query->setMinRow($startingRow);
$query->setMaxRow($endingRow);

$columnFeed = $spreadsheetService->getCellFeed($query);
foreach($columnFeed as $cellEntry){
    $result[$cellEntry->cell->getRow()] = $cellEntry->cell->getText();
}

by changing $startingRow and $endingRow I can iterate through the column. One has to be careful with the choice of these though, since if they are 'out of bounds' the google api will return a http 400 code. The cells don't have to have value in them, but they have to exist(scroll down your spreadsheet and the last row number you see should be your maximum for both values). I think per default a spreadsheet with 100(empty) rows is created.
This is probably not the most elegant or fastest solution, but it works for me.


text:
Q: Spring Integration java.lang.IllegalArgumentException: Found ambiguous parameter type I received the following error when trying to send a request to an http outbound gateway. After getting the response, I am converting the json payload to a list of objects from other posts I have read it could be a problem with the service activator or the transformer. I am still trying to get a handle on EIP and SI.
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'httpPostAtms' defined in class path resource [com/backbase/atm/config/InfrastructorConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.integration.dsl.IntegrationFlow]: Factory method 'httpPostAtms' threw exception; nested exception is java.lang.IllegalArgumentException: Found ambiguous parameter type [class java.lang.Object] for method match: [public default java.util.stream.Stream java.util.Collection.parallelStream(), public void java.util.Arrays$ArrayList.forEach(java.util.function.Consumer), public void java.util.Arrays$ArrayList.sort(java.util.Comparator), public boolean java.util.AbstractCollection.remove(java.lang.Object), public java.util.ListIterator java.util.AbstractList.listIterator(int), public java.lang.Object[] java.util.Arrays$ArrayList.toArray(java.lang.Object[]), public default boolean java.util.Collection.removeIf(java.util.function.Predicate), public boolean java.util.AbstractCollection.retainAll(java.util.Collection), public void java.util.Arrays$ArrayList.replaceAll(java.util.function.UnaryOperator)]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at com.backbase.atm.IngAtmApplication.main(IngAtmApplication.java:23) [classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.integration.dsl.IntegrationFlow]: Factory method 'httpPostAtms' threw exception; nested exception is java.lang.IllegalArgumentException: Found ambiguous parameter type [class java.lang.Object] for method match: [public default java.util.stream.Stream java.util.Collection.parallelStream(), public void java.util.Arrays$ArrayList.forEach(java.util.function.Consumer), public void java.util.Arrays$ArrayList.sort(java.util.Comparator), public boolean java.util.AbstractCollection.remove(java.lang.Object), public java.util.ListIterator java.util.AbstractList.listIterator(int), public java.lang.Object[] java.util.Arrays$ArrayList.toArray(java.lang.Object[]), public default boolean java.util.Collection.removeIf(java.util.function.Predicate), public boolean java.util.AbstractCollection.retainAll(java.util.Collection), public void java.util.Arrays$ArrayList.replaceAll(java.util.function.UnaryOperator)]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    ... 18 common frames omitted
Caused by: java.lang.IllegalArgumentException: Found ambiguous parameter type [class java.lang.Object] for method match: [public default java.util.stream.Stream java.util.Collection.parallelStream(), public void java.util.Arrays$ArrayList.forEach(java.util.function.Consumer), public void java.util.Arrays$ArrayList.sort(java.util.Comparator), public boolean java.util.AbstractCollection.remove(java.lang.Object), public java.util.ListIterator java.util.AbstractList.listIterator(int), public java.lang.Object[] java.util.Arrays$ArrayList.toArray(java.lang.Object[]), public default boolean java.util.Collection.removeIf(java.util.function.Predicate), public boolean java.util.AbstractCollection.retainAll(java.util.Collection), public void java.util.Arrays$ArrayList.replaceAll(java.util.function.UnaryOperator)]
    at org.springframework.util.Assert.isNull(Assert.java:113) ~[spring-core-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.integration.util.MessagingMethodInvokerHelper.findHandlerMethodsForTarget(MessagingMethodInvokerHelper.java:499) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.util.MessagingMethodInvokerHelper.<init>(MessagingMethodInvokerHelper.java:226) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.util.MessagingMethodInvokerHelper.<init>(MessagingMethodInvokerHelper.java:149) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.util.MessagingMethodInvokerHelper.<init>(MessagingMethodInvokerHelper.java:144) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.handler.MethodInvokingMessageProcessor.<init>(MethodInvokingMessageProcessor.java:60) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.transformer.MethodInvokingTransformer.<init>(MethodInvokingTransformer.java:47) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.dsl.IntegrationFlowDefinition.transform(IntegrationFlowDefinition.java:516) ~[spring-integration-java-dsl-1.2.2.RELEASE.jar:na]
    at org.springframework.integration.dsl.IntegrationFlowDefinition.transform(IntegrationFlowDefinition.java:496) ~[spring-integration-java-dsl-1.2.2.RELEASE.jar:na]
    at org.springframework.integration.dsl.IntegrationFlowDefinition.transform(IntegrationFlowDefinition.java:483) ~[spring-integration-java-dsl-1.2.2.RELEASE.jar:na]
    at com.backbase.atm.config.InfrastructorConfig.httpPostAtms(InfrastructorConfig.java:50) ~[classes/:na]
    at com.backbase.atm.config.InfrastructorConfig$$EnhancerBySpringCGLIB$$154e5ed2.CGLIB$httpPostAtms$1(<generated>) ~[classes/:na]
    at com.backbase.atm.config.InfrastructorConfig$$EnhancerBySpringCGLIB$$154e5ed2$$FastClassBySpringCGLIB$$30080451.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at com.backbase.atm.config.InfrastructorConfig$$EnhancerBySpringCGLIB$$154e5ed2.httpPostAtms(<generated>) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_45]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_45]
    at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_45]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    ... 19 common frames omitted

my config
    package com.backbase.atm.config;

import java.util.Arrays;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.dsl.core.Pollers;
import org.springframework.integration.dsl.http.Http;
import org.springframework.integration.dsl.support.Transformers;
import org.springframework.integration.scheduling.PollerMetadata;
import org.springframework.messaging.MessageChannel;

import com.backbase.atm.model.Atm;

@IntegrationComponentScan
@Configuration
@EnableIntegration
@ComponentScan
public class InfrastructorConfig {

    @Bean
    public MessageChannel requestChannel() {
        return new DirectChannel() ;
    }

    @Bean(name = PollerMetadata.DEFAULT_POLLER)
    public PollerMetadata poller() {
        return Pollers.fixedRate(500).get();
    }

    @Bean
    public IntegrationFlow httpPostAtms() {

        return IntegrationFlows.from("requestChannel")
                .handle(Http.outboundGateway("https://www.ing.nl/api/locator/atms/")
                        .httpMethod(HttpMethod.GET)
                        .expectedResponseType(String.class))
                .<String, String>transform(p -> p.substring(5))
                .transform(Arrays.asList(Transformers.fromJson(Atm[].class)))
                .channel("responseChannel")
                .get();

    }

}

my gateway
package com.backbase.atm.service;

import java.util.List;

import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.messaging.handler.annotation.Payload;

import com.backbase.atm.model.Atm;

@MessagingGateway
public interface IntegrationService {

    @Gateway(requestChannel = "requestChannel")
    @Payload("'string'")
    List<Atm> getAllAtms();
}

the object that I am trying to convert the payload to
 package com.backbase.atm.model;

public class Atm {

    private Address address;
    String distance;
    String type;

    public Atm() {
        super();
    }

    public Atm(Address address) {
        setAddress(address);
    }

    public Atm(Address address, String distance, String type) {
        super();
        this.address = address;
        this.distance = distance;
        this.type = type;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String getDistance() {
        return distance;
    }

    public void setDistance(String distance) {
        this.distance = distance;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Atm: address=").append(address).append(", distance=").append(distance).append(", type=")
                .append(type).append("");
        return builder.toString();
    }
}

sample payload response
[{"address":{"street":"Molenwerf","housenumber":"20","postalcode":"1541 WR","city":"Koog aan de Zaan","geoLocation":{"lat":"52.457912","lng":"4.799866"}},"distance":0,"type":"ING"}]

A: You have suspicious code:
.transform(Arrays.asList(Transformers.fromJson(Atm[].class)))

What drives you to use Arrays.asList() there?
You use Transformers.fromJson() which is just a factory and returns for you valid Transformer object. The .transform() can simply deal with that one.


text:
Q: I need to connect my project repo to common repo to work local I have two repos one is common component repo and one is separate project repo I have connected this repo in GitHub using in package JSON whatever I change in my common repo I have to create a build file and push it on GitHub every time I will do this then I can see a change in my septate repo by npm i but what my task is if I need to test something that I am doing in my common component I need to do that step to check changes but its make my work too hard to do everything this step I need to set like whatever I am changing in my common component that I am able to test locally by connecting to the common component repo so anyway can I connect like something symbolic like or any what that make this step smooth.
I have connected my common component repo like this in package.json
 "@common": "git+https://dev-user:ghp_RT5nojYRmTJgewvHNEB4JZiMwYktFh3MOTOu@github.com/Dev-Org/dev-frontend-common.git",


text:
Q: Ionic 2 redirecting users after login I'm trying to redirect to TabsPage after a user logs in using Auth0.
The authentication is working and *ngIf="!auth.authenticated()" *ngIf="auth.authenticated()" is working too, but if I use this.auth.authenticated() in /app/app.component.ts it always returns false.
This is the structure:

*

*LoginPage

*TabsPage

*

*HomePage

*RepositoriesPage

*...

I followed this tutorial to add Auth0 https://auth0.com/docs/quickstart/native/ionic2


text:
Q: How do I chain Promises with interval-promise Node.js module? I'm using the 'interval-promise' (github repo here) module to read a value in a Firebase Realtime DB node for ongoing logins.
The idea is to read a 'status' key from a Realtime DB node which might not exist yet, and to retry until it has a value.
const tryGetAuthStatus = (user) =>
        new Promise((resolve, reject) => {
            var login_node = user.child(provider);

            if (login_node.exists()) {
                resolve(login_node.val().status)
            }
        })

ref.child(uuid).once('value')     //Returns a promise
    .then((user) =>
        intervalPromise(
            async (iteration, stop) => await tryGetAuthStatus(user),    //Returns a promise
            attempts_pause,
            { iterations: attempts_max, stopOnError: true }
        )
    )
    .then((result) => console.log(result))    //undefined

As you can see I'm returning the intervalPromise Promise to continue the promise chain.
When the promise returned from firebaseTryGetAuth resolves, it returns the correct result (e.g. "authorized"), but the last 'then' in the chain gets no result from the returned intervalPromise.
How can I propagate the result?

A: interval()'s returned promise does not resolve/pass a long a value from your own async operation. It just does a resolve() call to end its own promise

https://github.com/andyfleming/interval-promise/blob/078528e4096649a56dd2473986d7a1a7eba7909f/src/index.js#L31
if (currentIteration === settings.iterations || stopRequested) {
  rootPromiseResolve()
  return
}

Due to this could do a couple things:

*

*Save the value of status to an outer scope variable and use it in your last then() callback

*Check the status directly from the function you are passing to interval()

//only use in then() callback
//outside use may result in use before set
let authStatus = null;

let authCheck = (user)=>{
  return async (iteration, stop) => {
    let status = await tryGetAuthStatus(user)
    //set variable for use in then()
    authStatus=status;

    //or check status now and do so some action
    //instead of in some later then()
    if(status == whatyouwant){
      someAction()
      //call stop() since no reason to continue
      //the async loop
      stop();
    }
  };
};

ref.child(uuid).once('value')
    .then((user) =>
        intervalPromise(
            authCheck(user),
            attempts_pause,
            { iterations: attempts_max, stopOnError: true }
        )
    )
    //if you want to go the set outer scope variable route
    .then(() =>{
      if(authStatus == whatever){
        doSomeAction();
      }
    })


text:
Q: PHP display database call before submission I'm troubleshooting someone else's code and I'm not accustomed to calling databases in this way.  It's using Codeigniter and all I want to do it assemble my own version of this SQL call to test in phpMyAdmin.
$this->db->select('c1.company_id, c1.name, u.first_name, u.last_name, c2.address1, c2.city, c2.prov_stat, c2.country, c1.url, u.email');
$this->db->from('company AS c1');
$this->db->join('contact AS c2', 'c1.company_id = c2.company_id', 'left');
$this->db->join('users as u', 'c1.user_id = u.id', 'left');
$this->db->where('c2.checked_by_ecole = 0');
$this->db->order_by('c1.name');

Is there an existing PHP function I can use to see what the SQL statement looked like in its final format before it was submitted?

A: Right before you run the query use get_compile_select()
$this->db->select('c1.company_id, c1.name, u.first_name, u.last_name, c2.address1, c2.city, c2.prov_stat, c2.country, c1.url, u.email');
$this->db->from('company AS c1');
$this->db->join('contact AS c2', 'c1.company_id = c2.company_id', 'left');
$this->db->join('users as u', 'c1.user_id = u.id', 'left');
$this->db->where('c2.checked_by_ecole = 0');
$this->db->order_by('c1.name');

die('<pre>'.$this->db->get_compile_select());

You can find the get() and get_compile_select() documentation for ci 3 here;


text:
Q: How can I optimize this mysql query I would like to ask, how can I optimize this query:
select
    h.jmeno hrac,
    n1.url hrac_url,
    t.nazev tym,
    n2.url tym_url,
    ss.pocet_zapasu zapasy,
    ss.pocet_minut minuty,
    s.celkem_golu goly,
    s.zk,
    s.ck
from
    hraci h
left join
    (
        select
            hrac_id,
            tym_id,
            count(minut_celkem) pocet_zapasu,
            sum(minut_celkem)  pocet_minut
        from
            statistiky_stridani ss
        join
            zapasy z
                on z.id = ss.zapas_id
        join
            souteze s
                on s.id = z.soutez_id
        join
            souteze_nazev sn
                on sn.id = s.soutez_id
        where
            s.rocnik_id = 2
        group by
            hrac_id
    ) ss on ss.hrac_id = h.id
left join
    (
        select
            hrac_id,
            tym_id,
            sum(typ_id = 1 or typ_id = 3) as celkem_golu,
            sum(typ_id = 4) as zk,
            sum(typ_id = 5) as ck
        from
            statistiky st
        join
            zapasy z
                on z.id = st.zapas_id
        join
            souteze s
                on s.id = z.soutez_id
        join
            souteze_nazev sn
                on sn.id = s.soutez_id
        where
            s.rocnik_id = 2
        group by
            hrac_id
    ) s on s.hrac_id = h.id
join
    navigace n1
        on n1.id = h.nav_id
join
    tymy t
        on t.id = ss.tym_id
join
    navigace n2
        on n2.id = t.nav_id
order by
    s.celkem_golu desc
limit
    10

Because query takes about 1,5 - 2 seconds. For example, table statistiky_stridani has about 500 000 rows and statistiky about 250 000 rows.
This returns EXPLAIN:

Thank you for your help

A: *

*Don't use LEFT JOIN instead of JOIN unless you really need the empty rows.

*Try to reformulate because JOIN ( SELECT ... ) JOIN ( SELECT ... ) optimizes poorly.

*Please do not use the same alias (s) for two different tables; it confuses the reader.

*Add the composite index INDEX(rocnik_id, soutez_id) to souteze.

*LEFT JOIN ... JOIN ... -- Please add parentheses to show whether the JOIN should be before doing the LEFT JOIN or after:
either
FROM ...
LEFT JOIN ( ... JOIN ... )

or
FROM ( ... LEFT JOIN ... )
JOIN ...

It may make a big difference in how the Optimizer performs the query, which may change the speed.
There may be more suggestions; work through those and ask again (if it is still "too slow").


text:
Q: RestKit with Core Data: Use NSPersistentStore with RestKit RKObjectManager I am using RestKit with Core Data. Till now I initialized RestKit as following:
[...]
RKObjectManager *objectManager = [RKObjectManager managerWithBaseURLString:@"http://URL"];
objectManager.objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"database.sql"];
[...]

without this xcode auto-generated Core Data properties:
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

Fetching data worked through calling objectsWithFetchRequest: in NSManagedObject. Now I would like to use NSFetchingResultsController and therefore I need at least such a managedObjectContext. But wherefrom do I get this managedObjectContext? My first idea was: from the auto-generated managedObjectContext in AppDelegate.m, but this 3 properties managedObjectContext, managedObjectModel and persistentStoreCoordinator are all depending on each other.
How can I "link" RestKit to Core Data correctly? How can I "link" a persistentStoreCoordinator to RestKit and the RKObjectManager?

A: You are already linking RestKit and Core Data with that code. Now, if I understand the question, you just need to be able to get access to the managed object context. Try creating a "Core Data Manager" object that contains all of the code required for the context, model and store coordinator with those properties. Then any of your classes that require that code can just inherit from the core data manager.

A: Found the answer at http://mobile.tutsplus.com/tutorials/iphone/advanced-restkit-development_iphone-sdk/
RKManagedObjectStore – The object store wraps the initialization and configuration of internal Core Data classes including NSManagedObjectModel, NSPersistentStoreCoordinator, and NSManagedObjectContext.
RestKit handles the "link" to Core Data quiet autonomous. There are no linkings to do.
Getting a NSFetchingResultsController is possible through a NSManagedObject calling the fetchAllSortedBy or a similar method in NSManagedObject+ActiveRecord.h. e.g.
fetchedResultsController = [Customer fetchAllSortedBy:@"surname" ascending:YES withPredicate:nil groupBy:@"surname"];


text:
Q: FTP server running on Port 2000 over NAT not working on Passive Mode I am running FILE-Zilla ftp server on windows in one of the LAN pc connect to my router. i am trying to access the FTP server from the network outside of the router using Router WAN ip (WAN-to-LAN) by adding Port-Forwarding rule (NAT) in the router. I have 2 cases here as per below configurations. the 1st is working and the 2nd is not (in Passive mode).

Note: i have added the custom inbound rule in the windows 7 firewall
  where the ftp server is running.

Configuration #1
Filezilla FTP server port: 21
Passive port range: 50000-51000

NAT - external port: 21
NAT - internal port: 21

Windows firewall inboud rule port allow port: 21, 50000-51000

Client connecting to: <Wan IP>:21

This is working if client is trying to connect using Active/Passive mode
Configuration #2
Filezilla FTP server port: 2000
Passive port range: 50000-51000

NAT - external port: 21
NAT - internal port: 2000

Windows firewall inboud rule port allow port: 2000, 50000-51000

Client connecting to: <Wan IP>:21

This is working only if client is set to Active mode.
Not working with Passive mode configuration by client. the client can connect and login is successfull but ends with the error message at server side like this without any directory listing.
227 Entering Passive Mode (192,168,1,2,195,85)

Note: both the case working in LAN-LAN network.

A: My guess is that the configuration #1 works only because the NAT is smart enough to translate the IP address in the PASV response from the server. But it likely does that only for the standard FTP port.

You should tell the FileZilla FTP server its external IP address. Go to Edit > Settings > Passive mode settings > IPv4 specific > External Server IP Address for passive mode transfers.
Currently your FTP server is sending its internal IP address to the client. And the client obviously cannot connect to the IP address.
And have the NAT forward the ports in the passive port range (50000-51000).

Though the change will break the LAN-LAN connections. To allow both LAN and WAN connections, check if the NAT can be configured to translate the IP address for the non standard ports too. Though the translation will work for unencrypted connection only anyway. And you should not use unencrypted connections!
The last option is to use the extended passive mode (EPSV), if your clients allow that. In the extended passive mode, there's no IP address in the response. The FTP client uses the primary IP address of the FTP server for data connections.


text:
Q: google-oauth-java-client - Force access token default lifetime I'm wondering if it's possible to change the default lifetime (3600) ?
In fact, i'm trying to solve an issue and i want to check if the issue is due to an expired access token..
Else, is it possible to force the access token used by a credential ?
Let me know if it's not clear.
Regards,
Sebastien

A: You cannot change the lifetime of an access token. You could, however, get a refresh token that can be used to get fresh access tokens (see Google OAuth2 docs).
Hope that helps.


text:
Q: Merging multiple projects into one solution while preserving git history I have multiple projects (solutions) each have a separate git repo setup.
I intend to merge the projects into a single solution to simplify build and distribution since all projects the same database solution. architecture is as follows
Project A (repo A):

*

*"A" solution

*Database Library Solution*

*Wix Installer Solution

*Wix Bundle Solution

Project B (repo B):

*

*"B" Solution

*Database Library Solution*

*Wix Installer Solution

*Wix Bundle Solution

*(the Database Library Solution is exactly the same in both projects, but with each change to it we need to copy paste the changes to the other project)
To simplify and unify the development environment I'd like to make it as following:
Master Project:

*

*Solution A

*

*Wix Installer and Bundle for A

*Solution B

*

*Wix Installer and Bundle for B

*Database Library Solution

How do I achieve this result by unifying the project into a single solution that has a brand new git repo, while preserving Solution A and B git history?

A: You can use git submodules to achieve this. Create the master git repo and add the required git repos and git submodules by adding a .gitmodules file like:
[submodule "module1"]
    path = /path/module1
    url = https://github.com/user/module1
[submodule "module2"]
    path = /path/module2
    url = https://github.com/user/module2

You can read about git submodules here


text:
Q: Can I use if-else for filereader Can I use if-else statement for filereader? I tried to use '==' but it doesn't seem to work.
I'm sorry if the question is a bit unintelligent, as I'm new to Java.
Thank You!
String Path = new File("").getAbsolutePath();
readFile = new FileReader(Path + "/src/agents_chats_analytics.csv");
br = new BufferedReader(readFile);
...
if(readFile == new FileReader(Path+"/src/agents_chats_analytics.csv");))
 {
   // do stuffs
 }
else if(readFile == new FileReader(Path+"/src/department_agents.csv");)
 {
   // do stuffs
 }
...

A: So, It was really hard to understand what you are trying to achieve, but, I guess, I got you right, so you can do it this way:
    String Path = new File("").getAbsolutePath();
    String readedFilePath = Path + "/src/agents_chats_analytics.csv";
    FileReader readFile = new FileReader(readedFilePath);

    if (readedFilePath.equals(Path + "/src/agents_chats_analytics.csv")) {
        readFile = new FileReader(Path + "/src/agents_chats_analytics.csv");
        // do stuffs
    } else if (readedFilePath.equals(Path + "/src/agents_chats_analytics.csv")) {
        readFile = new FileReader(Path + "/src/agents_chats_analytics.csv");
        // do stuffs
    }

You need to compare pathes not file readers.
Also, logical equality of object types in java should be done using equals method and not "==" operator. "==" will compare object references, so in your case such comparison always gives false.


text:
Q: cannot build silverlight library, what references do I need? I am converting a normal CLR library over to a silverlight library.
SqlConnection, SqlCommand, SqlClient aren't recognized.  What libraries do I reference?  I am working in Silverlight 3.0.

A: SqlConnection, SqlCommand, SqlClient are from system.data. System.Data is not part of the Silverlight.
For all database related activities, you should either use a webservice/wcf service/ria services/entity data framework for all crud operations.

A: As far as I can tell, it is not possible to directly access SqlServer from Silverlight. This makes sense since Silverlight is designed to create "web applications", implying that you'll need to use client-server methods to access the data. You could set up a WebMethod or WCF on a web server somewhere and point Silverlight at it to get the data.
References:
http://silverlight.net/learn/tutorials/sqldatagrid-cs/
http://forums.silverlight.net/forums/t/21012.aspx
http://www.codeproject.com/KB/silverlight/CntDbSlght.aspx


text:
Q: What notation to use when accessing an adjacency list? I'm attempting to do a DFS search on a certain graph, here I have attempted to write down the following code (I'm aware that there are many errors/warnings and mistakes I have made but this is only a start and I need some help).
int visited[];
static int last=-1;
int record_of_visit[];

void print_dfs(Graph* graph, int source_id)
{
    //printf("not yet implemented: put code for part 1 here\n");
    visited[source_id]=1;
    record_of_visit[++last]=source_id;
    int i;
    for (i=0;i<20;i++)
    {
        if (graph[source_id][i]==1)
        {
            if(visited[i] == 0)
                print_dfs(graph,i);
        }
    }
}

The graph.c file implementing the adjacency list can be found here.
The graph.h file can be found here.
Here I am trying to access the graph which is an already built adjacency list, but the compiler would give me error when I run this program indicating that
on if (graph[source_id][i]==1)

subscripted value is neither array nor pointer

What am I doing wrong here? Also any tips or suggestions on what to improve in my still raw DFS implementation would be appreciated!

A: You can access elements of a struct by a "dot", i.e. you can acces n from the first graph in your array by graph[0].n


text:
Q: non-www to www redirection except one url I can redirect all requests from https://example.com to https://www.example.com with these two lines.
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

But if request is like https://example.com/api/v1/xyz, I don't want to redirect it. It shouldn't be https://www.example.com/api/v1/xyz
I couldn't find any example on this one so I'm asking you guys. I'm not good at apache configurations.


text:
Q: Perform logical shift using arithmetic shift operator in C Right now I am reading the book Computer Systems : Programmer Perspective.
One problem in the book says to perform a logical right shift on a signed integer, I can't figure out how to start on this.
The following is the actual question from the book:

Fill in code for the following C functions.

*

*Function srl performs a logical right shift using an arithmetic right shift (given by value xsra), followed by other operations not including right shifts or division.

*Function sra performs an arithmetic right shift using a logical right shift (given by value xsrl), followed by other operations not including right shifts or division.
You may use the computation 8*sizeof(int) to determine w, the number of bits in data type int. The shift amount k can range from 0 to w − 1.
unsigned srl(unsigned x, int k) {
    /* Perform shift arithmetically */
    unsigned xsra = (int) x >> k;
    .
    .
    .
}

int sra(int x, int k) {
    /* Perform shift logically */
    int xsrl = (unsigned) x >> k;
    .
    .
    .
}

I hope you understand now the question.

A: I won't give you a complete answer as this is apparently homework, but I'll give you some hints to help you work it out for yourself:

*

*for a logical right shift of N bits you need to clear the top N bits of the result after arithmetic shifting

*you can clear bits in a value by applying an appropriate mask, typically using a bitwise AND or XOR

*to clear the top N bits of a value you need a mask with N 0s and remaining bits 1

*you can generate a suitable mask using left shift by W - N bits, where W is the number of bits in a word (which you can calculate as W = sizeof(int) * CHAR_BIT;)
E.g. for a logical right shift by 2
value              = 10001010
value >>= 2        = 11100010     // arithmetic right shift

mask               = 00111111     // mask has top 2 bits set to 0

value & mask       = 00100010     // apply mask to get logical right shift

The trickiest part is generating the mask, but if you think about left shifts applied so a suitable value, perhaps followed by one further bitwise operation, you should soon see a fairly simple solution.

A: It took me little time to create the mask as suggested by Paul. But I created it as follows.
First I left shifted 1 as follows
1 << (sizeof(int)*8-k);

If I consider k to be 10 and INT size as 32 I will get following mask
   00000000010000000000000000000000 ( 1 at 23 rd position 32 - 10 = 22 )

Then add it with -1 (0xffffffff)
   00000000010000000000000000000000
 + 11111111111111111111111111111111
 +++++++++++++++++++++++++++++++++++

   00000000001111111111111111111111 --> required mask with first 10 bits set to

Anding with the result of arithmetic shift will give logical shift result.
Following is the C code
unsigned srl(unsigned x, int k) {
/* Perform shift arithmetically */
        unsigned xsra = (int) x >> k;
    int mask = (1 << (sizeof(int)*8-k)) + -1;
    int result = xsra & mask;
}

And It works.


text:
Q: How to execute application code during this application installation in InstallShield 2016 Premier Edition (21-days trial)? I create now Windows installation project (ISM) of my C# WPF Prism MVVM modular application. I use for it InstallShield 2016 Premier (21-days trial). In my C# WPF application I have Properties.Settings.Default flag called IsFirstRunAfterInstallation. The type of this flag is bool. I need that this flag must be set to true during the installation process. After completion of the installation when the application is run first time, IsFirstRunAfterInstallation flag is checked as the following:
if (My_assembly_name.Properties.Settings.Default.IsFirstRunAfterInstallation)
{
    // do some actions here that must be done when application runs first time after its installation.
    . . . . . . . . . . . . . . .
    My_assembly_name.Properties.Settings.Default.IsFirstRunAfterInstallation = false;
    My_assembly_name.Properties.Settings.Default.Save();
}

And if IsFirstRunAfterInstallation flag is true, some C# code that is needed to perform when the application runs first time will be executed (as you can see above). So I need that IsFirstRunAfterInstallation flag is set to true like the folowing:
 My_assembly_name.Properties.Settings.Default.IsFirstRunAfterInstallation = true;
 My_assembly_name.Properties.Settings.Default.Save();

during each installation of my application on customer computer and is checked after the installation when the application runs first time. So I have the followin question: How to execute application code during the application installation using InstallShield 2016 Premier Edition (21-days trial)?

A: If the you need IsFirstRunAfterInstallation true (by default) for every version of your application then I do not think you need to do anything with installshield.
1- Set the IsFirstRunAfterInstallation default value true (in application properties).
2- Change the application version number for every release (from application properties OR directly in AssemblyInfo.cs class).
It will be always true on application first run/launch after installation because for application every new version, a separate directory is created in %AppData%\Local\\\\ and settings are copied/saved to user.config.
For above approach do you do not need to do anything custom/additional since application maintain version specific settings it self, however there are alternatives you may use:
1- Create a separate exe (a console application) or a dll and use it as custom action. OR
2- Launch your application from installshield and Pass a commandline parameter something /IsFirstLaunch:True
The parameters passed from installshield custom action can be received in application main:
private static void Main()
{
string[] args = Environment.GetCommandLineArgs();
//Process args here
}
    OR
private static void Main(string [] args)
{
//Process args here.
}


text:
Q: How to solve $\sum_{i=1}^{n} \sin(x_i - \mu) = 0$ for $\mu$? (Maximum likelihood estimation) The distribution is defined as:
$f(x; k, \mu) = exp(k\cos(x-\mu))$ (I have removed the term before it because it will be $0$ when we take the derivative of the log). We must find the MLE of $\mu$

My work so far:

*

*$\prod\limits_{i=1}^n exp(k\cos(x_i - \mu)) = exp(k\cos(x_1 - \mu)k\cos(x_2 - \mu)...k\cos(x_n - \mu)) = \exp(k\sum_{i=1}^{n} \cos(x_i - \mu))$

*taking log: $=k\sum_{i=1}^{n} \cos(x_i - \mu)$

*taking derivative wrt $\mu$: $=k\sum_{i=1}^{n} \sin(x_i - \mu)$

*setting to $0$: --> $\sum_{i=1}^{n} \sin(x_i - \mu) = 0$

I have no idea how to proceed from here. Is there anything I am missing or any calculation errors?

A: I guess using the last point of your question, you can use the definition of $\sin(A - B) = \sin(A) \cos (B) - \cos(A) \sin(B)$. Thus,
$$ \sum_i \sin(x_i - \mu) = \sum_i [\sin(x_i) \cos(\mu) - \cos(x_i)\sin(\mu)] = 0$$
now, after some trivial algebra you should get (if and only if $\mu \neq 0$ and $\sum_i \cos(x_i) \neq 0$)
$$\hat{\mu} = \tan^{-1}\left( \frac{\sum_{i=1}^n \sin (x_i)}{\sum_{i=1}^n \cos (x_i)} \right)$$ which you can now easily compute for any $x_i$'s.


text:
Q: How do I automate the conversion of a PHP array from one format to another, in VS Code? I have this array of countries with their dial codes:
$dial_codes = [
    'AF'=>array('name'=>'AFGHANISTAN','code'=>'93'),
    'AD'=>array('name'=>'ANDORRA','code'=>'376'),
    // more items
];

I want/need to turn the above array into this (which is more similar to Laravel Seeder format):
$dial_codes = [
    ['code' => 'AF', 'dialcode' => '93'],
    ['code' => 'AD', 'dialcode' => '376'],
    // more items
];

Question
Instead of doing this by hand, how do I automate it, in Visual studio code?

A: use REGEX when you need to restructure data from one to another.
I don't know about Visual Studio, but most IDE or Notepads(i.e Notepad++) allow you to search and replace, including applying regex.
Since the structure of your data is the same you can write something very simple to help you. Now, I am not a regex expert (just know basics so I can use it to help my daily routine) so below is very crude but will do what you are looking for and will give you an idea.

*

*Go to Search and Replace and enable use regex option.

Find:
'([A-Z]+)'=>array\('name'=>'([A-Z]+)','code'=>'([0-9]+)'\),

Replace with:
['code' => '$1', 'dialcode' => '$3'],

What happening here is we have 3 (groups), the other bit is a structure with some escaped characters as regex is sensitive for many symbols as they have a function.
Anyway, from that 3 groups we need only 2, and to get their content, in your replace field you add $1, $2 and $3 where you need the content of a group to be. The number after $ sign represents the order of a group.


text:
Q: Updating rows with same id and name in oracle database
i have a large data inside a table two employees have same name and same id in accident so i want to update one of the two employee so it becomes hard to me do you have any answer or solution
when i write this it updates the two rows
update EMPLOYEE
set id = 2 where Name='ahmed' and id=1

A: you can use ROWNUM
update EMPLOYEE
set id = 2 where Name='ahmed' and id=1 and ROWNUM = 1


text:
Q: find the annual percentage interest rate - ode I have deposited $1000$ dollars in my account such that the interest rate is continuously compounded.
In 15 years I have $15,000$ dollars.
I have to find the annual percentage interest rate.
My try :
The appropriate ode is $y'(x)=a(x)y(x)$  when $a(x)$  is the continuously compounded interest rate.
The solution of this ode is $y(x)=e^{\int_{x_0}^{x}a(x)}$.
The initial value of this problem : $y(0)=1000,y(15)=15,000.$
Then , $y(0)=e^{\int_{x_0}^{x}a(0)}=1000,y(15)=e^{\int_{x_0}^{x}a(15)}=15,000.$
How to find the annual percentage interest rate.
Thanks !

A:
The appropriate ode is $y'(x)=a(x)y(x)$  when $a(x)$  is the
continuously compounded interest rate.

We have to assume that $a(x)$ is constant $r$. Then the differential equation becomes
$$\frac1{y}\cdot y^{'}=r$$
$$\frac1{y}\cdot \frac{dy}{dx}=r$$
$$\frac1{y} \, dy=r \, dx$$
Integrating both sides
$$\int \frac1{y} \, dy= \int r \, dx$$
$$\ln(y)=r \cdot x +c$$
$$y=e^{rx+c}=C\cdot e^{rx}$$
With $y(0)=1000$ we obtain $C=1000$. Thus the equation is $15000=1000\cdot  e^{r\cdot 15}$. It remains to solve the equation for $r$, the continuous interest rate.


text:
Q: Generic Class object reference declaration when using getSuperclass() method Suppose there are two classes:
Circle extends Shape
The Class object of Circle can be accessed using:
Class<Circle> circleClass = Circle.class;
However, there is a compile error when getting the Class object of Shape in this way:
Class<Shape> shapeClass = circleClass.getSuperclass();
I do not understand why the compiler does not allow this declaration. Since Java only allows each class to have only one base class and the compiler knows what that base class (ie, Shape) is at compile time.


text:
Q: Are rationally connected varieties uniruled? A uniruled variety is the one which admits a dominant map from $X \times \mathbb P^1$.  I think it is true that uniruled varieties are rationally connected.  Is the converse true?  What about low dimensional cases, i.e. surfaces and threefolds?

A: Yes, rationally connected varieties are uniruled (a fact which follows essentially by definition).
In characteristic zero, one can think about this also by exploiting the following  characterization of uniruled and rationally connected varieties, that  can be found in Debarre's book Higher dimensional algebraic geometry, Chapter 4.
Let $X$ be a smooth projective variety of dimension $d$, defined over a field $\mathbb{K}$ of characteristic zero.
Recall that a rational curve $f \colon \mathbb{P}^1 \to X$ is called $r$-free if $f^*T_X \otimes \mathscr{O}_{\mathbb{P}^1}(-r)$ is generated by its global sections. By Grothendieck' s Theorem any vector bundle over $\mathbb{P}^1$ splits as a direct sum of line bundles, so $r$-free means $$f^*T_X = \mathscr{O}_{\mathbb{P}^1}(a_1) \oplus \ldots \oplus \mathscr{O}_{\mathbb{P}^1}(a_d),$$
with $a_i \geq r$ for every $i$. Now one has the following

Proposition. Assume $\textrm{char}(\mathbb{K})=0$. Then $X$ is uniruled if and only through a general point $x \in X$ there is a $0$-free rational curve.  Moreover $X$ is rationally connected if and only if through a general point $x \in X$ there is a $1$-free rational curve.

Remark. The condition $\textrm{char}(\mathbb{K})=0$ is an essential one. For instance, if $\textrm{char}(\mathbb{K})=p>0$ then the Fermat hypersurface of degree $p^r+1$ in $\mathbb{P}^N$, with $N \geq 4$ and $r \geq 1$, is uniruled by lines, none of which are free. Moreover, if $p^r >N$ any such a hypersurface has ample canonical class, then it contains no free rational curves at all.

A: Let $k$ be an algebraically closed uncountable field of characteristic zero. If $X$ is rationally connected then through two general points of $X$ there is a rational curve. In particular there is a rational curve through a general point of $X$. This means that the evaluation map
$$ev:\mathbb{P}^1\times Mor(\mathbb{P}^1,X)\rightarrow X$$
is dominant. Since $Mor(\mathbb{P}^1,X)$ has at most countably many components and $X$ is irreducible, there exists a component $Y$ of $Mor(\mathbb{P}^1,X)$ such that
$$ev:\mathbb{P}^1\times Y\rightarrow X$$
is dominant. Therefore $X$ is uniruled.


text:
Q: Renaming / moving files using File System Access API (javascript) I've been following this article to allow users to (semi) automatically save a client side generated XML file to a specific local folder. A third party program is watching this folder and will process its contents and output content in another file.
Problem is that it takes about 250 ms from the file is created until the content is actually written to the file using the close() method.
Sometimes the third party program will detect the file has been created and try to read its contents before its written. The program does not support adding a delay before trying to read the file content.
I've looked into writing the file to a temporary location and moving it once its closed, but this does not seem to be possible with this API. The same goes for renaming the file.
Creating / downloading the file using a normal dialog would probably work, but this requires manual steps that can be avoided using the file system access API.
Another solution would be to install a local program that can move the file from a temporary folder to the program watch folder when its closed, but I would rather avoid having to install software on the client.
Is there any other way to avoid this issue?
Thanks

A: There is now a way to rename and move files (currently implemented in Chrome behind the experimental web platform features flag):
// Get references to a file and a directory.
const [file] = await showOpenFilePicker();
const directory = await showDirectoryPicker();

// Rename the file.
await file.move('new_name');
// Move the file to a new directory.
await file.move(directory);
// Move the file to a new directory and rename it.
await file.move(directory, 'newer_name');

You can follow the spec work by subscribing to this PR.
Note that, confusingly, unflagged Chrome does have the .move() method on all file handles (not just OPFS ones), but using it throws a "User aborted a request" error.