问:
java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called
I want to display vertical list in RecyclerView. Each list row contains more than one YoutubeThumbnailView. To initialize I make a separate class that take parameter as reference of YoutubethumbnailView and video key. It gives Exception.

Here is my Recycler Adapter code

```<code>public class DashBoardRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 1;
private static final int TYPE_ITEM = 2;
ThumbnailImageView thumbnailImageView;

private ArrayList<VideoDetailsModel> nonCateList;
private Activity activity;
private ArrayList<ArrayList<DashBoardModel>> mainContent;

public DashBoardRecyclerAdapter(Activity activity,ArrayList<VideoDetailsModel> nonCateList,ArrayList<ArrayList<DashBoardModel>> mainContent) {
    this.activity = activity;
    this.nonCateList = nonCateList;
    this.mainContent = mainContent;
}
public class DashViewHolder extends RecyclerView.ViewHolder{
    private TextView suCategoryName;
    private TextView more;
    private TextView videoTitle;
    private TextView videoTitle2;
    private TextView videoDescription;
    private TextView videoDescription2;
    private YouTubeThumbnailView youTubeThumbnailViewOne;
    private YouTubeThumbnailView getYouTubeThumbnailViewTwo;

    public DashViewHolder(View itemView) {
        super(itemView);
        suCategoryName = (TextView)itemView.findViewById(R.id.dash_subcate_title);
        more = (TextView)itemView.findViewById(R.id.dash_more);
        videoTitle = (TextView)itemView.findViewById(R.id.dash_video_title);
        videoTitle2 = (TextView)itemView.findViewById(R.id.dash_video_title2);
        getYouTubeThumbnailViewTwo = (YouTubeThumbnailView)itemView.findViewById(R.id.dash_thumbnail_two);
        youTubeThumbnailViewOne = (YouTubeThumbnailView)itemView.findViewById(R.id.dash_thumbnail_one);
    }
}
public class HeaderViewHolder extends RecyclerView.ViewHolder{
    private TextView single_image_title,double_image_title,double_image_title2,more_item_title;
    YouTubeThumbnailView singleView,doubleView1,doubleView2,thirdView;
    public HeaderViewHolder(View itemView) {
        super(itemView);
        single_image_title = (TextView)itemView.findViewById(R.id.single_video_title);
        double_image_title = (TextView)itemView.findViewById(R.id.two_video_title);
        double_image_title2  = (TextView)itemView.findViewById(R.id.two_video_title2);
        more_item_title = (TextView)itemView.findViewById(R.id.more_video_title);
        singleView = (YouTubeThumbnailView)itemView.findViewById(R.id.single_video_dash_thumbnail);
        doubleView1 = (YouTubeThumbnailView)itemView.findViewById(R.id.two_video_thumbnail_one);
        doubleView2 = (YouTubeThumbnailView)itemView.findViewById(R.id.two_video_thumbnail_two);
        thirdView = (YouTubeThumbnailView)itemView.findViewById(R.id.third_thumbnail);

    }
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

    if(holder instanceof HeaderViewHolder){
        HeaderViewHolder headerView = (HeaderViewHolder)holder;

    }else {
        DashViewHolder holder1 = (DashViewHolder) holder;
        final ArrayList<DashBoardModel> content = mainContent.get(position-1);
        holder1.suCategoryName.setText(content.get(position-1).getSubCategoryName());
        holder1.videoTitle.setText(content.get(position-1).getVideoDetailsModels().get(0).getVideoTitle());
        // holder1.videoDescription.setText(dashBoardModels.get(position).getVideoDetailsModels().get(position).getDescription());
        holder1.videoTitle2.setText(content.get(position-1).getVideoDetailsModels().get(1).getVideoTitle());
        // holder1.videoDescription2.setText(dashBoardModels.get(position).getVideoDetailsModels().get(position+1).getDescription());
        thumbnailImageView = new ThumbnailImageView(holder1.youTubeThumbnailViewOne,content.get(position-1).getVideoDetailsModels().get(0).getVideoId());
        thumbnailImageView = new ThumbnailImageView(holder1.youTubeThumbnailViewOne,content.get(position-1).getVideoDetailsModels().get(1).getVideoId());
    }

}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if(viewType == TYPE_HEADER){
        if(nonCateList.size()==1){
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_video_layout,parent,false);
        return new HeaderViewHolder(v);
        }else if(nonCateList.size()==2){
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.two_video_layout,parent,false);
            return new HeaderViewHolder(v);
        }
        else if(nonCateList.size()>2){
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.one_video_with_more,parent,false);
            return new HeaderViewHolder(v);

        }
    }else if(viewType == TYPE_ITEM) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.dash_board, parent, false);
        return new DashViewHolder(v);
    }
    return null;
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
}

@Override
public int getItemCount()
{
    return mainContent.size()+1;
}
private boolean isPositionHeader (int position) {
    return position == 0;
}

    @Override
public int getItemViewType(int position) {
        if(isPositionHeader (position)) {
            return TYPE_HEADER;
        }
        return TYPE_ITEM;

    }
</code>```

}

Here is my ThumbnailImageView.java class

```<code>public class ThumbnailImageView {
private YouTubeThumbnailView youTubeThumbnailView;
String videoKey;

public ThumbnailImageView(YouTubeThumbnailView youTubeThumbnailView, String videoKey) {
    this.youTubeThumbnailView = youTubeThumbnailView;
    this.videoKey = videoKey;
    initializeThumbNail();
}

private void initializeThumbNail() {
    final YouTubeThumbnailLoader.OnThumbnailLoadedListener onThumbnailLoadedListener = new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
        @Override
        public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {

        }

        @Override
        public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
            youTubeThumbnailView.setVisibility(View.VISIBLE);
            //holder.relativeLayoutOverYouTubeThumbnailView.setVisibility(View.VISIBLE);
        }
    };

    youTubeThumbnailView.initialize(new Constant().YOU_TUBE_API_KEY, new YouTubeThumbnailView.OnInitializedListener() {
        @Override
        public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader youTubeThumbnailLoader) {

            youTubeThumbnailLoader.setVideo(videoKey);
            youTubeThumbnailLoader.setOnThumbnailLoadedListener(onThumbnailLoadedListener);
        }

        @Override
        public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
            //write something for failure
        }
    });
}
</code>```

here is my logcat message

```<code>FATAL EXCEPTION: main
  Process: com.dp.videostore, PID: 2200
  java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
   at com.google.android.youtube.player.internal.r.i(Unknown Source)
  at com.google.android.youtube.player.internal.o.k(Unknown Source)
  at com.google.android.youtube.player.internal.o.a(Unknown Source)
at com.google.android.youtube.player.internal.p.<init>(Unknown Source)
at com.google.android.youtube.player.internal.ac.a(Unknown Source)
at com.google.android.youtube.player.YouTubeThumbnailView$a.a(Unknown Source)
at com.google.android.youtube.player.internal.r.g(Unknown Source)
at com.google.android.youtube.player.internal.r$c.a(Unknown Source)
at com.google.android.youtube.player.internal.r$b.a(Unknown Source)
at com.google.android.youtube.player.internal.r$a.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
  at android.os.Looper.loop(Looper.java:148)
 at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
I have the same problem
"YouTubeThumbnailView Not connected. Call connect() and wait for onConnected() to be called"
in RecyclerView.Adapter by scrolling quickly and there are 3 youtube thumbnails in the recylerView.

In the adapter I put like this:
a field: private boolean readyForLoadingYoutubeThumbnail = true;
and at onBindViewHolder

```<code>/**
 * https://issuetracker.google.com/issues/35176819#c6
 * https://github.com/youtube/yt-android-player/issues/2#issuecomment-58913900
 * YouTubeThumbnailView Not connected. Call connect() and wait for onConnected() to be called
 */
