text:
Q: how to keep tabs visible on every activity I am very new to android programming and I am trying to implement tabs using fragments.
I am using this Tutorial. Everything goes fine but my problem is that I want to open a new activity and on this new activity I want to keep tab bar. I want tab bar visible on every new activity which opens inside tab. I have following code..
public class Tab1Fragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    if (container == null) {
        return null;
    }
    LinearLayout theLayout = (LinearLayout) inflater.inflate(
            R.layout.tab_frag1_layout, container, false);
    // Register for the Button.OnClick event
    Button b = (Button) theLayout.findViewById(R.id.btn_startActivity);
    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(Tab1Fragment.this.getActivity(),
                    "open new activity with tab bar", Toast.LENGTH_LONG).show();
            //Here I want to start new activity with tab bar
        }
    });
    return theLayout;
    // return (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout,
    // container, false);
}

}

A: Here is Main Activity.
  package com.example.tabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.sample.fragments.R;

public class FragmentTabs extends SherlockFragmentActivity implements FragmentChangeListener
{
private TabHost mTabHost;
    private int mContainerId;
    private FragmentTransaction fragmentTransaction;
    private FragmentManager fragmentManager;

private View tabIndicator1;
private View tabIndicator2;
private View tabIndicator3;

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

    mTabHost = (TabHost)findViewById(android.R.id.tabhost);
    mTabHost.setup();
    mContainerId=R.id.realtabcontent;
    fragmentManager = getSupportFragmentManager();

    tabIndicator1 = LayoutInflater.from(this).inflate(R.layout.tab, mTabHost.getTabWidget(), false);
    tabIndicator2 = LayoutInflater.from(this).inflate(R.layout.tab, mTabHost.getTabWidget(), false);
    tabIndicator3 = LayoutInflater.from(this).inflate(R.layout.tab, mTabHost.getTabWidget(), false);

    TextView tv1=(TextView)tabIndicator1.findViewById(R.id.txt);
    TextView tv2=(TextView)tabIndicator2.findViewById(R.id.txt);
    TextView tv3=(TextView)tabIndicator3.findViewById(R.id.txt);

    tv1.setText("Tab1");
    tv2.setText("Tab2");
    tv3.setText("Tab3");

    mTabHost.addTab(mTabHost.newTabSpec("1")
            .setContent(new DummyTabFactory(this))
            .setIndicator(tabIndicator1)
            );

    mTabHost.addTab(mTabHost.newTabSpec("2")
            .setContent(new DummyTabFactory(this))
            .setIndicator(tabIndicator2)
            );

    mTabHost.addTab(mTabHost.newTabSpec("3")
            .setContent(new DummyTabFactory(this))
            .setIndicator(tabIndicator3)
            );

    mTabHost.setOnTabChangedListener(new OnTabChangeListener()
    {
        @Override
        public void onTabChanged(String selectedTabID)
        {
            int tabIndex=Integer.valueOf(selectedTabID);

            switch(tabIndex)
            {
                case 1:
                    selectedTabID= tabIndicator1.getTag()==null?"Fragment1":tabIndicator1.getTag().toString();
                    break;

                case 2:
                    selectedTabID= tabIndicator2.getTag()==null?"Fragment2":tabIndicator2.getTag().toString();
                    break;

                case 3:
                    selectedTabID= tabIndicator3.getTag()==null?"Fragment3":tabIndicator3.getTag().toString();
                    break;
            };

            Fragment fragment=fragmentManager.findFragmentByTag(selectedTabID);

            if(fragment==null)
            {
                fragment=getFragment(selectedTabID);
            }
            replaceFragment(fragment,selectedTabID);
        }
    });

    renderDefaultTab();
}

public void clickMe(final View view)
{
    Fragment fragment=new AnotherFragment();
    replaceFragment(fragment,"AnotherFragment");
}

@Override
public void replaceFragment(final Fragment fragment, final String tag)
{
    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(mContainerId, fragment,tag);
    fragmentTransaction.addToBackStack(tag);
    fragmentTransaction.commit();
}

public void renderDefaultTab()
{
    Fragment fragment=getFragment("Fragment1");
    replaceFragment(fragment,"Fragment1");
}

public Fragment getFragment(final String tag)
{
    Fragment fragment=null;
    if(tag.equalsIgnoreCase("Fragment1"))
        fragment=new Fragment1();
    else if(tag.equalsIgnoreCase("Fragment2"))
        fragment=new Fragment2();
    else if(tag.equalsIgnoreCase("Fragment3"))
        fragment=new Fragment3();

    return fragment;
}

@Override
public void addToTab1Navigation(final String tag)
{
    tabIndicator1.setTag(tag);
}

@Override
public void addToTab2Navigation(final String tag)
{
    tabIndicator2.setTag(tag);
}

@Override
public void addToTab3Navigation(final String tag)
{
    tabIndicator3.setTag(tag);
}

@Override
public void onBackPressed()
{
    String name=fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount()-1).getName();

    Fragment fragment=fragmentManager.findFragmentByTag(name);

    if(fragment instanceof BaseFragment){
        String tag=((BaseFragment)fragment).getPreceddingFragmentTag();
        if(tag.equalsIgnoreCase("exit"))
            System.exit(0);
        else
        {
            fragment=fragmentManager.findFragmentByTag(tag);
            replaceFragment(fragment, tag);
        }
    }

}
}

and layout of this MainActivity.
     <?xml version="1.0" encoding="utf-8"?>

<TabHost
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="0"/>

      <FrameLayout
            android:id="@+android:id/realtabcontent"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>

        <TabWidget
            android:id="@android:id/tabs"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:layout_gravity="bottom"/>

    </LinearLayout>
</TabHost>

Fragment1:
    package com.example.tabs;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.actionbarsherlock.sample.fragments.R;

public class Fragment1 extends BaseFragment
{
    @Override
    public void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    public String toString(){
        return "Fragment1";
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
    {
        View view=inflater.inflate(R.layout.fragment1, container, false);
        return view;
    }

    @Override
    public void onViewCreated(final View view, final Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
        CustomAdapter adapt=new CustomAdapter(getActivity(),0);
        ListView lv=(ListView)view.findViewById(R.id.mylistview);
        lv.setAdapter(adapt);

        FragmentChangeListener fc=(FragmentChangeListener)getActivity();
        fc.addToTab1Navigation(this.toString());

        lv.setOnItemClickListener(new OnItemClickListener()
        {
            @Override public void onItemClick(final AdapterView<?> arg0, final View arg1, final int position, final long arg3)
            {
                Fragment fr=new CustomFragment();
                Bundle bundle=new Bundle();
                bundle.putString("response", "Option "+(position+1));
                fr.setArguments(bundle);
                FragmentChangeListener fc=(FragmentChangeListener)getActivity();
                fc.replaceFragment(fr,"CustomFragment");
            }
        });
    }

    @Override
    public String getPreceddingFragmentTag()
    {
        return "exit";
    }
}

Fragment2:
    package com.example.tabs;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.sample.fragments.R;

public class Fragment2 extends BaseFragment
{
    @Override
    public void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    public String toString(){
        return "Fragment2";
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
    {
        View view=inflater.inflate(R.layout.fragment2, container, false);

        FragmentChangeListener fc=(FragmentChangeListener)getActivity();
        fc.addToTab2Navigation(this.toString());

        return view;
    }

    @Override
    public String getPreceddingFragmentTag()
    {
        return "exit";
    }
}

Fragment3:
    package com.example.tabs;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.sample.fragments.R;

public class Fragment3 extends BaseFragment
{
    @Override
    public void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    public String toString(){
        return "Fragment3";
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
    {
        View view=inflater.inflate(R.layout.fragment3, container, false);

        FragmentChangeListener fc=(FragmentChangeListener)getActivity();
        fc.addToTab3Navigation(this.toString());

        return view;
    }

    @Override
    public String getPreceddingFragmentTag()
    {
        return "exit";
    }
}

FragmentChangeListener Interface.
    package com.example.tabs;

import android.support.v4.app.Fragment;

public interface FragmentChangeListener
{
    public void replaceFragment(final Fragment fragment, final String tag);
    public void addToTab1Navigation(String tag);
    public void addToTab2Navigation(String tag);
    public void addToTab3Navigation(String tag);
}

DummyTabFactory:
    package com.example.tabs;

import android.content.Context;
import android.view.View;
import android.widget.TabHost;

class DummyTabFactory implements TabHost.TabContentFactory
{
    private final Context mContext;

    public DummyTabFactory(final Context context)
    {
        mContext = context;
    }

    @Override
    public View createTabContent(final String tag)
    {
        View v = new View(mContext);
        v.setMinimumWidth(0);
        v.setMinimumHeight(0);
        return v;
    }
}

CustomFragemnt:
    package com.example.tabs;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.actionbarsherlock.sample.fragments.R;

public class CustomFragment extends BaseFragment
{
    @Override
    public void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    public String toString(){
        return "CustomFragment";
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
    {
        FragmentChangeListener fc=(FragmentChangeListener)getActivity();
        fc.addToTab1Navigation(this.toString());

        View view=inflater.inflate(R.layout.custom_fragment, container, false);
        TextView tv=(TextView)view.findViewById(R.id.response);
        tv.setText("You Clicked "+getArguments().getString("response"));

        return view;
    }

    @Override
    public String getPreceddingFragmentTag()
    {
        return "Fragment1";
    }
}

CustomAdapter:
    package com.example.tabs;

import com.actionbarsherlock.sample.fragments.R;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.app.Activity;

public class CustomAdapter extends ArrayAdapter<String>
{
    Context mcontext;

    public CustomAdapter(final Context context, final int textViewResourceId)
    {
        super(context, textViewResourceId);
        mcontext=context;
    }

    @Override
    public int getCount()
    {
        return 50;
    }

