text:
Q: Deadlocks in SOLR We are seeing thread pool exhausted on Tomcat. And the service hangs with high latency.
With this exception. Any help is appreciated.
    Thread Name:http-8080-541
    ID:610
    Time:Thu May 15 13:21:34 CDT 2014
    State:WAITING
    Priority:5
sun.misc.Unsafe.park(Native Method)
java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:834)
java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireQueued(AbstractQueuedSynchronizer.java:867)
java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(AbstractQueuedSynchronizer.java:1197)
java.util.concurrent.locks.ReentrantLock$NonfairSync.lock(ReentrantLock.java:214)
java.util.concurrent.locks.ReentrantLock.lock(ReentrantLock.java:290)
java.util.concurrent.ConcurrentHashMap$Segment.scanAndLock(ConcurrentHashMap.java:537)
java.util.concurrent.ConcurrentHashMap$Segment.remove(ConcurrentHashMap.java:553)
java.util.concurrent.ConcurrentHashMap.remove(ConcurrentHashMap.java:1111)
org.apache.lucene.util.WeakIdentityMap.reap(WeakIdentityMap.java:238)
org.apache.lucene.util.WeakIdentityMap.put(WeakIdentityMap.java:130)
org.apache.lucene.store.ByteBufferIndexInput.buildSlice(ByteBufferIndexInput.java:236)
org.apache.lucene.store.ByteBufferIndexInput.clone(ByteBufferIndexInput.java:187)
org.apache.lucene.store.ByteBufferIndexInput.clone(ByteBufferIndexInput.java:39)
org.apache.lucene.codecs.BlockTreeTermsReader$FieldReader$SegmentTermsEnum.initIndexInput(BlockTreeTermsReader.java:1314)
org.apache.lucene.codecs.BlockTreeTermsReader$FieldReader$SegmentTermsEnum$Frame.loadBlock(BlockTreeTermsReader.java:2348)
org.apache.lucene.codecs.BlockTreeTermsReader$FieldReader$SegmentTermsEnum.seekExact(BlockTreeTermsReader.java:1745)
org.apache.lucene.index.AtomicReader.docFreq(AtomicReader.java:94)
org.apache.lucene.index.BaseCompositeReader.docFreq(BaseCompositeReader.java:118)
org.apache.lucene.search.vectorhighlight.FieldTermStack.<init>(FieldTermStack.java:116)
org.apache.lucene.search.vectorhighlight.FastVectorHighlighter.getFieldFragList(FastVectorHighlighter.java:193)
org.apache.lucene.search.vectorhighlight.FastVectorHighlighter.getBestFragments(FastVectorHighlighter.java:184)
org.apache.solr.highlight.DefaultSolrHighlighter.doHighlightingByFastVectorHighlighter(DefaultSolrHighlighter.java:588)
org.apache.solr.highlight.DefaultSolrHighlighter.doHighlighting(DefaultSolrHighlighter.java:413)
org.apache.solr.handler.component.HighlightComponent.process(HighlightComponent.java:139)
org.apache.solr.handler.component.SearchHandler.handleRequestBody(SearchHandler.java:208)
org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:135)
org.apache.solr.core.SolrCore.execute(SolrCore.java:1820)
org.apache.solr.servlet.SolrDispatchFilter.execute(SolrDispatchFilter.java:656)
org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:359)
org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:155)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:465)
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
java.lang.Thread.run(Thread.java:722)


text:
Q: For given column vectors $x$, $y$ how to find an orthogonal matrix $Q$ such that $Qx=y$ Problem: Given $x=[1,7,2,3,-1]^T $and $y=[-4,4,4,0,-4]^T$, find an orthogonal matrix $Q$ such that $Qx=y$.
My attempt: I know the definition of an orthogonal matrix. By definition, if $Q$ is an orthogonal matrix then $Q^{-1}=Q^T$. Further, I know if system of equations $Ax=b$ where $A$ is square matrix, has a solution if $b$ is in column space of $A$ i.e. if $rank(A:b)=rank(A)$.
I didn't able to solve above problem :-( please help me.

A: If you let $v=\frac{x-y}{\mid\mid y-x\mid\mid}$.
$A=I-2vv^t$ should do the trick.
This is called the Householder reflection.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to apply ggplot on split dataset and combine the plots into a single grid I am trying to create the plot between .resid and .fitted of each split dataset as shown below split tables and combine them into a single 2 x 2 plot. Any help? If I want to use bind_rows, how can I create a new column with cyl as an .id?
library(datasets)
library(tidyverse)
ans_long = anscombe %>%
  pivot_longer(
    everything(),
    names_to = c(".value", "set"),
    names_pattern = "(.)(.)"
  )

ggplot(ans_long, aes(x, y, color = set)) + geom_point() + facet_wrap(~ set)

ans_long %>% split(.$set) %>% lapply(\(k) lm(y ~ x, k)) %>%
  map(broom::augment)
#> $`1`
#> # A tibble: 11 × 8
#>        y     x .fitted  .resid   .hat .sigma   .cooksd .std.resid
#>    <dbl> <dbl>   <dbl>   <dbl>  <dbl>  <dbl>     <dbl>      <dbl>
#>  1  8.04    10    8.00  0.0390 0.100    1.31 0.0000614     0.0332
#>  2  6.95     8    7.00 -0.0508 0.1      1.31 0.000104     -0.0433
#>  3  7.58    13    9.50 -1.92   0.236    1.06 0.489        -1.78
...
#>
#> $`2`
#> # A tibble: 11 × 8
#>        y     x .fitted .resid   .hat .sigma .cooksd .std.resid
#>    <dbl> <dbl>   <dbl>  <dbl>  <dbl>  <dbl>   <dbl>      <dbl>
#>  1  9.14    10    8.00  1.14  0.100    1.24 0.0523       0.970
#>  2  8.14     8    7.00  1.14  0.1      1.24 0.0523       0.970
#>  3  8.74    13    9.50 -0.761 0.236    1.28 0.0767      -0.704
#>  4  8.77     9    7.50  1.27  0.0909   1.22 0.0579       1.08
...
#>
#> $`3`
#> # A tibble: 11 × 8
#>        y     x .fitted  .resid   .hat  .sigma  .cooksd .std.resid
#>    <dbl> <dbl>   <dbl>   <dbl>  <dbl>   <dbl>    <dbl>      <dbl>
#>  1  7.46    10    8.00 -0.540  0.100  1.30    0.0118      -0.460
#>  2  6.77     8    7.00 -0.230  0.1    1.31    0.00214     -0.196
#>  3 12.7     13    9.50  3.24   0.236  0.00308 1.39         3.00
...
#>
#> $`4`
#> # A tibble: 11 × 8
#>        y     x .fitted  .resid  .hat .sigma     .cooksd .std.resid
#>    <dbl> <dbl>   <dbl>   <dbl> <dbl>  <dbl>       <dbl>      <dbl>
#>  1  6.58     8    7.00 -0.421  0.100   1.30   0.00717      -0.359
#>  2  5.76     8    7.00 -1.24   0.1     1.23   0.0623       -1.06
#>  3  7.71     8    7.00  0.709  0.1     1.28   0.0203        0.605
...

Created on 2022-10-09 by the reprex package (v2.0.1)

A: Use map_dfr and just pass the name of the new column to argument .id. From the documentation, my emphasis:

.id
Either a string or NULL. If a string, the output will contain a variable with that name, storing either the name (if .x is named) or the index (if .x is unnamed) of the input. If NULL, the default, no variable will be created.
Only applies to _dfr variant.

library(datasets)
library(tidyverse)

ans_long = anscombe %>%
  pivot_longer(
    everything(),
    names_to = c(".value", "set"),
    names_pattern = "(.)(.)"
  )

ans_long %>%
  split(.$set) %>%
  lapply(\(k) lm(y ~ x, k)) %>%
  map_dfr(broom::augment, .id = "set") %>%
  ggplot(aes(.fitted, .resid, color = set)) +
  geom_point() +
  labs(title = "Anscombe's Quartet",
       x = "Fitted Values", y = "Residuals") +
  facet_wrap(~ set)

Created on 2022-10-09 with reprex v2.0.2


text:
Q: Rspec Test : How do we check for an input field in a bootstrap modal? And how do we fill in that field? I have these two input fields in my modal:
Amount: <%= f.text_field :prin, :onKeyPress=>"return isNumberKey(event)"  , :required => 'true'%>
Rate: <%= f.number_field :interest_rate, :min => "12", :max => "30", :required =>'true'  %>

Typical fill_in doesn't work for this in spec test.

A: You can use within to identify the modal's class name and use fill_in like below
within(".your_modal_class_name") do
  fill_in 'prin', with: 'some_value'
  fill_in 'interest_rate', with: 'some_value'
end


text:
Q: ViewPager within ListView row item I have read a lot of related questions regarding this question. However, none of them has been answered. I am trying to add a ViewPager to each row in the ListView where there are two layouts within the pager. I believe this is doable because of SwipeListView.
Now I have implemented it. However, a blank page is showing with a line in the middle. No rows are appearing.

Here is my code:
MainActivity + ArrayAdapter
public class MainActivity extends Activity {

    ListView list;
    String[] heros;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        heros = getResources().getStringArray(R.array.heros);

        list = (ListView) findViewById(R.id.listView1);
        list.setAdapter(new CustomAdapter(this, heros));
    }

    public class CustomAdapter extends ArrayAdapter<String>
    {
        String[] heros;
        Context context;
        public CustomAdapter(Context context, String[] heros) {
            super(context, R.layout.pager_item_list, R.id.listView1, heros);
            // TODO Auto-generated constructor stub
            this.heros = heros;
            this.context = context;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View row = inflater.inflate(R.layout.pager_item_list, parent, false);

            Log.d("how many times", "I really don't know how it should be");

            ViewPager pager = (ViewPager) row.findViewById(R.id.pager);
            pager.setId(position);
            pager.setAdapter(new PagerCustomAdapter());

            pager.setCurrentItem(0);

            return row;
        }
    }
}

Here is my pageAdapter
public class PagerCustomAdapter extends PagerAdapter{
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return 2;
    }

    @Override
    public Object instantiateItem(View container, int position) {
        // TODO Auto-generated method stub

        LayoutInflater inflater = (LayoutInflater) container.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        int id = 0;

        Log.d("I am in pagerAdater", "I am here, dammit!");

        switch(position)
        {
            case 0:
                id = R.layout.fragment_top_item;
                break;
            case 1:
                id = R.layout.fragment_bottom_item;
                break;
        }
        View view = inflater.inflate(id, null);
        ((ViewPager)container).addView(view, 0);
        return view;
    }

    @Override
    public void destroyItem(View arg0, int arg1, Object arg2) {
        ((ViewPager) arg0).removeView((View) arg2);
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        // TODO Auto-generated method stub
        return arg0 == ((View) arg1);
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

}