Log.d(TAG, "readyForLoadingYoutubeThumbnail" + readyForLoadingYoutubeThumbnail);
final YouTubeInitializationResult result = YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(activity);
if (readyForLoadingYoutubeThumbnail) {
    Log.d(TAG, "initializing for youtube thumbnail view...");
    readyForLoadingYoutubeThumbnail = false;
    holder.youTubeThumbnailView.initialize("aaaaaaaaa", new YouTubeThumbnailView.OnInitializedListener() {
        @Override
        public void onInitializationSuccess(final YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {

            youTubeThumbnailLoader.setVideo(videoId);
            youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener(){

                @Override
                public void onThumbnailLoaded(YouTubeThumbnailView childYouTubeThumbnailView, String s) {
                    childYouTubeThumbnailView.setVisibility(View.VISIBLE);
                    holder.relativeLayoutOverYouTubeThumbnailView.setVisibility(View.VISIBLE);
                    youTubeThumbnailLoader.release(); // spy ga memory lick
                }

                @Override
                public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
                    youTubeThumbnailLoader.release(); // spy ga memory lick
                }
            });
            youTubeThumbnailView.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);

            readyForLoadingYoutubeThumbnail = true;
        }

        @Override
        public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
            //do nohing.. ada error, tambahin method ini jalan, error-nya lupa...
            readyForLoadingYoutubeThumbnail = true;
        }
    });
}
</code>```

It is works for me...

Body:
I want to display vertical list in RecyclerView. Each list row contains more than one YoutubeThumbnailView. To initialize I make a separate class that take parameter as reference of YoutubethumbnailView and video key. It gives Exception.

Here is my Recycler Adapter code

public class DashBoardRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 1;
private static final int TYPE_ITEM = 2;
ThumbnailImageView thumbnailImageView;

private ArrayList<VideoDetailsModel> nonCateList;
private Activity activity;
private ArrayList<ArrayList<DashBoardModel>> mainContent;

public DashBoardRecyclerAdapter(Activity activity,ArrayList<VideoDetailsModel> nonCateList,ArrayList<ArrayList<DashBoardModel>> mainContent) {
    this.activity = activity;
    this.nonCateList = nonCateList;
    this.mainContent = mainContent;
}
public class DashViewHolder extends RecyclerView.ViewHolder{
    private TextView suCategoryName;
    private TextView more;
    private TextView videoTitle;
    private TextView videoTitle2;
    private TextView videoDescription;
    private TextView videoDescription2;
    private YouTubeThumbnailView youTubeThumbnailViewOne;
    private YouTubeThumbnailView getYouTubeThumbnailViewTwo;

    public DashViewHolder(View itemView) {
        super(itemView);
        suCategoryName = (TextView)itemView.findViewById(R.id.dash_subcate_title);
        more = (TextView)itemView.findViewById(R.id.dash_more);
        videoTitle = (TextView)itemView.findViewById(R.id.dash_video_title);
        videoTitle2 = (TextView)itemView.findViewById(R.id.dash_video_title2);
        getYouTubeThumbnailViewTwo = (YouTubeThumbnailView)itemView.findViewById(R.id.dash_thumbnail_two);
        youTubeThumbnailViewOne = (YouTubeThumbnailView)itemView.findViewById(R.id.dash_thumbnail_one);
    }
}
public class HeaderViewHolder extends RecyclerView.ViewHolder{
    private TextView single_image_title,double_image_title,double_image_title2,more_item_title;
    YouTubeThumbnailView singleView,doubleView1,doubleView2,thirdView;
    public HeaderViewHolder(View itemView) {
        super(itemView);
        single_image_title = (TextView)itemView.findViewById(R.id.single_video_title);
        double_image_title = (TextView)itemView.findViewById(R.id.two_video_title);
        double_image_title2  = (TextView)itemView.findViewById(R.id.two_video_title2);
        more_item_title = (TextView)itemView.findViewById(R.id.more_video_title);
        singleView = (YouTubeThumbnailView)itemView.findViewById(R.id.single_video_dash_thumbnail);
        doubleView1 = (YouTubeThumbnailView)itemView.findViewById(R.id.two_video_thumbnail_one);
        doubleView2 = (YouTubeThumbnailView)itemView.findViewById(R.id.two_video_thumbnail_two);
        thirdView = (YouTubeThumbnailView)itemView.findViewById(R.id.third_thumbnail);

    }
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

    if(holder instanceof HeaderViewHolder){
        HeaderViewHolder headerView = (HeaderViewHolder)holder;

    }else {
        DashViewHolder holder1 = (DashViewHolder) holder;
        final ArrayList<DashBoardModel> content = mainContent.get(position-1);
        holder1.suCategoryName.setText(content.get(position-1).getSubCategoryName());
        holder1.videoTitle.setText(content.get(position-1).getVideoDetailsModels().get(0).getVideoTitle());
        // holder1.videoDescription.setText(dashBoardModels.get(position).getVideoDetailsModels().get(position).getDescription());
        holder1.videoTitle2.setText(content.get(position-1).getVideoDetailsModels().get(1).getVideoTitle());
        // holder1.videoDescription2.setText(dashBoardModels.get(position).getVideoDetailsModels().get(position+1).getDescription());
        thumbnailImageView = new ThumbnailImageView(holder1.youTubeThumbnailViewOne,content.get(position-1).getVideoDetailsModels().get(0).getVideoId());
        thumbnailImageView = new ThumbnailImageView(holder1.youTubeThumbnailViewOne,content.get(position-1).getVideoDetailsModels().get(1).getVideoId());
    }

}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if(viewType == TYPE_HEADER){
        if(nonCateList.size()==1){
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_video_layout,parent,false);
        return new HeaderViewHolder(v);
        }else if(nonCateList.size()==2){
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.two_video_layout,parent,false);
            return new HeaderViewHolder(v);
        }
        else if(nonCateList.size()>2){
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.one_video_with_more,parent,false);
            return new HeaderViewHolder(v);

        }
    }else if(viewType == TYPE_ITEM) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.dash_board, parent, false);
        return new DashViewHolder(v);
    }
    return null;
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
}

@Override
public int getItemCount()
{
    return mainContent.size()+1;
}
private boolean isPositionHeader (int position) {
    return position == 0;
}

    @Override
public int getItemViewType(int position) {
        if(isPositionHeader (position)) {
            return TYPE_HEADER;
        }
        return TYPE_ITEM;

    }

}

Here is my ThumbnailImageView.java class

public class ThumbnailImageView {
private YouTubeThumbnailView youTubeThumbnailView;
String videoKey;

public ThumbnailImageView(YouTubeThumbnailView youTubeThumbnailView, String videoKey) {
    this.youTubeThumbnailView = youTubeThumbnailView;
    this.videoKey = videoKey;
    initializeThumbNail();
}

private void initializeThumbNail() {
    final YouTubeThumbnailLoader.OnThumbnailLoadedListener onThumbnailLoadedListener = new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
        @Override
        public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {

        }

        @Override
        public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
            youTubeThumbnailView.setVisibility(View.VISIBLE);
            //holder.relativeLayoutOverYouTubeThumbnailView.setVisibility(View.VISIBLE);
        }
    };

    youTubeThumbnailView.initialize(new Constant().YOU_TUBE_API_KEY, new YouTubeThumbnailView.OnInitializedListener() {
        @Override
        public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader youTubeThumbnailLoader) {

            youTubeThumbnailLoader.setVideo(videoKey);
            youTubeThumbnailLoader.setOnThumbnailLoadedListener(onThumbnailLoadedListener);
        }

        @Override
        public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
            //write something for failure
        }
    });
}

here is my logcat message

FATAL EXCEPTION: main
  Process: com.dp.videostore, PID: 2200
  java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
   at com.google.android.youtube.player.internal.r.i(Unknown Source)
  at com.google.android.youtube.player.internal.o.k(Unknown Source)
  at com.google.android.youtube.player.internal.o.a(Unknown Source)
at com.google.android.youtube.player.internal.p.<init>(Unknown Source)
at com.google.android.youtube.player.internal.ac.a(Unknown Source)
at com.google.android.youtube.player.YouTubeThumbnailView$a.a(Unknown Source)
at com.google.android.youtube.player.internal.r.g(Unknown Source)
at com.google.android.youtube.player.internal.r$c.a(Unknown Source)
at com.google.android.youtube.player.internal.r$b.a(Unknown Source)
at com.google.android.youtube.player.internal.r$a.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
  at android.os.Looper.loop(Looper.java:148)
 at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
I have the same problem
"YouTubeThumbnailView Not connected. Call connect() and wait for onConnected() to be called"
in RecyclerView.Adapter by scrolling quickly and there are 3 youtube thumbnails in the recylerView.

In the adapter I put like this:
a field: private boolean readyForLoadingYoutubeThumbnail = true;
and at onBindViewHolder

/**
 * https://issuetracker.google.com/issues/35176819#c6
 * https://github.com/youtube/yt-android-player/issues/2#issuecomment-58913900
 * YouTubeThumbnailView Not connected. Call connect() and wait for onConnected() to be called
 */
Log.d(TAG, "readyForLoadingYoutubeThumbnail" + readyForLoadingYoutubeThumbnail);
final YouTubeInitializationResult result = YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(activity);
if (readyForLoadingYoutubeThumbnail) {
    Log.d(TAG, "initializing for youtube thumbnail view...");
    readyForLoadingYoutubeThumbnail = false;
    holder.youTubeThumbnailView.initialize("aaaaaaaaa", new YouTubeThumbnailView.OnInitializedListener() {
        @Override
        public void onInitializationSuccess(final YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {

            youTubeThumbnailLoader.setVideo(videoId);
            youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener(){

                @Override
                public void onThumbnailLoaded(YouTubeThumbnailView childYouTubeThumbnailView, String s) {
                    childYouTubeThumbnailView.setVisibility(View.VISIBLE);
                    holder.relativeLayoutOverYouTubeThumbnailView.setVisibility(View.VISIBLE);
                    youTubeThumbnailLoader.release(); // spy ga memory lick
                }

                @Override
                public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
                    youTubeThumbnailLoader.release(); // spy ga memory lick
                }
            });
            youTubeThumbnailView.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);

            readyForLoadingYoutubeThumbnail = true;
        }

        @Override
        public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
            //do nohing.. ada error, tambahin method ini jalan, error-nya lupa...
            readyForLoadingYoutubeThumbnail = true;
        }
    });
}

It is works for me...


来源: stackexchange

问:
freemarker error: expected hash. evaluated instead to freemarker.template.SimpleScalar
My template looks like this:

```<code>  <#assign senti = "${scmr.results[model]}">
    <#if senti??>
      <td>${senti} ---- ${senti.sentimentType}</td>
      <td>${senti.score?html}</td>
    </#if>
</code>```

The output looks like this:

```<code>POSITIVE(1.0/1) ---- Expected hash. senti evaluated instead to freemarker.template.SimpleScalar on line 5, column 27 in com/addthis/sentiment/sentidemo.ftl.
</code>```

the output text before "----" indicates that senti is, indeed, a valid java Sentiment object. Methods getSentimentType and getScore are present and working.

So, why am I getting the error?

答:
had the same error when using swagger generated models with ninjaframework , fixed by adding below class in conf package</p>

```<code>package conf;

import com.google.inject.Inject;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.MethodAppearanceFineTuner;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapperBuilder;
import ninja.NinjaDefault;
import ninja.template.TemplateEngineFreemarker;

/**
 * Created by varya on 07/12/17.
 */
public class Ninja extends NinjaDefault {
    @Inject
    protected TemplateEngineFreemarker templateEngineFreemarker;

    @Override
    public void onFrameworkStart() {
        super.onFrameworkStart();

        Configuration freemarkerConfiguration = templateEngineFreemarker.getConfiguration();
        DefaultObjectWrapperBuilder owb = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_23);
        owb.setMethodAppearanceFineTuner(new MethodAppearanceFineTuner() {
            @Override
            public void process(BeansWrapper.MethodAppearanceDecisionInput in, BeansWrapper.MethodAppearanceDecision out) {
                out.setMethodShadowsProperty(false);
            }
        });

        freemarkerConfiguration.setObjectWrapper(owb.build());

    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My template looks like this:

  <#assign senti = "${scmr.results[model]}">
    <#if senti??>
      ${senti} ---- ${senti.sentimentType}
      ${senti.score?html}
    </#if>

The output looks like this:

POSITIVE(1.0/1) ---- Expected hash. senti evaluated instead to freemarker.template.SimpleScalar on line 5, column 27 in com/addthis/sentiment/sentidemo.ftl.

the output text before "----" indicates that senti is, indeed, a valid java Sentiment object. Methods getSentimentType and getScore are present and working.

So, why am I getting the error?

Body:
had the same error when using swagger generated models with ninjaframework , fixed by adding below class in conf package

package conf;

import com.google.inject.Inject;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.MethodAppearanceFineTuner;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapperBuilder;
import ninja.NinjaDefault;
import ninja.template.TemplateEngineFreemarker;

/**
 * Created by varya on 07/12/17.
 */
public class Ninja extends NinjaDefault {
    @Inject
    protected TemplateEngineFreemarker templateEngineFreemarker;

    @Override
    public void onFrameworkStart() {
        super.onFrameworkStart();

        Configuration freemarkerConfiguration = templateEngineFreemarker.getConfiguration();
        DefaultObjectWrapperBuilder owb = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_23);
        owb.setMethodAppearanceFineTuner(new MethodAppearanceFineTuner() {
            @Override
            public void process(BeansWrapper.MethodAppearanceDecisionInput in, BeansWrapper.MethodAppearanceDecision out) {
                out.setMethodShadowsProperty(false);
            }
        });

        freemarkerConfiguration.setObjectWrapper(owb.build());

    }

}


问:
Bizarre behavior in gdb
I'm experiencing a very strange bug in my code.

I use a variable m_requestedStructures in my program, and the debugger is accessing the wrong address when inspecting it. For example, I have in the code:

```<code>qDebug() << "requested: " << m_requestedStructures << " " << &m_requestedStructures
</code>```

and I set a breakpoint here. When the breakpoint is reached, I compare the printed value and address of m_requestedStructures with those that gdb is accessing:

```<code>requested:  0   0xfce640
Breakpoint 1
157         qDebug() << "requested: " << m_requestedStructures << " " << &m_requestedStructures;
(gdb) p m_requestedStructures
$5 = -1167616
(gdb) p &m_requestedStructures
$6 = (int *) 0xfce644
(gdb)
</code>```