    @Override
    public View getView(final int position, final View convertView, final  ViewGroup parent)
    {
        View row;
        if(convertView==null)
        {
             LayoutInflater inflater = ((Activity)mcontext).getLayoutInflater();
             row = inflater.inflate(R.layout.row, parent, false);
        }
        else
        {
            row=convertView;
        }
        TextView tv=(TextView)row.findViewById(R.id.textView1);
        tv.setText("Option "+(position+1));
        return row;
    }
}

BaseFragment:
    package com.example.tabs;

import com.actionbarsherlock.app.SherlockFragment;

public abstract class BaseFragment extends SherlockFragment
{
    public abstract String getPreceddingFragmentTag();
}

AnotherFragment:

     package com.example.tabs;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.sample.fragments.R;

public class AnotherFragment extends BaseFragment
{
    @Override
    public void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
    {
        FragmentChangeListener fc=(FragmentChangeListener)getActivity();
        fc.addToTab1Navigation(this.toString());

        View view=inflater.inflate(R.layout.another_fragment, container, false);
        return view;
    }
    @Override
    public String toString()
    {
        return "AnotherFragment";
    }

    @Override
    public String getPreceddingFragmentTag()
    {
        return "CustomFragment";
    }
}

Layout for AnotherFragment.
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/response"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/another"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Layout for CustomFragment:
    *<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/response"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/response"
        android:text="@string/another_fragment"
        android:onClick="clickMe" />

</RelativeLayout>*

Layout for Frament1:
    <?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"
    android:orientation="vertical">

    <ListView
        android:id="@+id/mylistview"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>

</LinearLayout>

Layout for Fragment2:
     <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/some_text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Layout for Fragment3:
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/icon"
        android:contentDescription="@string/desc" />

</RelativeLayout>

Layout for Row.xml
    <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"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:padding="5dp" />

</RelativeLayout>

Tab.xml
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:context=".MainActivity"
    android:layout_margin="3dp"
    android:background="@drawable/two_state_button"
    android:layout_weight="1">

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_compose_inverse"
        android:layout_centerHorizontal="true"
        android:contentDescription="@string/desc"/>

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/img"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"></menu>

A: My suggestion is you should you fragments instead on using new activity. Fragment will be displayed withing your current activity and you don't need to take care about tabs.
but if your need is to use Activity then Create tabhost in newActivity layout as well as you made in this Activity's Layout.
and while creating intent of another activity, send the current Tab number in extras to new Activity.
 Intent i = new Intent(Activity.this, NewActivity.Class);
 i.putIntExtra("CurrentVisibleTab", currentTabIndex);
 startActivity(i).

In New Activity.
tabHost.setDefault(getIntent().getIntExtra("CurrentVisibleTab"));

Hope this will helpful.


text:
Q: GCM service not avalible I follow the example of http://hmkcode.com/android-google-cloud-messaging-tutorial/ , every thing is fine but its alway response SERVICE_NOT_AVALIBLE
The device time is correctly setup, package name is correct,too.
could anyone help me in this case
my MainActivity.java
Button btnRegId;
EditText etRegId;
GoogleCloudMessaging gcm;
String regid;
String PROJECT_NUMBER = "943411953393";

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

    btnRegId = (Button) findViewById(R.id.btnGetRegId);
    etRegId = (EditText) findViewById(R.id.etRegId);

    btnRegId.setOnClickListener(this);
}
public void getRegId(){
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
                }
                regid = gcm.register(PROJECT_NUMBER);
                msg = "Device registered, registration ID=" + regid;
                Log.i("GCM",  msg);

            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();

            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            etRegId.setText(msg + "\n");
        }
    }.execute(null, null, null);
}
@Override
public void onClick(View v) {
    getRegId();
}

My AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.gmc"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="14" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission
        android:name="com.example.gmc.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.example.gmc.permission.C2D_MESSAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver
            android:name=".GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.example.gmc" />
            </intent-filter>
        </receiver>
        <service android:name=".GcmMessageHandler" />

        <meta-data android:name="com.google.android.gms.version"
           android:value="@integer/google_play_services_version" />
    </application>
</manifest>

A: try this
@Override
protected String doInBackground(Void... params) {
     String msg = "";
     int backoff = 2000;
     try {
          if (gcm == null) {
               gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
          }
     }
     catch (IOException ex) {
          ex.printStackTrace()
     }
     for(int i=0;i<5;i++){
          try {
               regid = gcm.register(PROJECT_NUMBER);
               msg = "Device registered, registration ID=" + regid;
               Log.i("GCM",  msg);
               break;
          }
          catch (IOException ex) {
               msg = "Error :" + ex.getMessage();
               backoff =backoff * 2;
               Thread.sleep(backoff);
          }
     }
     return msg;
}

you need to try several attempts increasing the wait time for each try.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Overloading << Cannot Access Inherited Private Data I am trying to overload the operator<< from the class second. The problem is some of the data I am trying to access is private in class first. Why am I unable to access the private data since I am using the friend function?
I found that the overload is only working with non-inherited private data.
class first
{
public:

    student(string a, string b, float c, int d);

private:
    string a;
    string b;
    float c;
    int d;
    int e;
    static int count;
};

class second : public first
{
public:

    second(string a, string b, float c, int d, string f);

    friend ostream &operator << (ostream &output, second &dS);
    friend istream &operator >> (istream &input, second &dS);

private:
    string f;
};

// Separate File

ostream &operator <<(ostream& output, second& dS){

    output << iS.a << endl;

    output << iS.f << endl;

return output;
}

This is the error I am getting:
overload.cpp:27:18: error: 'a' is a private member of 'first'
    output << dS.a << endl;
                 ^
./example.hpp:51:9: note: declared private here
        string a;

A: When you write
friend ostream &operator << (ostream &output, second &dS);

you are allowing some external function with that signature to have access to any internal attribute/member your second class has access. That means operator<< will have access to the attribute f even though it is private. However, your second class does not have access to the private data from the base class. Thus, it cannot give that access to a friend function.

A: As the others said, the second Class does not have access to the private members of the first class. You could try writing some set and get methods in the first class. The get methods would return the value (that i'm assume you're seeking). You could call this function in the second class. Not sure if that's going overboard for what you're looking for though. Might just want to do the overloading in the fist class


text:
Q: Is there a mapping between NSFont.Weight and the integer values? The NSFont API has two different ways to specify a weight. First, there is a struct NSFont.Weight which contains a floating point rawValue property. It's used in functions like:
NSFont.systemFont(ofSize fontSize: CGFloat, weight: NSFont.Weight) -> NSFont

Then there is another function for getting other fonts, which uses an integer.
NSFontManager.font(withFamily family: String, traits: NSFontTraitMask,
                   weight: Int, size: CGFloat) -> NSFont?

The documentation for that function says that integers are not simply rounded versions of the floats. The weight can be in the range 0-15, with 5 being a normal weight. But:
NSFont.Weight.regular.rawValue == 0.0
NSFont.Weight.light.rawValue == -0.4000000059604645
NSFont.Weight.black.rawValue == 0.6200000047683716

I don't see any mention of how to convert between the NSFont.Weight and the integers. Maybe it's just some odd legacy API that they never clean up. Am I missing something?


text:
Q: Android stop async loading list element when no more visible As described in many tutorials and in Android developers pages too, I'm using an async task to load images as thumbnails in a ListView. The task loads full size image from SDcard, resize it and put it in the ImageView of list item's layout.
Everything works well, except for the fact that after scrolling list fast up & down, the image of a single visible element is updated two or three times with different images before getting the right one.
This behavior is related, in my opinion, to the recycling views in ListView: when an asynctask is ready to inject the list's element-X image in the referred view, the view itself might be already been recycled and assigned to list's element-Y.
I'm conscious about some ugliness of my code, for example the fact that I've implemented neither volatile nor persistent cache for thumbnails (targeted for next release), but the problem would be only partially hidden by that.
I found a possible solution using libraries for loading image, but I'm investigating how to fix in my code because the problem is more generally related to using async code in conjunction with list and today I deal with images, but tomorrow I'could face the same problem loading text or any other kind of data.
Possible solutions I'm investigating are:

*

*Inform the asynctask about the item of the list it is working for, once loaded image updates it only if the item is visible

*When list detaches the view from element (how can I detect this?), stop the asynctask

*Override list's OnScrollListener to check when OnScroll event happens if an item exits from visible items' list and the stop its asynctask, if exists.

Is one of these solutions viable or con you suggest a different one?
This is my list's adapter (I'm using an expandable list in a fragment):
@Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

    Log.i(TAG, "ExpandableListAdapter.getChildView entered, getting view n. " + groupPosition + "-" + childPosition + ", convertview = " + convertView);

    ViewHolder holder;

    if (convertView == null) {

        convertView = inf.inflate(R.layout.selfie_list_item_layout, parent, false);
        holder = new ViewHolder();

        holder.date = (TextView) convertView.findViewById(R.id.selfieListItemDateView);
        holder.place = (TextView) convertView.findViewById(R.id.selfieListItemPlaceView);
        holder.thumb = (ImageView) convertView.findViewById(R.id.selfieListItemThumbView);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    Integer mChildIndex = (Integer) getChild(groupPosition, childPosition);
    SelfieItem mChildObj = selfies.get(mChildIndex);
    String mText = mChildObj.getDate().toString();
    holder.date.setText(mText);
    holder.thumb.setImageBitmap(BitmapFactory.decodeResource(convertView.getResources(), R.drawable.selfie_place_holder));

    File selfieFile = mChildObj.getFile();

    new LoadSelfieTask(mFragmentContext).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, selfieFile, holder.thumb);

    return convertView;
}