I have tried both pagerAdapter & FragmentPagerAdapter and both had the same result
I added two log messages in getView() and instantiateItem() and both are being read in logcat as expected. There are neither warnings nor errors in LogCat.
What am I missing?
Update
XML of activity_main
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" >
</ListView>

</RelativeLayout>

XML of pager_item_list
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical" >

    <android.support.v4.view.ViewPager
         android:id="@+id/pager"
         android:layout_width="match_parent"
         android:layout_height="match_parent" >
    </android.support.v4.view.ViewPager>
</LinearLayout>

A: I am not sure what you're trying to achieve.. Do you want to change the view when a event happens? like when you click on it? or do you want the same result like the SwipeListView.
If you want to change the view you coult try to use a ViewFlipper
anc change the layout when the event occurs. But i'm not sure if this is the result you want

A: A ViewPager when used inside a ListView row needs to have a unique android:id (as in each row must have a different id). This is because the FragmentManager that is associated with the ViewPager adapter uses the id along with the position to store the fragments. This means if you just use the defaults things will get overwritten.
Below is a sample PagerAdapter that allows you to override the default makeFragmentName method.
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Parcelable;
import android.support.v13.app.FragmentCompat;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

public abstract class TaggedFragmentPagerAdapter extends PagerAdapter {

    private final FragmentManager mFragmentManager;

    private FragmentTransaction mCurTransaction = null;

    private Fragment mCurrentPrimaryItem = null;

    public TaggedFragmentPagerAdapter(FragmentManager fm) {
        mFragmentManager = fm;
    }

    /**
     * Return the Fragment associated with a specified position.
     */
    public abstract Fragment getItem(int position);

    public String getItemTag(int position) {
        // Maintain backward compatibility
        return String.valueOf(getItemId(position));
    }

    @Override
    public void startUpdate(ViewGroup container) {
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }

        // Do we already have this fragment?
        String name = makeFragmentName(position, container.getId(), getItemTag(position));
        Fragment fragment = mFragmentManager.findFragmentByTag(name);
        if (fragment != null) {
            // FIXME : Start fix.
            if (!fragment.isDetached()) {
                mCurTransaction.detach(fragment);
            }
            // FIXME : End fix.
            mCurTransaction.attach(fragment);
        } else {
            fragment = getItem(position);
            mCurTransaction.add(container.getId(), fragment, name);
        }
        if (fragment != mCurrentPrimaryItem) {
            FragmentCompat.setMenuVisibility(fragment, false);
            FragmentCompat.setUserVisibleHint(fragment, false);
        }

        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }
        mCurTransaction.detach((Fragment) object);
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment) object;
        if (fragment != mCurrentPrimaryItem) {
            if (mCurrentPrimaryItem != null) {
                FragmentCompat.setMenuVisibility(mCurrentPrimaryItem, false);
                FragmentCompat.setUserVisibleHint(mCurrentPrimaryItem, false);
            }
            if (fragment != null) {
                FragmentCompat.setMenuVisibility(fragment, true);
                FragmentCompat.setUserVisibleHint(fragment, true);
            }
            mCurrentPrimaryItem = fragment;
        }
    }

    @Override
    public void finishUpdate(ViewGroup container) {
        if (mCurTransaction != null) {
            mCurTransaction.commitAllowingStateLoss();
            mCurTransaction = null;
            mFragmentManager.executePendingTransactions();
        }
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return ((Fragment) object).getView() == view;
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
    }

    /**
     * Return a unique identifier for the item at the given position.
     *
     * <p> The default implementation returns the given position. Subclasses should override this method if the positions of items
     * can change. </p>
     *
     * @param position Position within this adapter
     * @return Unique identifier for the item at position
     */
    public long getItemId(int position) {
        return position;
    }

    protected String makeFragmentName(int position, int viewId, String tagName) {
        return "android:switcher:" + viewId + ":" + tagName;
    }
}

A: I faced a similar issue, and what I did is I explicity set the height of the viewPager and its parent. This worked for me.
<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="200dip"
    android:orientation="vertical" >

   <android.support.v4.view.ViewPager
      android:id="@+id/pager"
      android:layout_width="match_parent"
      android:layout_height="200dip" >
   </android.support.v4.view.ViewPager>
 </LinearLayout>

I don't know if there is a better solution, but if you do get a better solution please comment!


text:
Q: Conceptual Tagging of articles I have a set of articles and i want to extract the concept from each of the article . The concept may be independent ,or either linked together to form a new concept .
For this ,recently I came across various paid API , eg,HP's IDOL on DEMAND (http://www.autonomy.com/technology/idol-functions/conceptual-search) , Data harmony(http://www.dataharmony.com/services-view/mai-components/) , ALCHEMY API (http://www.alchemyapi.com/products/features/concept-tagging/ ) ,etc . But I have a very huge set of documents and cant afford using the priced API .Is there any free tool which can do this ? Also I'am aware of DBPedia data-sets , which are used for linking concepts together. But I haven't figured out how to use them . Any help on that would be useful .
Also, I had used Stanbol NLP tools  long back .I wanted to know whether this could be done thru that , or for that matter by any  other tool .

A: I realise that this doesn't answer your question about Stanbol, but HP's IDOL OnDemand is open to the public and is currently completely free as-in-beer.  As you've identified it as a potential solution, now would be the time to try it out!
Disclaimer: I work for HP and am involved with IDOL OnDemand.


text:
Q: How to open different activity by clicking on different cards in a recycler view with cards I have created a RecyclerView and added cards.I want to open different activity by clicking on different cards.
My codes are:
MainActivity
public class MainActivity extends AppCompatActivity {
    RecyclerView mRecyclerView;
    RecyclerView.LayoutManager mLayoutManager;
    RecyclerView.Adapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRecyclerView = (RecyclerView)findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);

        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mAdapter = new CardAdapter();
        mRecyclerView.setAdapter(mAdapter); }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

CardAdapter
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {

    List<NatureItem> mItems;

    public CardAdapter() {
        super();
        mItems = new ArrayList<NatureItem>();
        NatureItem nature = new NatureItem();
        nature.setName("The Great Barrier Reef");
        nature.setDes("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt" +
                "ut labore et dolore magna aliqua. Ut enim ad minim veniam.");
        nature.setThumbnail(R.drawable.tag_logo);
        mItems.add(nature);

        nature = new NatureItem();
        nature.setName("Grand Canyon");
        nature.setDes("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt" +
                "ut labore et dolore magna aliqua.");
        nature.setThumbnail(R.drawable.tag_logo);
        mItems.add(nature);

        nature = new NatureItem();
        nature.setName("Baltoro Glacier");
        nature.setDes("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt" +
                "ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis.");
        nature.setThumbnail(R.drawable.tag_logo);
        mItems.add(nature);

        nature = new NatureItem();
        nature.setName("Iguazu Falls");
        nature.setDes("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt" +
                "ut labore et dolore magna aliqua. Ut enim ad minim veniam.");
        nature.setThumbnail(R.drawable.tag_logo);
        mItems.add(nature);

        nature = new NatureItem();
        nature.setName("Aurora Borealis");
        nature.setDes("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt" +
                "ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud.");
        nature.setThumbnail(R.drawable.tag_logo);
        mItems.add(nature);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.recycler_view_card_item, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int i) {
        NatureItem nature = mItems.get(i);
        viewHolder.tvNature.setText(nature.getName());
        viewHolder.tvDesNature.setText(nature.getDes());
        viewHolder.imgThumbnail.setImageResource(nature.getThumbnail());
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        public ImageView imgThumbnail;
        public TextView tvNature;
        public TextView tvDesNature;

        public ViewHolder(View itemView) {
            super(itemView);
            imgThumbnail = (ImageView) itemView.findViewById(R.id.img_thumbnail);
            tvNature = (TextView) itemView.findViewById(R.id.tv_nature);
            tvDesNature = (TextView) itemView.findViewById(R.id.tv_des_nature);
        }
    }
}

NatureItem
public class NatureItem {
    private String mName;
    private String mDes;
    private int mThumbnail;

    public String getName() {
        return mName;
    }

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

    public String getDes() {
        return mDes;
    }

    public void setDes(String des) {
        this.mDes = des;
    }

    public int getThumbnail() {
        return mThumbnail;
    }

    public void setThumbnail(int thumbnail) {
        this.mThumbnail = thumbnail;
    }
}

XML files are normal. RecyclerView in activity_main.xml and one xml for card view

A: Create listener for each "Card" as specified here.
As for opening different activity from different cards I would suggest each card (in this case "NatureItem") to keep Class of an activity that should be started.
You would be able to do:
Intent intent = new Intent(context, nature.getClass());
context.startActivity(intent);

A: In your adapter's ViewHolder class add this:
public ViewHolder(View itemView) {
    super(itemView);
    .....
    .....

    itemView.setOnClickListener(new View.OnClickListener(){
         // Start your activity
    });
}

A: NatureItem .java
class NatureItem {
    private String name;
    private String des;
    private int setThumbnail;
    private int activityType; //1...n
    //its methods
    public int getActivityType(){
        return activityType;
    }

    public void setSetThumbnail(int setThumbnail) {
        this.setThumbnail = setThumbnail;
    }

    public void setActivityType(int activityType){
        this.activityType = activityType;
    }

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

    public void setDes(String des) {
        this.des = des;
    }

    public String getName() {
        return name;
    }

    public String getDes() {
        return des;
    }

    public int getThumbnail() {
        return setThumbnail;
    }
}

ViewHolder.java
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    public ImageView imgThumbnail;
    public TextView tvNature;
    public TextView tvDesNature;
    Callbacks callbacks;
    View itemView;
    public interface Callbacks{
        public void onItemSelect(View v,int position);
    }
    public ViewHolder(View itemView,Callbacks callbacks) {
        super(itemView);
        this.itemView = itemView;
        this.callbacks = callbacks;
        imgThumbnail = (ImageView) itemView.findViewById(R.id.img_thumbnail);
        tvNature = (TextView) itemView.findViewById(R.id.tv_nature);
        tvDesNature = (TextView) itemView.findViewById(R.id.tv_des_nature);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(callbacks!=null){
            callbacks.onItemSelect(itemView,getAdapterPosition());
        }
    }
}