As can be seen, both the value and the address differ.

Another symptom I'm seeing is that I had a function, QueueManager::checkPopulation_() which I removed quite a while ago, but gdb still tries to tab-complete it, and if I set a breakpoint on it, it will break at the point where the function used to be.

It appears to me that the symbols aren't read correctly. I've tried rebuilding from a clean directory, but the problem persists. Does anyone have any idea what might be causing this or how to fix it?

Thanks in advance!

Edit: I just tried setting a breakpoint on a new function I've added. The function QueueManager::run() appears in gdb's tab complete, but when I try to set the breakpoint, I get

```<code>the class GlobalSearch::QueueManager does not have any method named run
</code>```

Also, inspecting other variables, both locally scoped and members of QueueManager, seems to work fine.

Here is the compiler/linker output. The file containing the class is queuemanager.cpp, which is part of a static library libglobalsearch.a, which is used in a dynamic library xtalopt.so:

```<code>$ make VERBOSE=1 xtalopt
/usr/bin/cmake -H/git/xtalopt-public -B/git/xtalopt-public/build --check-build-system CMakeFiles/Makefile.cmake 0
make -f CMakeFiles/Makefile2 xtalopt
make[1]: Entering directory `/git/xtalopt-public/build'
/usr/bin/cmake -H/git/xtalopt-public -B/git/xtalopt-public/build --check-build-system CMakeFiles/Makefile.cmake 0
/usr/bin/cmake -E cmake_progress_start /git/xtalopt-public/build/CMakeFiles 63
make -f CMakeFiles/Makefile2 src/xtalopt/CMakeFiles/xtalopt.dir/all
make[2]: Entering directory `/git/xtalopt-public/build'
make -f src/spglib/CMakeFiles/spglib.dir/build.make src/spglib/CMakeFiles/spglib.dir/depend
make[3]: Entering directory `/git/xtalopt-public/build'
cd /git/xtalopt-public/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /git/xtalopt-public /git/xtalopt-public/src/spglib /git/xtalopt-public/build /git/xtalopt-public/build/src/spglib /git/xtalopt-public/build/src/spglib/CMakeFiles/spglib.dir/DependInfo.cmake --color=
make[3]: Leaving directory `/git/xtalopt-public/build'
make -f src/spglib/CMakeFiles/spglib.dir/build.make src/spglib/CMakeFiles/spglib.dir/build
make[3]: Entering directory `/git/xtalopt-public/build'
make[3]: Nothing to be done for `src/spglib/CMakeFiles/spglib.dir/build'.
make[3]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles  18 19 20 21 22 23
[  9%] Built target spglib
make -f src/libssh/CMakeFiles/ssh_static.dir/build.make src/libssh/CMakeFiles/ssh_static.dir/depend
make[3]: Entering directory `/git/xtalopt-public/build'
cd /git/xtalopt-public/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /git/xtalopt-public /git/xtalopt-public/src/libssh /git/xtalopt-public/build /git/xtalopt-public/build/src/libssh /git/xtalopt-public/build/src/libssh/CMakeFiles/ssh_static.dir/DependInfo.cmake --color=
make[3]: Leaving directory `/git/xtalopt-public/build'
make -f src/libssh/CMakeFiles/ssh_static.dir/build.make src/libssh/CMakeFiles/ssh_static.dir/build
make[3]: Entering directory `/git/xtalopt-public/build'
make[3]: Nothing to be done for `src/libssh/CMakeFiles/ssh_static.dir/build'.
make[3]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles  26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
[ 33%] Built target ssh_static
make -f src/globalsearch/CMakeFiles/globalsearch.dir/build.make src/globalsearch/CMakeFiles/globalsearch.dir/depend
make[3]: Entering directory `/git/xtalopt-public/build'
cd /git/xtalopt-public/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /git/xtalopt-public /git/xtalopt-public/src/globalsearch /git/xtalopt-public/build /git/xtalopt-public/build/src/globalsearch /git/xtalopt-public/build/src/globalsearch/CMakeFiles/globalsearch.dir/DependInfo.cmake --color=
make[3]: Leaving directory `/git/xtalopt-public/build'
make -f src/globalsearch/CMakeFiles/globalsearch.dir/build.make src/globalsearch/CMakeFiles/globalsearch.dir/build
make[3]: Entering directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles
[ 33%] Building CXX object src/globalsearch/CMakeFiles/globalsearch.dir/queuemanager.cpp.o
cd /git/xtalopt-public/build/src/globalsearch && /usr/bin/c++   -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB -DQT_PLUGIN -DQT_SHARED -D_HAVE_EXECINFO_H_ -DQT_DEBUG -fPIC -g -I/usr/include/QtOpenGL -I/usr/include/QtGui -I/usr/include/QtCore -I/usr/include/eigen2 -I/git/xtalopt-public/build -I/usr/include/openbabel-2.0 -I/git/xtalopt-public/src   -o CMakeFiles/globalsearch.dir/queuemanager.cpp.o -c /git/xtalopt-public/src/globalsearch/queuemanager.cpp
Linking CXX static library libglobalsearch.a
cd /git/xtalopt-public/build/src/globalsearch && /usr/bin/cmake -P CMakeFiles/globalsearch.dir/cmake_clean_target.cmake
cd /git/xtalopt-public/build/src/globalsearch && /usr/bin/cmake -E cmake_link_script CMakeFiles/globalsearch.dir/link.txt --verbose=1
/usr/bin/ar cr libglobalsearch.a  CMakeFiles/globalsearch.dir/optbase.cpp.o CMakeFiles/globalsearch.dir/queuemanager.cpp.o CMakeFiles/globalsearch.dir/structure.cpp.o CMakeFiles/globalsearch.dir/tracker.cpp.o CMakeFiles/globalsearch.dir/optimizer.cpp.o CMakeFiles/globalsearch.dir/bt.cpp.o CMakeFiles/globalsearch.dir/sshconnection.cpp.o CMakeFiles/globalsearch.dir/sshmanager.cpp.o CMakeFiles/globalsearch.dir/random.cpp.o CMakeFiles/globalsearch.dir/ui/abstractdialog.cpp.o CMakeFiles/globalsearch.dir/ui/abstracttab.cpp.o CMakeFiles/globalsearch.dir/moc_optbase.cxx.o CMakeFiles/globalsearch.dir/moc_queuemanager.cxx.o CMakeFiles/globalsearch.dir/moc_structure.cxx.o CMakeFiles/globalsearch.dir/moc_tracker.cxx.o CMakeFiles/globalsearch.dir/moc_optimizer.cxx.o CMakeFiles/globalsearch.dir/moc_bt.cxx.o CMakeFiles/globalsearch.dir/moc_sshconnection.cxx.o CMakeFiles/globalsearch.dir/moc_sshmanager.cxx.o CMakeFiles/globalsearch.dir/moc_random.cxx.o CMakeFiles/globalsearch.dir/ui/moc_abstractdialog.cxx.o CMakeFiles/globalsearch.dir/ui/moc_abstracttab.cxx.o
/usr/bin/ranlib libglobalsearch.a
make[3]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles  1 2 3 4 5 6 7 8 9 10 11 12 13 14
[ 55%] Built target globalsearch
make -f src/xtalopt/CMakeFiles/xtalopt.dir/build.make src/xtalopt/CMakeFiles/xtalopt.dir/depend
make[3]: Entering directory `/git/xtalopt-public/build'
cd /git/xtalopt-public/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /git/xtalopt-public /git/xtalopt-public/src/xtalopt /git/xtalopt-public/build /git/xtalopt-public/build/src/xtalopt /git/xtalopt-public/build/src/xtalopt/CMakeFiles/xtalopt.dir/DependInfo.cmake --color=
make[3]: Leaving directory `/git/xtalopt-public/build'
make -f src/xtalopt/CMakeFiles/xtalopt.dir/build.make src/xtalopt/CMakeFiles/xtalopt.dir/build
make[3]: Entering directory `/git/xtalopt-public/build'
Linking CXX shared library xtalopt.so
cd /git/xtalopt-public/build/src/xtalopt && /usr/bin/cmake -E cmake_link_script CMakeFiles/xtalopt.dir/link.txt --verbose=1
/usr/bin/c++  -fPIC  -fPIC -g  -shared -Wl,-soname,xtalopt.so -o xtalopt.so CMakeFiles/xtalopt.dir/extension.cpp.o CMakeFiles/xtalopt.dir/xtalopt.cpp.o CMakeFiles/xtalopt.dir/genetic.cpp.o CMakeFiles/xtalopt.dir/structures/xtal.cpp.o CMakeFiles/xtalopt.dir/optimizers/xtaloptoptimizer.cpp.o CMakeFiles/xtalopt.dir/optimizers/vasp.cpp.o CMakeFiles/xtalopt.dir/optimizers/gulp.cpp.o CMakeFiles/xtalopt.dir/optimizers/pwscf.cpp.o CMakeFiles/xtalopt.dir/optimizers/castep.cpp.o CMakeFiles/xtalopt.dir/testing/xtalopttest.cpp.o CMakeFiles/xtalopt.dir/ui/dialog.cpp.o CMakeFiles/xtalopt.dir/ui/tab_init.cpp.o CMakeFiles/xtalopt.dir/ui/tab_edit.cpp.o CMakeFiles/xtalopt.dir/ui/tab_opt.cpp.o CMakeFiles/xtalopt.dir/ui/tab_sys.cpp.o CMakeFiles/xtalopt.dir/ui/tab_progress.cpp.o CMakeFiles/xtalopt.dir/ui/tab_plot.cpp.o CMakeFiles/xtalopt.dir/ui/tab_log.cpp.o CMakeFiles/xtalopt.dir/moc_extension.cxx.o CMakeFiles/xtalopt.dir/moc_xtalopt.cxx.o CMakeFiles/xtalopt.dir/moc_genetic.cxx.o CMakeFiles/xtalopt.dir/structures/moc_xtal.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_xtaloptoptimizer.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_vasp.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_gulp.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_pwscf.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_castep.cxx.o CMakeFiles/xtalopt.dir/testing/moc_xtalopttest.cxx.o CMakeFiles/xtalopt.dir/ui/moc_dialog.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_init.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_edit.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_opt.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_sys.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_progress.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_plot.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_log.cxx.o -lavogadro ../globalsearch/libglobalsearch.a ../spglib/libspglib.a -lQtOpenGL -lGLU -lGL -lSM -lICE -lX11 -lXext -lopenbabel -lQtGui -lQtCore ../libssh/libssh_static.a -lnsl -lresolv -lrt -lz -lssl -lcrypto
make[3]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles  45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
[100%] Built target xtalopt
make[2]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_start /git/xtalopt-public/build/CMakeFiles 0
make[1]: Leaving directory `/git/xtalopt-public/build'
</code>```

答:
Just FYI:

Grep has a -e switch, so you can handle multiple expressions at once.  E.g:

```<code>grep -v -e \* -e quit--- -e Syms\ Read -e \(gdb\) | awk '{print $4}' > libs
</code>```