And the following is async code:
   @Override
    protected Bitmap doInBackground(Object... params) {

        File selfieFile = (File)params[0];
        Bitmap mySrcBitmap = null;
        Bitmap myDestBitmap = null;

        if (selfieFile.exists()) {

            mySrcBitmap = BitmapFactory.decodeFile(selfieFile.getAbsolutePath());

        }

        if (mySrcBitmap != null) {

            // Get info about view to be updated
            mImageViewToBeUpdated = (ImageView) params[1];
            mImageHeight = mImageViewToBeUpdated.getHeight();
            mImageWidth = mImageViewToBeUpdated.getWidth();

            if (mySrcBitmap.getWidth() >= mySrcBitmap.getHeight()){

                myDestBitmap = Bitmap.createBitmap(
                        mySrcBitmap,
                        mySrcBitmap.getWidth()/2 - mySrcBitmap.getHeight()/2,
                        0,
                        mySrcBitmap.getHeight(),
                        mySrcBitmap.getHeight()
                );

            }else{

                myDestBitmap = Bitmap.createBitmap(
                        mySrcBitmap,
                        0,
                        mySrcBitmap.getHeight()/2 - mySrcBitmap.getWidth()/2,
                        mySrcBitmap.getWidth(),
                        mySrcBitmap.getWidth()
                );
            }

            mySrcBitmap = Bitmap.createScaledBitmap(myDestBitmap, mImageWidth, mImageHeight, true);

        }

        return mySrcBitmap;

    }

Thanks in advance for your answers.

A: If you need something quick, try Picasso http://square.github.io/picasso/
Your code is, for each row, create an AsyncTask to fetch image from external storage. You will create another AsynTask to fetch the same image again when you scroll back to a row item. I would suggest you to create a cache to store the result of AsynTask, and have proper cache replacement policy.

A: I found the answer to my question in the example code of this Android Developers Training Lesson.
In ImageWorker.java we can find the method that launches the backgroud task thad loads the image:
/**
 * Load an image specified by the data parameter into an ImageView (override
 * {@link ImageWorker#processBitmap(Object)} to define the processing logic). A memory and
 * disk cache will be used if an {@link ImageCache} has been added using
 * {@link ImageWorker#addImageCache(android.support.v4.app.FragmentManager, ImageCache.ImageCacheParams)}. If the
 * image is found in the memory cache, it is set immediately, otherwise an {@link AsyncTask}
 * will be created to asynchronously load the bitmap.
 *
 * @param data The URL of the image to download.
 * @param imageView The ImageView to bind the downloaded image to.
 */
public void loadImage(Object data, ImageView imageView) {
    if (data == null) {
        return;
    }

    BitmapDrawable value = null;

    if (mImageCache != null) {
        value = mImageCache.getBitmapFromMemCache(String.valueOf(data));
    }

    if (value != null) {
        // Bitmap found in memory cache
        imageView.setImageDrawable(value);
    } else if (cancelPotentialWork(data, imageView)) {
        //BEGIN_INCLUDE(execute_background_task)
        final BitmapWorkerTask task = new BitmapWorkerTask(data, imageView);
        final AsyncDrawable asyncDrawable =
                new AsyncDrawable(mResources, mLoadingBitmap, task);
        imageView.setImageDrawable(asyncDrawable);

        // NOTE: This uses a custom version of AsyncTask that has been pulled from the
        // framework and slightly modified. Refer to the docs at the top of the class
        // for more info on what was changed.
        task.executeOnExecutor(AsyncTask.DUAL_THREAD_EXECUTOR);
        //END_INCLUDE(execute_background_task)
    }
}

A reference to AsyncTask instance is saved in an AsyncDrawable class:
/**
 * A custom Drawable that will be attached to the imageView while the work is in progress.
 * Contains a reference to the actual worker task, so that it can be stopped if a new binding is
 * required, and makes sure that only the last started worker process can bind its result,
 * independently of the finish order.
 */
private static class AsyncDrawable extends BitmapDrawable {
    private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;

    public AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
        super(res, bitmap);
        bitmapWorkerTaskReference =
            new WeakReference<BitmapWorkerTask>(bitmapWorkerTask);
    }

    public BitmapWorkerTask getBitmapWorkerTask() {
        return bitmapWorkerTaskReference.get();
    }
}

At the end of background activity, the AsyncTask verifies if it is the last to be "attached" to the view it has to update and performs update only if no other task have been "attached" to the view
    /**
     * Returns the ImageView associated with this task as long as the ImageView's task still
     * points to this task as well. Returns null otherwise.
     */
    private ImageView getAttachedImageView() {
        final ImageView imageView = imageViewReference.get();
        final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);

        if (this == bitmapWorkerTask) {
            return imageView;
        }

        return null;
    }

   /**
     * Once the image is processed, associates it to the imageView
     */
    @Override
    protected void onPostExecute(BitmapDrawable value) {
        //BEGIN_INCLUDE(complete_background_work)
        // if cancel was called on this task or the "exit early" flag is set then we're done
        if (isCancelled() || mExitTasksEarly) {
            value = null;
        }

        final ImageView imageView = getAttachedImageView();
        if (value != null && imageView != null) {
            if (BuildConfig.DEBUG) {
                Log.d(TAG, "onPostExecute - setting bitmap");
            }
            setImageDrawable(imageView, value);
        }
        //END_INCLUDE(complete_background_work)
    }

A: Cancelling AsyncTasks? Is that a good idea? I have found that it does not work many times and postExecute() is always called so its a possibility your image will be still laid out in the listview, maybe a wrong one which will further mess up your scenario..


text:
Q: C program in ubuntu using visual studio code The code I wrote:
 #include<stdio.h>

 int main()
 {
 int i,m,maths=0,english=0,e,science=0,s,all=0;
 for(i=1;i<=5;i++)
 {
    printf("enter the marks of english:\n");
    scanf("%d",&e);
    printf("enter the marks of maths:\n");
    scanf("%d",&m);
    printf("enter the  marks of science:\n");
    scanf("%d",&s);
    if(m>=95 && s>=95 && e>=95)
     all++;
    if(m>=90)
    maths++;
    if(e>=90)
    english++;
    if(s>=90)
    science++;

 }
  printf("95% or above in all subject : %d \n",all);
   printf("90% or above in maths :%d\n",maths);
  printf("90% or above in english: %d\n",english);
  printf("90% or above in science: %d\n",science);
 }

I have to  input the marks of 5 students through keyboard and
I am getting the following error that
I don't understand. Why am I getting  this kind of error?
 gcc studentMarks.c -o studentMarks.out
studentMarks.c: In function 'main':
   studentMarks.c:24:17: warning: ' ' flag used with '%o' gnu_printf format [-Wformat=]
   printf("95% or above in all subject : %d \n",all);
             ^
  studentMarks.c:24:44: warning: format '%d' expects a matching 'int' argument [-Wformat=]
   printf("95% or above in all subject : %d \n",all);
                                       ~^
 studentMarks.c:25:17: warning: ' ' flag used with '%o' gnu_printf format [-Wformat=]
 printf("90% or above in maths :%d\n",maths);
             ^
 studentMarks.c:25:37: warning: format '%d' expects a matching 'int' argument [-Wformat=]
 printf("90% or above in maths :%d\n",maths);
                                ~^
 studentMarks.c:26:17: warning: ' ' flag used with '%o' gnu_printf format [-Wformat=]
 printf("90% or above in english: %d\n",english);
             ^
studentMarks.c:26:39: warning: format '%d' expects a matching 'int' argument [-Wformat=]
 printf("90% or above in english: %d\n",english);
                                  ~^
 studentMarks.c:27:17: warning: ' ' flag used with '%o' gnu_printf format [-Wformat=]
 printf("90% or above in science: %d\n",science);
             ^
 studentMarks.c:27:39: warning: format '%d' expects a matching 'int' argument [-Wformat=]
 printf("90% or above in science: %d\n",science);
                                  ~^

A: In C programming %o represent octal values. So when you are writing 95% or its reading it as %o. Since there is a space between % and o, C compiler doesn't recognize it as octal or percentage and that's why its giving warnings.
But, if you replace 95% with 95%% then c compiler reads it as 95 percent.
#include<stdio.h>

 int main()
 {
 int i,m,maths=0,english=0,e,science=0,s,all=0;
 for(i=1;i<=5;i++)
 {
    printf("enter the marks of english:\n");
    scanf("%d",&e);
    printf("enter the marks of maths:\n");
    scanf("%d",&m);
    printf("enter the  marks of science:\n");
    scanf("%d",&s);
    if(m>=95 && s>=95 && e>=95)
     all++;
    if(m>=90)
    maths++;
    if(e>=90)
    english++;
    if(s>=90)
    science++;

 }
  printf("95%% or above in all subject : %d \n",all);
   printf("90%% or above in maths :%d\n",maths);
  printf("90%% or above in english: %d\n",english);
  printf("90%% or above in science: %d\n",science);
 }

This should work now.

A: For each line, from lines 24 through 27, the compiler is emitting two warnings (not errors as you indicate) to help you out.
The first is caused when your compiler encounters % o from the longer substring 95% or.
The compiler and the printf function interprets % o as %o with a blank flag to allow for a - to be emitted if the signed numeric type is negative.
The second warning is caused because of the first interpretation and the fact that you included only one argument after the format string. If you had accidentally provided two signed integer arguments after the format string, then you would not have seen any warnings.
If you try to execute the code as is in spite of the warnings, then you'd get undefined behavior.
Any time you want to include a % in your format string and you want to emit it literally, then you have to encode it as %%.
As an aside, unrelated to your question, the value you provided to the gcc -o option is unusual. One would typically call the output executable studentMarks or studentmarks, not studentMarks.out.


text:
Q: Getting CSV file of Wikipedia geolocations? Where do I get a CSV file containing (a reference to) all Wikipedia articles with lon/lat coordinates?
I am aware of Retrieving Wikipedia's coordinate information? which refers to this page:
https://de.wikipedia.org/wiki/Wikipedia:WikiProjekt_Georeferenzierung/Hauptseite/Wikipedia-World/en
At one time that page offered a CSV download but it is no longer present, only the option to download a PostGIS data dump.
I prefer to get the dewiki geolocations


text:
Q: Multiple fade animations using keyframes causing transparency after end I have a fade keyframe animation on the body of a page. I also want to add an additional keyframe animation on an element so it comes in just after.
This element overlaps another and even after completion of the animation, it has ever so slight transparency causing the element below to show through. You can see this better on high gamut displays.
Chrome only.
Tested OK in Firefox and Edge
[Edit}
Running the snippet below doesn't recreate the issue but in CodePen you can see it
https://codepen.io/rachelreveley/pen/LYEOQPz