CardAdapter .java
class CardAdapter extends RecyclerView.Adapter<ViewHolder> {

    List<NatureItem> mItems;
    ViewHolder.Callbacks callbacks;

    public CardAdapter(ViewHolder.Callbacks callbacks) {
        super();
        this.callbacks = callbacks;
        mItems = new ArrayList<NatureItem>();
        NatureItem nature = new NatureItem();
        nature.setName("The Great Barrier Reef");
        nature.setDes("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt" +
                "ut labore et dolore magna aliqua. Ut enim ad minim veniam.");
        nature.setThumbnail(R.drawable.tag_logo);
        mItems.add(nature);

        nature = new NatureItem();
        nature.setName("Grand Canyon");
        nature.setActivityType(1); //activity type
        nature.setDes("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt" +
                "ut labore et dolore magna aliqua.");
        nature.setThumbnail(R.drawable.tag_logo);
        mItems.add(nature);

        nature = new NatureItem();
        nature.setName("Baltoro Glacier");
        nature.setActivityType(2);
        nature.setDes("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt" +
                "ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis.");
        nature.setThumbnail(R.drawable.tag_logo);
        mItems.add(nature);

        nature = new NatureItem();
        nature.setName("Iguazu Falls");
        nature.setActivityType(3);
        nature.setDes("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt" +
                "ut labore et dolore magna aliqua. Ut enim ad minim veniam.");
        nature.setThumbnail(R.drawable.tag_logo);
        mItems.add(nature);

        nature = new NatureItem();
        nature.setName("Aurora Borealis");
        nature.setDes("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt" +
                "ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud.");
        nature.setThumbnail(R.drawable.tag_logo);
        mItems.add(nature);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.recycler_view_card_item, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(v, callbacks);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int i) {
        NatureItem nature = mItems.get(i);
        viewHolder.tvNature.setText(nature.getName());
        viewHolder.tvDesNature.setText(nature.getDes());
        viewHolder.imgThumbnail.setImageResource(nature.getThumbnail());
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }
    public NatureItem getItem(int pos){
        return mItems.get(pos);
    }
}

MainActivity.java
class MainActivity extends AppCompatActivity implements ViewHolder.Callbacks{
    RecyclerView mRecyclerView;
    RecyclerView.LayoutManager mLayoutManager;
    CardAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);

        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mAdapter = new CardAdapter(this);
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onItemSelect(View v, int position) {
        NatureItem natureItem = mAdapter.getItem(position);
        if (natureItem.getActivityType() == 1) {
            //start this activity
        } else if (natureItem.getActivityType() == 2) {
            //start this activity
        }
    }
}


text:
Q: Jhipster - Failed to sign in I have included my jhipster .war into an ear with others multiples .war.
I succeeded to deploy it on my jboss 6.2 server and i can access to the application but i cannot sign in. I have this message : Failed to sign in! Please check your credentials and try again.
It works fine when i launch it alone (using the mvnw command with the command prompt).
Is it a problem with the application-dev.xml ? In this file i have a datasource configuration (url of database, username, password).
Do I need to remove this ? Because i have the same configuration in my application.xml in my ear-project. Or may be the problem comes from somewhere else.
Thanks for your help.
edit :
I can see the red banner which is written "development" when i start the application with mvnw because i started it with the dev profile.
But i cannot see the red banner now when i start my global application deploying on jboss server. So does it mean that it's running with the prod profile ?
I think the problem comes from the jboss server..

A: do you use ./mvnw -Pprod comand to generate war?
read this https://jhipster.github.io/production/

A: Check your database structure is correctly sync with your liquibase.
also check file

/src/main/resources/config/liquibase/changelog/00000000000000_initial_schema.xml


text:
Q: Django DRF: custom Permission: tokenauthentication: Why to use isAuthenticated for permission I have the following

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    )
}

How does DRF get the request.user
def hello_world(request):
    print(request.user)
    return Response()

I am trying
curl --location --request GET "http://127.0.0.1:8000/hello-world/" \
--header "Authorization:Token ssssss28acbd550a9806c6ac9ce13f1bbc73137" \
--header 'Content-Type: application/json'

so in the output i see the request.user is printed as per the token supplied i.e eg: test
Then what is the use of using isAuthenticated
It only checks whether Authentication header is provided or not
Why cant that be checked by tokenauthentication itself

A: To my understanding, token authentication is not a custom permission. Authentication and permission are 2 different things.
If you check out the DRF site https://www.django-rest-framework.org/api-guide/authentication/, they say:
Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The permission and throttling policies can then use those credentials to determine if the request should be permitted.
So authentication is the underlying mechanism of how you authenticate users, e.g. token authentication, session authentication etc ... Permission regulates whether a request should be granted based on the identifying credentials which were retrieved from the authentication mechanism.
So in your example, the default authentication mechanism uses tokens. This applies to all your views (unless you override this explicitly in a particular view). You then send a http request to the endpoint handled by the hello_world view. In this http request you supply a token in the header. The authentication mechanism will attempt to match this token with a unique django user model instance in the database. This happens through DRF's Request class which extends the standard django HttpRequest, an instance of which is passed to the hello_world view. If you delve into the source code, you can see that user in request.user has a property decorator:
@property
    def user(self):
        """
        Returns the user associated with the current request, as authenticated
        by the authentication classes provided to the request.
        """
        if not hasattr(self, '_user'):
            with wrap_attributeerrors():
                self._authenticate()
        return self._user

so that request.user triggers the authentication mechanism in the background if self._user hasn't been previously set and returns a django user model instance. I think this is roughly how DRF gets request.user.
To answer the second part of your question, again, token authentication only refers to the mechanism, it doesn't make any checks. So the use of isAuthenticated permission is to ensure only authenticated users, who have been authenticated by token authentication, are granted a successful response. Removing isAuthenticated would allow a user to receive a successful response without providing a token.


text:
Q: Windows CMD interpret code following alias Is it possible to get windows process some code after an alias in the cmd? Basically I want to do sth. like this:
doskey mysvn = D:\portableSVN\bin\svn.exe --config-dir D:\portableSVN\config
mysvn up
mysvn ci -m "message"

This does not work, after interpreting mysvn it just stops and I get:
Subcommand argument required
Type 'svn help' for usage.

Currently, I modify the PATHfor the session and use the standard config folder, but I would rather not have my credentials and proxy settings on every pc I use my portable svn on. Of course I can delete them afterwards, but still they are recoverable.
If necessary, it is also possible to execute batch files as long as they don't need admin rights.

A: Try with
doskey mysvn=D:\portableSVN\bin\svn.exe --config-dir D:\portableSVN\config $*

See doskey /? for more information


text:
Q: How to show text box in django Models.py
class AllUsers(models.Model):
    user_fullname = models.CharField(max_length=200)
    user_email = models.EmailField()
    dob = models.DateField()
    user_cv = models.FileField(upload_to = get_upload_file_name)
    user_department_id = models.ForeignKey(Department)
    user_FK = models.ForeignKey(User)
    coverletter = models.TextField() //THIS IS TEXT AREA

Forms.py:
class AllUsersForm(forms.ModelForm):
    dob= forms.DateField(widget=DateInput())
    class Meta:
        model = AllUsers

        fields = ('user_fullname','user_email','dob','user_cv','user_department_id',
                  'coverletter')

PROBLEM:

coverletter has text-field but so small to enter any text . why?

A: Try something like this
coverletter = forms.CharField(required=False,
              widget=forms.Textarea(
                # rows and colums of the textarea
                attrs={'rows': 4, 'cols': 40}))

A: You should specify widget for this field. It can be done in model:
coverletter = models.TextField(widget=forms.Textarea)

A: Here's an example that is similar to what I have in my forms.py for a textarea. Perhaps it might work for you as well.
class AllUsersForm(forms.ModelForm):
    dob= forms.DateField(widget=DateInput())
    class Meta:
        model = AllUsers

        fields = ('user_fullname','user_email','dob','user_cv','user_department_id',
                  'coverletter')

        widgets = {
            'coverletter': Textarea(attrs={'class': '???', 'rows': 5}),
        }

I believe the "rows:" declaration is what might make the textarea more visible for you.


text:
Q: Why Object is made static in Singleton pattern? Why is the Object made static in the Singleton pattern?
What is actual use of it?
What will happen if we don't make object static?
public class SingleObject {

   //create an object of SingleObject
   private static SingleObject instance = new SingleObject();

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}

   //Get the only object available
   public static SingleObject getInstance(){
       return instance;
   }

   public void showMessage(){
       System.out.println("Hello World!");
   }
}

A: You usually keep the single instance of the Singleton class in a static variable of that class. This doesn't make that instance static. Only the reference to it is static.
Since you can only obtain that single instance via a static method of the class (you can't explicitly construct instances of a Singleton class via a constructor - otherwise it wouldn't be a singleton), the reference to that instance must be stored in a static variable.

A: Just adding/elaborating eran's answer,since getInstance method is static method, getInstance method can be called from main methods/other methods by using classname i.e. SingleObject.getInstance(); This means you will never need an object reference to call getInstance()
If it would have been instance method , you would have needed an object to call getInstance. Now there is no way to create an object of class SingleObject outside the class (since constructor is private ) & this is the real trouble.
Conclusion 1:
This means we need to have a static method.
Conclusion 2:
SO NEED TO HAVE A STATIC METHOD, MAKES THE PROPERTY TO BE STATIC, since instance property is not available inside static method.

A:
What will happen if we don't make object static?

That means that the getInstance method will have to be non-static, because a static method can't refer to a non-static variable in the current class1.
But the getInstance method has to be static ... or this API design doesn't make sense2.

1 - ... unless it is passed a reference to the object, which won't work in this context.
2 - You would need the reference to the singleton instance in order to get the reference to the singleton instance.  But you can't create that instance because the class is private ... to stop someone making a 2nd instance.


text:
Q: Using composite key in AspNetUsers table in MVC 5 application I'm purposely not posting any code here as I'm really just looking for some guidance to the following problem:
I have created a three new fields in my AspNetUsers table - FirstName, LastName, and NickName. I also created a composite key using those three fields. When I try to create a new user that has all three of these fields the same, the application throws an error as expected when the unique rule is violated.
I would like it to simply post back to the Register User form indicating that the NickName must be changed to something else.
Do I need to implement a Custom User Store? Is there a simpler way?
Thank you for any suggestions.