nm has a -A switch (print filename).  E.g:

```<code>cat libs | xargs nm -A --demangle | grep checkPopulation
</code>```

ContentLicense: CC BY-SA 2.5

Title: Bizarre behavior in gdb

Body:
I'm experiencing a very strange bug in my code.

I use a variable m_requestedStructures in my program, and the debugger is accessing the wrong address when inspecting it. For example, I have in the code:

qDebug() << "requested: " << m_requestedStructures << " " << &m_requestedStructures

and I set a breakpoint here. When the breakpoint is reached, I compare the printed value and address of m_requestedStructures with those that gdb is accessing:

requested:  0   0xfce640
Breakpoint 1
157         qDebug() << "requested: " << m_requestedStructures << " " << &m_requestedStructures;
(gdb) p m_requestedStructures
$5 = -1167616
(gdb) p &m_requestedStructures
$6 = (int *) 0xfce644
(gdb)

As can be seen, both the value and the address differ.

Another symptom I'm seeing is that I had a function, QueueManager::checkPopulation_() which I removed quite a while ago, but gdb still tries to tab-complete it, and if I set a breakpoint on it, it will break at the point where the function used to be.

It appears to me that the symbols aren't read correctly. I've tried rebuilding from a clean directory, but the problem persists. Does anyone have any idea what might be causing this or how to fix it?

Thanks in advance!

Edit: I just tried setting a breakpoint on a new function I've added. The function QueueManager::run() appears in gdb's tab complete, but when I try to set the breakpoint, I get

the class GlobalSearch::QueueManager does not have any method named run

Also, inspecting other variables, both locally scoped and members of QueueManager, seems to work fine.

Here is the compiler/linker output. The file containing the class is queuemanager.cpp, which is part of a static library libglobalsearch.a, which is used in a dynamic library xtalopt.so:

$ make VERBOSE=1 xtalopt
/usr/bin/cmake -H/git/xtalopt-public -B/git/xtalopt-public/build --check-build-system CMakeFiles/Makefile.cmake 0
make -f CMakeFiles/Makefile2 xtalopt
make[1]: Entering directory `/git/xtalopt-public/build'
/usr/bin/cmake -H/git/xtalopt-public -B/git/xtalopt-public/build --check-build-system CMakeFiles/Makefile.cmake 0
/usr/bin/cmake -E cmake_progress_start /git/xtalopt-public/build/CMakeFiles 63
make -f CMakeFiles/Makefile2 src/xtalopt/CMakeFiles/xtalopt.dir/all
make[2]: Entering directory `/git/xtalopt-public/build'
make -f src/spglib/CMakeFiles/spglib.dir/build.make src/spglib/CMakeFiles/spglib.dir/depend
make[3]: Entering directory `/git/xtalopt-public/build'
cd /git/xtalopt-public/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /git/xtalopt-public /git/xtalopt-public/src/spglib /git/xtalopt-public/build /git/xtalopt-public/build/src/spglib /git/xtalopt-public/build/src/spglib/CMakeFiles/spglib.dir/DependInfo.cmake --color=
make[3]: Leaving directory `/git/xtalopt-public/build'
make -f src/spglib/CMakeFiles/spglib.dir/build.make src/spglib/CMakeFiles/spglib.dir/build
make[3]: Entering directory `/git/xtalopt-public/build'
make[3]: Nothing to be done for `src/spglib/CMakeFiles/spglib.dir/build'.
make[3]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles  18 19 20 21 22 23
[  9%] Built target spglib
make -f src/libssh/CMakeFiles/ssh_static.dir/build.make src/libssh/CMakeFiles/ssh_static.dir/depend
make[3]: Entering directory `/git/xtalopt-public/build'
cd /git/xtalopt-public/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /git/xtalopt-public /git/xtalopt-public/src/libssh /git/xtalopt-public/build /git/xtalopt-public/build/src/libssh /git/xtalopt-public/build/src/libssh/CMakeFiles/ssh_static.dir/DependInfo.cmake --color=
make[3]: Leaving directory `/git/xtalopt-public/build'
make -f src/libssh/CMakeFiles/ssh_static.dir/build.make src/libssh/CMakeFiles/ssh_static.dir/build
make[3]: Entering directory `/git/xtalopt-public/build'
make[3]: Nothing to be done for `src/libssh/CMakeFiles/ssh_static.dir/build'.
make[3]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles  26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
[ 33%] Built target ssh_static
make -f src/globalsearch/CMakeFiles/globalsearch.dir/build.make src/globalsearch/CMakeFiles/globalsearch.dir/depend
make[3]: Entering directory `/git/xtalopt-public/build'
cd /git/xtalopt-public/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /git/xtalopt-public /git/xtalopt-public/src/globalsearch /git/xtalopt-public/build /git/xtalopt-public/build/src/globalsearch /git/xtalopt-public/build/src/globalsearch/CMakeFiles/globalsearch.dir/DependInfo.cmake --color=
make[3]: Leaving directory `/git/xtalopt-public/build'
make -f src/globalsearch/CMakeFiles/globalsearch.dir/build.make src/globalsearch/CMakeFiles/globalsearch.dir/build
make[3]: Entering directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles
[ 33%] Building CXX object src/globalsearch/CMakeFiles/globalsearch.dir/queuemanager.cpp.o
cd /git/xtalopt-public/build/src/globalsearch && /usr/bin/c++   -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB -DQT_PLUGIN -DQT_SHARED -D_HAVE_EXECINFO_H_ -DQT_DEBUG -fPIC -g -I/usr/include/QtOpenGL -I/usr/include/QtGui -I/usr/include/QtCore -I/usr/include/eigen2 -I/git/xtalopt-public/build -I/usr/include/openbabel-2.0 -I/git/xtalopt-public/src   -o CMakeFiles/globalsearch.dir/queuemanager.cpp.o -c /git/xtalopt-public/src/globalsearch/queuemanager.cpp
Linking CXX static library libglobalsearch.a
cd /git/xtalopt-public/build/src/globalsearch && /usr/bin/cmake -P CMakeFiles/globalsearch.dir/cmake_clean_target.cmake
cd /git/xtalopt-public/build/src/globalsearch && /usr/bin/cmake -E cmake_link_script CMakeFiles/globalsearch.dir/link.txt --verbose=1
/usr/bin/ar cr libglobalsearch.a  CMakeFiles/globalsearch.dir/optbase.cpp.o CMakeFiles/globalsearch.dir/queuemanager.cpp.o CMakeFiles/globalsearch.dir/structure.cpp.o CMakeFiles/globalsearch.dir/tracker.cpp.o CMakeFiles/globalsearch.dir/optimizer.cpp.o CMakeFiles/globalsearch.dir/bt.cpp.o CMakeFiles/globalsearch.dir/sshconnection.cpp.o CMakeFiles/globalsearch.dir/sshmanager.cpp.o CMakeFiles/globalsearch.dir/random.cpp.o CMakeFiles/globalsearch.dir/ui/abstractdialog.cpp.o CMakeFiles/globalsearch.dir/ui/abstracttab.cpp.o CMakeFiles/globalsearch.dir/moc_optbase.cxx.o CMakeFiles/globalsearch.dir/moc_queuemanager.cxx.o CMakeFiles/globalsearch.dir/moc_structure.cxx.o CMakeFiles/globalsearch.dir/moc_tracker.cxx.o CMakeFiles/globalsearch.dir/moc_optimizer.cxx.o CMakeFiles/globalsearch.dir/moc_bt.cxx.o CMakeFiles/globalsearch.dir/moc_sshconnection.cxx.o CMakeFiles/globalsearch.dir/moc_sshmanager.cxx.o CMakeFiles/globalsearch.dir/moc_random.cxx.o CMakeFiles/globalsearch.dir/ui/moc_abstractdialog.cxx.o CMakeFiles/globalsearch.dir/ui/moc_abstracttab.cxx.o
/usr/bin/ranlib libglobalsearch.a
make[3]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles  1 2 3 4 5 6 7 8 9 10 11 12 13 14
[ 55%] Built target globalsearch
make -f src/xtalopt/CMakeFiles/xtalopt.dir/build.make src/xtalopt/CMakeFiles/xtalopt.dir/depend
make[3]: Entering directory `/git/xtalopt-public/build'
cd /git/xtalopt-public/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /git/xtalopt-public /git/xtalopt-public/src/xtalopt /git/xtalopt-public/build /git/xtalopt-public/build/src/xtalopt /git/xtalopt-public/build/src/xtalopt/CMakeFiles/xtalopt.dir/DependInfo.cmake --color=
make[3]: Leaving directory `/git/xtalopt-public/build'
make -f src/xtalopt/CMakeFiles/xtalopt.dir/build.make src/xtalopt/CMakeFiles/xtalopt.dir/build
make[3]: Entering directory `/git/xtalopt-public/build'
Linking CXX shared library xtalopt.so
cd /git/xtalopt-public/build/src/xtalopt && /usr/bin/cmake -E cmake_link_script CMakeFiles/xtalopt.dir/link.txt --verbose=1
/usr/bin/c++  -fPIC  -fPIC -g  -shared -Wl,-soname,xtalopt.so -o xtalopt.so CMakeFiles/xtalopt.dir/extension.cpp.o CMakeFiles/xtalopt.dir/xtalopt.cpp.o CMakeFiles/xtalopt.dir/genetic.cpp.o CMakeFiles/xtalopt.dir/structures/xtal.cpp.o CMakeFiles/xtalopt.dir/optimizers/xtaloptoptimizer.cpp.o CMakeFiles/xtalopt.dir/optimizers/vasp.cpp.o CMakeFiles/xtalopt.dir/optimizers/gulp.cpp.o CMakeFiles/xtalopt.dir/optimizers/pwscf.cpp.o CMakeFiles/xtalopt.dir/optimizers/castep.cpp.o CMakeFiles/xtalopt.dir/testing/xtalopttest.cpp.o CMakeFiles/xtalopt.dir/ui/dialog.cpp.o CMakeFiles/xtalopt.dir/ui/tab_init.cpp.o CMakeFiles/xtalopt.dir/ui/tab_edit.cpp.o CMakeFiles/xtalopt.dir/ui/tab_opt.cpp.o CMakeFiles/xtalopt.dir/ui/tab_sys.cpp.o CMakeFiles/xtalopt.dir/ui/tab_progress.cpp.o CMakeFiles/xtalopt.dir/ui/tab_plot.cpp.o CMakeFiles/xtalopt.dir/ui/tab_log.cpp.o CMakeFiles/xtalopt.dir/moc_extension.cxx.o CMakeFiles/xtalopt.dir/moc_xtalopt.cxx.o CMakeFiles/xtalopt.dir/moc_genetic.cxx.o CMakeFiles/xtalopt.dir/structures/moc_xtal.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_xtaloptoptimizer.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_vasp.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_gulp.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_pwscf.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_castep.cxx.o CMakeFiles/xtalopt.dir/testing/moc_xtalopttest.cxx.o CMakeFiles/xtalopt.dir/ui/moc_dialog.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_init.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_edit.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_opt.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_sys.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_progress.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_plot.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_log.cxx.o -lavogadro ../globalsearch/libglobalsearch.a ../spglib/libspglib.a -lQtOpenGL -lGLU -lGL -lSM -lICE -lX11 -lXext -lopenbabel -lQtGui -lQtCore ../libssh/libssh_static.a -lnsl -lresolv -lrt -lz -lssl -lcrypto
make[3]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles  45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
[100%] Built target xtalopt
make[2]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_start /git/xtalopt-public/build/CMakeFiles 0
make[1]: Leaving directory `/git/xtalopt-public/build'