div {width: 300px; height: 300px;}
.one {
  background-color: black;
}
.two {
  background-color: yellow;
  margin: -100px 0 0 100px
}

body {
    animation: fade 1s ease forwards;
}
.two {
    animation: delayed-fade 1s ease forwards;
}

// animation: fade 2s ease forwards;
@keyframes fade {
    0%   {opacity: 0;}
    100% {opacity: 100%;}
  }

// animation: delayed-fade 4s ease forwards;
@keyframes delayed-fade {
    0%   {opacity: 0;}
    20%  {opacity: 0;}
    100% {opacity: 100%;}
  }


text:
Q: How to replace AsynTask with RxJava in this case I have a class that goes to decrease the image but I'm currently on AsyncTask, now I want to replace it because AsyncTask is now deprecated.So can someone help me out with a workaround
Here is my code:
class DecreaseImageTask(
    val uri: Uri? = null,
    val bitmap: Bitmap? = null,
    var context: Context,
    var listener: (String?) -> Unit
) : AsyncTask<Void, Long, String?>() {

    override fun doInBackground(vararg params: Void?): String? {
        return when {
            uri != null -> {
                decreaseImageSize(imagePath = FileUtils.getPathURI(context, uri) ?: "")
            }
            bitmap != null -> {
                decreaseImageSize(bitmap = bitmap)
            }
        }
    }

    override fun onPostExecute(result: String?) {
        super.onPostExecute(result)
        listener(result)
    }
}

A: You could change your decreaseImageSize to accept a callback as a parameter.
In this case, the function will no longer need to return a string, which is passed as a parameter to the callback function and then used as
a parameter in its body:
fun decreaseImageSize(imagePath: String? = null, bitmap: Bitmap? = null, callback: (String) -> Unit) {
    ...

    val result = "" // The result of the previous decreaseImageSize function

    callback(result)
}

Then, instead of calling the AsyncTask use the new decreaseImageSize function:
    decreaseImageSize(imagePath = FileUtils.getPathURI(context, uri) ?: "") { result ->
        // Execute the code after the image is decreased
    }

    decreaseImageSize(bitmap = bitmap) { result ->
        // Execute the code after the image is decreased
    }


text:
Q: Are dynamite shocks specific to Angry Birds Space Level 1-27? In Angry Birds Space level 1-27, the shock of blowing up the dynamite box on one side of the planetoid immediately causes the dynamite box on the opposite side to blow up also, without anything falling on it first. For example, see this walk-through video .  I've also hit the opposite dynamite box first and it works the same way on this level.  As an avid Angry Birds player this behaviour surprised me because it was unexpected considering classic vicinity triggers for dynamite.
Is this shock-wave behaviour level-specific to Space 1-27, or does dynamite have that effect in general in AB Space physics?
As a comparison point, I can have two dynamite boxes in much nearer vicinity on the same plane in classic Angry Birds and they won't trigger one another to explode immediately.

A: See the little red lights on top of the boxes?  Those are some kind of transmitters, and that's why when one gets blown the other does too.  When they aren't present you won't see this behavior in Angry Birds Space.  The other games have similar mechanics, but I don't think it's quite as explicit visually.  Perhaps it will make it into a future update to the original game or Seasons :)


text:
Q: Spark: avoid task restart when writing I have a Spark application that reads CSVs and writes Parquet files.
In some cases (too little allocated memory, lost executor), the Parquet tasks may fail and retry; I noticed in this case there are duplicated records, i.e. some CSVs were written to Parquet files many times as it retries.
What is the state of the art to avoid such duplicates? I already use --conf spark.yarn.maxAppAttempts=1 but this works only for jobs, not tasks. Should the application fail if one stage fail, or is there any way to rollback?

A: Spark uses FileOutputCommitter to manage staging output files and final output files.
The behavior of FileOutputCommitter has direct impact on the performance of jobs that write data. It has two methods, commitTask and commitJob.
Apache Spark 2.0 and higher versions use Apache Hadoop 2, which uses the value of mapreduce.fileoutputcommitter.algorithm.version to control how commitTask and commitJob work.
Currently Spark ships with two default Hadoop commit algorithms — version 1 & version 2.
In version 1, commitTask moves data generated by a task from the task temporary directory to job temporary directory and when all tasks complete, commitJob moves data to from job temporary directory the final destination. This ensures the Transactional writes at job level.
In version 2, commitTask will move data generated by a task directly to the final destination and commitJob is basically a no-op. This ensures the Transactional writes at Task level. You may see duplicates, if the job is re-submitted.
In your case, set the dataframe.write.option("mapreduce.fileoutputcommitter.algorithm.version", "1") to ensure the Transactional writes at job level.
Reference: https://databricks.com/blog/2017/05/31/transactional-writes-cloud-storage.html


text:
Q: How to store the value of model in a variable? I am creating a directive, in which i want to compare the value stored in a model (say "name" as model and it is having value "Angular")
to be stored in a variable.
I tried something like below,
var nameValue=name;

but it(nameValue) is not having the value "Angular"
Example:

app.directive('kmRadio', function() {

  return{
    restrict:'E',
    compile: function(element,attrs) {
      var model=ngModelName;

      console.info(attrs.kmModel);
      console.info("{{'+attrs.kmModel+'}}");

      if(attrs.kmTitle==model) {
        previewString="<input type="+"radio"+" checked>";
      }
      else {
        previewString="<input type="+"radio"+">";
      }

      var htmlText=''+previewString+''+

        element.replaceWith(htmlText);
    }
  }
})

Can anyone tell me how to retrieve the value stored in model(ng-model)

A: You can link attributes in the directive scope to the parent with the scope attribute. A detailed explanation can be found here: What is the difference between '@' and '=' in directive scope in AngularJS?
In essence adding
return{
    restrict:'E',
    scope: {
       kmModel: '=kmModel'
    }
    compile: function(element,attrs) {
      var model=ngModelName;
  console.info(attrs.kmModel);
  console.info("{{'+attrs.kmModel+'}}");

  if(attrs.kmTitle==model) {
    previewString="<input type="+"radio"+" checked>";
  }
  else {
    previewString="<input type="+"radio"+">";
  }

  var htmlText=''+previewString+''+

    element.replaceWith(htmlText);
}

}
Would solve your problem.

A: You can simplify things a bit with ng-checked, and a link function:
app.directive('kmRadio', function() {
  return {
    restrict: 'E',
    scope: true,
    replace: true,
    template: "<input type='radio' ng-checked='title == model' />",
    link: function(scope, element, attrs) {
      scope.model = scope.$eval(attrs.kmModel);
      scope.title = attrs.kmTitle;

      console.info('attrs.kmModel: ', attrs.kmModel);
      console.info('scope.$eval(attrs.kmModel):', scope.model);
    }
  }
})

Here is a working demo: http://plnkr.co/edit/owTLnPUbbZIhwUtfoivt?p=preview


text:
Q: Conditional thread lock in c# Is it possible to have a conditional thread lock when the underlying condition is not constant?
I have two functions A and B, and a condition to decide which function to execute.
A is thread safe by itself, multiple calls to A can execute simultaneously, B is not, and is Synchronized. But during execution of B the condition can change (from false to true) and therefore all threads executing A at that time will throw errors.
if (condition)
{
    A();
}
else
{
    B();
}

A - thread safe
B - Synchronized using [MethodImpl(MethodImplOptions.Synchronized)]

Therefore, I am looking for a way to lock A but only when B is running.
Please suggest a way to achieve this.
Some elaborations:
I am creating a cache, and performance is very crucial, thus a blanket lock is not feasible.
Condition is whether or not the requested data is present in the cache.
A() = AddToUpdates() - Executed on a cache hit, just adds to the number of updates for a particular cache key, using a concurrent dictionary.
B() = ProccessUpdates() and EvictLeastPriorityEntry() - Executed on a cache miss, all previous updates will be processed and the underlying data structure storing the ordering of cache entries will be re-arranged.
And then the entry with least priority will be removed.
As mentioned in the accepted answer ReaderWriterLock seems to be the way to go.
Just one problem though,
Let's say, thread1 starts execution and a cache hit occurs, (on the entry with the least priority) meaning the if condition is true and enters the if block. But before calling A(), control is switched to thread2.
thread2 - cache miss occurs, reordering and eviction (Entry which A() from thread1 needed access to) is performed.
Now when controlled is returned to thread1, error will occur.
This is the solution I feel should work:
_lock.EnterReadLock();
if (condition)
{
    A();
}
_lock.ExitReadLock();

if (!condition)
{
    B();
}

void A()
{
   // ....
}

void B()
{
    _lock.EnterWriteLock();
    // ...
    _lock.ExitWriteLock();
}

Will this work?
Thank you.

A: Your question looks a lot like this:

*

*A() is some read only method, so thread safe. Different execution of A in parallel is OK.

*B() is like writing/mutating things that A method uses. So A() becomes not thread safe if executed at same time.
For example B() could write in a List and A() executions read on this list. And you would get exception "InvalidOperationException: Collection Was Modified" thrown from A() .
I advise you to look for "producer/consumer problem" in google and look for the tons of example there are.
But in case you absolutely want to begins B execution while A execution(s) has/have not terminated, you can add checkpoint in A() using Monitor class, it is used to lock a resource and synchronize with other threads. It is more complex though and i would go first for producer/consumer pattern to see if it fill the needs
Some more things:

*

*I would check is the use of BlockingCollection<T> class that may fit your exact need too (and is easy to use)

*The use of MethodImplOptions.Synchronized is not recommended because it use public lock. We use usually use private lock (object readonly _lock = new object();) so no one except the maintainer of this object can lock on it, thus preventing dead lock (and preventing other people  accusing your code of a bug because other people locked your instance of class without knowing you do the same internally)

A: I possible solution to your problem might be the ReaderWriterLockSlim class. This is a synchronization primitive that allows multiple concurrent readers, or one exclusive writer, but not both of those at the same time.

Use ReaderWriterLockSlim to protect a resource that is read by multiple threads and written to by one thread at a time. ReaderWriterLockSlim allows multiple threads to be in read mode, allows one thread to be in write mode with exclusive ownership of the lock, and allows one thread that has read access to be in upgradeable read mode, from which the thread can upgrade to write mode without having to relinquish its read access to the resource.