text:
Q: How to decrease the value of a variable that you don't know in advance? I have a function that accepts a parameter. In order for this function to 'converge', this parameter must be lower a bit than its original value.
The problem is that the value of this parameter is unknown in advance. So one time it could be 0.01 and another 0.0000084662, so I'm unable to know in advance how much to subtract from it.
Is there an easy way to decrease this parameter without knowing its value in advance? It just needs to be decreased a bit. The parameter will always be in the range [0.0-1.0].
Edit:
it seems that doing it like param = param * 0.1 did the job!

A: If you are certain the parameter does not approach the limits of the type in which it is stored, just multiply by a number less then 1 (make the number closer to zero):
new_val = old_val * 0.99;  # new_val is 99% of old_val

If the sign is important, the following code decreases the number by 1%:
new_val = old_val - abs(0.01 * old_val);

A: Well, let's say a bit for you is 5%, then:
   def my_func(parameter):
       return parameter - (0.05 * parameter)


text:
Q: PayPal Payment Not Showing Up In Magento I'm using PayPal on a Magento 1.4.0.1 site. When a new order from a guest is placed using PayPal the order doesn't receive payment authorization.  The status remains at "pending".
This doesn't happen in all cases, we have plenty of PayPal orders that go through, so perhaps it's for users who didn't have PayPal accounts authorized or needed to add funds to them.  The customer information doesn't show up in PayPal either.
In the end we have a Magento order # with a status of pending waiting for a PayPal authorization that doesn't seem to be coming.  Any ideas?

A: You need to configure the IPN location of your Magento install within your Paypal configuration panel.
Source: https://www.paypal.com/ipn
What is an IPN?
From Paypal's manual pages:

Instant Payment Notification (IPN) is PayPal's message service that
  sends a notification when a transaction is affected. Once IPN is
  integrated, sellers can automate their back office so they don't have
  to wait for payments to come in to trigger order fulfillment.

Enabling in Paypal
The below instructions are from the Magento Wiki, and are intended for the Sandbox Developer site - however they would be applicable for your production site as well.

Go back to your Paypal Developer Account and login if necessary. Click
  on to "Test Accounts": Choose your "seller account" (this should be a
  premier account) Click the button to "Enter Sandbox Test Site" This
  will log you in as that user.
You need to go to Profile and turn on IPN (My Account>Profile)
Starting with Magento 1.4.0.0, the ipn url is now :
  http://www.yoursite.com/paypal/ipn/standard/, however since 1.4.1.0 it
  changed again to be just http://www.yoursite.com/paypal/ipn/
But in fact this is not important because magento passes the
  notify_url thru the API to Paypal and the notify_url parameter
  overrides the Paypal account IPN url. It is why if you have multiple
  websites on a single magento instance, it can work with one single
  Paypal account.

IPNs will send information about payment status and can move orders into different states/statuses depending upon the payment's decline/accept. You can configure a number of options in Paypal, such as the frequency of retries upon failure. If you have a business account with Paypal please give them a call and ask for Merchant Technical Services, they should be able to assist you with getting this set up if you feel the above is too technical.


text:
Q: Creating new C# version of existing COM object to use in Delphi program We had a bit of a problem where we have lost some source code for a very old ActiveX component we had. We've got a Delphi7 program that calls the Active X component. Thats a bit of a moster and can't be changed too much. However, some of the functionality in the Active X component needs to be updated. Since we've been moving our apps to C#, its been decided to redo the ActiveX as a C# class library.
I've got a basic C# class library working to prove the concept. I can hack the GUIDs and registry so it just looks liek the old one. If I look at the type lib for the old one and the new one, they are basically the same. Couple of slight differences but not anything i would have thought would be a problem.
Now as far as I can see there are three ways to use the new class library:

*

*Late binding by looking up the ProgId. This works ok.

*Import the type library. (Project| Import Type Library) This works ok.

*Import as an ActiveX component. This generates a tlb file. This doesn't work. When I go to create the component I get 'No such interface exists'. The class is loading to a point but not completely.
Now unfortunately, the Delphi program is using option 3. So I have to try to get my class library working in this circumstance. Any ideas how I get past that error? I googled and found some references but nothing that says what the problem is.
Second question. I should know how to do this since I've done it once but I seemed to have fluked it. When I am in Delphi I do an Import ActiveX component to generate a TLB file. Now the first C# class library  generated is showing up in the list of ActiveX controls and I can Create Unit for it. But I've created another simplier class library for testign purposes and damned if I can get the library to show in the list of ActiveX controls and so I can't import it.
The Create Unit for the Active X component generates a different format of TLB.pas to the Import Type Library format and its the ActiveX one that I require.

A: An ActiveX Control does way more then just implementing your interfaces. It is more like an TComponent or TWinControl. It requires you to implement a lot more ActiveX Control interfaces. Your C# object exposed through COM/ActiveX is not a Control, but a simple class.
It does not show up in Import ActiveX Control since it is not an ActiveX Control. I do not think it is feasible to make your C# class an Active Control.

A: Another possibility, although probably not the most elegant, would be to create a new ActiveX com object in Delphi which in turn calls your C# class by either method which you already have working.
Since you stated that this is for an existing Delphi 7 application, you might want to just use Com Interop on the C# side, expose the object as com visible, and the consume it directly from your Delphi 7 application.
The first option would probably allow you to get by with minimal changes to your existing application, but does add an additional layer that most likely is not necessary.


text:
Q: Updating Mule application through the mmc I'm trying to update an application in the evaluation version of Mule ESB EE.
I upload to repository, create a new deployment and start it.
But the server is still serving up the old .xml
I've tried stopping and starting the service, creating a new one with another name and whatnot but still no luck. Only thing that works is hot-deploying (drop the zip file into the directory) but that has the drawback of not showing up in the mmc.
Checking the Mulesoft forums yields one similar question that was posted 8 months ago (around october 2012) with no resolution.
Has anyone here run into this and knows of a fix?
Edit
I figured out a workaround:

*

*When exporting the project in Mule Studio, instead of "Publish to Application Repository" select "Mule Studio Project to Mule......" (the zip file)

*Using the mmc interface go to deployments tab, select repository and create new.

*Import the .zip file you just created and deploy as usual.

(Also added this answer to the Mulesoft forum question)

A: I guess the workaround is all there is so I'm marking this as solved with that as the solution
Workaround:

*

*When exporting the project in Mule Studio, instead of "Publish to Application Repository" select "Mule Studio Project to Mule......" (the zip file)

*Using the mmc interface go to deployments tab, select repository and create new.

*Import the .zip file you just created and deploy as usual.


text:
Q: Values aren't updating in AppDelegate I need to store ints and some floats to share between views, I know that doing so in the AppDelegate is faux pas but this is an introductory iOS course I'm taking and we haven't gotten very advanced at all, I mean AT ALL (no MVC paradigm, no Objective-C lessons, no Core Data, no errors we might encounter or how to handle them, etc).  My app is for servers in a restaurant, I have 6 views loaded as subviews from the app's ViewController with different items to order with '+' and '-' buttons to increase or decrease the quantity ordered.  In the AppDelegate I have int's and float's for each item quantity and the subtotal that I declared as properties.
Every the quantity of an item changes it calls a method to update the item counter, display the quantity, and update and display the subtotal for that view.  Within that method I also
make an instance (?) of the delegate so I can access the int and float properties I declared.
-(void)updateAppSubtotal{
    NSString *preSubString;
    NSString *subString;

    Final2AppDelegate* delegate = (Final2AppDelegate *)[[UIApplication sharedApplication]delegate];
    delegate.eggTotal = eggs;
    delegate.craTotal = crabs;
    delegate.capTotal = caps;
    delegate.quiTotal = quis;
    delegate.bruTotal = brus;
    delegate.pepTotal = peps;
    delegate.tarTotal = tars;
    delegate.balTotal = bals;
    delegate.appSubtotal = appSub;

    appSub = (eggs*eggPrice)+(crabs*crabPrice)+(caps*capPrice)+(quis*quiPrice)+(brus*bruPrice)+
(peps*pepPrice)+(tars*tarPrice)+(bals*balPrice);

    if(appSub < 10){
        preSubString = [[NSString alloc]initWithFormat:@"%1.2f",appSub];
    }else if(appSub < 100 && appSub >= 10){
        preSubString = [[NSString alloc]initWithFormat:@"%2.2f",appSub];
    }else if(appSub < 1000 && appSub >= 100){
        preSubString = [[NSString alloc]initWithFormat:@"%3.2f",appSub];
    }else{
        preSubString = [[NSString alloc]initWithFormat:@"%4.2f",appSub];
    }
    subString = [[NSString alloc]initWithFormat:@"$%@",preSubString];
    appSubtotal.text = subString;

    [preSubString release];
    [subString release];
}