Body:
Just FYI:

Grep has a -e switch, so you can handle multiple expressions at once.  E.g:

grep -v -e \* -e quit--- -e Syms\ Read -e \(gdb\) | awk '{print $4}' > libs

nm has a -A switch (print filename).  E.g:

cat libs | xargs nm -A --demangle | grep checkPopulation


问:
moment.format returning 3 days off
I have the following code in my Angular app:

```<code>ctrl.getDate = function() {
  console.log(ctrl.day.date); => 2017-12-06T05:00:00.000Z
  return moment(ctrl.day.date).format('MMMM do YYYY'); => December 3rd
    2017
  };
</code>```

What is going on here?  The date passed is clearly 2017-12-06 but for some reason the '.format' method is changing it to a day 3 days earlier.

答:
As Aleksey said capitalisation matters, with "do" you take the day of week and with "Do" you'll have the day of month.
https://momentjs.com/docs/#/displaying/format/</p>

Title: moment.format returning 3 days off

Body:
I have the following code in my Angular app:

ctrl.getDate = function() {
  console.log(ctrl.day.date); => 2017-12-06T05:00:00.000Z
  return moment(ctrl.day.date).format('MMMM do YYYY'); => December 3rd
    2017
  };

What is going on here?  The date passed is clearly 2017-12-06 but for some reason the '.format' method is changing it to a day 3 days earlier.


问:
Which Thread Hold Lock in wait() and notify() multithreading
I have a confusion in multithreading in below code ...

```<code>public class ThreadTest implements Runnable {
        private int num;
        private static SecondThread obj = new SecondThread();

        public void run() {
            synchronized (obj) { //which thread holding lock here
                try {

                    obj.wait();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
</code>```

which thread is owner while synchronize method is called.

which thread holding lock ThreadTest or SecondThread

what is mean by releasing lock here obj.wait(); means ? Once lock is released can same object come inside synchronized block and access code until previous thread get notified ?

答:
Which thread is owner while synchronize method is called.

The thread that entered the synchronized block.

Which thread holding lock ThreadTest or SecondThread

The thread that entered the synchronized block.

What is mean by releasing lock here obj.wait(); means?

It means that the lock is released. It seems perfectly clear. Unclear what you're asking.

Once lock is released can same object come inside synchronized block and access code

Yes.

until previous thread get notified?

Until the thread that is in wait() exits wait().

Body:
I have a confusion in multithreading in below code ...

public class ThreadTest implements Runnable {
        private int num;
        private static SecondThread obj = new SecondThread();