Example:
private readonly ReaderWriterLockSlim _lock = new();

void A()
{
    _lock.EnterReadLock();
    try
    {
        //...
    }
    finally { _lock.ExitReadLock(); }
}

void B()
{
    _lock.EnterWriteLock();
    try
    {
        //...
    }
    finally { _lock.ExitWriteLock(); }
}


text:
Q: How to revert ubuntu updates and installs to specific time? Title may no be clear, i want to revert all updates and installations from my ubuntu to specific time. I have two netbeans on it with different version numbers. I want to revert all updates and installations since the day i installed second netbeans.
How can i achieve this?

A: Maybe i'm wrong. But all i know ubuntu doesnt have "time machine" or "system restore" like tool. You can not revert all update that you have installed. About ur netbeans you can remove using terminal with command: sudo apt-get remove netbeans or apt-get purge netbeans


text:
Q: How can I debug a hanging ssh connection? I have two virtual servers with the same host provider. After regenerating my SSH keys on my client machine (local) I con only connect to one of the virtual servers. When I connect to the other (both are being done via the terminal) it just hangs. It's not timing out and I see nothing in the SSH logs that indicates a connection error.
Any ideas?

A: try to launch ssh -v or even ssh -vv instead of just ssh.


text:
Q: React native Enzyme Mount Native elements "unrecognized in this browser" React Native app with Expo.
Installed Jest and Enzyme
Want to run Enzyme Mount on the component so I can test state updates.
I have this simple test
describe("State checking", () => {
    test("Make sure that State gets added from Route params", () => {
        const component = mount(<Categories/>);
        const instance = component.instance();
        console.log(instance);
    })
})

When running this, I get this error from the test:
Warning: <View /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.
Warning: The tag <View> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.

What is going on here? Does it not recognize that I am using React Native?
I have researched this issue but get nothing useful.
Thank you for your time.


text:
Q: Weird behaviour of Kafka consumer/mirrormaker at different DCs I have been setting up 2 clusters of Kafka (0.8.1.1) located across DCs , one in Asia and another one in Europe. All of them are running on EC2 m1.xlarge machines.
My goal is to replicate data of a topic from Asia cluster to Europe cluster with "high and stable" speed.
I ended up with 3 solutions to achieve this goal as following :
(Let N = number of partitions of a topic in Asia cluster.)
1) Using the Kafka provided Mirrormaker , with —num.streams = N.
It runs super slow at the rate of around 30 Mbps while we expect around 1 Gbps as we have noticed this rate at Asia cluster when producer producing data to Kafka brokers.
2) I tried creating my own version of Consumer using High-level API in Europe to consume data directly from Asia cluster , and ended up with the same rate around 30 to 40 Mbps
I have designed the consumer this way.

*

*1 Consumer Group (1 kafka.javaapi.consumer.ConsumerConnector)

*N threads to handle N streams from 1 Consumer Group

3) I tried creating another version of Consumer using High-level API , and ended up with around 400 Mbps! , which is much more higher than 2 mentioned ways
Here is my new design

*

*N Consumer Group (N kafka.javaapi.consumer.ConsumerConnector) with the same group ID

*N Threads to handle N Consumer Group

*1 Consumer Group handles 1 Stream

Also , the more number of N (partition)  , the higher speeds I've got from the solution 3) while solution 1) and 2) remains the speed at 30Mbps irrespective to value of N.
Right now , to reach speed at 400 Mbps for solution 3) , I have to set our N to be ridiculously large at N = 60 , with each message in a topic in Asia cluster has average size of 50KB.
So my real question is , I don't see the technical differences between solution 3) and the rest but how the speed of consuming data with solution 3) becomes so hugely different from the rest?


text:
Q: C++ Character Frequency Linked List For my project, I need to read in a file and count the times each character appears and store it in a linked list. Below is what I have for the reading in the file portion of the program:
ifstream inFile;
ofstream outFile;

inFile.open(inputfile.txt);

char ch;

list<charFrequency> charFreqList;
list<charFrequency>::iterator i;

inFile >> ch;
while (!inFile.eof())
{
    charFrequency cf(ch);
    charFreqList.push_back(cf);

    for (i = charFreqList.begin(); i != charFreqList.end(); ++i)
    {
        if (i->getCharacter() == cf.getCharacter())
        {
            i->increment();
            charFreqList.pop_back();
        }
    }

    inFile >> ch;
}

inFile.close();

I need the program to go through and if the character is already in the linked list, it just needs to increment the count of the character but only leave one instance of the character in the list, however, I get an error message stating "list iterator not implementable". I know it has to do with the pop_back() as it removes the last element, but I don't know about avoiding this issue.
Thanks in advance for the help!

A: You don't need to push into the list and remove it back. You could do something like below, or break from the if condition in your code and then remove the last element (not in the loop)
list<charFrequency> charFreqList;
list<charFrequency>::iterator i;
while (!inFile.eof())
{
    charFrequency cf(ch);
    Predicate pre(ch); //Write your predicate functor

    //check if the char is present
    i = std::find_if(charFreqList.begin(), charFreqList.end(), pred);
    if( i != charFreqList.end() )
      i->increment();
    else
      charFreqList.push_back(ch); //insert only when not present

    inFile >> ch;
}

However, std::list is a wrong choice of datastructure here, it shall give a bad run time complexity.

A: First, only add a charFrequency if the character doesn't exist, otherwise you increment the count.  It would also be easier if a new charFrequency started with a count of 1.
Second, change your input loop to not check for eof().  This is explained in many threads on SO.
class charFrequency
{
   int count;
   char ch;
   public:
       void increment() { ++count; }
       char getCharacter() const { return ch; }
       int getCount() const { return count; }
       charFrequency(char c) : ch(c), count(1) {}
};

Last, for kicks, let's use some C++ and use the std::find_if() algorithm function instead of writing a loop.  Introduce a function object below that finds a character.
struct FindCharacter
{
    char ch;
    FindCharacter(char c) : ch(c) {}
    bool operator()(charFrequency& cf) const
    { return cf.getCharacter() == ch;   }
};

So now putting this all together, we have this:
#include <list>
#include <algorithm>
#include <fstream>

    //...
    while (ifs)
    {
        ifs >> ch;

        // Search for character
        std::list<charFrequency>::iterator it = std::find_if(charFreqList.begin(), charFreqList.end(), FindCharacter(ch));

        // if not found, add new charFrequency to list
        if ( it == charFreqList.end())
            charFreqList.push_back(charFrequency(ch));
        else
            it->increment();  // increment
    }
    //...