Then on the view for the 'bill' I use this to (attempt) to populate the labels with the quantities and the subtotals:
- (void)viewDidLoad {

    NSString *preSubString;
    NSString *subString;
    NSString *preTaxString;
    NSString *taxString;
    NSString *preTotString;
    NSString *totString;

    Final2AppDelegate *delegate = (Final2AppDelegate *)[[UIApplication sharedApplication]delegate];

    subFloat = delegate.appSubtotal + delegate.bevSubtotal + delegate.entSubtotal + delegate.sidSubtotal +
delegate.desSubtotal;

    if(subFloat < 10){
        preSubString = [[NSString alloc]initWithFormat:@"%1.2f",subFloat];
    }else if(subFloat < 100 && subFloat >= 10){
        preSubString = [[NSString alloc]initWithFormat:@"%2.2f",subFloat];
    }else if(subFloat < 1000 && subFloat >= 100){
        preSubString = [[NSString alloc]initWithFormat:@"%3.2f",subFloat];
    }else{
        preSubString = [[NSString alloc]initWithFormat:@"%4.2f",subFloat];
    }
    subString = [[NSString alloc]initWithFormat:@"$%@",preSubString];
    billSubtotal.text = subString;

    taxFloat = subFloat*taxRate;
    if(taxFloat < 10){
        preTaxString = [[NSString alloc]initWithFormat:@"%1.2f",taxFloat];
    }else if(taxFloat < 100 && taxFloat >= 10){
        preTaxString = [[NSString alloc]initWithFormat:@"%2.2f",taxFloat];
    }else if(taxFloat < 1000 && taxFloat >= 100){
        preTaxString = [[NSString alloc]initWithFormat:@"%3.2f",taxFloat];
    }else{
        preTaxString = [[NSString alloc]initWithFormat:@"%4.2f",taxFloat];
    }
    taxString = [[NSString alloc ]initWithFormat:@"$%@",preTaxString];
    tax.text = taxString;

    totalFloat = subFloat + taxFloat;
    if(totalFloat < 10){
        preTotString = [[NSString alloc]initWithFormat:@"%1.2f",totalFloat];
    }else if(totalFloat < 100 && totalFloat >= 10){
        preTotString = [[NSString alloc]initWithFormat:@"%2.2f",totalFloat];
    }else if(totalFloat < 1000 && totalFloat >= 100){
        preTotString = [[NSString alloc]initWithFormat:@"%3.2f",totalFloat];
    }else{
        preTotString = [[NSString alloc]initWithFormat:@"%4.2f",totalFloat];
    }

    totString = [[NSString alloc]initWithFormat:@"$%@",preTotString];
    total.text = totString;

    eggFinalQty.text = [NSString stringWithFormat:@"%d",delegate.eggTotal];
    crabFinalQty.text = [NSString stringWithFormat:@"%d",delegate.craTotal];
    capFinalQty.text = [NSString stringWithFormat:@"%d",delegate.capTotal];
    quiFinalQty.text = [NSString stringWithFormat:@"%d",delegate.quiTotal];
    bruFinalQty.text = [NSString stringWithFormat:@"%d",delegate.bruTotal];
    pepFinalQty.text = [NSString stringWithFormat:@"%d",delegate.pepTotal];
    tarFinalQty.text = [NSString stringWithFormat:@"%d",delegate.tarTotal];
    balFinalQty.text = [NSString stringWithFormat:@"%d",delegate.balTotal];
    oldFinalQty.text = [NSString stringWithFormat:@"%d",delegate.oldTotal];
    vodkaFinalQty.text = [NSString stringWithFormat:@"%d",delegate.vodTotal];
    martiniFinalQty.text = [NSString stringWithFormat:@"%d",delegate.martTotal];
    redFinalQty.text = [NSString stringWithFormat:@"%d",delegate.redTotal];
    whiteFinalQty.text = [NSString stringWithFormat:@"%d",delegate.whiTotal];
    ipaFinalQty.text = [NSString stringWithFormat:@"%d",delegate.ipaTotal];
    oliFinalQty.text = [NSString stringWithFormat:@"%d",delegate.oldTotal];
    ribFinalQty.text = [NSString stringWithFormat:@"%d",delegate.ribTotal];
    ravFinalQty.text = [NSString stringWithFormat:@"%d",delegate.ravTotal];
    coqFinalQty.text = [NSString stringWithFormat:@"%d",delegate.coqTotal];
    bufFinalQty.text = [NSString stringWithFormat:@"%d",delegate.bufTotal];
    walFinalQty.text = [NSString stringWithFormat:@"%d",delegate.walTotal];
    cubFinalQty.text = [NSString stringWithFormat:@"%d",delegate.cubTotal];
    bleFinalQty.text = [NSString stringWithFormat:@"%d",delegate.bleTotal];
    sauFinalQty.text = [NSString stringWithFormat:@"%d",delegate.sauTotal];
    cacFinalQty.text = [NSString stringWithFormat:@"%d",delegate.cacTotal];
    souFinalQty.text = [NSString stringWithFormat:@"%d",delegate.souTotal];
    pesFinalQty.text = [NSString stringWithFormat:@"%d",delegate.pesTotal];
    temFinalQty.text = [NSString stringWithFormat:@"%d",delegate.temTotal];
    salFinalQty.text = [NSString stringWithFormat:@"%d",delegate.salTotal];
    lobFinalQty.text = [NSString stringWithFormat:@"%d",delegate.lobTotal];
    dreFianlQty.text = [NSString stringWithFormat:@"%d",delegate.dreTotal];
    marFinalQty.text = [NSString stringWithFormat:@"%d",delegate.marTotal];
    cheFinalQty.text = [NSString stringWithFormat:@"%d",delegate.cheTotal];
    fonFinalQty.text = [NSString stringWithFormat:@"%d",delegate.fonTotal];
    mouFinalQty.text = [NSString stringWithFormat:@"%d",delegate.mouTotal];
    pieFinalQty.text = [NSString stringWithFormat:@"%d",delegate.pieTotal];
    hazFinalQty.text = [NSString stringWithFormat:@"%d",delegate.hazTotal];
    briFinalQty.text = [NSString stringWithFormat:@"%d",delegate.briTotal];
    choFinalQty.text = [NSString stringWithFormat:@"%d",delegate.choTotal];
    iceFinalQty.text = [NSString stringWithFormat:@"%d",delegate.iceTotal];

    [preSubString release];
    [subString release];
    [preTaxString release];
    [taxString release];
    [preTotString release];
    [totString release];

    [super viewDidLoad];
}

But when the view loads all of the quantity labels for each item and the labels for tax, subtotal and total are all 0.  The values don't seem to be updating and I'm not sure why.  I had spoken to a friend of mine that took this class last semester (I'm doing a directed study for it so thank you so much everyone on StackOverflow for being my resource of information and ideas) and I'm doing pretty much the same thing he did.
Why aren't the values in delegate being updated?
F.Y.I. I have a similar update method for each view and each one uses Final2AppDelegate *delegate = (Final2AppDelegate *)[[UIApplication sharedApplication]delegate];.  Would this have something to do with it since there's multiple instances (?) of the delegate?

Edit

I had tried using the viewWillAppear and viewDidAppear methods also but no such luck.  I couldn't get the labels to be updated with a regular string either.  I made sure all of my connections were made but something still isn't working.  I'm thinking of just recreating the view for this because I had to redo the other views a couple days ago just to be sure, but I don't know how that would affect this.

Edit 2

So I made labels on the beverage view that update to the value of delegate.foo and it does seem that they are updating correctly and I used the same statements that I've been trying to get to work in the 'Bill' view to display the counts and that worked correctly too.  Is there something in the middle that is happening?  I'm going to try and add a new label on the appetizer view that updates with the count of one of the drinks to see if that will share data between the views.

Edit 3

Well that didn't work either (I don't know why I though it might) so there's obviously some trouble trying to access the data from different views.  Since all of my ViewControllers are just getting pointers to the same  instance every time I don't see how this would make a difference.  I can access the values in the view that I create them in but if I try from other views I just get 0.  Anyone have any more insight to shed some light on this?
Would maybe using the app's ViewController that all of the other views are subviews of instead of the AppDelegate make a difference?
Also I'm creating a new pointer to the AppDelegate every time the update method is called, which is every time one of the plus or minus buttons is pressed.  Would that affect it at all?

App View Controller Code

This is how I'm controlling the views.  I was thinking that the viewDid/WillAppear and viewDid/WillDisappear might not be getting called because of how it's controlled, but this is beyond me.  I know the code is longer than it has to be but at this point I'm just trying to get this project done and be done with this directed study!  :D
-(IBAction)loadBeverageView:(id)sender{
    [self clearView];
    [self.view insertSubview:beverageViewController.view atIndex:0];
}

-(IBAction)loadAppetizerView:(id)sender{
    [self clearView];
    [self.view insertSubview:appetizerViewController.view atIndex:0];
}

-(IBAction)loadEntreeView:(id)sender{
    [self clearView];
    [self.view insertSubview:entreeViewController.view atIndex:0];
}

-(IBAction)loadSideView:(id)sender{
    [self clearView];
    [self.view insertSubview:sideViewController.view atIndex:0];
}

-(IBAction)loadDessertView:(id)sender{
    [self clearView];
    [self.view insertSubview:dessertViewController.view atIndex:0];
}

-(IBAction)loadBillView:(id)sender{
    [self clearView];
    [self.view insertSubview:billViewController.view atIndex:0];
}

-(void)clearView{
    if(beverageViewController.view.superview){
        [beverageViewController.view removeFromSuperview];
    }else if(appetizerViewController.view.superview){
        [appetizerViewController.view removeFromSuperview];
    }else if(entreeViewController.view.superview){
        [entreeViewController.view removeFromSuperview];
    }else if(sideViewController.view.superview){
        [sideViewController.view removeFromSuperview];
    }else if(dessertViewController.view.superview){
        [dessertViewController.view removeFromSuperview];
    }else{
        [billViewController.view removeFromSuperview];
    }
}

A: Your problem is probably that you are attempting to update your bill view in viewDidLoad. If you've already loaded that viewController or added it to a tab bar controller or whatever then viewDidLoad will not be called again - this is only called once, when your view controller has finished loading its views from a nib (or manually).
To update a view when it is presented by another controller, viewWillAppear is the standard method to use, though this won't be called if you are swapping views the way you do in your question.  If your aim is just to get this nightmare over with, you could just manually call viewWillAppear (not sure if that has any side effects), or put your update logic into a new method and call that each time you present one of your views.
You can see this for yourself by adding log statements or setting breakpoints in various methods. This will tell you when various methods are actually executed.
Also, your calling of the app delegate is fine - you are not creating new instances, just getting pointers to the same instance each time.
I hope you've only wasted time on this course, and not any money!


text:
Q: Волшебный запрос который роняет Apache Работаю локально(OpenServer) через Idiorm, и вот такой запрос роняет Apache

select cards.uid, cards.balance, cards.expires_at, profiles.name, profiles.gender, profiles.phone, profiles.email, profiles.send_sms, profiles.send_email, profiles.birthday, cards.is_activated as act, cards.is_blocked as block
from cards left join profiles on profiles.id = cards.profile_id
where cards.client_id = 4

Месяца полтора назад, тоже такая ситуевина была-запрос ложил на лопатки Apache,чуть поизвращавшись сделал другой запрос который работал нормально.
Логи апача пусты-молча в даун уходит.
Может кто объяснить в чем прикол? Я просто не понимаю в чем дело

A: причины падения могут быть разные, по моему мнению наиболее вероятна просадка по памяти апача или мускуля, для того что бы понять советую использывать функцию для анализа плана (explain), и еще поглядеть надо в логи апача, что ему конкретно не нравится и там уже копать подробнее.

A: Слово block зарезервировано, используйте тильды или поменяйся алиас
https://dev.mysql.com/doc/refman/5.7/en/keywords.html