        public void run() {
            synchronized (obj) { //which thread holding lock here
                try {

                    obj.wait();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

which thread is owner while synchronize method is called.

which thread holding lock ThreadTest or SecondThread

what is mean by releasing lock here obj.wait(); means ? Once lock is released can same object come inside synchronized block and access code until previous thread get notified ?


问:
Swift : Firebase Unresolved identifier FirebaseApp.configure() && FIRApp.configure()
i am using xcode 7.3 and swift 2.2. I have added pod 'Firebase/Auth' to my pod file then it gives me error stating unresolved identifier for both of them but when i reinstall my pod file with out pod 'Firebase/Auth'. It does not shows the issue for FirebaseApp.configure().Only after adding Auth to my pod file it is showing the issue. I tried even updating my pod file but still same issue.

And this is how i installed pod,

Can anybody suggest me how can i solve this issue.? Even restarting and cleaning also does not solves the issue..

答:
You just need to add 'import Firebase' and remove the rest import statements of Firebase.  And add

  FirebaseApp.configure(). FIRApp.configure() does not work anymore.


问:
static method patterns for constructor functions in javascript
```<code>function Foo(){...}
Foo.bar = function (){...};
</code>```

Is this the only pattern for adding a static method to a constructor function?  In particular, is it not possible to create the static method bar() within the definition of Foo() itself?

答:
```<code> ( function (fn) {
     fn.bar = function (...) { ... } ;
     ...
 } ) ( Foo.prototype ) ;
</code>```

In other word, you create an anonymous function that will populate the prototype of Foo.

Body:
function Foo(){...}
Foo.bar = function (){...};

Is this the only pattern for adding a static method to a constructor function?  In particular, is it not possible to create the static method bar() within the definition of Foo() itself?

Body:
 ( function (fn) {
     fn.bar = function (...) { ... } ;
     ...
 } ) ( Foo.prototype ) ;

In other word, you create an anonymous function that will populate the prototype of Foo.


问:
how does controller select which compute node to deploy instances on ?
I'm new to openstack , and I'm trying to understand how it works, my question is
in case I have 3 compute nodes , how does the controller ( nova ) select which one to deploy on , and the second instance will be on the same compute node or an other ?

thank you

答:
Nova-scheduler running on the controller decides on which compute the guests should be deployed on. The nova.conf have scheduler_default_filters key. From the values of scheduler_default_filters nova takes clue for  guest creation.

Commonly used values for scheduler_default_filters  are:
Have not been attempted for scheduling purposes (RetryFilter).

Are in the requested availability zone (AvailabilityZoneFilter).

Have sufficient RAM available (RamFilter).

Can service the request (ComputeFilter)

Satisfy any architecture, hypervisor type, or virtual machine mode properties
specified on the instance's image properties (ImagePropertiesFilter).

Are on a different host than other instances of a group (if requested) (ServerGroupAntiAffinityFilter).

Are in a set of group hosts (if requested) (ServerGroupAffinityFilter).


问:
Getting the GUID of the current user?
I want to add a user's GUID in with the information I retrieve from a user when they submit a post. How can I get the GUID?

I am using the default authentication system that comes along with an ASP.NET MVC application.

答:
You could simply use the username instead of hitting the database for something like this:</p>

```<code>[Authorize]
public ActionResult PostComment()
{
    var username = User.Identity.Name;
    // Here you know the user trying to post a comment
    ...
}
</code>```

Title: Getting the GUID of the current user?

Body:
You could simply use the username instead of hitting the database for something like this:

[Authorize]
public ActionResult PostComment()
{
    var username = User.Identity.Name;
    // Here you know the user trying to post a comment
    ...
}


问:
Local Sync and force imports of Perforce
Could you explain what does this phrase mean:

"Within your changelist, select the sc.p4sm file and use the
contextmenu P4SyncManager/Sync (use local, force imports from local
hard disk) to get the set of files from the perforce."

What does mean:

use local

force imports from local hard disk

And which commands line flags responsible for these parameters?

Thank you very much.

答:
For others that may wonder regarding P4SyncManager.

This tool is specific to Harman/Becker corporation and is not distributed outside company.


问:
How to do a specific action on the first iteration of a while loop in a bash script
I need to make a script do a specific action on first loop iteration.

```<code>for file in /path/to/files/*; do
    echo "${file}"
done
</code>```

I want this output:

```<code>First run: file1
file2
file3
file4
...
</code>```

答:
You can create an array with the files, then remove and keep the first element from this array, process it separately and then process the remaining elements of the array:</p>

```<code># create array with files
files=(/path/to/files/*)

# get the 1st element of the array
first=${files[0]}

# remove the 1st element of from array
files=("${files[@]:1}")

# process the 1st element
echo First run: "$first"

# process the remaining elements
for file in "${files[@]}"; do
   echo "$file"
done
</code>```

Body:
I need to make a script do a specific action on first loop iteration.

for file in /path/to/files/*; do
    echo "${file}"
done

I want this output:

First run: file1
file2
file3
file4
...

Body:
You can create an array with the files, then remove and keep the first element from this array, process it separately and then process the remaining elements of the array:

# create array with files
files=(/path/to/files/*)

# get the 1st element of the array
first=${files[0]}

# remove the 1st element of from array
files=("${files[@]:1}")

# process the 1st element
echo First run: "$first"

# process the remaining elements
for file in "${files[@]}"; do
   echo "$file"
done


问:
Execute custom Javascript function on button click in Angular 4
I am beginner in Angular 4 and writing a login component in Angular 4. On click of a Forgot password I want to flip the controls on page to show Reset password elements. I have a javascript function created called rotateCard(this) which I want to call on button click. It is inline javascript in html. I have added html in component.html. below is the code.

but it is giving error as "ReferenceError: rotateCard is not defined"

```<code><form (ngSubmit)="doLoginUser()" #login="ngForm" >

    <div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="card-container manual-flip">
                <div class="card">
                    <div class="front">
                        <div class="content">
                            <div class="main">
                                <img src="../../../../images/logo.png" class="crm-logo" width="139" height="43" />
                                <form>
                                    <div class="form-group">
                                        <input type="text" class="form-control crm-field" placeholder="Email"
                                        id="inputEmail" name="username" ngControl="username" required
                                        autofocus [(ngModel)]="username">
                                    </div>
                                    <div class="form-group">
                                        <input type="password" class="form-control crm-field" name="password" placeholder="Password"
                                        id="inputPassword" ngControl="password" required [(ngModel)]="password">
                                    </div>
                                    <button type="button" class="btn btn-primary btn-block orange-btn">LOGIN</button>
                                </form>
                                <button class="btn btn-simple login-link" onClick="rotateCard(this)">
                                    Forgot Password
                                </button>
                            </div>
                        </div>
                    </div> <!-- end login -->
                    <div class="back">
                        <div class="content">
                            <div class="main">
                                <img src="../../../../images/logo.png" class="crm-logo" width="139" height="43" />
                                <p class="title">Forgot Password</p>
                                <form>
                                    <div class="form-group">
                                        <input type="text" class="form-control crm-field" name="email" placeholder="Email">
                                    </div>
                                    <button type="button" class="btn btn-primary btn-block orange-btn">RESET PASSWORD</button>
                                </form>
                                <button class="btn btn-simple login-link" onClick="rotateCard(this)">
                                    Login
                                </button>
                            </div>
                        </div>
                    </div> <!-- end forgot password -->
                </div> <!-- end card -->
            </div> <!-- end card-container -->
        </div> <!-- end col md 5 -->
    </div> <!-- end row -->
    <div class="space-200"></div>
    </div>

</form>

<script src="../../../../js/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="../../../../js/bootstrap.min.js" type="text/javascript"></script>

<script type="text/javascript">
    function rotateCard(btn){
        var $card = $(btn).closest('.card-container');
        console.log($card);
        if($card.hasClass('hover')){
            $card.removeClass('hover');
        } else {
            $card.addClass('hover');
        }
    }
</script>
</code>```

答:
If you want to execute functions if someone clicks on a element, you could add the (click) listener to your element.

Like this:

```<code><button (click)="yourFunction()">Send</button>
</code>```

Then add the function in your component:

```<code>yourFunction() {
    //your logic
}
</code>```

I hope that helps you out.

Like to official documentation:
https://angular.io/guide/user-input

Body:
I am beginner in Angular 4 and writing a login component in Angular 4. On click of a Forgot password I want to flip the controls on page to show Reset password elements. I have a javascript function created called rotateCard(this) which I want to call on button click. It is inline javascript in html. I have added html in component.html. below is the code.

but it is giving error as "ReferenceError: rotateCard is not defined"

<form (ngSubmit)="doLoginUser()" #login="ngForm" >

                                <form>

                                        <input type="text" class="form-control crm-field" placeholder="Email"
                                        id="inputEmail" name="username" ngControl="username" required
                                        autofocus [(ngModel)]="username">

                                        <input type="password" class="form-control crm-field" name="password" placeholder="Password"
                                        id="inputPassword" ngControl="password" required [(ngModel)]="password">

                                    <button type="button" class="btn btn-primary btn-block orange-btn">LOGIN</button>
                                </form>
                                <button class="btn btn-simple login-link" onClick="rotateCard(this)">
                                    Forgot Password
                                </button>

Forgot Password

                                <form>

                                        <input type="text" class="form-control crm-field" name="email" placeholder="Email">

                                    <button type="button" class="btn btn-primary btn-block orange-btn">RESET PASSWORD</button>
                                </form>
                                <button class="btn btn-simple login-link" onClick="rotateCard(this)">
                                    Login
                                </button>

</form>

Body:
If you want to execute functions if someone clicks on a element, you could add the (click) listener to your element.

Like this:

<button (click)="yourFunction()">Send</button>

Then add the function in your component:

yourFunction() {
    //your logic
}

I hope that helps you out.

Like to official documentation:
https://angular.io/guide/user-input


答:
Why don' t put it in the component.ts file? .. and also remember in Angular 4 you can set css animation directly from Component.ts (https://angular.io/guide/animations) ..

So for example in your component.html .. something like:

```<code><button class="btn btn-simple login-link" (click)="rotateCard()">
                                    Login
                                </button>
</code>```

then in you Component.ts file:

in the header section (near import ) ..

```<code>declare var $:any;
</code>```

then after in your ComponentClass

```<code>rotateCard(){
        var $card = $("#USE ID NOT THIS FOR SELECTOR").closest('.card-container');
        console.log($card);
        if($card.hasClass('hover')){
            $card.removeClass('hover');
        } else {
            $card.addClass('hover');
        }
    }
</code>```

Hope it helps you!!

Title: Execute custom Javascript function on button click in Angular 4

Body:
Why don' t put it in the component.ts file? .. and also remember in Angular 4 you can set css animation directly from Component.ts (https://angular.io/guide/animations) ..

So for example in your component.html .. something like:

<button class="btn btn-simple login-link" (click)="rotateCard()">
                                    Login
                                </button>

then in you Component.ts file:

in the header section (near import ) ..

declare var $:any;

then after in your ComponentClass

rotateCard(){
        var $card = $("#USE ID NOT THIS FOR SELECTOR").closest('.card-container');
        console.log($card);
        if($card.hasClass('hover')){
            $card.removeClass('hover');
        } else {
            $card.addClass('hover');
        }
    }

Hope it helps you!!


问:
Custom button in tabbar problem
I've a TabBarController Application.

This code in didFinishingLaunching method:

```<code>UIImage *buttonImage = [UIImage imageNamed:@"post-button2.png"];

UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];

NSLog(@"Button size: %f, %f", buttonImage.size.width, buttonImage.size.height);

button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];

CGFloat heightDifference = buttonImage.size.height - self.tabBarController.tabBar.frame.size.height;

NSLog(@"self.tabBarController.tabBar.frame.size.height: %f", self.tabBarController.tabBar.frame.size.height);
NSLog(@"heightDifference: %f", heightDifference);
NSLog(@"%Tabbar: %f, %f", tabBarController.tabBar.center.x, tabBarController.tabBar.center.y);
if (heightDifference < 0)
    button.center = tabBarController.tabBar.center;
else {
    CGPoint center = self.tabBarController.tabBar.center;
    center.y = center.y - heightDifference/2.0;
    button.center = tabBarController.tabBar.center;
}

NSLog(@"%Button: %f, %f", button.center.y, button.center.x);

[tabBarController.view addSubview:button];

[self.window addSubview:tabBarController.view];
[self.window makeKeyAndVisible];
</code>```

The output is:

Where is the problem? I can solve with hardcoded code:

```<code>CGPoint center = tabBarController.tabBar.center;
center.x = 160.00;
center.y = 455.50;

button.center = center;
</code>```

But I'm not sure that is correct.

Ty.

答:
To set the image of a tab you need to set the tabBarItem of the viewcontroller associated with the tab.

See UITabBarItem ref for how to create one with custom image.

So you create a UITabBarItem object with the custom image and then make it the tabBarItem property of the viewcontroller for the tab.

The UITabBarController will then manage putting the image in the right place.

Title: Custom button in tabbar problem

Body:
I've a TabBarController Application.

This code in didFinishingLaunching method:

UIImage *buttonImage = [UIImage imageNamed:@"post-button2.png"];

UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];

NSLog(@"Button size: %f, %f", buttonImage.size.width, buttonImage.size.height);

button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];

CGFloat heightDifference = buttonImage.size.height - self.tabBarController.tabBar.frame.size.height;

NSLog(@"self.tabBarController.tabBar.frame.size.height: %f", self.tabBarController.tabBar.frame.size.height);
NSLog(@"heightDifference: %f", heightDifference);
NSLog(@"%Tabbar: %f, %f", tabBarController.tabBar.center.x, tabBarController.tabBar.center.y);
if (heightDifference < 0)
    button.center = tabBarController.tabBar.center;
else {
    CGPoint center = self.tabBarController.tabBar.center;
    center.y = center.y - heightDifference/2.0;
    button.center = tabBarController.tabBar.center;
}

NSLog(@"%Button: %f, %f", button.center.y, button.center.x);

[tabBarController.view addSubview:button];

[self.window addSubview:tabBarController.view];
[self.window makeKeyAndVisible];

The output is:

Where is the problem? I can solve with hardcoded code:

CGPoint center = tabBarController.tabBar.center;
center.x = 160.00;
center.y = 455.50;

button.center = center;

But I'm not sure that is correct.

Ty.


问:
How to filter by year and week in MongoDB
I need to calculate a sum of some fields grouped by Week and year , for exemple
when dt_extract is : 02-01-2017 : so the number of the week is 1 and Year 2017 but the problem with my query i don't know exactly is 2017 or 2016  i juste control the week but i need to get the number of the week and also the year to calculate my Sum .

```<code>var group1 = {

$group :{

        _id:{
                "$isoWeek": "$dt_extract"},

        "Sum_Reliability_Rate_Numerator":{
        "$sum":"$mlf16_txfiabnum"
        }

}
}

var sort ={

$sort : { _id : -1 }

}
}

 db.mplf_tmp_v3.aggregate([group1,sort])
</code>```

This query it's work but i can't find for which year (in my collection i have 2016, 2017 and soon i will get 2018)

I did this request but i got no result

```<code>var match = {

$match : {

         "dt_extract": {"$in":
     [
         "2017-01-02",
         "2017-12-04"
         ]
     }

}

}

var group = {

$group :{
            "_id":{
                "$isoweek" :"$dt_extract" ,

        },

        "Sum_Reliability_Rate_Numerator":{
        "$sum":"$mlf16_txfiabnum"
        }
}
}

 db.supplierswarnings.aggregate([match,group])
</code>```

Here an exemple of the Document for this collection

```<code>{
    "_id" : ObjectId("5a2813a32539c8990f725a8f"),
    "dt_extract" : ISODate("2017-05-14T00:00:00.000+02:00"),
    "mlf16_annee" : "2017",
    "mlf16_semind" : "19",
    "mlf16_semcal" : "19",
    "mlf16_cptmag" : "0000900156",
    "mlf16_codraft" : "02",
    "mlf16_cptfou" : "0000115768",
    "mlf16_codadrdl" : "01",
    "mlf16_codadres" : "01",
    "mlf16_grpges" : "4P",
    "mlf16_clasges" : "2",
    "mlf16_txservnum" : 1,
    "mlf16_txservden" : 13,
    "mlf16_txdocnum" : 0,
    "mlf16_txdocden" : 1,
    "mlf16_txfiabnum" : 0,
    "mlf16_txfiabden" : 0,
    "mlf16_refret2j" : 1,
    "mlf16_refret7j" : 1,
    "mlf16_refret21j" : 0,
    "mlf16_natcouv" : "0",
    "mlf16_nbligndiff" : 0,
    "mlf16_nbrefdiff" : 0,
    "mlf16_cptfou_six" : "115768",
    "dt_year" : 2017
}
</code>```

答:
```<code>var project = {
     $project:{
       correctWeek:{
            $cond:[
                {$lt:[{ $isoWeekYear:"$dt_extract"},{$year:"$dt_extract"}]},
                1,
                {$isoWeek:"$dt_extract"}
            ]
         }
       }
   }

 var group = {

    $group :{
                "_id":"$correctWeek",

            "Sum_Reliability_Rate_Numerator":{
            "$sum":"$mlf16_txfiabnum"
            }
    }
    }

db.supplierswarnings.aggregate([match,project,group])
</code>```

or
instead of using $isoWeek in your question why not use $week

```<code> var group = {

        $group :{
                    "_id":{$week:"$dt_extract"},

                "Sum_Reliability_Rate_Numerator":{
                "$sum":"$mlf16_txfiabnum"
                }
        }
        }
</code>```

Body:
I need to calculate a sum of some fields grouped by Week and year , for exemple
when dt_extract is : 02-01-2017 : so the number of the week is 1 and Year 2017 but the problem with my query i don't know exactly is 2017 or 2016  i juste control the week but i need to get the number of the week and also the year to calculate my Sum .

var group1 = {

$group :{

        _id:{
                "$isoWeek": "$dt_extract"},

        "Sum_Reliability_Rate_Numerator":{
        "$sum":"$mlf16_txfiabnum"
        }

}
}

var sort ={

$sort : { _id : -1 }

}
}

 db.mplf_tmp_v3.aggregate([group1,sort])

This query it's work but i can't find for which year (in my collection i have 2016, 2017 and soon i will get 2018)

I did this request but i got no result

var match = {

$match : {

         "dt_extract": {"$in":
     [
         "2017-01-02",
         "2017-12-04"
         ]
     }

}

}

var group = {

$group :{
            "_id":{
                "$isoweek" :"$dt_extract" ,

        },

        "Sum_Reliability_Rate_Numerator":{
        "$sum":"$mlf16_txfiabnum"
        }
}
}

 db.supplierswarnings.aggregate([match,group])

Here an exemple of the Document for this collection

{
    "_id" : ObjectId("5a2813a32539c8990f725a8f"),
    "dt_extract" : ISODate("2017-05-14T00:00:00.000+02:00"),
    "mlf16_annee" : "2017",
    "mlf16_semind" : "19",
    "mlf16_semcal" : "19",
    "mlf16_cptmag" : "0000900156",
    "mlf16_codraft" : "02",
    "mlf16_cptfou" : "0000115768",
    "mlf16_codadrdl" : "01",
    "mlf16_codadres" : "01",
    "mlf16_grpges" : "4P",
    "mlf16_clasges" : "2",
    "mlf16_txservnum" : 1,
    "mlf16_txservden" : 13,
    "mlf16_txdocnum" : 0,
    "mlf16_txdocden" : 1,
    "mlf16_txfiabnum" : 0,
    "mlf16_txfiabden" : 0,
    "mlf16_refret2j" : 1,
    "mlf16_refret7j" : 1,
    "mlf16_refret21j" : 0,
    "mlf16_natcouv" : "0",
    "mlf16_nbligndiff" : 0,
    "mlf16_nbrefdiff" : 0,
    "mlf16_cptfou_six" : "115768",
    "dt_year" : 2017
}

Body:
var project = {
     $project:{
       correctWeek:{
            $cond:[
                {$lt:[{ $isoWeekYear:"$dt_extract"},{$year:"$dt_extract"}]},
                1,
                {$isoWeek:"$dt_extract"}
            ]
         }
       }
   }

 var group = {

    $group :{
                "_id":"$correctWeek",

            "Sum_Reliability_Rate_Numerator":{
            "$sum":"$mlf16_txfiabnum"
            }
    }
    }

db.supplierswarnings.aggregate([match,project,group])

or
instead of using $isoWeek in your question why not use $week

 var group = {

        $group :{
                    "_id":{$week:"$dt_extract"},

                "Sum_Reliability_Rate_Numerator":{
                "$sum":"$mlf16_txfiabnum"
                }
        }
        }


问:
java.lang.IllegalStateException: Not connected. Call connect() - YouTube API
I am trying to get the ThumbnailView working on my ArrayAdapter but I am getting the following error:

```<code>java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
        at com.google.android.youtube.player.internal.r.i(Unknown Source)
        at com.google.android.youtube.player.internal.o.k(Unknown Source)
        at com.google.android.youtube.player.internal.o.a(Unknown Source)
        at com.google.android.youtube.player.internal.p.<init>(Unknown Source)
        at com.google.android.youtube.player.internal.ac.a(Unknown Source)
        at com.google.android.youtube.player.YouTubeThumbnailView$a.a(Unknown Source)
</code>```

My ArrayAdapter looks like this:

Code for ArrayAdapter

My xml video_items.xml Looks like this:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="@drawable/listviewbox"
    android:padding="10dp"
    android:layout_height="match_parent">

    <!-- Video Thumbnail -->
    <com.google.android.youtube.player.YouTubeThumbnailView
        android:id="@+id/imageView_thumbnail"
        android:layout_width="85dp"
        android:layout_height="85dp"
        android:layout_alignParentLeft="true"
        android:layout_margin="5dp"
        android:background="@color/panelcolor"
        android:scaleType="centerCrop" />

    <!-- Video Title -->
    <TextView
        android:id="@+id/video_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/imageView_thumbnail"
        android:layout_toRightOf="@+id/imageView_thumbnail"
        android:paddingBottom="5dp"
        android:paddingRight="5dp"
        android:text="@string/videotext"
        android:textColor="@android:color/black"
        android:textSize="16sp" />

</RelativeLayout>
</code>```

What could be wrong here?

答:
refers to: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called

I have the same problem
"YouTubeThumbnailView Not connected. Call connect() and wait for onConnected() to be called"
in RecyclerView.Adapter by scrolling quickly and there are 3 youtube thumbnails in the recylerView.

In the adapter I put like this:
a field: private boolean readyForLoadingYoutubeThumbnail = true;
and at onBindViewHolder

```<code>/**
 * https://issuetracker.google.com/issues/35176819#c6
 * https://github.com/youtube/yt-android-player/issues/2#issuecomment-58913900
 * YouTubeThumbnailView Not connected. Call connect() and wait for onConnected() to be called
 */
Log.d(TAG, "readyForLoadingYoutubeThumbnail" + readyForLoadingYoutubeThumbnail);
final YouTubeInitializationResult result = YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(activity);
if (readyForLoadingYoutubeThumbnail) {
    Log.d(TAG, "initializing for youtube thumbnail view...");
    readyForLoadingYoutubeThumbnail = false;
    holder.youTubeThumbnailView.initialize("aaaaaaaaaaaaa", new YouTubeThumbnailView.OnInitializedListener() {
        @Override
        public void onInitializationSuccess(final YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {

            youTubeThumbnailLoader.setVideo(videoId);
            youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener(){

                @Override
                public void onThumbnailLoaded(YouTubeThumbnailView childYouTubeThumbnailView, String s) {
                    childYouTubeThumbnailView.setVisibility(View.VISIBLE);
                    holder.relativeLayoutOverYouTubeThumbnailView.setVisibility(View.VISIBLE);
                    youTubeThumbnailLoader.release(); // spy ga memory lick
                }

                @Override
                public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
                    youTubeThumbnailLoader.release(); // spy ga memory lick
                }
            });
            youTubeThumbnailView.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);

            readyForLoadingYoutubeThumbnail = true;
        }

        @Override
        public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
            //do nohing.. ada error, tambahin method ini jalan, error-nya lupa...
            readyForLoadingYoutubeThumbnail = true;
        }
    });
}
</code>```

It is works for me...

Body:
I am trying to get the ThumbnailView working on my ArrayAdapter but I am getting the following error:

java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
        at com.google.android.youtube.player.internal.r.i(Unknown Source)
        at com.google.android.youtube.player.internal.o.k(Unknown Source)
        at com.google.android.youtube.player.internal.o.a(Unknown Source)
        at com.google.android.youtube.player.internal.p.<init>(Unknown Source)
        at com.google.android.youtube.player.internal.ac.a(Unknown Source)
        at com.google.android.youtube.player.YouTubeThumbnailView$a.a(Unknown Source)

My ArrayAdapter looks like this:

Code for ArrayAdapter

My xml video_items.xml Looks like this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="@drawable/listviewbox"
    android:padding="10dp"
    android:layout_height="match_parent">

    <com.google.android.youtube.player.YouTubeThumbnailView
        android:id="@+id/imageView_thumbnail"
        android:layout_width="85dp"
        android:layout_height="85dp"
        android:layout_alignParentLeft="true"
        android:layout_margin="5dp"
        android:background="@color/panelcolor"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/video_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/imageView_thumbnail"
        android:layout_toRightOf="@+id/imageView_thumbnail"
        android:paddingBottom="5dp"
        android:paddingRight="5dp"
        android:text="@string/videotext"
        android:textColor="@android:color/black"
        android:textSize="16sp" />

</RelativeLayout>

What could be wrong here?

Body:
refers to: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called

I have the same problem
"YouTubeThumbnailView Not connected. Call connect() and wait for onConnected() to be called"
in RecyclerView.Adapter by scrolling quickly and there are 3 youtube thumbnails in the recylerView.

In the adapter I put like this:
a field: private boolean readyForLoadingYoutubeThumbnail = true;
and at onBindViewHolder

/**
 * https://issuetracker.google.com/issues/35176819#c6
 * https://github.com/youtube/yt-android-player/issues/2#issuecomment-58913900
 * YouTubeThumbnailView Not connected. Call connect() and wait for onConnected() to be called
 */
Log.d(TAG, "readyForLoadingYoutubeThumbnail" + readyForLoadingYoutubeThumbnail);
final YouTubeInitializationResult result = YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(activity);
if (readyForLoadingYoutubeThumbnail) {
    Log.d(TAG, "initializing for youtube thumbnail view...");
    readyForLoadingYoutubeThumbnail = false;
    holder.youTubeThumbnailView.initialize("aaaaaaaaaaaaa", new YouTubeThumbnailView.OnInitializedListener() {
        @Override
        public void onInitializationSuccess(final YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {

            youTubeThumbnailLoader.setVideo(videoId);
            youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener(){

                @Override
                public void onThumbnailLoaded(YouTubeThumbnailView childYouTubeThumbnailView, String s) {
                    childYouTubeThumbnailView.setVisibility(View.VISIBLE);
                    holder.relativeLayoutOverYouTubeThumbnailView.setVisibility(View.VISIBLE);
                    youTubeThumbnailLoader.release(); // spy ga memory lick
                }

                @Override
                public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
                    youTubeThumbnailLoader.release(); // spy ga memory lick
                }
            });
            youTubeThumbnailView.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);

            readyForLoadingYoutubeThumbnail = true;
        }

        @Override
        public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
            //do nohing.. ada error, tambahin method ini jalan, error-nya lupa...
            readyForLoadingYoutubeThumbnail = true;
        }
    });
}

It is works for me...


问:
Is it possible continue a stopped async function?
I'm trying to learn about promises, and I wonder about to start and stop an async function, like my example show. It starts at the begining and stop when you click the button, but it seems can't continue.

var stop = 0;
var elParrafo = document.getElementById('miParrafo');

function sendStop() {
  stop = 1;
}

function sendStart() {
  stop = 0;
}

function esperar(ms) {
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, ms)
  });
}

async function trabajar() {
  while (stop === 0) {
    elParrafo.innerHTML += " > ";
    await esperar(50);
  }
}

trabajar();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="" action="index.html" method="post">
  <input type="button" value="Stop" onclick="sendStop()">
  <input type="button" value="Start" onclick="sendStart()">
</form>
<p id="miParrafo"></p></code>```

答:
There is a difference between stopping/restarting and pausing. You are describing the feature to pause and to continue.

If you wish to pause/continue you need the while loop to keep running and add an internal condition to check if you are currently paused or not.

You could off course just re-call trabajar(); to restart but restarting and continuing is logically 2 different things and a restart might want to clear the existing output while continue does not.

There is probably many ways to do this but the quickest to demonstrate pause/continue as well as stop/restart can be done similar to the below. Again, feel free to just re-call trabajar(); but that is up to you.

var stop = false;
var pause = false;
var elParrafo = document.getElementById('miParrafo');

function sendPause() {
  pause = true;
}

function sendContinue() {
  pause = false;
}

function sendStop() {
  stop = true;
}

function sendRestart() {
  sendStop();
  setTimeout(function() {
    stop = false;
    pause = false;
    elParrafo.innerHTML = "";
    trabajar();
  }, 50)
}

function esperar(ms) {
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, ms)
  });
}