text:
Q: Grid editing in Kendo I hava a kendo grid which is set to be editable. It is working fine. all I need is to show a empty row in my grid regardless of any items present or not. This editable row should always come. for that I have searched various questions here also but none of them is working except the below:
 $("#Grid").kendoGrid({
            dataSource: TableDataSource,
            autoBind: true,
            scrollable: true,
            sortable: {
                allowUnsort: false
            },
            pageable: {
                refresh: true,
                buttonCount: 5,
                pageSizes: 5
            },
            noRecords: {
                template: "No records found."
            },
            dataBound : function () {
                var firstItem = this.dataSource.view()[0];
                if (firstItem.isNew() == false) {
                   firstItem.isNew();
                    this.addRow();
                }
            },
   editable: true,

But here the problem is that it only shows a new row if grid have atleast one record coming from database . If Grid is empty, it is not adding a row in grid.
If I remove if condition , then the grid goes into infinite loop and crashes the browser.
I also tried this in document.ready but there is no success. Grid just don't respond
 $(function(){
        var grid = $("#Grid").data("kendoGrid");
       grid.dataSource.insert( {} );//Not working
       grid.addRow(); // Not working

    });


text:
Q: Standard deviation a sample of compiling times in Android For me thesis I have a sample of compiling times in Android, however, some people says the standard deviation is calculated by this method: $$\sqrt{\frac{\sum (x-\bar x)^2}{(n-1)}}.$$
Other methods divide by the # of tests. What is the difference between the two? Sorry for my bad English.

A: The difference is whether you would like to use a biased (with $n$) or non-biased (with $n-1$) estimator. Please see Wiki on unbiased estimation of standard deviation for detailed info.


text:
Q: how to use any owl.carousel? how can i use any owl.carousel in my template html ?
this is my source. i repeat cod but Does not work :
...

1

2

3

4

5

6

7

8

9

10

11

12

1

2

3

4

5

6

7

8

9

10

11

12

...
this is my source :  [https://drive.google.com/file/d/1NhADd8J0ARRzRAutfs5u-_zrYqdg5nS3/view?usp=sharing][1]

A: Check this out: https://jsfiddle.net/97j9gmtm/2/ You need to put the "owl-carousel" class on your carousels, independently a number of them.
$(document).ready(function(){
    $('.owl-one').owlCarousel({
        loop:true,
        margin:10,
        nav:true,
        responsive:{
            0:{
                items:1
            },
            600:{
                items:2
            },
            1000:{
                items:3
            }
        }
    });

    $('.owl-two').owlCarousel({
        loop:true,
        margin:10,
        nav:true,
        responsive:{
            0:{
                items:1
            },
            600:{
                items:2
            },
            1000:{
                items:3
            }
        }
    });

    $('.owl-three').owlCarousel({
        loop:true,
        margin:10,
        nav:true,
        responsive:{
            0:{
                items:1
            },
            600:{
                items:2
            },
            1000:{
                items:3
            }
        }
    });
});

Or if they are all going to have them same settings you could use:
$(".owl-carousel").each(function(){
    $(this).owlCarousel({
      loop:true,
        margin:10,
        nav:true,
        navText: ['next','prev'],
        responsive:{
            0:{
                items:1
            },
            600:{
                items:1
            },
            1000:{
                items:1
            }
        }
    });
  });


text:
Q: shell script -S and -Sd code not working correctly I have the following code:
#Option -s for each set of files with the same name, presents sorted by size#

elif [ $1 = "-S" ]
then
    shift
    for i in $*
    do
        find $i -type f -print|while read F1
            do

                basename "${F1}"
            done | sort | uniq -d | while read F2
            do
                    find $i -type f -name "${F2}" -exec ls -l -S -R '{}' \;
            done
        done

#Option -d performs sorting in descending order.

elif [ $1 = "-d" ]
then
    shift
    for i in $*
    do
        find $i -type f -print|while read F1
            do

                basename "${F1}"
            done | sort | uniq -d | while read F2
            do
                    find $i -type f -name "${F2}" -exec ls -l '{}' \;
            done
        done

I was supposed to print them by size with the command -S and then in descending order with -Sd. My output doesn't seem to do that. At this point I can't figure out what is wrong in my code.
-rw-r--r-- 1 quetzal quetzal 33 Out  7 20:27 aa/cc/t1
-rw-r--r-- 1 quetzal quetzal 8 Out  7 20:36 aa/t1
-rw-r--r-- 1 quetzal quetzal 0 Out  8 08:16 aa/cc/t2
-rw-r--r-- 1 quetzal quetzal 0 Out  8 08:15 aa/t2
-rw-r--r-- 1 quetzal quetzal 16 Out  8 08:16 aa/cc/t4
-rw-r--r-- 1 quetzal quetzal 0 Out 10 12:53 aa/dd/t4

A: Reverse the sort like this:
elif [ $1 = "-d" ]
then
shift
for i in $*
do
    find $i -type f -print|while read F1
        do

            basename "${F1}"
        done | sort -r | uniq -d | while read F2
        do
                find $i -type f -name "${F2}" -exec ls -l '{}' \;
        done
    done


text:
Q: fedora 17 with fedup 0.7 I get the bug described here when trying to upgrade to Fedora 20 from Fedora 17.

The symptom is that the first stage of upgrade (before rebooting)
  works successfully, but when you reboot to complete the upgrade, the
  second stage begins but almost immediately aborts and reboots back to
  your previous Fedora system.

Guess I'm running fedup 0.7 (see terminal output)
[root@localhost mylaptop]# yum install fedup
Loaded plugins: langpacks, presto, refresh-packagekit
Package fedup-0.7.3-5.fc17.noarch already installed and latest version
Nothing to do

There is a mention about getting fedup 0.8 from updates repository but that's in my repolist:
[root@localhost mylaptop]# yum repolist
Loaded plugins: langpacks, presto, refresh-packagekit
repo id                         repo name                                 status
adobe-linux-x86_64              Adobe Systems Incorporated                     2
fedora/17/x86_64                Fedora 17 - x86_64                        27,033
updates/17/x86_64               Fedora 17 - x86_64 - Updates              13,163
repolist: 40,198

The solution described is to update fedup to 0.8 but as you can see in the output it won't because 0.7 is installed and latest version. What am I to do next?
[UPDATE]
Got the fedup package from http://kojipkgs.fedoraproject.org//packages/fedup/0.8.0/3.fc18/noarch/fedup-0.8.0-3.fc18.noarch.rpm
After installing (double clicking the file); as root copied the files I've already downloaded using fedup 0.7
cp -R /var/lib/fedora-upgrade /var/lib/system-upgrade
cp -R /var/tmp/fedora-upgrade /var/tmp/system-upgrade

Running fedup again as root:
 fedup --network 20 --nogpgcheck

[UPDATE]
After that it will boot through the update upgrade and boots into .... Fedora 17 :(
Can reboot again and have the upgrade option again that will boot into 17 again minus a working wifi.

A: You need to enable the updates-testing repo:
su -c 'yum install fedup --enablerepo=updates-testing'

For additional information see: https://fedoraproject.org/wiki/QA:Updates_Testing
Generally you leave this repo disabled unless you are involved in testing ;)

A: Try to update to the next version first. Then the next and so on. Skipping versions is not recommended.
And don't forget to add the product option for the latest versions.

A: I ended up having the exact same symptomes as you describe when trying to upgrade Fedora 17 to 20 using fedup and using your steps to solve it.
My final solution was updating to Fedora 18 using the yum way described here
After this step I was able to go from Fedora 18 to 20 using fedup like you wrote.
  sudo fedup --network 20 --nogpgcheck

Since I tried your described way in the beginning I also had fedup 0.8 installed when I was trying. So without this step you might still need to update fedup 0.7 to 0.8 under Fedora 18 using
sudo yum --enablerepo=updates-testing update fedup

You can check with sudo yum info fedup what version you have installed.


text:
Q: Package scanning Spring 3 context:component-scan in the <context:component-scan base-package=
is there any diference in doing com.mycompany.proyect.dao or com.mycompany. I have this doubt because in both ways works. I have a project A that access some data, this project is packed as a jar, then the project B imports project A. Both have different package structure like com.mycompany.proyectA.dao and com.mycompany.proyectB.dao. So, to make the component scanning work. i declared the context:component-scan as follows com.mycompany. I must to say that this declaration is working, but in every example in spring (or other places) always use com.mycompany.dao. Are there some issues working in this way?
Thank you.

A: As far as I can tell, there seems to some conflict between DAO methods in com.mycompany.proyectA.dao and com.mycompany.proyectB.dao
The solution is to split into 2 context:component-scan one for projectADao and one for projectBDao.
Further more you can split the context:component-scan in 2 xml files like daoA.xml and daoB.xml and then have a context:component-scan in each , ex: context:component-scan as com.mycompany.proyectA.dao and  context:component-scan as com.mycompany.proyectB.dao respectively.


text:
Q: What's resolutions and overrides in a `bower.json` file? In a bower.json file, what are the resolution and overrides properties used for?
{
  "name": "name",
  "dependencies": {
    "angular": "~1.4.8",
    ...
    "jquery": "2.2.4"
  },
  "overrides": {
    "ionic": {
      "main": [
        "release/js/ionic.js",
        "release/js/ionic-angular.js"
      ]
    }
  },
  "resolutions": {
    "angular-ui-router": "~0.2.15",
    "angular": "~1.5.3"
  }
}

A: Multiple Bower packages can list different versions of the same library as a dependency. The resolutions section specifies which version of the library to use whenever this type of situation occurs. If not specified in bower.json, you will receive a command line prompt upon running bower install.
The overrides section makes it possible to override default paths to assets installed through Bower when using a task runner like Gulp. If you intend to move files from their default location in the bower_components folder to accommodate your build process, for example, it could prove handy in this type of setup.

A: Resolution
The resolution section appears when you need to resolve dependency versions (after bower install) when conflicts occur. It's for making a decision regarding which concrete version of a dependency to use when the need to resolve dependency conflicts arises - bower automatically injects this decision as the "resolution" record. So the next time a conflict occurs (when updating the dependency tree, etc), the resolved version will be based on the "resolution" data in your configuration file.

Overrides
Overrides section is used to override the file(s) references when pointing to dependent library.
Task runners in most cases use the bower configuration library metadata to inject links to these libraries into a page's content. When we want to inject a bootstrap link into a page, we do not need to go into the "bower_components" folder, find the package, and investigate the file content. We can use the component metadata to find the main, injectable file reference.
The "overrides" section is used to change this data to use another file, or even a set of files, as a package's main entry point.

A: We use resolutions object in your bower.json file to specify the component name & version to automatically resolve the conflict when running bower commands.
Overrides section is used to override the file(s) references when pointing to dependent library.


text:
Q: Creating Title String in sitefinity I am trying to create a unique title in sitefinity, the current title is something like this: "Chicken Sandwich". This is the code that is creating the title:
Page.Title  = (this._Product.PageTitle != "" ) ? this._Product.PageTitle : this._Product.Name;

I want to title to be something like this "Nutritional Information for Chicken Sandwich".

A: In Sitefinity 4/5 you kind of have 2 different titles. The first one is the 'name' of the page, the second is the Title for search engines. The name is seen throughout the backend of Sitefinity and is used in the navigation widgets. See screenshot here
You can retrieve both by the following statements:
string shorttitle = new PageManager().GetPageNode(new Guid(SiteMapBase.GetCurrentProvider().CurrentNode.Key)).Title;

and
string longtitle = new PageManager().GetPageNode(new Guid(SiteMapBase.GetCurrentProvider().CurrentNode.Key)).Page.HtmlTitle;

Hope it helps!
Jochem


text:
Q: Getting Error in this C program for Romans to Integers using Structures.Can someone please look into this Getting Error in this C program for Romans to Integers using Structures.Can someone please look into this errors.
details about this program is to convert Roaman to integers without using arrays.
struct key_value
{
    char* key;
    int value;
};
int main(void) {
    //int number_of_keys = 7,
    int result = 0, x1, x2;
    //struct key_value *kv = malloc(sizeof(struct key_value) * number_of_keys);
    struct key_value kv[7];
    char input[50];
    kv[0].key = "I";
    kv[0].value = 1;
    kv[1].key = "V";
    kv[1].value = 5;
    kv[2].key = "X";
    kv[2].value = 10;
    kv[3].key = "L";
    kv[3].value = 50;
    kv[4].key = "C";
    kv[4].value = 100;
    kv[5].key = "D";
    kv[5].value = 500;
    kv[6].key = "M";
    kv[6].value = 1000;
    int i = 0;
    scanf("%s", input);
    while (input[i] != '\0') {
        /* Stop looping when we reach the null-character. */
        for (int j = 0; j < 7; j++) {
            if (input[i] == kv[j].key) {
                x1 = kv[j].value;
            }
        }
        if (i + 1 < strlen(input)) {
            for (int k = 0; k < 7; k++) {
                if (input[i] == kv[k].key) {
                    x2 = kv[k].value;
                }
            }
            if (x1 >= x2) {
                result = result + x1;
            }
            else {
                result = result + x2 - x1;
                i++;
            }
        }
        else {
            result = result + x1;
        }
    }
    printf("Result is %d", result);
    free(kv);
}

The errors are:
main.c:37:17: warning: comparison between pointer and integer
37 |      if(input[i]==kv[j].key){
  |                 ^~
main.c:43:17: warning: comparison between pointer and integer
43 |      if(input[i]==kv[k].key){
  |                 ^~
main.c:61:5: warning: attempt to free a non-heap object 'kv' [-Wfree-nonheap-object]
61 |     free(kv);
  |     ^~~~~~~~


text:
Q: responsive template joomla I am using joomla 3.0 I want to create a responsive template , I am using gantry for that. gantry
I have my main menu, in gantry framework I activate posicion top and header, I put my menu in position header-a
But dont show me nothing. anyone know How work this framework, I saw all documentacion apparently is very easy
anyone know good documentacion to create a responsive template

A: Gantry is a good choice for a responsive Joomla template.
It may not be obvious but you need to install RokNavMenu as the default menu system in Gantry.
It's a free download from the RocketTheme website.


text:
Q: How should I handle the fd passed to fdopen or fdopendir if the function fails? If I have the following:
const int fd = open("somedir", O_DIRECTORY);
if (fd == -1) {
    return FAIL;
}
DIR *const dir = fdopendir(fd);
if (!dir) {
    // close(fd) OR NOT?
    return FAIL;
}
// Do stuff with dir
return closedir(dir) ? FAIL : SUCCESS;

What is the state of the fd passed should fdopendir or fdopen fail? Should I close it, risking extraneous system calls at best or undefined behavior at worst if fd is invalidated by the call, or should I not call close(), and risk leaking resources/open file descriptors? I could not find docs that specify how to handle the fd passed to these functions should the functions fail.


text:
Q: What is the name to describe the critical point for: $f(x) = 2-x^3$ It's neither the local minimum or maximum, but I was wondering if there is another way to describe it like infimum or supremum?  I've been reading about those but they don't seem to suit it either.
Please enlighten me.

A: Here's your function $f$ plotted:

The point where the curvature changes its sign is called the inflection point. The curvature corresponds to the second derivative; to find an inflection point, we can set the second derivative to zero to find candidates for inflection points (when it goes from having one sign to another, it must go through zero). To find this point in your case, calculate the second derivative and set equal to zero:
$$\frac{d^2f}{dx^2}=0 \leftrightarrow -6x=0 \leftrightarrow x=0$$
which is precisely the value of $x$ for which we find our inflection point in $f$. You can check that this actually is an inflection point by looking at points right before and after $x=0$ and see that $f''(x)$ in fact does have a different sign in those cases.


text:
Q: Magento Split Order via product's attribute manufacturer I am trying to split order by using product's manufacturer attribute.Like if there are 3 products in cart as 2 lee(manufacturer) products and 1 Levis(manufacturer) product.So when we place order it should generate 2 order one for lee and other one is for levis.
So with some help i am able to split order(problem in total but's it's ok)but it's creating order per product like 5 product 5 orders, so i am just asking is it possible to do as i want?
Here is code for split order which i am using currently
class PMTECH_Splitorder_Model_Checkout_Type_Onepage extends Mage_Checkout_Model_Type_Onepage
{
    /**
        * Create order based on checkout type. Create customer if necessary.
        *
        * @return Mage_Checkout_Model_Type_Onepage
    */
    public function saveOrder()
    {
        $this->validate();
        $isNewCustomer = false;
        switch ($this->getCheckoutMethod()) {
            case self::METHOD_GUEST:
            $this->_prepareGuestQuote();
            break;
            case self::METHOD_REGISTER:
            $this->_prepareNewCustomerQuote();
            $isNewCustomer = true;
            break;
            default:
            $this->_prepareCustomerQuote();
            break;
        }

        $cart = $this->getQuote();

        $key=0;
        foreach ($cart->getAllItems() as $item)
        {

            $key= $key+1;
            $temparray[$key]['product_id']=  $item->getProduct()->getId();

            $temparray[$key]['qty']= $item->getQty();
            $cart->removeItem($item->getId());
            $cart->setSubtotal(0);
            $cart->setBaseSubtotal(0);

            $cart->setSubtotalWithDiscount(0);
            $cart->setBaseSubtotalWithDiscount(0);

            $cart->setGrandTotal(0);
            $cart->setBaseGrandTotal(0);

            $cart->setTotalsCollectedFlag(false);
            $cart->collectTotals();
        }
        $cart->save();

        foreach ($temparray as $key => $item)
        {
            $customer_id = Mage::getSingleton('customer/session')->getId();

            $store_id = Mage::app()->getStore()->getId();
            $customerObj = Mage::getModel('customer/customer')->load($customer_id);
            $quoteObj = $cart;
            $storeObj = $quoteObj->getStore()->load($store_id);
            $quoteObj->setStore($storeObj);
            $productModel = Mage::getModel('catalog/product');
            $productObj = $productModel->load($item['product_id']);
            $quoteItem = Mage::getModel('sales/quote_item')->setProduct($productObj);
            $quoteItem->setBasePrice($productObj->getFinalPrice());
            $quoteItem->setPriceInclTax($productObj->getFinalPrice());
            $quoteItem->setData('original_price', $productObj->getPrice());
            $quoteItem->setData('price', $productObj->getPrice());
            $quoteItem->setRowTotal($productObj->getFinalPrice());
            $quoteItem->setQuote($quoteObj);
            $quoteItem->setQty($item['qty']);
            $quoteItem->setStoreId($store_id);
            $quoteObj->addItem($quoteItem);

            $quoteObj->setBaseSubtotal($productObj->getFinalPrice());
            $quoteObj->setSubtotal($productObj->getFinalPrice());
            $quoteObj->setBaseGrandTotal($productObj->getFinalPrice());
            $quoteObj->setGrandTotal($productObj->getFinalPrice());

            $quoteObj->setStoreId($store_id);
            $quoteObj->collectTotals();
            $quoteObj->save();
            $this->_quote=$quoteObj;

            $service = Mage::getModel('sales/service_quote', $quoteObj);
            $service->submitAll();

            if ($isNewCustomer) {
                try {
                    $this->_involveNewCustomer();
                    } catch (Exception $e) {
                    Mage::logException($e);
                }
            }

            $this->_checkoutSession->setLastQuoteId($quoteObj->getId())
            ->setLastSuccessQuoteId($quoteObj->getId())
            ->clearHelperData();

            $order = $service->getOrder();
            if ($order) {
                Mage::dispatchEvent('checkout_type_onepage_save_order_after',
                array('order'=>$order, 'quote'=>$quoteObj));
                $quoteObj->removeAllItems();
                $quoteObj->setTotalsCollectedFlag(false);
                $quoteObj->collectTotals();

            }

            /**
                * a flag to set that there will be redirect to third party after confirmation
                * eg: paypal standard ipn
            */
            $redirectUrl = $this->getQuote()->getPayment()->getOrderPlaceRedirectUrl();
            /**
                * we only want to send to customer about new order when there is no redirect to third party
            */
            if (!$redirectUrl && $order->getCanSendNewEmailFlag()) {
                try {
                    $order->sendNewOrderEmail();
                    } catch (Exception $e) {
                    Mage::logException($e);
                }
            }

            // add order information to the session
            $this->_checkoutSession->setLastOrderId($order->getId())
            ->setRedirectUrl($redirectUrl)
            ->setLastRealOrderId($order->getIncrementId());

            // as well a billing agreement can be created
            $agreement = $order->getPayment()->getBillingAgreement();
            if ($agreement) {
                $this->_checkoutSession->setLastBillingAgreementId($agreement->getId());
            }
        }

        // add recurring profiles information to the session
        $profiles = $service->getRecurringPaymentProfiles();
        if ($profiles) {
            $ids = array();
            foreach ($profiles as $profile) {
                $ids[] = $profile->getId();
            }
            $this->_checkoutSession->setLastRecurringProfileIds($ids);
            // TODO: send recurring profile emails
        }

        Mage::dispatchEvent(
        'checkout_submit_all_after',
        array('order' => $order, 'quote' => $this->getQuote(), 'recurring_profiles' => $profiles)
        );

        return $this;
    }

}

And i think it will be helpful to insert data in flat order quote item so i have  that field in this table with product's manufacturer id inserted in it
Thank you in advance for any help.

A: I found solution on my own, posting answer so may be it can help someone.
i am posting what i made changes in code.
foreach ($cart->getAllItems() as $item)
        {

            $key= $key+1;
            $product = Mage::getModel('catalog/product')->load($item->getProduct()->getId());

            $temparray[$product->getManufacturer()][] = array('product_id'=>$item->getProduct()->getId(),'qty'=>$item->getQty());
            //added this above line for grouping products by brands
            $cart->removeItem($item->getId());
            $cart->setSubtotal(0);
            $cart->setBaseSubtotal(0);

            $cart->setSubtotalWithDiscount(0);
            $cart->setBaseSubtotalWithDiscount(0);

            $cart->setGrandTotal(0);
            $cart->setBaseGrandTotal(0);

            $cart->setTotalsCollectedFlag(false);
            $cart->collectTotals();
        }
        $cart->save();

        foreach ($temparray as $key => $items)
        { // this ends as it is in my question code
            foreach($items as $item){ //added this foreach
                $customer_id = Mage::getSingleton('customer/session')->getId();

                $store_id = Mage::app()->getStore()->getId();
                $customerObj = Mage::getModel('customer/customer')->load($customer_id);
                $quoteObj = $cart;
                $storeObj = $quoteObj->getStore()->load($store_id);
                $quoteObj->setStore($storeObj);
                $productModel = Mage::getModel('catalog/product');
                $productObj = $productModel->load($item['product_id']);
                $quoteItem = Mage::getModel('sales/quote_item')->setProduct($productObj);
                $quoteItem->setBasePrice($productObj->getFinalPrice());
                $quoteItem->setPriceInclTax($productObj->getFinalPrice());
                $quoteItem->setData('original_price', $productObj->getPrice());
                $quoteItem->setData('price', $productObj->getPrice());
                $quoteItem->setRowTotal($productObj->getFinalPrice() * $item['qty']);
                $quoteItem->setQuote($quoteObj);
                $quoteItem->setQty($item['qty']);
                $quoteItem->setManufacturerName($key);//not sure about this that i need to add this or not
                $quoteItem->setStoreId($store_id);
                $quoteObj->addItem($quoteItem);

                $quoteObj->setBaseSubtotal($productObj->getFinalPrice());
                $quoteObj->setSubtotal($productObj->getFinalPrice());
                $quoteObj->setBaseGrandTotal($productObj->getFinalPrice());
                $quoteObj->setGrandTotal($productObj->getFinalPrice());

                $quoteObj->setStoreId($store_id);
                $quoteObj->collectTotals();
                $quoteObj->save();
                $this->_quote=$quoteObj;
            }

Okay so by doing this now i am able to split order by brand as i want.


text:
Q: Is there a way to add this JavaScript to an HTML file? Can I add JavaScript code like this to an HTML file? How?
fill(0, 0, 0);
ellipse(200, 200, 375, 375);
fill(60, 0, 255);
triangle(200, 104, 280, 280, 120, 280);
fill(255, 255, 255);
var answer = floor(random(1, 5));
if (answer === 2) {
    text("NOT YET", 176, 200);
}
else if( answer===3)
{
    text("IMPLEMENTED", 159, 229);
}
else if(answer===4){
    text("Yes",185,229);
}
else if(answer===1){
    text("NO",185,229);
}
else if(answer===5){
    text("Try Again",185,200);
}

A: <script type="text/javascript">
// code in here
</script>

You don't even really need the 'type' attribute any more!


text:
Q: Bulk upload string columns as VARCHAR to Amazon Redshift Is it possible to pass VARCHARS to an SQL DB (AWS Redshift) instead of Strings in bulk without creating the table on my own?
I have the following code:
import pandas as pd

d = {'actually_a_string': "Super_Long_String_Even_Longer_Than_256_Characters"}

df = pd.DataFrame(data=d)

Now I want to bulk upload it to AWS Redshift.
Problem is: they only allow Strings to have characters < 256.
So when I bulk upload it with:
import sqlalchemy as sa
import psycopg2
engine = sa.create_engine('postgres://[USER]:[PASSWORD]@[URL]/[PORT]/[DB_NAME]'
df.to_sql(con=engine, name='test', if_exists='replace', index=False)

It gives me the following error:
(psycopg2.errors.StringDataRightTruncation) value too long for type character varying(256)

Redshift actually allows VARCHARS to be huge, like 60k characters or so.

Is it possible to tell postgres to pass VARCHARS instead of Strings somehow?
My table is huge so I really don't want to create it on my own and define all columns etc.

Thank you in advance :)

A:
I found a way to bulk upload it
orders.to_sql(con=engine,
dtype={col_name: sqlalchemy.types.VARCHAR (length=60000) for col_name in orders},
name='orders_shopify_de', if_exists='replace', index=False, method='multi')

With this it's working, although defining a hardcoded length for every column is not the best solution.
So case closed. Thank you for your help. :)


text:
Q: Simulink Project dependency management and dependency resolution What is the best practice for managing dependencies within a Simulink Project when the project is worked on across a team and the project has dependencies on different models and libraries?
An parallel example would be when building an application using Gradle and declaring the dependencies of a project including the required version numbers.  Grade will resolve and download the versions that are required to build the project.
e.g. the following declares a dependency on version 2.1 of library and version 1.0 upwards of some-library, so that the latest version 1.x (1.0, 1.1, 1.2...) that is available will be downloaded and used.
dependencies {
    compile("com.example:library:2.1")
    compile("com.example:some-library:1.+")
}

The documentation for Simulink (and also here covering manifests) seems to talk about models within a project having version numbers. It doesn't seem to mention libraries that are imported into the project.  Models that are only used within a single project could all be contained in the overall project, but what happens if there are (for example) generic S-Functions defined within a separate project or library (or library defined within a project) that are applicable across multiple projects?  This requirement is all with the aim of helping to support an automatic build process triggered by a Continuous Integration server, such as Jenkins.
I'm interested in a workflow that will easily support dependency management and automatic dependency resolution with a Github Flow git branching policy.

A: I've spent much time on this problem. Finally I didn't find an appropriate solution online, but I'd like to share the workflow we are using now and which fulfills our needs.
In short: We created our own dependency management by using git submodules.
Assumption:  In fact, it is more a version management of persistent dependencies rather than offering the possibility to dynamically add new or remove old packages or libraries. This also works, but requires the git submodules to be added to or removed from the main git repository.
Objectives:

*

*Consistent setup for everyone who works on the project.

*Traceability of depdendencies.

*Continous Integration with less effort.

How we do it (Example):

*

*We have Project A and Project B which shall be used in Project C.

*All three projects are under git version control and still under development.

*We have set up additional release repositories for Project A and Project B, e.g. located on a network drive.

*In Project C we add the release repositories of Project A and Project B as git submodules

*We have set up some kind of auto-deployment to push only relevant files into these release repositories. For example if we want to make changes of Project B accessible to Project C, we only create a version tag in Project B's repository and it gets pushed to its release repository.

*In Project C we update our git submodules and can checkout a new submodule version (if needed).

Advantages:

*

*Since git stores the checked out version (commit) of git submodules in the main project, we can ensure that everyone works with the same files.

*Changing the commit of a submodule is traceable in the main project.

*The relation between the main project and the dependencies is always consistent.

*Continuous Integration should work "out of the box". We are using GitLab and GitLab Runner and only had to setup our runner to fetch submodules recursively (in case of nested submodules).

I think this approach works as long as the repositories won't get too big, since you do not fetch only the version you need but also the whole version history.


text:
Q: Unit spacing with siunitx in an equation I'm just starting to get to grips with the siunitx package, but I've noticed that there seems to be some issues with regards to unit notation spacing in an equation.  With siunitx it is possible to put a space between the numerical value and the unit by leaving a space after the number of before the unit (e.g., \num{3.7d10} \si{\becquerel} or \num{3.7d10}\si{ \becquerel}).
However, when I do this in equation mode there doesn't seem to be a way to create a space between the number and the unit. Am I missing something, or is this an inherent fault/problem?
\documentclass[12pt,a4paper]{report}
% International language package - allows use of special characters
\usepackage[utf8]{inputenc}
% Line spacing package - allows user to set line spacing
\usepackage{amsmath}
% Graphics package - allows document to include various graphics files
\usepackage{chemformula}
% SI Unit package - allows for standard unit notation
\usepackage{siunitx}
\DeclareSIUnit\curie{Ci}

\begin{document}

% no spaces
\num{3.7d10}\si{\becquerel} \\

% space before unit
\num{3.7d10}\si{ \becquerel} \\

% space after number
\num{3.7d10} \si{\becquerel} \\

% no spaces
\begin{equation}
\num{1}\si{\becquerel} = \num{2.703d11}\si{\curie} \\
\end{equation}

% spaces before units
\begin{equation}
\num{1}\si{ \becquerel} = \num{2.703d11}\si{ \curie} \\
\end{equation}

% spaces after number
\begin{equation}
\num{1} \si{\becquerel} = \num{2.703d11} \si{\curie} \\
\end{equation}

\end{document}

A: Unless I'm missing something obvious, you can just use
\documentclass{article}

\usepackage{siunitx}

\begin{document}

\begin{equation}
  \SI{1.234}{\m\per\square\s}
\end{equation}

\end{document}

Another possibility (but not a recommended one) is
\documentclass{article}

\usepackage{siunitx}

\begin{document}

\begin{equation}
  \num{1.234}\,\si{\m\per\square\s}
\end{equation}

\end{document}

The second approach should only be used if you want alignment points at both the numbers and the units, as shown here.

A: When you're typesetting a numerical quantity with units, you're supposed to use the \SI macro:
\SI{3.7d10}{\becquerel}

That effectively formats the first argument using \num, the second using \si, and inserts the proper spacing between them, even when typesetting an equation (i.e. when in math mode).
Normally spaces are ignored in math mode, so that you can write e.g. 3\times 10 or 3 \times 10 and the result will be the same.


text:
Q: get the offset of a tuple element I have wrote the following code to get the offset of a tuple element
template<size_t Idx,class T>
 constexpr size_t tuple_element_offset() {
        return static_cast<size_t>(
                    reinterpret_cast<char*>(&std::get<Idx>(*reinterpret_cast<T*>(0))) - reinterpret_cast<char*>(0));
    }

This is actually similar to the implementation of the offsetof macro.
It looks ugly, but compiles and works fine on gcc-4.6
typedef std::tuple<int,char,long> mytuple;

mytuple var = std::make_tuple(4,'c',1000);
char * ptr = reinterpret_cast<char*>(&var);
long * pt = reinterpret_cast<long*>(ptr+tuple_element_offset<2,mytuple>());

std::cout << *pt << std::endl;

prints "1000".
I don't know too much about constexpr, so my questions are:

*

*Is it legal c++?

*More important, why I am allowed to call
std::get (which is non constexpr)
inside a constexpr function?

As far as I understand constexpr, the compiler is forced to evaluate the result
of the expression at compile time, so no zero-dereferentiation can occurs in practice.

A:
Is it legal C++?

If by "legal" you mean "well-formed," then, yes.
If by "legal" you mean "valid and will work on any compiler and Standard Library implementation, then, no, because std::tuple is not POD.

Why I am allowed to call std::get (which is not constexpr) inside a constexpr function?

Basically, a constexpr function doesn't necessarily have to consist of just a constant expression.  If you tried to use your tuple_element_offset() function in a constant expression, you'd get a compilation error.
The idea is that a function might be usable in a constant expression in some circumstances but not in others, so there isn't a restriction that a constexpr function must always be usable in a constant expression (since there isn't such a restriction, it's also possible that a particular constexpr function might never be usable in a constant expression, as is the case with your function).
The C++0x draft has a good example (from 5.19/2):
constexpr const int* addr(const int& ir) { return &ir; } // OK

// OK: (const int*)&(const int&)x is an address contant expression
static const int x = 5;
constexpr const int* xp = addr(x);

// Error, initializer for constexpr variable not a constant expression;
// (const int*)&(const int&)5 is not a constant expression because it takes
// the address of a temporary
constexpr const int* tp = addr(5);