text:
Q: Choosing up a Ruby / rails enviroment under windows 8 I am a junior programmer and beginning web developer seeking to build a reasonable developement enviroment under windows 8. I bought a new computer a few days ago and for a bunch of different reasons i'm stuck in Win8 for a while to come (let's not get into the specifics of that).
From what I have found on the net, developing in the middle of Windows is at best not worth it, so I'm seeking to set some kind of VM running a unix system. I can hanlde the setup itself, but i'm a bit lost at what ind of VM-ware system i should set up.
I want a unix (i'm thinking Fedora) system with packet manager and terminal but also a graphical text editor and the option of storing(using) files on my windows filesystem.
Do anyone have a suggestion about what kind of system i should consider?
Thanks in advance.

A: Ruby on Windows is ok, but VM is the way to go.
Here's my write up on how to get VM on Windows
Go all the way down to the section on Windows.
Once you install Ubuntu VM on Windows, follow the Ubuntu section in getting Ruby.

A: Vagrant is what you want. They changed the logo from an actual vagrant to a synthetic V :-(


text:
Q: Angular JS ng-repeat consumes more browser memory I have the following code

Id	Name	Ratings

    {{user.id}}
    {{user.name}}

{{item.rating}}

users is an array of user objects with only id and name. number of user objects in array - 150
items is an array of item objects with only id and rating. number of item objects in array - 150
When i render this in browser, it takes about 250MB of heap memory when i tried profiling in my chrome - v23.0.1271.95.
I am using AngularJS v1.0.3.
Is there an issue with angular or am i doing anything wrong here?
Here is the JS fiddle
http://jsfiddle.net/JSWorld/WqSGR/5/

A: Well it's not the ng-repeat per se. I think it's the fact that you are adding bindings with the {{item.rating}}.
All those bindings register watches on the scope so:

*

*150 * 2 = 300(for the 2 user infos)

*150 * 150 = 22500(for the rating info)

*Total of 22800 watch functions + 22800 dom elements.

That would push the memory to a conceivable value of 250MB
From Databinding in angularjs

You can't really show more than about 2000 pieces of information to a
  human on a single page. Anything more than that is really bad UI, and
  humans can't process this anyway.

A: I want to say the leak is in the second array because you are potentially looping through the same array and displaying every item for every user row in users so depending on how large your test data is that view could get rather large. I could do a little more investigating. btw your fiddle is something entirely different.

A: Right now you are looping through 150 X 150 = 22500 items. And registering a watch (or through a directive just adding item rating) to each one.
Instead - consider adding the user's rating to the user object itself. It will increase the size of each user object but you will only loop through 150 items and register watches only on them.
Also - consider looking into Indexes. It's apparent that there could be similar users or item ratings. Just index them, so instead of looping through heavy objects, you can reduce them.
One more thing - if you are going to be running the directive the same instance, at least change the code:
var text = myTemplate.replace("{{rating}}",myItem.rating);

to a concat style string calculation:
var text = '
' + myItem.rating + '
';

This will save you a HUGE chunk on calculation. I've made a JSperf for this case, notice the difference, it's about 99% faster ;-)


text:
Q: ipad - sliding menus on a view based app I have a view based app and I would like to implement one of those sliding menus (I don't know if there's a specific name to call them), like Mail.
The idea is this: I have a board with several objects. When the user taps and hold on a object for half a second a popover appears showing the object properties. The properties are: object color, object text, object text color and object shadow color.
Every of these 4 properties, when tapped, will make a new window slide from right into the popover, bringing the adjustments. Tap done and the view is pushed to the right bringing the first view again... the process repeats for all views.
how do I add these "sliding menus" to a view based app inside a popover?
thanks in advance

A: Are you talking about iPhone or iPad? Your tag is only for iPhone.
On the iPad, there's a specific UI element called a Popover. When you click on the "Reply" icon in Mail, a menu appears with "Reply" and "Forward". This is a Popover. On iPhone, there's another kind of UI element, used for example when you want to copy text. It shows "Select", "Cut" and so on. That's called a Callout. Note that you can't use Popovers on the iPhone.
If you're talking about Mail on the iPhone, you have to find out how to use a UINavigationController, and then use the method -pushViewController:animated: to make a new page slide onto the screen.

A: its the default animation for UINavigationController. so if you implement a UINavigationController as your root view for your UIPopoverController, then push the view controllers you want, it should be the desired effect.

A: .h
IBOutlet UIScrollView *scrollView;

@property ( nonatomic , retain )  IBOutlet UIScrollView *scrollView;

-(void)AppleVijayAtFacebookDotCom:(id)sender;

-(void)createMenuWithButtonSize:(CGSize)buttonSize withOffset:(CGFloat)offset noOfButtons:(int)totalNoOfButtons;

.m
@synthesize scrollView;

-(void)AppleVijayAtFacebookDotCom:(id)sender{

    NSLog(@"AppleVijayAtFacebookDotCom called");

    UIButton *button=(UIButton *)sender;

    if (button.tag == 0) {

        NSLog(@"hey have clicked first button, this is my tag : %i \n\n",button.tag);
    }
    else if (button.tag == 1) {

        NSLog(@"hey have clicked second button, this is my tag : %i \n\n",button.tag);

    }
    // ......like this

    NSLog(@"button clicked is : %iBut \n\n",button.tag);

}

-(void)createMenuWithButtonSize:(CGSize)buttonSize withOffset:(CGFloat)offset noOfButtons:(int)totalNoOfButtons{

for (int i = 0; i < totalNoOfButtons; i++) {

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    [button addTarget:self action:@selector(AppleVijayAtFacebookDotCom:) forControlEvents:UIControlEventTouchUpInside];

        //[button1 setImage:[UIImage imageNamed:@"Button.png"] forState:UIControlStateNormal];//with image

        //OR

    [button setTitle:[NSString stringWithFormat:@"%iBut",i] forState:UIControlStateNormal];//with title

    button.frame = CGRectMake(i*(offset+buttonSize.width), 8.0, buttonSize.width, buttonSize.height);

    button.clipsToBounds = YES;

    button.showsTouchWhenHighlighted=YES;

    button.layer.cornerRadius = 10;//half of the width

    button.layer.borderColor=[UIColor redColor].CGColor;

    button.layer.backgroundColor=[UIColor blackColor].CGColor;

    button.layer.borderWidth=2.0f;

    button.tag=i;

    [self.scrollView addSubview:button];

}

self.scrollView.contentSize=CGSizeMake((buttonSize.width + offset) * totalNoOfButtons, buttonSize.height);

    //self.navigationItem.titleView=self.scrollView;//if u have navigationcontroller then enable this line

}
Dont forget to connect the scrollView in interface builder
while creating the scrollview in IB make sure ur scrollView height is 44.which is default to navigation bar.so it will look nice.
in viewDidLoad call

[self createMenuWithButtonSize:CGSizeMake(70.0, 30.0) withOffset:20.0f noOfButtons:30];

OUTPUT


text:
Q: Max Date based on Date & TimeStamp Can someone help for the below issue in R
DF1:
Item   Date
A      2020-04-08 03:36:28
B      2020-04-08 05:16:28

Output:
Item   Date
B      2020-04-08 05:16:28

Here, maximum date along with timestamp should be selected.

A: perhaps this works:
library(tidyverse)
now <- Sys.time()
#"2020-04-16 18:04:30 BST"
now2 <- as.POSIXlt(now)
now <- Sys.time()
now3 <- as.POSIXlt(now)
# [1] "2020-04-16 18:06:23 BST"
df <- data.frame(group = c("a", "b"),
                 time = c(now2, now3))
str(df)

df %>%
  slice(which.max(time))
#   group                time
# 1     b 2020-04-16 18:06:23

OR if you have character variable, convert first with as.POSIXct
df <- data.frame(group = c("a", "b"),
                 time = c("2020-04-08 03:36:28", "2020-04-08 05:16:28"))
df <- df %>%
  mutate(time2 = as.POSIXct(time)) %>%
  select(-time)

df %>%
  slice(which.max(time2))
#   group               time2
# 1     b 2020-04-08 05:16:28

A: In base R, we can do
DF1[which.max(DF1$Date),, drop = FALSE]


text:
Q: Obtain Inner JSON Array Values I'm attempting to get the values for the "filterInputParameters" array within the serviceResponseValue map.  Right now I have attempted to iterate through the map but could only obtain the first level of data such as the displayName and I need to go one-two levels deeper for the values in filterInputParamters array.  Please let me know if you need more information.
Dart Code:
var jsonString = response;

   var dropDown = querySelector("#asset");

   Map jsonObject = JSON.decode(jsonString) as Map;
       dropDownList = jsonObject["serviceResponseValue"] as List<Map>;

   LinkedHashMap<String, Map> dataMap = new LinkedHashMap<String, Map>();

//the one causing issues and returning null
     var ddValues2 = dropDownList
       //extract the 'displayValue'
       .map((e2) => e2['filterInputParameters']['value']);
       //create a set to eliminate duplicates
       //.toSet().toList()
       //sort the result
       //..sort();

       ddValues2.forEach((e2) {
         print(e2);

       });

A: Map jsonObject = JSON.decode(jsonString) as Map;
print(jsonObject["serviceResponseValue"][0]["filterInputParameters"]);

In JSON [ ] indicate a List and { } a Map.
You access a list element by passing a numeric index (xxx[5] to get the 6th item)
and a String to access a Map item (xxx["serviceResponeValue"]).
Your JSON starts with
 {  // the outer element is a map
   "serviceResponseValue":[  // this map item can be accessed with a
                             // string index"serviceResponseValue"
                             // after the colon `:` starts the associated value, a list
                             // the first item can be accessed using [0]
      {  // which contains a map

...
       "filterInputParameters":[  // this item of the map is returned by ["filterInputParameters"]
          {
             "id":"8a4984e047d0e40d0147d0e410020008",


text:
Q: codeigniter php change table orientation to vertical How can change dthe table orientation from horizontal to vertical?
example
$this->table->set_heading('Name', 'Surname');
$tabClient = $this->table->generate($client);
echo $tabClient;

provide
Name   Surname
Mark   Mark
Greg   Greg

its possible to change to:
Name    Mark Greg
Surname Mark Greg

A: Change it like this:
    //assuming your clients array is in this structure
    $clients = array(
        array("John", "Doe"),
        array("Jane", "Smith"),
    );

    $this->load->library('table');
    $fnames[] = "Name";
    $lnames[] = "Surname";
    foreach ($clients as $client) {
        $fnames[] = $client[0];
        $lnames[] = $client[1];
    }

    $this->load->library('table');
    $this->table->add_row($fnames);
    $this->table->add_row($lnames);

    $tabClient = $this->table->generate();
    echo $tabClient;


text:
Q: phpstorm xdebug eval fatal error on breakpoint cakephp I have phpstorm 6.02 setup and configured for xdebug on osx (mountain lion) apache with a cakephp application.
If I set a breakpoint in my "AppController" it stops no problem and works.
When I setup a breakpoint in my UsersController, it doesnt stop and I see this error in my logs:
2013-06-02 15:07:16 Error: I GOT HERE TO INDEX FUNCTION
2013-06-02 15:07:16 Error: current url is :/users
2013-06-02 15:07:16 Error: Fatal Error (4): parse error in [xdebug eval, line 1]
2013-06-02 15:07:16 Error: [FatalErrorException] parse error
Request URL: /users
Stack Trace:
#0 /Users/joelnylund/Sites/solutionstreet_maa/cakephp/lib/Cake/Error/ErrorHandler.php(184): ErrorHandler::handleFatalError(4, 'parse error', 'xdebug eval', 1)
#1 [internal function]: ErrorHandler::handleError(4, 'parse error', 'xdebug eval', 1, Array)
#2 /Users/joelnylund/Sites/solutionstreet_maa/cakephp/lib/Cake/Core/App.php(926): call_user_func('ErrorHandler::h...', 4, 'parse error', 'xdebug eval', 1, Array)
#3 /Users/joelnylund/Sites/solutionstreet_maa/cakephp/lib/Cake/Core/App.php(899): App::_checkFatalError()
#4 [internal function]: App::shutdown()
#5 {main}

Any ideas what could be causing this and what I can do to fix it?
NOTE: I updated my xdebug to the latest rev (2.2.3) and now I dont get this error, but I also dont get a stop at any breakpoints.

A: I'm assuming you have turned on xdebug in the browser and the page shows a green bug. Also, that phpstorm is showing the green telephone icon and the port is setup correctly in the settings for xdebug in phpstorm?
Have you tried also setting breakpoints sooner in the flow? It seems like it's erroring before your breakpoint possibly.
Set a breakpoint at
/Users/joelnylund/Sites/solutionstreet_maa/cakephp/lib/Cake/Core/App.php line 899 and see if that breaks.

A: I strongly recommend you to update PHPStorm, they released 8.0.x already. Anyways your last information sounds like you misconfigured Xdebug in your webservers configuration or use the wrong xdebug-library (xdebug libs must match with php-version in order to work)
Since recent versions of PHPStorm, you will see a popup asking to "connect" while browsing with active xdebug cookie and enabled debug-mode in PHPStorm. If that popup occurs your configurations and libs are fine.
There is a wide range of possible failures to cause xdebug not working properly. Thats why, in case of errors, you always might run a simple test, with a rudimentary "index.php" in your webservers root directory to ensure everything is working around your application.
After all, if your xdebug-configuration is correct and it is still not breaking, your breakpoint presumably wont be passed due to program termination or any other code-related processess such as "return;".


text:
Q: Can't click on the POI i put on a Forge viewer Hi i tried a forge viewer with some point of interest to put iot on it. me program is in react.

here's my code poiExtension.js here we have all the poi's called by a json (x,y,z):
    let Autodesk = window.Autodesk;
let THREE = window.THREE;

// Extension Three.js pour afficher des points d'intérêts sous la forme de billboards de taille fixe faisant face à la caméra
// NB: Ne fonctionne bien qu'en mode perspective
class POIExtension extends Autodesk.Viewing.Extension {
    constructor(viewer, options) {
        super();
        this.viewer = viewer;
        var texture = THREE.ImageUtils.loadTexture("img/icone_pointeur.png");
        this.selectedMaterial = new THREE.MeshBasicMaterial( { map: texture, transparent: true, alphaTest: 0.5, color: 0xFF0000 } );
        this.defaultMaterial = new THREE.MeshBasicMaterial( { map: texture, transparent: true, alphaTest: 0.5, color: 0x00FF00 } );
        this.loaded_poi = [];
        this.planeGeometry = new THREE.PlaneGeometry(0.6, 1, 1, 1);
        this.spriteScaleFactor = 0.8;
        this.spriteAltitude = 15.0;
    }

    load () {
        let self = this;
        this.viewer.addEventListener(Autodesk.Viewing.CAMERA_CHANGE_EVENT,
            (event) => {
                this.animate(self);
            }
        );
        return true
    }

    unload () {
        return true
    }

    setSettings(settings) {
        const scale = 1.0 / 255.0;
        this.selectedMaterial.color.setRGB(
            settings.selectedPointColor[0] * scale,
            settings.selectedPointColor[1] * scale,
            settings.selectedPointColor[2] * scale);

        this.defaultMaterial.color.setRGB(
                settings.defaultPointColor[0] * scale,
                settings.defaultPointColor[1] * scale,
                settings.defaultPointColor[2] * scale);

        this.spriteScaleFactor = settings.spriteScaleFactor;
        this.spriteAltitude = settings.spriteAltitude;
    }

    clearAllPOI () {
        this.loaded_poi.map((poiParticle) => {
            this.viewer.impl.scene.remove( poiParticle.mesh );
        });
        this.loaded_poi = [];

    }

    createPOI (poi, isSelected) {
        let poiParticle = {
            poi: poi,
            mesh: new THREE.Mesh(this.planeGeometry, isSelected === true ? this.selectedMaterial : this.defaultMaterial)
        }
        this.loaded_poi.push(poiParticle);
        poiParticle.original_position = {
            x: poi.x,
            y: poi.y,
            z: poi.z
        }
        poiParticle.mesh.position.set(poi.x, poi.y, this.spriteAltitude);
        this.viewer.impl.scene.add(poiParticle.mesh);
        this.viewer.impl.sceneUpdated(true);
        this.animate();
    }

    animate() {
        // THIS IS A HUGE HACK REQUIRED BECAUSE SOME STATE IN FORGE I'SNT SET CORRECTLY IN SOME BROWSER
        if (this.hacked === undefined) {
            this.viewer.toolbar._controls[1];
            let menu_1 = this.viewer.toolbar._controls[2];
            if ((menu_1 !== undefined) && (menu_1._controls!== undefined)) {
                let menu_2 = menu_1._controls[0];
                if ((menu_2 !== undefined) && (menu_2.subMenu !== undefined) && (menu_2.subMenu._controls !== undefined)) {
                    menu_2.subMenu._controls[2].onClick();
                    this.hacked = true;
                }
            }
        }
        // END HACK

        this.loaded_poi.map((poiParticle) => {
            var vec = new THREE.Vector3();
            var defaultDepth = 10;

            poiParticle.mesh.scale.x = poiParticle.mesh.scale.y = poiParticle.mesh.scale.z = this.spriteScaleFactor * vec.setFromMatrixPosition( poiParticle.mesh.matrixWorld ).sub( this.viewer.impl.camera.position ).length() / defaultDepth;
            poiParticle.mesh.position.set(poiParticle.original_position.x, poiParticle.original_position.y, poiParticle.original_position.z );

            poiParticle.mesh.quaternion.copy( this.viewer.impl.camera.quaternion );
            this.viewer.impl.scene.updateMatrixWorld(true);
        });
    }
}

export default POIExtension;

And here's is my poiList.js (the clickable list on the right):
    import React, { Component } from 'react';
import './poiList.css';

// Composant react affichant la liste des points d'intérêts
// C'est ce composant qui communique avec l'extension POI
class PoiList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            poi: [],
            selectedPoi: undefined,
            settings: {
                defaultPointColor: [61, 183, 255],
                selectedPointColor: [37, 27, 255],
                defaultPointTransparancy: 0.4,
                spriteScaleFactor: 0.8,
                //altitude par défaut
                spriteAltitude: 15.0
            }
        };
    }

    componentDidMount() {
        fetch('/settings')
            .then(response => {
                if (!response.ok) {
                    console.log(`status ${response.status}`);
                    throw new Error(`status ${response.status}`);
                }
                return response.json();
            })
            .then(json => {
                this.setState({
                    settings: json
                });

            })
            .catch(e => {
                console.log(`Settings call failed: ${e}`);
                this.setState({
                    message: `Settings call failed: ${e}`
                });
            })
        fetch('/poi')
            .then(response => {
                if (!response.ok) {
                    console.log(`status ${response.status}`);
                    throw new Error(`status ${response.status}`);
                }
                return response.json();
            })
            .then(json => {
                this.setState({
                    poi: json.poi
                });

            })
            .catch(e => {
                console.log(`POI call failed: ${e}`);
                this.setState({
                    message: `POI call failed: ${e}`
                });
            });
    }

    render() {
        if(this.props.poiExtension !== undefined) {
            this.props.poiExtension.clearAllPOI();
            this.props.poiExtension.setSettings(this.state.settings);
        }
        let self = this;
        let poiList = [];
        let index = 0;
        this.state.poi.map((poi) => {
            if(this.props.poiExtension !== undefined) {
                this.props.poiExtension.createPOI(poi, this.state.selectedPoi === poi);
            }
            let colorState = index % 2 === 1 ? "lightgrey" : "";
            colorState = this.state.selectedPoi === poi ? "selected" : colorState;
            let classC = "poiEntry " + colorState;
            let poiItem = (

 {
                    self.setState({
                        selectedPoi: poi,
                    });
                }}>
                    {poi.type} ({poi.x}, {poi.y}, {poi.z})

            );
            index++;

            poiList.push(poiItem);
        })

        return(

BATIMENT E17

                    { poiList }

        );
    }
}

export default PoiList;

i don't know how to do it....then if someone can help me i'll be very happy :)

A: Looks like your issue does not really has to do with Forge or Viewer.js but...
If by "can't click on POIs" you meant when you clicked on a POI's DIV nothing happens (no highlight visible) then Redux serialize your states so the way you test whether the current selectedPOI is selected won't work - use a serializable key (ID string etc) to identify your POIs:
colorState = this.state.selectedPoi.id === poi.id ? "selected" : colorState;


text:
Q: Android won't use my long (wide aspect ratio) drawable images on long devices I have a multi-page app that is working great except for image loading. Each page has a fullscreen image. I have 5 drawable folders -- the default one without any page images in it and then these four:

*

*drawable-long

*drawable-notlong

*drawable-long-xhdpi

*drawable-notlong-xhdpi
My app is set to only landscape. The image files in notlong are 4x3 aspect ratio. In long they are 16x9 aspect ratio.
On the Nexus 7 and 5, both devices report a screen type of long yet use the 4x3 images from drawnble-notlong-xhdpi. How can I get them to use the long images?
If I remove the two notlong folders, on app startup I get a NotFoundException on the image resource (which crashes the app).
I did add the equivalent layout views but still the 4x3 image is being displayed.

A: This is a duplicate of Android resource notlong / long identifiers not working as it turns out there was a bug -- my code telling me if the screen was long or not was wrong. For a Nexus 7, 1920/1200 = 1.6 which is less than the 1.667 ratio that triggers the long view as mentioned in the linked to Q&A. So Android is working correctly however the normal aspect ratio can be quite a ways from 4x3 so one has to take that into account.


text:
Q: Unable to store value in the model instance that has retrieved from model form I a m new to django. I have been trying the following:
I have a form that is associated with the model.
Form Name: ContactForm
Model Name : Contact
in view.py
if request.method == 'POST':
    form = ContactForm(request.POST)
    mInstance = form.save()
    mInstance.trackerID = 23232;  **// This value is not being stored in the database?**
    mInstance.save()

I have been struggling with quite some time. Kindly advice where i am committing mistake?
I checked with database, trackerID is always empty.

A: you should try:
if request.method == 'POST':
    form = ContactForm(request.POST)
    mInstance = form.save(commit=False)
    mInstance.trackerID = 23232;
    mInstance.save()

Note the commit=False parameter.
More info:
https://docs.djangoproject.com/en/1.6/topics/forms/modelforms/#the-save-method


text:
Q: Исчезает операционная система У меня была Windows 10 на ноутбуке, решила установить Linux. Сделала загрузочную флешку, всё хорошо установилось.
После первого перезапуска всё было окей, после второго ОС исчезла. Переустанавливала несколько раз, она всё время исчезала.
Думала, что это что-то с Linux и решила поставить Windows 10 назад. Установила (всё прошло успешно, я это делаю не впервые, поэтому уверена, что всё сделала правильно), но после перезапуска она также исчезла. В BIOS её нет, при включении ноутбука пишет, что не найдена ОС и нужно нажать Сtrl+Alt+Delete  для перезапуска.
Подскажите, как решить эту проблему?


text:
Q: tree code giving wrong output. logic error https://jsfiddle.net/mikeyounes/4ndtmaun/1/
https://api.myjson.com/bins/5a9vo
i am using an html and jquery code to take json nested objects and output them as a tree. its working. the problem is that the nodes arent coming out in their right place. for example, a node is coming out as a child instead of being a sibling. i believe the error is in this function. i can give u the whole code and the json but when im posting it im not getting any help, theyre too long maybe. been stuck for long on this, would be appreciated if u checked it out.
function traverse(node, o) {
    for (var i in o) {
        if(i == "__text" || i == "_href") {
            continue;
        }

        if (o[i] !== null && typeof(o[i])=="object") {
            if(o[i].__text) {

                var ul = $("<ul>").appendTo(node)
                var node=$('<li>').appendTo(ul)

                if(o[i]._href) {
                    var n = $("<span>").appendTo(node)
                    $(n).text(o[i].__text).attr("href", o[i]._href)
                } else {
                    $(node).text(o[i].__text)
                }
            }
        } traverse(node,o[i]);
    } else {
        var ul = $("<ul>").appendTo(node)
        if(o[i].__text) {
            var li = $('<li>' + o[i]._text + '<\/li>').appendTo(ul)

            if(o[i]._href) {
                var n = $("<span>").appendTo(node)
                $(n).text(o[i].__text).attr("href", o[i]._href)
            }
        } else {
            $('<li>' + o[i] + '</li>').appendTo(node)
        }
    }
}

A: First of all, the code you posted here does not compile. Second of all, it differs from the code you provided via jsfiddle.net and that one does compile. Thus, probably an edit is in order.
Second of all, in the code you provided via jsfiddle.net, move var ul = $("<ul>").appendTo(node) to right before entering the for loop. This is necessary because all the children of a parent node should be place in the same ul tag. I think that should do it.
Also, naming a local variable as one of the function parameters is misleading and can lead to logical errors while implementing an algorithm (see the local variable node), though it does seem to have caused problems in this particular case.


text:
Q: How to hide 0 notification count in django-notifications-hq I ham trying to hide the notification count when it's 0 in django-notifications-hq
I have tried the below method but it is not updating regularly and displaying the number correctly.
 {% live_notify_badge as nc %}
                      {% if nc > 0|add:0 %}

                      {% live_notify_badge %}
                      {% endif %}

A: nc is not the number of notifications. It generates some HTML that will make Javascript calls to fetch the number of notifications.
You can obtain the number of unread notifications in the template with:
{{ user.notifications.unread.count }}

So we can check if an unread notification exists, and use this to render the {% live_notify_badge %}:
{% if user.notifications.unread.exists %}

        {% live_notify_badge %}

{% endif %}
Note however that this will be rendered at server side, so that means that when the user fetches the page, and there are no notifications, it will not display the badge. If however later there are notifictions these will not be rendered.


text:
Q: PHP date format issue using strtotime() I am using
$jsdate = date("Y, m, d", strtotime('-1 month', (strtotime($date))));

to convert my dates from
2011-03-28
to
2011, 02, 28

Problem is this is producing unpredictable results. For example today I got
2011-03-28
converted to
2011, 02, 28  // OK

 AND

2011-03-29
to
2011, 03, 01 // not OK!

Does anyone know what's wrong here? I wonder if the calculation is inaccurate because of the -1 month.
Is there a way of simply subtracting 1 from m in ...date("Y, m, d", ...?
MORE INFO:
My data needs to be formatted as JavaScript Date Object in which January is 0, Feb is 1, etc. Therefore there is not a need to specifically subtract 1 month but actually subtract 1 from the month integer. At the end, the resulting string is not supposed to be 1 month earlier, but actually the same date, represented using JS Date Object style. I believe @vprimachenko's answer below is a good solution. I apologize if this wasn't clear in my OP.
Thanks!

A: you might use
$datee = explode('-',$date);
if($datee[1]-- < 0) {
    $datee[1]=12;
    $datee[0]--;
}
$jsdate = implode(', ',$datee);

A: strtotime might work in an unexpected way but it is logical
strtotime('-1 months',strtotime('2011-03-29')  // is 2011-02-29
date('Y-m-d','2011-02-29'); //gets converted to the next real date

Here is one kind of fix
http://www.phpreferencebook.com/tips/fixing-strtotime-1-month/

A: The calculation isn't inaccurate, per se. There is no 2/29/2011. If you change your input to 3/29/2012, you'll see that it returns 2/29/2012, because 2012 is a leap year. The same would happen with using something like 7/31/2011. June only has 30 days, so July 31 minus one month would be July 1 (because June 31 doesn't exist).
You could just extract the month, subtract 1, and remake the date, but that will result in attempting to make dates that don't exist.
If you really need the corresponding day of the prior month, you'll probably need to do an if statement of something along the lines of the following to make the day roll back to the last day of February:
$jsdate = date("Y, m, d", strtotime('-1 month', (strtotime($date))));
if($month == '3') {
   $jsdate = date("Y, m, d", strtotime('-1 day', (strtotime($jsdate))));
}

You'll also have to account for the rest of the days in March that February doesn't have, as well as leap years, and do something similar for 31-day months that follow 30-day months.


text:
Q: Replace certain words with link, but exclude word that already in a link I wanted to use regex/string replace function in PHP so I can replace certain keyword with links:
Say there is a string: `

"Hello guys I want to ask a programming questions."

The output should be

"Hello guys I want to ask a programming questions."

It sounds like something can be easily done with regex/string functions, however, I found out that if there is already a link in the string, like:

"Hello guys I want to ask a programming related questions."

The normal regex/string replace function will make it:

"Hello guys I want to ask a programming related questions."

Note that there is a "" inside another  tag.  What should I do so if the string, say "programming" is already in a link, it won't convert it? Is it possible?
Thanks!

A: try to use negative assertion

Lookbehind assertions start with (?<= for positive assertions and (?< ! for negative assertions for negative assertions
Lookahead assertions start with (?= for positive assertions and (?! for negative assertions

examples:

http://www.ibm.com/developerworks/library/os-php-regex2/
http://sabirul-mostofa.blogspot.com/2011/05/php-regex-lookaround-assertion.html
PHP Regex negative look behind assertion, preg_replace_callback

A: This would work
<?php
$str='Hello guys I want to ask a programming-related questions.';

$str=strip_tags($str);
$str=str_replace("programming",'programming',$str);

var_dump($str);

OUTPUT:
string(101) "Hello guys I want to ask a programming-related questions."

A: In the string replace function pass your word to be replaced with space before and after the word like this.. This may solve your problem I think
$str= "Hello guys I want to ask a programming questions. Hello guys I want to ask a programming questions.";
$str=str_replace(" programming ",'programming',$str);
var_dump($str);

Output
"Hello guys I want to ask a programming questions. Hello guys I want to ask a programming questions."


text:
Q: How to associate software with a specific link in the browser I have a certain website that includes movies on streaming, and always copies the link and infects the VLC.
Is it possible for the browser to automatically offer me to open the link on VLC?
As I open Telegram links jumps the
next post


text:
Q: Why my RadioButton (in one RadionGroup)can be selected at the same time? Here is my layout xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="男" />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="女" />
    </RadioGroup>

</LinearLayout>

the result is that both radiobutton have been checked
how to fix it?
and if I change the LinearLayout to TableLayout,waht other questions should I notice?

A: I finally get it after many tests!!
The conclusion is: In a RadioGroup,if a RadioButton is set checked="true",you
must give the RadioButton an id (android:id="@+id/name"); If not, the status will not change to disselected with the "checked radiobutton" when you select other radiobutton.
So,don't forget add an id to the radiobutton!
but I don't know how the source code works?


text:
Q: PMD errors unable to resolve in java using eclipse I have created a below java service in eclipse and reviewed the code using PMD plugin I'm getting below errors
** Errors **
DataflowAnomalyAnalysis: Found 'DD'-anomaly for variable 'result' (lines '80'-'83').
SignatureDeclareThrowsException: A method/constructor should not explicitly throw java.lang.Exception

java service
@GetMapping("OCR/GetBarcodeRead")
    @ApiOperation("Get result from Barcode Zxing library")
    public String getBarcodeRead() throws Exception {

        String result = new String();

        try {
            result = service.zxing();
        } catch (Exception e) {
            System.out.println(e);
            result = "";

        }

        return result;

    }

Could someone help me to resolve this issue? Thanks in advance

A: Your method declaring you throwing Exception, but you aren't, so remove it
public String getBarcodeRead() {

Also remove new String() and initialize it with ""
String result = "";