async function trabajar() {
  while (!stop) {
    if (!pause) {
      elParrafo.innerHTML += " > ";
    }
    await esperar(50);
  }
}

trabajar();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="" action="index.html" method="post">
  <input type="button" value="Pause" onclick="sendPause()">
  <input type="button" value="Continue" onclick="sendContinue()">
  <input type="button" value="Stop" onclick="sendStop()">
  <input type="button" value="Restart" onclick="sendRestart()">
</form>
<p id="miParrafo"></p></code>```

Body:
I'm trying to learn about promises, and I wonder about to start and stop an async function, like my example show. It starts at the begining and stop when you click the button, but it seems can't continue.

var stop = 0;
var elParrafo = document.getElementById('miParrafo');

function sendStop() {
  stop = 1;
}

function sendStart() {
  stop = 0;
}

function esperar(ms) {
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, ms)
  });
}

async function trabajar() {
  while (stop === 0) {
    elParrafo.innerHTML += " > ";
    await esperar(50);
  }
}

trabajar();

<form class="" action="index.html" method="post">
  <input type="button" value="Stop" onclick="sendStop()">
  <input type="button" value="Start" onclick="sendStart()">
</form>

Body:
There is a difference between stopping/restarting and pausing. You are describing the feature to pause and to continue.

If you wish to pause/continue you need the while loop to keep running and add an internal condition to check if you are currently paused or not.

You could off course just re-call trabajar(); to restart but restarting and continuing is logically 2 different things and a restart might want to clear the existing output while continue does not.

There is probably many ways to do this but the quickest to demonstrate pause/continue as well as stop/restart can be done similar to the below. Again, feel free to just re-call trabajar(); but that is up to you.

var stop = false;
var pause = false;
var elParrafo = document.getElementById('miParrafo');

function sendPause() {
  pause = true;
}

function sendContinue() {
  pause = false;
}

function sendStop() {
  stop = true;
}

function sendRestart() {
  sendStop();
  setTimeout(function() {
    stop = false;
    pause = false;
    elParrafo.innerHTML = "";
    trabajar();
  }, 50)
}

function esperar(ms) {
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, ms)
  });
}

async function trabajar() {
  while (!stop) {
    if (!pause) {
      elParrafo.innerHTML += " > ";
    }
    await esperar(50);
  }
}

trabajar();

<form class="" action="index.html" method="post">
  <input type="button" value="Pause" onclick="sendPause()">
  <input type="button" value="Continue" onclick="sendContinue()">
  <input type="button" value="Stop" onclick="sendStop()">
  <input type="button" value="Restart" onclick="sendRestart()">
</form>
<p id="miParrafo"></p>


问:
Azure Failover database not replicating login/user
I've set up Geo-replication on an Azure Database Server.

One of the databases running on the server has a login and user that I created through SSMS:

https://learn.microsoft.com/en-us/azure/sql-database/sql-database-manage-logins

I cant connect to the failover database with that user. The user is visible in the replicated database, but the login is not visible in the master db. Moreover, chaning the connection string to point the the replication DNS name doesnt work.

Do I need to create the login manually on the failover?

答:
You need to use contained users (those which are stored in the database, not in the masted database), that way you dont need to do anything.

https://learn.microsoft.com/en-us/sql/relational-databases/security/contained-database-users-making-your-database-portable


答:
It is inline javascript in html

You shouldn't really do this. Looking at your function it looks pretty trivial to move this into the component definition rather than have it in the HTML.

Without seeing the component though I can't be much more help


问:
How to resolve this "required a bean" error
I am new to Springboot and I learning by Sping's tutorials and guides on "https://spring.io/guides".

Right now I try to understand and redo the tutorial: "Accessing data with MySQL"

Unfortunatelly I got the Error during Mavenbuild:

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
  2017-12-07 10:26:42.708 ERROR 8100 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

APPLICATION FAILED TO START

Description:

Field goodRepository in xxx.controller.GoodController required a bean of type 'xxx.repositories.GoodRepository' that could not be found.

Action:

Consider defining a bean of type 'xxx.repositories.GoodRepository' in your configuration.

Process finished with exit code 1

Here is my Code:

Good.java:

```<code>import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import lombok.Data;

@Entity
@Data
public class Good {

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

    private String name;

    public Good() {
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

GoodRepository:

```<code>import org.springframework.data.repository.CrudRepository;

import xxx.model.Good;

public interface GoodRepository extends CrudRepository<Good, Long>
{

}
</code>```

GoodController:

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import xxx.model.Good;
import xxx.repositories.GoodRepository;

@Controller
@RequestMapping(path="/goods")
public class GoodController {

    @Autowired
    private GoodRepository goodRepository;

    @GetMapping(path="/add")
    public @ResponseBody String addNewGod( @RequestParam String name)
    {
        Good god= new Good();
        god.setName(name);
        goodRepository.save(god);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<Good> getAllGods()
    {
        return goodRepository.findAll();
    }

}
</code>```

My application.properties:

```<code>spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/gccontest
spring.datasource.username=xxx
spring.datasource.password=xxx
</code>```

the mysql-db exists on this port...

What did I where wrong?

答: Mark your GoodRepository implementation class as @service/@component and have a try</p>

Body:
I am new to Springboot and I learning by Sping's tutorials and guides on "https://spring.io/guides".

Right now I try to understand and redo the tutorial: "Accessing data with MySQL"

Unfortunatelly I got the Error during Mavenbuild:

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
  2017-12-07 10:26:42.708 ERROR 8100 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

APPLICATION FAILED TO START

Description:

Field goodRepository in xxx.controller.GoodController required a bean of type 'xxx.repositories.GoodRepository' that could not be found.

Action:

Consider defining a bean of type 'xxx.repositories.GoodRepository' in your configuration.

Process finished with exit code 1

Here is my Code:

Good.java:

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

import lombok.Data;

@Entity
@Data
public class Good {

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

    private String name;

    public Good() {
    }

    public void setName(String name) {
        this.name = name;
    }
}

GoodRepository:

import org.springframework.data.repository.CrudRepository;

import xxx.model.Good;

public interface GoodRepository extends CrudRepository<Good, Long>
{

}

GoodController:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import xxx.model.Good;
import xxx.repositories.GoodRepository;

@Controller
@RequestMapping(path="/goods")
public class GoodController {

    @Autowired
    private GoodRepository goodRepository;

    @GetMapping(path="/add")
    public @ResponseBody String addNewGod( @RequestParam String name)
    {
        Good god= new Good();
        god.setName(name);
        goodRepository.save(god);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<Good> getAllGods()
    {
        return goodRepository.findAll();
    }

}

My application.properties:

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/gccontest
spring.datasource.username=xxx
spring.datasource.password=xxx

the mysql-db exists on this port...

What did I where wrong?


问:
Php JSON encode array and unexpected token error in decoding
I got an array from an SQL query, encoded it and when I decode in javascript I receive the error

Unexpected token a in JSON at position 0

The var_dump of the array before the encode:

```<code>array(1) { [0]=> array(10) { ["order_id"]=> string(10) "1512642144"
["order_erp_id"]=> string(1) "0" ["order_type"]=> string(3) "web"
["order_date"]=> string(23) "2017-12-07 11:22:24.263" ["order_total"]=>
string(4) "0.00" ["order_desc1"]=> string(3) "web" ["order_desc2"]=>
string(4) "test" ["no_items"]=> string(1) "0" ["order_count"]=> int(1)
["item_arr"]=> string(0) "" } }
[{"order_id":"1512642144","order_erp_id":"0","order_type":"web",
"order_date":"2017-12-07 11:22:24.263","order_total":"0.00",
"order_desc1":"web","order_desc2":"test","no_items":"0",
"order_count":1,"item_arr":""}]
</code>```

then I  encode and send it with:

```<code>echo json_encode($order_item_arr);
</code>```

On the client side, I receive the data and before the decoding step I have this from the console.log(data); in javascript:

```<code>array(1) {
[0]=>
array(10) {
["order_id"]=>
string(10) "1512642144"
["order_erp_id"]=>
string(1) "0"
["order_type"]=>
string(3) "web"
["order_date"]=>
string(23) "2017-12-07 11:22:24.263"
["order_total"]=>
string(4) "0.00"
["order_desc1"]=>
string(3) "web"
["order_desc2"]=>
string(4) "test"
["no_items"]=>
string(1) "0"
["order_count"]=>
int(1)
["item_arr"]=>
string(0) ""
  }
}

[{"order_id":"1512642144","order_erp_id":"0","order_type":"web",
"order_date":"2017-12-07 11:22:24.263","order_total":"0.00",
"order_desc1":"web","order_desc2":"test","no_items":"0",
"order_count":1,"item_arr":""}]
</code>```

So it looks like quite ok, and when I decode it with JSON.parse(data); I have the error:

```<code>VM414:1 Uncaught SyntaxError: Unexpected token a in JSON at position 0
</code>```

答:
Uncaught SyntaxError: Unexpected token a in JSON at position 0

So the very first character in your "JSON" is a, which can't be valid JSON. And your echo json_encode($order_item_arr); line will not output it.

The var_dump of the array before the encode:

```<code>array(1) { [0]=> array
</code>```

… and there is your problem. You can see that the first character is a.

You are trying to parse your var_dump as if it were JSON.

Don't do that. Parse the JSON instead.

Body:
I got an array from an SQL query, encoded it and when I decode in javascript I receive the error

Unexpected token a in JSON at position 0

The var_dump of the array before the encode:

array(1) { [0]=> array(10) { ["order_id"]=> string(10) "1512642144"
["order_erp_id"]=> string(1) "0" ["order_type"]=> string(3) "web"
["order_date"]=> string(23) "2017-12-07 11:22:24.263" ["order_total"]=>
string(4) "0.00" ["order_desc1"]=> string(3) "web" ["order_desc2"]=>
string(4) "test" ["no_items"]=> string(1) "0" ["order_count"]=> int(1)
["item_arr"]=> string(0) "" } }
[{"order_id":"1512642144","order_erp_id":"0","order_type":"web",
"order_date":"2017-12-07 11:22:24.263","order_total":"0.00",
"order_desc1":"web","order_desc2":"test","no_items":"0",
"order_count":1,"item_arr":""}]

then I  encode and send it with:

echo json_encode($order_item_arr);

On the client side, I receive the data and before the decoding step I have this from the console.log(data); in javascript:

array(1) {
[0]=>
array(10) {
["order_id"]=>
string(10) "1512642144"
["order_erp_id"]=>
string(1) "0"
["order_type"]=>
string(3) "web"
["order_date"]=>
string(23) "2017-12-07 11:22:24.263"
["order_total"]=>
string(4) "0.00"
["order_desc1"]=>
string(3) "web"
["order_desc2"]=>
string(4) "test"
["no_items"]=>
string(1) "0"
["order_count"]=>
int(1)
["item_arr"]=>
string(0) ""
  }
}

[{"order_id":"1512642144","order_erp_id":"0","order_type":"web",
"order_date":"2017-12-07 11:22:24.263","order_total":"0.00",
"order_desc1":"web","order_desc2":"test","no_items":"0",
"order_count":1,"item_arr":""}]

So it looks like quite ok, and when I decode it with JSON.parse(data); I have the error:

VM414:1 Uncaught SyntaxError: Unexpected token a in JSON at position 0

Body:
Uncaught SyntaxError: Unexpected token a in JSON at position 0

So the very first character in your "JSON" is a, which can't be valid JSON. And your echo json_encode($order_item_arr); line will not output it.

The var_dump of the array before the encode:

array(1) { [0]=> array

… and there is your problem. You can see that the first character is a.

You are trying to parse your var_dump as if it were JSON.

Don't do that. Parse the JSON instead.