问:
Android: gridView set not scrollable?
I'm trying to do filter section by gridView. In a wide screen it's fine. But when it's small screen is not working correctly. (One view is two or three times, some is dissapearing) It's because gridView item's shrinking and scroll is appearing. So i trying to remove gridView scroll.

My activity is.

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="fill_parent"
     android:layout_width="fill_parent"
    android:fillViewport="true"
    android:scrollbars="vertical">
<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        android:theme="@style/ThemeOverlay.AppCompat.Dark"
        app:titleTextColor="@android:color/white"
        app:contentInsetStartWithNavigation="0dp">
    </android.support.v7.widget.Toolbar>

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="11"
            android:orientation="vertical"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp">

        <TextView
            android:text="Price"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="start|bottom"
            android:textStyle="bold"
            android:textColor="@color/colorPrimary"
            android:layout_marginTop="20dp" />

        <TextView
            android:id="@+id/seekbar_value"
            android:text="Any"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center|bottom"
            android:textStyle="bold"/>

        <org.florescu.android.rangeseekbar.RangeSeekBar
            android:id="@+id/range_seekbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:showLabels="false"
            app:valuesAboveThumbs="false"
            app:barHeight="5dp"
            app:alwaysActive="true"
            app:thumbDisabled="@drawable/seekbar_button"
            app:textAboveThumbsColor="@color/colorPrimary"
            app:defaultColor="@color/colorPrimary"
            app:activeColor="@color/colorButton" />

        <TextView
            android:text="Block"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="start|bottom"
            android:textStyle="bold"
            android:textColor="@color/colorPrimary"
            android:layout_marginTop="20dp"/>

            <GridView
                android:id="@+id/gridViewBlock"
                android:numColumns="auto_fit"
                android:gravity="center"
                android:columnWidth="60dp"
                android:stretchMode="columnWidth"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"/>

            <TextView
            android:text="Floor"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="start|bottom"
            android:textStyle="bold"
            android:textColor="@color/colorPrimary"
            android:layout_marginTop="20dp"/>

           <!--  This Grid View is my problem -->
            **<GridView
                android:id="@+id/gridViewFloor"
                android:numColumns="auto_fit"
                android:gravity="center"
                android:columnWidth="60dp"
                android:stretchMode="columnWidth"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"/>**

        </LinearLayout>

        <Button
            android:text="See result"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:textStyle="bold"
            android:background="@color/colorButton"
            android:textColor="@android:color/white" />

    </LinearLayout>

</LinearLayout>
</ScrollView>
</code>```

And i programmatically adding gridView items:

```<code>public class FIlterActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private RangeSeekBar seekbar;
    private TextView seekbarValue;
    private GridView gridViewBlock;
    private GridView gridViewFloor;
    private FilterButtonAdapter filterBlockAdapter;
    private FilterButtonAdapter filterFloorAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_filter);
        toolbar = (Toolbar)findViewById(R.id.toolbar);
        toolbar.setTitle(getString(R.string.activity_filter));
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        gridViewBlock = (GridView) findViewById(R.id.gridViewBlock);

        filterBlockAdapter = new FilterButtonAdapter(this, Filter.filter_blocks, Filter.blocks_selected);
        gridViewBlock.setAdapter(filterBlockAdapter);

        gridViewBlock.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                final TextView textView = (TextView)view.findViewById(R.id.filter_button);
                String value = textView.getText().toString();
                boolean contain = false;

                for(int i = 0; i < Filter.blocks_selected.size(); i++){
                    if(value.equals(Filter.blocks_selected.get(i).toString())) {
                        view.setBackgroundResource(R.drawable.button_disabled);
                        Filter.blocks_selected.remove(i);
                        if(Filter.blocks_selected.size() == 0){
                            Filter.blocks_selected.add(Filter.filter_blocks[0]);
                            adapterView.getChildAt(0).setBackgroundResource(R.drawable.button_enabled);
                        }
                        contain = true;
                        break;
                    }
                }
                if(!contain){
                    if(value.equals("Any")){
                        Filter.blocks_selected.clear();
                        Filter.blocks_selected.add(Filter.filter_blocks[0]);
                        for(int i = 1; i < Filter.filter_blocks.length; i++){
                            adapterView.getChildAt(i).setBackgroundResource(R.drawable.button_disabled);
                        }
                    }
                    else{
                        for(int i = 0; i < Filter.blocks_selected.size(); i++){
                            if(Filter.blocks_selected.get(i).toString().equals("Any")){
                                adapterView.getChildAt(0).setBackgroundResource(R.drawable.button_disabled);
                                Filter.blocks_selected.remove(i);
                                break;
                            }
                        }
                    }
                    view.setBackgroundResource(R.drawable.button_enabled);
                    Filter.blocks_selected.add(value);}
                filterBlockAdapter.notifyDataSetChanged();
            }
        });

        gridViewFloor = (GridView) findViewById(R.id.gridViewFloor);
        filterFloorAdapter = new FilterButtonAdapter(this, Filter.filter_floors, Filter.floor_selected);
        gridViewFloor.setAdapter(filterFloorAdapter);

        gridViewFloor.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                final TextView textView = (TextView)view.findViewById(R.id.filter_button);
                String value = textView.getText().toString();
                boolean contain = false;

                for(int i = 0; i < Filter.floor_selected.size(); i++){
                    if(value.equals(Filter.floor_selected.get(i).toString())) {
                        view.setBackgroundResource(R.drawable.button_disabled);
                        Filter.floor_selected.remove(i);
                        if(Filter.floor_selected.size() == 0){
                            Filter.floor_selected.add(Filter.filter_floors[0]);
                            adapterView.getChildAt(0).setBackgroundResource(R.drawable.button_enabled);
                        }
                        contain = true;
                        break;
                    }
                }
                if(!contain){
                    if(value.equals("Any")){
                        Filter.floor_selected.clear();
                        Filter.floor_selected.add(Filter.filter_floors[0]);
                        for(int i = 1; i < Filter.filter_floors.length; i++){
                            adapterView.getChildAt(i).setBackgroundResource(R.drawable.button_disabled);
                        }
                    }
                    else{
                        for(int i = 0; i < Filter.floor_selected.size(); i++){
                            if(Filter.floor_selected.get(i).toString().equals("Any")){
                                adapterView.getChildAt(0).setBackgroundResource(R.drawable.button_disabled);
                                Filter.floor_selected.remove(i);
                                break;
                            }
                        }
                    }
                    view.setBackgroundResource(R.drawable.button_enabled);
                    Filter.floor_selected.add(value);}
                filterFloorAdapter.notifyDataSetChanged();
            }
        });

        seekbar = (RangeSeekBar)findViewById(R.id.range_seekbar);
        seekbarValue = (TextView)findViewById(R.id.seekbar_value);

        seekbar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener() {
            @Override
            public void onRangeSeekBarValuesChanged(RangeSeekBar bar, Object minValue, Object maxValue) {
                if(String.valueOf(bar.getAbsoluteMaxValue()).equals(maxValue.toString())){

                    if(String.valueOf(bar.getAbsoluteMinValue()).equals(minValue.toString()))
                        seekbarValue.setText("Бүх");
                    else {
                        seekbarValue.setText(minValue.toString() + " $ - +");
                    }
                } else if(String.valueOf(bar.getAbsoluteMinValue()).equals(minValue.toString())){
                    seekbarValue.setText(maxValue.toString() + " $ - -");
                } else{
                    seekbarValue.setText(minValue.toString() + " $ - " + maxValue.toString() + " $");
                }
            }
        });
    }
}
</code>```

And Filter Button Adapter

```<code>public class FilterButtonAdapter extends BaseAdapter {

    private Context context;
    private final String[] filterValues;
    private List<String> checkedFilterValues = new ArrayList<String>();

    public FilterButtonAdapter(Context context, String[] filterValues, List<String> checkedFilterValues){
        this.context = context;
        this.filterValues = filterValues;
        this.checkedFilterValues = checkedFilterValues;
    }
    @Override
    public int getCount() {
        return filterValues.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View gridView;
        if(convertView == null){

            gridView = new View(context);
            gridView = inflater.inflate(R.layout.layout_button, null);

            final TextView textView = (TextView)gridView.findViewById(R.id.filter_button);
            textView.setText(filterValues[position]);

            boolean contain = false;
            for(int i = 0; i < Filter.blocks_selected.size(); i++){
                if(filterValues[position].equals(checkedFilterValues.get(i)))
                {
                    gridView.setBackgroundResource(R.drawable.button_enabled);
                    contain = true;
                    break;
                }
            }
            if(!contain){
                gridView.setBackgroundResource(R.drawable.button_disabled);
            }
        } else gridView = (View)convertView;
        return gridView;
    }
}
</code>```

Filter class:

```<code>public class Filter {

    public static String price = "any";
    public static long priceMax = 0;
    public static long priceMin = 0;
    public static final String[] filter_blocks = new String[]{
            "any", "A", "B", "C"
    };
    public static final String[] filter_floors = new String[]{
            "any", "1", "2", "3", "4", "5", "6",
            "7", "8", "9", "10", "11", "12+"
    };

    public static List<String> blocks_selected = new ArrayList<String>(){{
        add("any");
    }
    };

    public static List<String> floor_selected = new ArrayList<String>(){{
        add("any");
    }
    };

    public static int floor = 10;

}
</code>```

My android studio emulator is 2.7 QVGA API 25

答:
Try this

```<code>ViewCompat.setNestedScrollingEnabled(gridView, true);
</code>```

Title: Android: gridView set not scrollable?

Body:
I'm trying to do filter section by gridView. In a wide screen it's fine. But when it's small screen is not working correctly. (One view is two or three times, some is dissapearing) It's because gridView item's shrinking and scroll is appearing. So i trying to remove gridView scroll.

My activity is.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="fill_parent"
     android:layout_width="fill_parent"
    android:fillViewport="true"
    android:scrollbars="vertical">
<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        android:theme="@style/ThemeOverlay.AppCompat.Dark"
        app:titleTextColor="@android:color/white"
        app:contentInsetStartWithNavigation="0dp">
    </android.support.v7.widget.Toolbar>

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="11"
            android:orientation="vertical"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp">

        <TextView
            android:text="Price"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="start|bottom"
            android:textStyle="bold"
            android:textColor="@color/colorPrimary"
            android:layout_marginTop="20dp" />

        <TextView
            android:id="@+id/seekbar_value"
            android:text="Any"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center|bottom"
            android:textStyle="bold"/>

        <org.florescu.android.rangeseekbar.RangeSeekBar
            android:id="@+id/range_seekbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:showLabels="false"
            app:valuesAboveThumbs="false"
            app:barHeight="5dp"
            app:alwaysActive="true"
            app:thumbDisabled="@drawable/seekbar_button"
            app:textAboveThumbsColor="@color/colorPrimary"
            app:defaultColor="@color/colorPrimary"
            app:activeColor="@color/colorButton" />

        <TextView
            android:text="Block"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="start|bottom"
            android:textStyle="bold"
            android:textColor="@color/colorPrimary"
            android:layout_marginTop="20dp"/>

            <GridView
                android:id="@+id/gridViewBlock"
                android:numColumns="auto_fit"
                android:gravity="center"
                android:columnWidth="60dp"
                android:stretchMode="columnWidth"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"/>

            <TextView
            android:text="Floor"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="start|bottom"
            android:textStyle="bold"
            android:textColor="@color/colorPrimary"
            android:layout_marginTop="20dp"/>

            **<GridView
                android:id="@+id/gridViewFloor"
                android:numColumns="auto_fit"
                android:gravity="center"
                android:columnWidth="60dp"
                android:stretchMode="columnWidth"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"/>**

        </LinearLayout>

        <Button
            android:text="See result"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:textStyle="bold"
            android:background="@color/colorButton"
            android:textColor="@android:color/white" />

    </LinearLayout>

</LinearLayout>
</ScrollView>

And i programmatically adding gridView items:

public class FIlterActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private RangeSeekBar seekbar;
    private TextView seekbarValue;
    private GridView gridViewBlock;
    private GridView gridViewFloor;
    private FilterButtonAdapter filterBlockAdapter;
    private FilterButtonAdapter filterFloorAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_filter);
        toolbar = (Toolbar)findViewById(R.id.toolbar);
        toolbar.setTitle(getString(R.string.activity_filter));
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        gridViewBlock = (GridView) findViewById(R.id.gridViewBlock);

        filterBlockAdapter = new FilterButtonAdapter(this, Filter.filter_blocks, Filter.blocks_selected);
        gridViewBlock.setAdapter(filterBlockAdapter);

        gridViewBlock.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                final TextView textView = (TextView)view.findViewById(R.id.filter_button);
                String value = textView.getText().toString();
                boolean contain = false;

                for(int i = 0; i < Filter.blocks_selected.size(); i++){
                    if(value.equals(Filter.blocks_selected.get(i).toString())) {
                        view.setBackgroundResource(R.drawable.button_disabled);
                        Filter.blocks_selected.remove(i);
                        if(Filter.blocks_selected.size() == 0){
                            Filter.blocks_selected.add(Filter.filter_blocks[0]);
                            adapterView.getChildAt(0).setBackgroundResource(R.drawable.button_enabled);
                        }
                        contain = true;
                        break;
                    }
                }
                if(!contain){
                    if(value.equals("Any")){
                        Filter.blocks_selected.clear();
                        Filter.blocks_selected.add(Filter.filter_blocks[0]);
                        for(int i = 1; i < Filter.filter_blocks.length; i++){
                            adapterView.getChildAt(i).setBackgroundResource(R.drawable.button_disabled);
                        }
                    }
                    else{
                        for(int i = 0; i < Filter.blocks_selected.size(); i++){
                            if(Filter.blocks_selected.get(i).toString().equals("Any")){
                                adapterView.getChildAt(0).setBackgroundResource(R.drawable.button_disabled);
                                Filter.blocks_selected.remove(i);
                                break;
                            }
                        }
                    }
                    view.setBackgroundResource(R.drawable.button_enabled);
                    Filter.blocks_selected.add(value);}
                filterBlockAdapter.notifyDataSetChanged();
            }
        });

        gridViewFloor = (GridView) findViewById(R.id.gridViewFloor);
        filterFloorAdapter = new FilterButtonAdapter(this, Filter.filter_floors, Filter.floor_selected);
        gridViewFloor.setAdapter(filterFloorAdapter);

        gridViewFloor.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                final TextView textView = (TextView)view.findViewById(R.id.filter_button);
                String value = textView.getText().toString();
                boolean contain = false;

                for(int i = 0; i < Filter.floor_selected.size(); i++){
                    if(value.equals(Filter.floor_selected.get(i).toString())) {
                        view.setBackgroundResource(R.drawable.button_disabled);
                        Filter.floor_selected.remove(i);
                        if(Filter.floor_selected.size() == 0){
                            Filter.floor_selected.add(Filter.filter_floors[0]);
                            adapterView.getChildAt(0).setBackgroundResource(R.drawable.button_enabled);
                        }
                        contain = true;
                        break;
                    }
                }
                if(!contain){
                    if(value.equals("Any")){
                        Filter.floor_selected.clear();
                        Filter.floor_selected.add(Filter.filter_floors[0]);
                        for(int i = 1; i < Filter.filter_floors.length; i++){
                            adapterView.getChildAt(i).setBackgroundResource(R.drawable.button_disabled);
                        }
                    }
                    else{
                        for(int i = 0; i < Filter.floor_selected.size(); i++){
                            if(Filter.floor_selected.get(i).toString().equals("Any")){
                                adapterView.getChildAt(0).setBackgroundResource(R.drawable.button_disabled);
                                Filter.floor_selected.remove(i);
                                break;
                            }
                        }
                    }
                    view.setBackgroundResource(R.drawable.button_enabled);
                    Filter.floor_selected.add(value);}
                filterFloorAdapter.notifyDataSetChanged();
            }
        });

        seekbar = (RangeSeekBar)findViewById(R.id.range_seekbar);
        seekbarValue = (TextView)findViewById(R.id.seekbar_value);

        seekbar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener() {
            @Override
            public void onRangeSeekBarValuesChanged(RangeSeekBar bar, Object minValue, Object maxValue) {
                if(String.valueOf(bar.getAbsoluteMaxValue()).equals(maxValue.toString())){

                    if(String.valueOf(bar.getAbsoluteMinValue()).equals(minValue.toString()))
                        seekbarValue.setText("Бүх");
                    else {
                        seekbarValue.setText(minValue.toString() + " $ - +");
                    }
                } else if(String.valueOf(bar.getAbsoluteMinValue()).equals(minValue.toString())){
                    seekbarValue.setText(maxValue.toString() + " $ - -");
                } else{
                    seekbarValue.setText(minValue.toString() + " $ - " + maxValue.toString() + " $");
                }
            }
        });
    }
}

And Filter Button Adapter

public class FilterButtonAdapter extends BaseAdapter {

    private Context context;
    private final String[] filterValues;
    private List<String> checkedFilterValues = new ArrayList<String>();

    public FilterButtonAdapter(Context context, String[] filterValues, List<String> checkedFilterValues){
        this.context = context;
        this.filterValues = filterValues;
        this.checkedFilterValues = checkedFilterValues;
    }
    @Override
    public int getCount() {
        return filterValues.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View gridView;
        if(convertView == null){

            gridView = new View(context);
            gridView = inflater.inflate(R.layout.layout_button, null);

            final TextView textView = (TextView)gridView.findViewById(R.id.filter_button);
            textView.setText(filterValues[position]);

            boolean contain = false;
            for(int i = 0; i < Filter.blocks_selected.size(); i++){
                if(filterValues[position].equals(checkedFilterValues.get(i)))
                {
                    gridView.setBackgroundResource(R.drawable.button_enabled);
                    contain = true;
                    break;
                }
            }
            if(!contain){
                gridView.setBackgroundResource(R.drawable.button_disabled);
            }
        } else gridView = (View)convertView;
        return gridView;
    }
}

Filter class:

public class Filter {

    public static String price = "any";
    public static long priceMax = 0;
    public static long priceMin = 0;
    public static final String[] filter_blocks = new String[]{
            "any", "A", "B", "C"
    };
    public static final String[] filter_floors = new String[]{
            "any", "1", "2", "3", "4", "5", "6",
            "7", "8", "9", "10", "11", "12+"
    };

    public static List<String> blocks_selected = new ArrayList<String>(){{
        add("any");
    }
    };

    public static List<String> floor_selected = new ArrayList<String>(){{
        add("any");
    }
    };

    public static int floor = 10;

}

My android studio emulator is 2.7 QVGA API 25

Body:
Try this

ViewCompat.setNestedScrollingEnabled(gridView, true);


来源: stackexchange

问:
Accessing files in a project that is on the build path of another
I'm working on a framework-type project in Eclipse, that has a res folder attached with, as you guessed Resources inside of it. At the moment, they are crucial text-files that are to be read.

I also have a main test rig that is apart of it's own Eclipse project, as I plan to expand it in the future. This test rig has included the framework project on it's Build Path, so I can access classes from the framework as they are added.

But this is where my problems lie: If I want to import a class, that works fine. If I want to access a file through an InputStream, or Reader, it breaks. I know this is because the files included from the secondary project aren't placed inside the test rigs bin folder, rather they reside in their own bin in the other project.

Is there a way I can get my main project to access resources from the other without having to do ../../ trickery in my file paths? I plan on making this a real thing and don't want file paths doing things like that.

答:
In eclipse do this,

```<code>Build Path ---> Configure Path ----> Click Project Tab ---> Add the project.
</code>```

Also, you can package the other project in a jar and import it as an external jar.

ContentLicense: CC BY-SA 3.0

Body:
In eclipse do this,

Build Path ---> Configure Path ----> Click Project Tab ---> Add the project.

Also, you can package the other project in a jar and import it as an external jar.


问:
Matplotlib 3d plot: how to get rid of the excessive white space?
If I make a 3d plot in Matplotlib:

```<code>from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')

x_labels = [10,20,30]
x = [1,2,3,4]
y = [3,1,5,1]
legend = False

for label in x_labels:
    x_3d = label*np.ones_like(x)
    ax.plot(x_3d, x, y, color='black', label='GMM')
    if legend == False:
        ax.legend()
        legend = True

ax.set_zlabel('test')
</code>```

It will produce:

The left side have excessive white space. I want to know if it is possible to get rid of it?

答:
It's probably too late, but I came across similar problems and here is what I did to remove the white space: use fig.subplot_adjust() to put left/right outside the normal region. In your case I found fig.subplot_adjust(left=-0.11) gives a reasonable result.

Full code below:

```<code>from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')

x_labels = [10,20,30]
x = [1,2,3,4]
y = [3,1,5,1]
legend = False

for label in x_labels:
    x_3d = label*np.ones_like(x)
    ax.plot(x_3d, x, y, color='black', label='GMM')
    if legend == False:
        ax.legend()
        legend = True

ax.set_zlabel('test')

fig.tight_layout()
fig.subplots_adjust(left=-0.11)  # plot outside the normal area
</code>```

Body:
If I make a 3d plot in Matplotlib:

from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')

x_labels = [10,20,30]
x = [1,2,3,4]
y = [3,1,5,1]
legend = False

for label in x_labels:
    x_3d = label*np.ones_like(x)
    ax.plot(x_3d, x, y, color='black', label='GMM')
    if legend == False:
        ax.legend()
        legend = True

ax.set_zlabel('test')

It will produce:

The left side have excessive white space. I want to know if it is possible to get rid of it?

Body:
It's probably too late, but I came across similar problems and here is what I did to remove the white space: use fig.subplot_adjust() to put left/right outside the normal region. In your case I found fig.subplot_adjust(left=-0.11) gives a reasonable result.

Full code below:

from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')

x_labels = [10,20,30]
x = [1,2,3,4]
y = [3,1,5,1]
legend = False

for label in x_labels:
    x_3d = label*np.ones_like(x)
    ax.plot(x_3d, x, y, color='black', label='GMM')
    if legend == False:
        ax.legend()
        legend = True

ax.set_zlabel('test')

fig.tight_layout()
fig.subplots_adjust(left=-0.11)  # plot outside the normal area


问:
How to get the last id from inserted row?
I'm trying to get the ID of my master table to be inserted to my transaction table. The insert is happening inside a loop.

Behavior:

Insert master

Get id

Insert Transaction

Insert Master

Get id

Insert Transaction

Controller:

```<code> //Insert Master
 foreach($arr_master as $res_master){

    /*$data['ID_REQUIREMENT_TRANS'] this is an auto-increment column. Inserted automatically*/

    $data['ID_REQUIREMENT']     = $res_master;
    $data['SENT_BY_DATE']       = date("Y-m-d H:i:s");
    $data['STATUS']             = 1;

    $this->MAdmin->ins_assign_pic($data);

        //Insert Trans
        foreach($arr_trans as $res_trans){

            $data_d['ID_REQUIREMENT_TRANS'] = $id; //Need to get the last inserted id of the master table
            $data_d['RECEIVED_BY']              = $res_trans;
            $data_d['RECEIVED_BY_DATE']     = NULL;
            $data_d['STATUS']                   = 1;

            $this->MAdmin->ins_assign_pic_d($data_d);
        }
    }
</code>```

Model:

```<code>function ins_assign_pic($data){
    $q_ins_assign_pic   = $this->db->insert('pm_requirement_assign_pic',$data);
    return $q_ins_assign_pic;

    $id = $this->db->insert_id();
    return $id;      //How to send this to my controller
    return true;
}

function ins_assign_pic_d($data_d){
    $q_ins_assign_pic_d = $this->db->insert('pm_requirement_assign_pic_d',$data_d);

    return $q_ins_assign_pic_d;
}
</code>```

答:
Way 1

```<code>SELECT MAX( id ) FROM tableName;
</code>```

Way 2

```<code>SELECT tableName.id FROM tableName ORDER BY tableName.id DESC LIMIT 0,1;
</code>```

Body:
I'm trying to get the ID of my master table to be inserted to my transaction table. The insert is happening inside a loop.

Behavior:

Insert master

Get id

Insert Transaction

Insert Master

Get id

Insert Transaction

Controller:

 //Insert Master
 foreach($arr_master as $res_master){

    /*$data['ID_REQUIREMENT_TRANS'] this is an auto-increment column. Inserted automatically*/

    $data['ID_REQUIREMENT']     = $res_master;
    $data['SENT_BY_DATE']       = date("Y-m-d H:i:s");
    $data['STATUS']             = 1;

    $this->MAdmin->ins_assign_pic($data);

        //Insert Trans
        foreach($arr_trans as $res_trans){

            $data_d['ID_REQUIREMENT_TRANS'] = $id; //Need to get the last inserted id of the master table
            $data_d['RECEIVED_BY']              = $res_trans;
            $data_d['RECEIVED_BY_DATE']     = NULL;
            $data_d['STATUS']                   = 1;

            $this->MAdmin->ins_assign_pic_d($data_d);
        }
    }

Model:

function ins_assign_pic($data){
    $q_ins_assign_pic   = $this->db->insert('pm_requirement_assign_pic',$data);
    return $q_ins_assign_pic;

    $id = $this->db->insert_id();
    return $id;      //How to send this to my controller
    return true;
}

function ins_assign_pic_d($data_d){
    $q_ins_assign_pic_d = $this->db->insert('pm_requirement_assign_pic_d',$data_d);

    return $q_ins_assign_pic_d;
}

Body:
Way 1

SELECT MAX( id ) FROM tableName;

Way 2

SELECT tableName.id FROM tableName ORDER BY tableName.id DESC LIMIT 0,1;


问:
How do I declare an array from a function globally?
I am trying to declare an array from the function globally so that my other functions can use it as well but I have no idea how to since I am using a csvtojson for converter which makes the whole thing very long and was wondering if this is the way to declare or no?

JS:

```<code>//require the csvtojson converter class
var Converter = require("csvtojson").Converter;
 // create a new converter object
var converter = new Converter({});
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';

// call the fromFile function which takes in the path to your
// csv file as well as a callback function
var JSarray = converter.fromFile("./NTA-SAM-Inventory-List-Security-
Management-New_2017.csv",function(err, result, callback){
if(err){
    console.log("An Error Has Occured");
    console.log(err);
}
// the result of the conversion
console.log(result);
result.toArray(function(err,doc){
    if(err) throw err;
    console.log('ohhhhh');
    return callback(null, doc);
}
});
</code>```

var array=[JSarray(function(err,doc)] This is how I declare the array.
My array is doc and so I can return callback but how should I get the array considering I have converter.fromFile("./NTA-SAM-Inventory-List-Security-
    Management-New_2017.csv" which is too long so do I omit it when declaring the array or am I doing it wrong ? Thanks.

Update
 Just wanted to clarify if I did it correctly.

```<code>var JSarray = converter.fromFile("./NTA-SAM-Inventory-List-Security-M
anagement-New_2017.csv",function(err, result, callback){
// if an error has occured then handle it
if(err){
    console.log("An Error Has Occured");
    console.log(err);
}
// the result of the conversion
console.log(result);
result.toArray(function(err,doc){
    if(err) throw err;
    console.log('ohhhhh');
    return callback(null, doc);
    var myArray= doc;
    GLOBAL.GlobalMyArray = myArray;
});
});
</code>```

Is this correct following your answer in declaring it globally?

答:
You can set an array global inside of a function by assigning it to the window object.

```<code>function myFunction() {
    var myArray = new Array();
    window.GlobalMyArray = myArray;
}
</code>```

Once it is set you can use GlobalMyArray from anywhere.

Using Node.Js you can use global

```<code>function myFunction() {
    var myArray = new Array();
     GLOBAL.GlobalMyArray = myArray;
}
</code>```

You can now access the array globally using GLOBAL.GlobalMyArray

In which case it is very useful to do:

```<code>GLOBAL.window = GLOBAL
</code>```

Like in the web browser.

Body:
I am trying to declare an array from the function globally so that my other functions can use it as well but I have no idea how to since I am using a csvtojson for converter which makes the whole thing very long and was wondering if this is the way to declare or no?

JS:

//require the csvtojson converter class
var Converter = require("csvtojson").Converter;
 // create a new converter object
var converter = new Converter({});
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';

// call the fromFile function which takes in the path to your
// csv file as well as a callback function
var JSarray = converter.fromFile("./NTA-SAM-Inventory-List-Security-
Management-New_2017.csv",function(err, result, callback){
if(err){
    console.log("An Error Has Occured");
    console.log(err);
}
// the result of the conversion
console.log(result);
result.toArray(function(err,doc){
    if(err) throw err;
    console.log('ohhhhh');
    return callback(null, doc);
}
});

var array=[JSarray(function(err,doc)] This is how I declare the array.
My array is doc and so I can return callback but how should I get the array considering I have converter.fromFile("./NTA-SAM-Inventory-List-Security-
    Management-New_2017.csv" which is too long so do I omit it when declaring the array or am I doing it wrong ? Thanks.

Update
 Just wanted to clarify if I did it correctly.

var JSarray = converter.fromFile("./NTA-SAM-Inventory-List-Security-M
anagement-New_2017.csv",function(err, result, callback){
// if an error has occured then handle it
if(err){
    console.log("An Error Has Occured");
    console.log(err);
}
// the result of the conversion
console.log(result);
result.toArray(function(err,doc){
    if(err) throw err;
    console.log('ohhhhh');
    return callback(null, doc);
    var myArray= doc;
    GLOBAL.GlobalMyArray = myArray;
});
});

Is this correct following your answer in declaring it globally?

Body:
You can set an array global inside of a function by assigning it to the window object.

function myFunction() {
    var myArray = new Array();
    window.GlobalMyArray = myArray;
}

Once it is set you can use GlobalMyArray from anywhere.

Using Node.Js you can use global

function myFunction() {
    var myArray = new Array();
     GLOBAL.GlobalMyArray = myArray;
}

You can now access the array globally using GLOBAL.GlobalMyArray

In which case it is very useful to do:

GLOBAL.window = GLOBAL

Like in the web browser.


问:
problems exporting Solar php5 root directory from localhost to live server or even other computer
Ok,
This seems like something that would be obvious, but I haven't been able to figure this out.

I just started using Solar PHP5 Framework http://solarphp.com. It is a great php5 framework. But with any new framework the is a learning curve.

Issue:  Solar uses many pre-written scripts to make directories and files for you. Making it easy to rapidly deploy a site. Being that it uses these scripts, it makes symbolic links to files and directories. (Example: Chapter 1 in the manual) This is great until you need to export your entire root directory to upload to your server or make another instance on another development computer. The problem for me is, when I do this, the files are editable, but do not reflect any changes when I refresh a page. Its like it doesn't update any code. The only way I can accomplish changes or updates, is to (essentially) run the site set-up each time, which involves running all the setup scripts, setting up the DB connections, etc. This is a total pain.

Question Is there any advice out there on doing this where I can just export the working root directory, to easily upload to server or other dev machine, without having to run those scripts over and over again. I know its something easy but I do not know exactly what to search for.

Is the a certain method for exporting directories/files that use symbolic links?

答: You might try using rsync instead of ftp to deploy the site. rsync will respect symlinks. Of course you will need have ssh access or mount the server over ftp/sftp with FUSE. If youre using SVN you could also ssh into the server and do an svn export or checkout.</p>

ContentLicense: CC BY-SA 2.5


问:
How can I switch languages in CodeIgniter
I have managed to create the site with CodeIgniter in two languages and the URL works fine when I switch it from there directly from:

```<code>localhost/projectname/en/index.php
</code>```

to:

```<code>localhost/projectname/it/index.php
</code>```

Now I am trying to create the two little flags that when clicked cause the URL to switch. I can't seem to find a way to do that, and I have tried a lot. If you have any experience with this thing, please help me out!

答:
Configuring Multi-Language Support

First we need to configure the necessary files before we can start using language support. The CodeIgniter config file, located in the application/config directory, contains an option called language which defines the default language of the application.

```<code>$config['language'] = 'english';
</code>```

We also need to create the actual files which contain our messages in different languages. These files need to be placed inside the application/language directory with a separate directory for each language. For example, English language files should reside in the application/language/english directory, and French language files should be located in application/language/french.

Let’s create some language files that contain error messages for a sample application. Create the file english/message_lang.php (it’s important that all of the language files have the suffix _lang.php). The following code contains some sample entries for the content of our language file:

```<code>$lang["msg_first_name"] = "First Name";
$lang["msg_last_name"] = "Last Name";
$lang["msg_dob"] = "Date of Birth";
$lang["msg_address"] = "Address";
</code>```

Of course, you can have multiple language files inside a single language directory. It’s recommended to group your messages into different files based on their context and purpose, and prefix your message keys with a file-specific keyword for consistency.

Another way is to create separate message files for each controller. The advantage of this technique is that only the required messages are loaded instead of an entire language file which can create a certain level of performance overhead.

Loading the Language Files inside Controller

Even though we create language files, they are not effective until we load them inside controllers. The following code shows how we can load the files inside a controller:

```<code>class TestLanguage extends CI_Controller
{
    public function __construct() {
        parent::__construct();
        $this->lang->load("message","english");
    }

    function index() {
        $data["language_msg"] = $this->lang->line("msg_hello_english");
        $this->load->view('language_view', $data);
    }
}
</code>```

We usually work with the language files within the controllers and views (using language files inside models is not such a good thing). Here we’ve used a controller’s constructor to load the language file so it can be used throughout the whole class, then we reference it in the class’ index() method.

The first parameter to the lang->load() method will be the language’s filename without the _lang suffix. The second paramter, which is optional, is the language directory. It will point to default language in your config if it’s not provided here.

We can directly reference the entries of a language file using the lang->line() method and assign it’s return to the data passed into the view templates. Inside the view, we can then use the above language message as $language_msg.

There may be an occasion when we need to load language files directly from the views as well. For example, using language items for form labels might be considered a good reason for directly loading and accessing messages inside views. It’s possible to use the same access method for these files inside views as inside controllers.

```<code>$this->lang->line("msg_hello_english");
</code>```

Though it works perfectly, it could be confusing to have $this when our view template code isn’t an actual class. We can also use the following code with the support of the language helper to load language entries inside views, which gives us cleaner code.

```<code>lang("msg_view_english");
</code>```

That’s basically all you need to know to get started working with CodeIgniter language files. But even though this is simple enough, it’s unnecessary and duplicated effort to load the necessary language files in each of the controllers, especially if your project contains hundreds of classes. Luckily, we can use CodeIgniter hooks to build a quick and effective solution for loading language files automatically for each controller.

Assigning Language Loading Responsibilities to Hooks

CodeIgniter calls a few built-in hooks as part of its execution process. You can find a complete list of hooks in the user guide. We’ll use the post_controller_constructor hook which is called immediately after our controller is instantiated and prior to any other method calls.

We enable hooks in our application by setting the enable_hooks parameter in the main config file.

```<code>$config['enable_hooks'] = TRUE;
</code>```

Then we can open the hooks.php file inside the config directory and create a custom hook as shown in the following code:

```<code>$hook['post_controller_constructor'] = array(
    'class' => 'LanguageLoader',
    'function' => 'initialize',
    'filename' => 'LanguageLoader.php',
    'filepath' => 'hooks'
);
</code>```

This defines the hook and provides the necessary information to execute it. The actual implementation will be created in a custom class inside the application/hooks directory.

```<code>class LanguageLoader
{
    function initialize() {
        $ci =& get_instance();
        $ci->load->helper('language');
        $ci->lang->load('message','english');
    }
}
</code>```

In here we don’t have the access to the language library using $this->lang, so we need to get the CI object instance using the get_instance() function, and then we load the language as we did earlier. Now the language file will be available for every controller of our application without the need to manually load it inside the controllers.

Switching Between Different Languages

Once we have established support for multiple languages, a link for each language can be provided to the user, generally in one of our application’s menus, which the users can click and switch the language. A session or cookie value can be used to keep track of the active language.

Let’s see how we can manage language switching using the hooks class we generated earlier. First we need to create a class to switch the language; we’ll be using a separate controller for this as shown below:

```<code>class LangSwitch extends CI_Controller
{
    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
    }

    function switchLanguage($language = "") {
        $language = ($language != "") ? $language : "english";
        $this->session->set_userdata('site_lang', $language);
        redirect(base_url());
    }
}
</code>```

Then we need to define links to switch each of the available languages.

```<code><a href='<?php echo $base_url; ?>langswitch/switchLanguage/english'>English</a>
<a href='<?php echo $base_url; ?>langswitch/switchLanguage/french'>French</a>
</code>```

Whenever the user chooses a specific language, the switchLanguage() method of the LangSwitch class will assign the selected languages to the session and redirect the user to the home page.

Now the active language will be changed in the session, but still it won’t get affected until we load the specific language file for the active language. We also need to modify our hooks class to load the language dynamically from the session.

```<code>$lang["msg_first_name"] = "First Name";
$lang["msg_last_name"] = "Last Name";
$lang["msg_dob"] = "Date of Birth";
$lang["msg_address"] = "Address";
</code>```0

Inside the LanguageLoader class we get the active language and load the necessary language files, or we load the default language if the session key is absent. We can load multiple language files of a single language inside this class.

Read more from here Multi-Language Support in CodeIgniter

Body:
I have managed to create the site with CodeIgniter in two languages and the URL works fine when I switch it from there directly from:

localhost/projectname/en/index.php

to:

localhost/projectname/it/index.php

Now I am trying to create the two little flags that when clicked cause the URL to switch. I can't seem to find a way to do that, and I have tried a lot. If you have any experience with this thing, please help me out!

Body:
Configuring Multi-Language Support

First we need to configure the necessary files before we can start using language support. The CodeIgniter config file, located in the application/config directory, contains an option called language which defines the default language of the application.

$config['language'] = 'english';

We also need to create the actual files which contain our messages in different languages. These files need to be placed inside the application/language directory with a separate directory for each language. For example, English language files should reside in the application/language/english directory, and French language files should be located in application/language/french.

Let’s create some language files that contain error messages for a sample application. Create the file english/message_lang.php (it’s important that all of the language files have the suffix _lang.php). The following code contains some sample entries for the content of our language file:

$lang["msg_first_name"] = "First Name";
$lang["msg_last_name"] = "Last Name";
$lang["msg_dob"] = "Date of Birth";
$lang["msg_address"] = "Address";

Of course, you can have multiple language files inside a single language directory. It’s recommended to group your messages into different files based on their context and purpose, and prefix your message keys with a file-specific keyword for consistency.

Another way is to create separate message files for each controller. The advantage of this technique is that only the required messages are loaded instead of an entire language file which can create a certain level of performance overhead.

Loading the Language Files inside Controller

Even though we create language files, they are not effective until we load them inside controllers. The following code shows how we can load the files inside a controller:

class TestLanguage extends CI_Controller
{
    public function __construct() {
        parent::__construct();
        $this->lang->load("message","english");
    }

    function index() {
        $data["language_msg"] = $this->lang->line("msg_hello_english");
        $this->load->view('language_view', $data);
    }
}

We usually work with the language files within the controllers and views (using language files inside models is not such a good thing). Here we’ve used a controller’s constructor to load the language file so it can be used throughout the whole class, then we reference it in the class’ index() method.

The first parameter to the lang->load() method will be the language’s filename without the _lang suffix. The second paramter, which is optional, is the language directory. It will point to default language in your config if it’s not provided here.

We can directly reference the entries of a language file using the lang->line() method and assign it’s return to the data passed into the view templates. Inside the view, we can then use the above language message as $language_msg.

There may be an occasion when we need to load language files directly from the views as well. For example, using language items for form labels might be considered a good reason for directly loading and accessing messages inside views. It’s possible to use the same access method for these files inside views as inside controllers.

$this->lang->line("msg_hello_english");

Though it works perfectly, it could be confusing to have $this when our view template code isn’t an actual class. We can also use the following code with the support of the language helper to load language entries inside views, which gives us cleaner code.

lang("msg_view_english");

That’s basically all you need to know to get started working with CodeIgniter language files. But even though this is simple enough, it’s unnecessary and duplicated effort to load the necessary language files in each of the controllers, especially if your project contains hundreds of classes. Luckily, we can use CodeIgniter hooks to build a quick and effective solution for loading language files automatically for each controller.

Assigning Language Loading Responsibilities to Hooks

CodeIgniter calls a few built-in hooks as part of its execution process. You can find a complete list of hooks in the user guide. We’ll use the post_controller_constructor hook which is called immediately after our controller is instantiated and prior to any other method calls.

We enable hooks in our application by setting the enable_hooks parameter in the main config file.

$config['enable_hooks'] = TRUE;

Then we can open the hooks.php file inside the config directory and create a custom hook as shown in the following code:

$hook['post_controller_constructor'] = array(
    'class' => 'LanguageLoader',
    'function' => 'initialize',
    'filename' => 'LanguageLoader.php',
    'filepath' => 'hooks'
);

This defines the hook and provides the necessary information to execute it. The actual implementation will be created in a custom class inside the application/hooks directory.

class LanguageLoader
{
    function initialize() {
        $ci =& get_instance();
        $ci->load->helper('language');
        $ci->lang->load('message','english');
    }
}

In here we don’t have the access to the language library using $this->lang, so we need to get the CI object instance using the get_instance() function, and then we load the language as we did earlier. Now the language file will be available for every controller of our application without the need to manually load it inside the controllers.

Switching Between Different Languages

Once we have established support for multiple languages, a link for each language can be provided to the user, generally in one of our application’s menus, which the users can click and switch the language. A session or cookie value can be used to keep track of the active language.

Let’s see how we can manage language switching using the hooks class we generated earlier. First we need to create a class to switch the language; we’ll be using a separate controller for this as shown below:

class LangSwitch extends CI_Controller
{
    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
    }

    function switchLanguage($language = "") {
        $language = ($language != "") ? $language : "english";
        $this->session->set_userdata('site_lang', $language);
        redirect(base_url());
    }
}

Then we need to define links to switch each of the available languages.

<a href='<?php echo $base_url; ?>langswitch/switchLanguage/english'>English</a>
<a href='<?php echo $base_url; ?>langswitch/switchLanguage/french'>French</a>

Whenever the user chooses a specific language, the switchLanguage() method of the LangSwitch class will assign the selected languages to the session and redirect the user to the home page.

Now the active language will be changed in the session, but still it won’t get affected until we load the specific language file for the active language. We also need to modify our hooks class to load the language dynamically from the session.

class LanguageLoader
{
    function initialize() {
        $ci =& get_instance();
        $ci->load->helper('language');

        $site_lang = $ci->session->userdata('site_lang');
        if ($site_lang) {
            $ci->lang->load('message',$ci->session->userdata('site_lang'));
        } else {
            $ci->lang->load('message','english');
        }
    }
}

Inside the LanguageLoader class we get the active language and load the necessary language files, or we load the default language if the session key is absent. We can load multiple language files of a single language inside this class.

Read more from here Multi-Language Support in CodeIgniter


问:
How can I measure CPU time of a specific set of threads?
I run C++ program in Linux.

There are several threads pool (for computation, for io, for ... such things).

The system call clock() gives me a way to measure the CPU time spent by all the CPU cores for the process.

However, I want to measure the CPU time spent only by the threads in the computation threads pool.

How can I achieve it?

Thanks :D

答:
To get CPU clock ID of every thread you can use: pthread_getcpuclockid
and using this CPU clock ID you can retrieve the current thread CPU time using: clock_gettime.

Following is the sample code to demonstrate the same:

```<code>struct timespec currTime;
clockid_t threadClockId;

//! Get thread clock Id
pthread_getcpuclockid(pthread_self(), &threadClockId);
//! Using thread clock Id get the clock time
clock_gettime(threadClockId, &currTime);
</code>```

Body:
To get CPU clock ID of every thread you can use: pthread_getcpuclockid
and using this CPU clock ID you can retrieve the current thread CPU time using: clock_gettime.

Following is the sample code to demonstrate the same:

struct timespec currTime;
clockid_t threadClockId;

//! Get thread clock Id
pthread_getcpuclockid(pthread_self(), &threadClockId);
//! Using thread clock Id get the clock time
clock_gettime(threadClockId, &currTime);


问:
YIi2 get records not contained in another table
I would like to retrieve records in one table not contained in another

I have two tables

```<code>tb_users having columns
   id(primary key)
   username,
   firstname,

2. tbl_paychecks
     id(primary key)
     user_id(foreignkey)
     amount
     created_at
     ...
</code>```

NOw i would like to retrieve all the users without paychecks that it all tbl_users whose id's are not in the tbl_paychecks

So in my users model

```<code>public function getNOPaychecks()
  {
    return self::find()
      ->leftJoin('tbl_paychecks','`tbl_paychecks`.`user_id` != `tbl_user`.`id`')
       ->where(['tbl_paycheks.user_id'=>null])
       ->all();
   }
</code>```

But the above still returns an error of

```<code>unknown column tbl_paycheks.user_id in 'where clause
</code>```

Where am i going wrong?

答:
Not sure why your code is not working.Try doing it as two queries.</p>

```<code>public function getNOPaychecks()
{
   $paycheckUsers = ArrayHelper::getColumn(PayCheckModelClassName::find()->select(['user_id'])->asArray()->all(),'user_id');
   return self::find()
      ->where(['NOT IN','id',$paycheckUsers])
      ->all();
}
</code>```

Body:
I would like to retrieve records in one table not contained in another

I have two tables

tb_users having columns
   id(primary key)
   username,
   firstname,

2. tbl_paychecks
     id(primary key)
     user_id(foreignkey)
     amount
     created_at
     ...

NOw i would like to retrieve all the users without paychecks that it all tbl_users whose id's are not in the tbl_paychecks

So in my users model

public function getNOPaychecks()
  {
    return self::find()
      ->leftJoin('tbl_paychecks','`tbl_paychecks`.`user_id` != `tbl_user`.`id`')
       ->where(['tbl_paycheks.user_id'=>null])
       ->all();
   }

But the above still returns an error of

unknown column tbl_paycheks.user_id in 'where clause

Where am i going wrong?

Body:
Not sure why your code is not working.Try doing it as two queries.

public function getNOPaychecks()
{
   $paycheckUsers = ArrayHelper::getColumn(PayCheckModelClassName::find()->select(['user_id'])->asArray()->all(),'user_id');
   return self::find()
      ->where(['NOT IN','id',$paycheckUsers])
      ->all();
}


问:
How to sanity check a date in Java
I find it curious that the most obvious way to create Date objects in Java has been deprecated and appears to have been "substituted" with a not so obvious to use lenient calendar.

How do you check that a date, given as a combination of day, month, and year, is a valid date?

For instance, 2008-02-31 (as in yyyy-mm-dd) would be an invalid date.

答:
```<code>// to return valid days of month, according to month and year
int returnDaysofMonth(int month, int year) {
    int daysInMonth;
    boolean leapYear;
    leapYear = checkLeap(year);
    if (month == 4 || month == 6 || month == 9 || month == 11)
        daysInMonth = 30;
    else if (month == 2)
        daysInMonth = (leapYear) ? 29 : 28;
    else
        daysInMonth = 31;
    return daysInMonth;
}

// to check a year is leap or not
private boolean checkLeap(int year) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, year);
    return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
}
</code>```

OwnerDisplayName: Bloodboiler

Title: How to sanity check a date in Java


问:
LaTeX: \newenvironment with only one optional arg (and no mandatory)

I try to set a new environment within a class that would take only an optional argument, or none.

This would be used like this :

```<code>\begin{myEnv}          -->  "Label:"
</code>```

or

```<code>\begin{myEnv}[myLabel] -->  "Label: myLabel"
</code>```

I try to define this environment with basic macros. I would rather not to use xparse package.

I have found several examples of \newenvironment with an optional argument together with a mandatory one. But I do not need a mandatory argument!

Is there a way to do this with \newenvironment or \def macros ?

答:
No problem, just declare the environment with one argument, and make that optional:</p>

```<code>\documentclass{minimal}
\newenvironment*{myEnv}[1][]{%
  Label: #1%
  \par
  \ignorespaces
}{%
  \par
  end%
  \par
  \ignorespacesafterend
}
\begin{document}
\begin{myEnv}
  abc
\end{myEnv}
\begin{myEnv}[myLabel]
  abc
\end{myEnv}
\end{document}
</code>```

Body:
I try to set a new environment within a class that would take only an optional argument, or none.

This would be used like this :

\begin{myEnv}          -->  "Label:"

or

\begin{myEnv}[myLabel] -->  "Label: myLabel"

I try to define this environment with basic macros. I would rather not to use xparse package.

I have found several examples of \newenvironment with an optional argument together with a mandatory one. But I do not need a mandatory argument!

Is there a way to do this with \newenvironment or \def macros ?

Body:
No problem, just declare the environment with one argument, and make that optional:

\documentclass{minimal}
\newenvironment*{myEnv}[1][]{%
  Label: #1%
  \par
  \ignorespaces
}{%
  \par
  end%
  \par
  \ignorespacesafterend
}
\begin{document}
\begin{myEnv}
  abc
\end{myEnv}
\begin{myEnv}[myLabel]
  abc
\end{myEnv}
\end{document}


问:
How to fetch last row using distinct and group by same column
I want to retrieve balance of last row from table  using distinct accountid from last ledgerid

```<code>|---ledgerid---|--accountid--|--blance--|
|     1        |      1      |    500   |
|     2        |      1      |    800   |
</code>```

i want output as

```<code>|---ledgerid---|--accountid--|--blance--|
|     2        |      1      |    800   |
</code>```

答:
```<code>SELECT l1.* FROM ledger l1 LEFT JOIN ledger l2 ON
(l1.accountid = l2.accountid AND l1.ledgerid < l2.ledgerid)
 WHERE l2.ledgerid IS NULL
</code>```

Body:
I want to retrieve balance of last row from table  using distinct accountid from last ledgerid

|---ledgerid---|--accountid--|--blance--|
|     1        |      1      |    500   |
|     2        |      1      |    800   |

i want output as

|---ledgerid---|--accountid--|--blance--|
|     2        |      1      |    800   |


问:
Exception with Freetts when using kevin or mbrola
I am trying to run a program using freetts. I am able to compile the program however I am not able to use kevin or mbrola voices I get the follwing output message at the end

System property "mbrola.base" is undefined.  Will not use MBROLA voices.

  LINE UNAVAILABLE: Format is pcm_signed 16000.0 Hz 16 bits 1 channel big endian

```<code>import javax.speech.*;
import javax.speech.synthesis.*;
import java.util.*;

class freetts {

    public static void main(String[] args) {
        try{
            Calendar calendar = new GregorianCalendar();
            String sayTime = "It is " + calendar.get(Calendar.HOUR) + " " + calendar.get(Calendar.MINUTE) + " " + (calendar.get(Calendar.AM_PM)==0 ? "AM":"PM");
            Synthesizer synth = Central.createSynthesizer(null);
            synth.allocate();
            synth.resume();
            synth.speakPlainText(sayTime, null);
            synth.waitEngineState(Synthesizer.QUEUE_EMPTY);
            synth.deallocate();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}
</code>```

答:
I know i am posting it little late, but this may help someone. I tried with both  kevin and mbrola, and it worked for me. Please find the code below.

```<code>    package com.mani.texttospeech;

import java.beans.PropertyVetoException;
import java.util.Locale;

import javax.speech.AudioException;
import javax.speech.Central;
import javax.speech.EngineException;
import javax.speech.EngineStateError;
import javax.speech.synthesis.Synthesizer;
import javax.speech.synthesis.SynthesizerModeDesc;
import javax.speech.synthesis.Voice;

/**
 *
 * @author Manindar
 */
public class SpeechUtils {

    SynthesizerModeDesc desc;
    Synthesizer synthesizer;
    Voice voice;

    public void init(String voiceName) throws EngineException, AudioException, EngineStateError, PropertyVetoException {
        if (desc == null) {
            System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");
            desc = new SynthesizerModeDesc(Locale.US);
            Central.registerEngineCentral("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral");
            synthesizer = Central.createSynthesizer(desc);
            synthesizer.allocate();
            synthesizer.resume();
            SynthesizerModeDesc smd = (SynthesizerModeDesc) synthesizer.getEngineModeDesc();
            Voice[] voices = smd.getVoices();
            for (Voice voice1 : voices) {
                if (voice1.getName().equals(voiceName)) {
                    voice = voice1;
                    break;
                }
            }
            synthesizer.getSynthesizerProperties().setVoice(voice);
        }
    }

    public void terminate() throws EngineException, EngineStateError {
        synthesizer.deallocate();
    }

    public void doSpeak(String speakText) throws EngineException, AudioException, IllegalArgumentException, InterruptedException {
        synthesizer.speakPlainText(speakText, null);
        synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
    }

    public static void main(String[] args) throws Exception {
        SpeechUtils su = new SpeechUtils();
        su.init("kevin16");
//        su.init("kevin");
//        su.init("mbrola_us1");
//        su.init("mbrola_us2");
//        su.init("mbrola_us3");
        // high quality
        su.doSpeak("Hi this is Manindar. Welcome to audio world.");
        su.terminate();
    }
}
</code>```

And add the below dependencies to your pom.xml file.

```<code><dependencies>
        <dependency>
            <groupId>net.sf.sociaal</groupId>
            <artifactId>freetts</artifactId>
            <version>1.2.2</version>
        </dependency>
    </dependencies>
</code>```

Hope this will be helpful.

Body:
I am trying to run a program using freetts. I am able to compile the program however I am not able to use kevin or mbrola voices I get the follwing output message at the end

System property "mbrola.base" is undefined.  Will not use MBROLA voices.

  LINE UNAVAILABLE: Format is pcm_signed 16000.0 Hz 16 bits 1 channel big endian

import javax.speech.*;
import javax.speech.synthesis.*;
import java.util.*;

class freetts {

    public static void main(String[] args) {
        try{
            Calendar calendar = new GregorianCalendar();
            String sayTime = "It is " + calendar.get(Calendar.HOUR) + " " + calendar.get(Calendar.MINUTE) + " " + (calendar.get(Calendar.AM_PM)==0 ? "AM":"PM");
            Synthesizer synth = Central.createSynthesizer(null);
            synth.allocate();
            synth.resume();
            synth.speakPlainText(sayTime, null);
            synth.waitEngineState(Synthesizer.QUEUE_EMPTY);
            synth.deallocate();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

Body:
I know i am posting it little late, but this may help someone. I tried with both  kevin and mbrola, and it worked for me. Please find the code below.

    package com.mani.texttospeech;

import java.beans.PropertyVetoException;
import java.util.Locale;

import javax.speech.AudioException;
import javax.speech.Central;
import javax.speech.EngineException;
import javax.speech.EngineStateError;
import javax.speech.synthesis.Synthesizer;
import javax.speech.synthesis.SynthesizerModeDesc;
import javax.speech.synthesis.Voice;

/**
 *
 * @author Manindar
 */
public class SpeechUtils {

    SynthesizerModeDesc desc;
    Synthesizer synthesizer;
    Voice voice;

    public void init(String voiceName) throws EngineException, AudioException, EngineStateError, PropertyVetoException {
        if (desc == null) {
            System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");
            desc = new SynthesizerModeDesc(Locale.US);
            Central.registerEngineCentral("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral");
            synthesizer = Central.createSynthesizer(desc);
            synthesizer.allocate();
            synthesizer.resume();
            SynthesizerModeDesc smd = (SynthesizerModeDesc) synthesizer.getEngineModeDesc();
            Voice[] voices = smd.getVoices();
            for (Voice voice1 : voices) {
                if (voice1.getName().equals(voiceName)) {
                    voice = voice1;
                    break;
                }
            }
            synthesizer.getSynthesizerProperties().setVoice(voice);
        }
    }

    public void terminate() throws EngineException, EngineStateError {
        synthesizer.deallocate();
    }

    public void doSpeak(String speakText) throws EngineException, AudioException, IllegalArgumentException, InterruptedException {
        synthesizer.speakPlainText(speakText, null);
        synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
    }

    public static void main(String[] args) throws Exception {
        SpeechUtils su = new SpeechUtils();
        su.init("kevin16");
//        su.init("kevin");
//        su.init("mbrola_us1");
//        su.init("mbrola_us2");
//        su.init("mbrola_us3");
        // high quality
        su.doSpeak("Hi this is Manindar. Welcome to audio world.");
        su.terminate();
    }
}

And add the below dependencies to your pom.xml file.

<dependencies>
        <dependency>
            <groupId>net.sf.sociaal</groupId>
            <artifactId>freetts</artifactId>
            <version>1.2.2</version>
        </dependency>
    </dependencies>

Hope this will be helpful.


问:
How to Remove validation from left table data in django
2nd Screenshot of APIAPI Sample Screenshot

I'm New in Django, i want to help regarding validations in screenshot there is company_name, location, title and user_location fields except user info with proper validation
but i want to remove validations from  company_name, location, title and user_location fields how to do?

Please find the above api screenshot and

Please find the below scripts,

views.py

```<code>class UserRegistrationView(generics.CreateAPIView):
    """
    Register a new user.
    """
    queryset = User.objects.all()
    permission_classes = (permissions.AllowAny, )

    def get_serializer_class(self, user_type=None):
        if user_type == 'student':
            return StudentRegistrationSerializer
        return ProfessionalRegistrationSerializer

    def post(self, request, user_type=None, format=None):
        serializer_class = self.get_serializer_class(user_type)
        serializer = serializer_class(data=request.data, context={'request': request})

        if serializer.is_valid(raise_exception=True)

            user = serializer.save(work_status=user_type)
            token, created = Token.objects.get_or_create(user=user)
            data = BasicUserSerializer(user, context={'request': request}).data
            data.update({"token": token.key})
            return Response(data)
</code>```

serializes.py

```<code>class ProfessionalRegistrationSerializer(serializers.HyperlinkedModelSerializer):

    password = serializers.CharField(max_length=20, write_only=True)
    experiences = ExperienceSerializer(required=False)
    email = serializers.EmailField()
    first_name = serializers.CharField(max_length=30)
    last_name = serializers.CharField(max_length=30)

    class Meta:
        model = User
        fields = ('url', 'id', 'first_name', 'last_name', 'email', 'password',
        'experiences', 'headline')

    def validate_email(self, value):
        from validate_email_address import validate_email
        if User.all_objects.filter(email=value.lower()).exists():
            raise serializers.ValidationError('User with this email already exists.')
        # if not validate_email(value.lower(), check_mx=True):
        #     raise serializers.ValidationError('It looks like you may have entered an incorrect email address.')
        return value.lower()

    def create(self, validated_data):
        experiences = validated_data.pop('experiences')
        password = validated_data.pop('password')
        email = validated_data.pop('email')
        user = User.objects.create(
            username=email.lower(),
            email=email.lower(),
            role_id=1)
        user.set_password(password)
        user.save()
        user_location = experiences.pop('user_location')
        if hasattr(user, 'location'):
            user.location.location = user_location
            user.save()
        else:
            UserLocation.objects.create(user=user, location=user_location)
            Experience.objects.create(user=user)
        return user
</code>```

Another serializes.py for Experiance

```<code>class ExperienceSerializer(serializers.HyperlinkedModelSerializer):

    user_location = LocationField()
    location = LocationField()

    class Meta:
        model = Experience
        fields = ('id', 'company_name', 'company', 'description', 'location',
        'title', 'start_date', 'end_date', 'is_current', 'user_location')
</code>```

I want to Remove Validation from company_name, company, description, location, title, start_date, end_date, user_location

actually these fields are second page means after complete the first step users move on second step so second step fields are optional

```<code>class ExperienceSerializer(serializers.HyperlinkedModelSerializer):

    user_location = LocationField()
    location = LocationField()

    class Meta:
        model = Experience
        fields = ('id', 'company_name', 'company', 'description', 'location',
            'title', 'start_date', 'end_date', 'is_current', 'user_location')

        def create(self, validated_data):

            return Experience.objects.create(field_a='value', field_b='value')
</code>```

in the above class, what should be do to remove validation of

```<code>"error_msg": {
        "location": [
            "Expected a dictionary of items but got type \"str\"."
        ],
        "start_date": [
            "Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]."
        ],
        "end_date": [
            "Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]."
        ],
        "user_location": [
            "Expected a dictionary of items but got type \"str\"."
        ]
    }
</code>```

Experience Model

```<code>class Experience(models.Model):

    """
    """

    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='experiences')
    company_name = models.CharField(max_length=200, db_index=True, blank=True)
    company = models.ForeignKey('organisations.Organisation', null=True, blank=True, on_delete=models.SET_NULL)
    description = models.TextField(null=True, blank=True)
    location = models.ForeignKey('regions.Location', null=True, blank=True, on_delete=models.SET_NULL)
    start_date = models.DateField(null=True, blank=True)
    end_date = models.DateField(null=True, blank=True)
    title = models.CharField(max_length=200, db_index=True, blank=True)
    is_current = models.BooleanField(default=False)
    is_associated = models.BooleanField(default=False)
    created_at = models.DateTimeField(_('created at'), auto_now_add=True)
    modified_at = models.DateTimeField(_('modified at'), auto_now=True)

    class Meta:
        db_table = 'experience'
        verbose_name = _('experience')
        verbose_name_plural = _('experiences')
        ordering = ('-start_date',)

    def __str__(self):
        return getattr(self, 'title', '')

    @property
    def experience(self):
        if self.end_date:
            return (self.end_date - self.start_date).days
        else:
            return (datetime.datetime.now().date() - self.start_date).days

    def get_formated_experience(self):
        days = self.experience
        total_months = round(days/30)
        years = int(total_months/12)
        months = round(((total_months/12)%1)*12)
        year_txt = 'years' if years > 1 else 'year'
        month_txt = 'months' if months > 1 else 'month'
        return "%s %s %s %s" %(years, year_txt, months, month_txt)
</code>```

Location Model

```<code>class Location(models.Model):
    """
    """
    id = models.TextField(primary_key=True)
    display_name = models.TextField(null=True, blank=True)
    latitude = models.DecimalField(max_digits=15, decimal_places=10, null=True, blank=True)
    longitude = models.DecimalField(max_digits=15, decimal_places=10, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = LocationManager()
</code>```

答:
You are getting Two types of validation error according to snapshot.

Field  is required

Expected a dictionary and got a string

The required field error occurs when you have set field as required in your model. You can change this by adding blank=True in your model for that field.
For second error, your serializer is expecting a dictionary and you are sending a string. You can remove this validation by writing your custom create method.

```<code>class ExperienceSerializer(serializers.HyperlinkedModelSerializer):

    user_location = LocationField()
    location = LocationField()

    class Meta:
        model = Experience
        fields = ('id', 'company_name', 'company', 'description', 'location',
                'title', 'start_date', 'end_date', 'is_current', 'user_location')

    def create(self, validated_data):
        # you create code for that models.
</code>```

Your seriailzers will be like this

```<code>class ProfessionalRegistrationSerializer(serializers.HyperlinkedModelSerializer):

    password = serializers.CharField(max_length=20, write_only=True)
    experiences = ExperienceSerializer(required=False)
    email = serializers.EmailField()
    first_name = serializers.CharField(max_length=30)
    last_name = serializers.CharField(max_length=30)

    class Meta:
        model = User
        fields = ('url', 'id', 'first_name', 'last_name', 'email', 'password',
        'experiences', 'headline')

    def validate_email(self, value):
        from validate_email_address import validate_email
        if User.all_objects.filter(email=value.lower()).exists():
            raise serializers.ValidationError('User with this email already exists.')
        # if not validate_email(value.lower(), check_mx=True):
        #     raise serializers.ValidationError('It looks like you may have entered an incorrect email address.')
        return value.lower()

    def create(self, validated_data):
        experiences = validated_data.get('experiences')
        password = validated_data.get('password')
        email = validated_data.get('email')
        user = User.objects.create(
            username=email.lower(),
            email=email.lower(),
            role_id=1)
        user.set_password(password)
        user.save()
        user_location = experiences.get('user_location')
        location_object = None
        if user_location:
            location_object, created = Location.objects.get_or_create(display_name=user_location.get('display_name'), latitude= user_location.get('latitude'), longitude=user_location.get('longitude'))
        user_experience = Experience.objects.create(user=user, company_name=experiences.get('company_name'), location=location_object)
        return user
</code>```

```<code>class ExperienceSerializer(serializers.HyperlinkedModelSerializer):

    user_location = LocationField()
    location = LocationField()

    class Meta:
        model = Experience
        fields = ('id', 'company_name', 'company', 'description', 'location',
                'title', 'start_date', 'end_date', 'is_current', 'user_location')
</code>```

Body:
2nd Screenshot of APIAPI Sample Screenshot

I'm New in Django, i want to help regarding validations in screenshot there is company_name, location, title and user_location fields except user info with proper validation
but i want to remove validations from  company_name, location, title and user_location fields how to do?

Please find the above api screenshot and

Please find the below scripts,

views.py

class UserRegistrationView(generics.CreateAPIView):
    """
    Register a new user.
    """
    queryset = User.objects.all()
    permission_classes = (permissions.AllowAny, )

    def get_serializer_class(self, user_type=None):
        if user_type == 'student':
            return StudentRegistrationSerializer
        return ProfessionalRegistrationSerializer

    def post(self, request, user_type=None, format=None):
        serializer_class = self.get_serializer_class(user_type)
        serializer = serializer_class(data=request.data, context={'request': request})

        if serializer.is_valid(raise_exception=True)

            user = serializer.save(work_status=user_type)
            token, created = Token.objects.get_or_create(user=user)
            data = BasicUserSerializer(user, context={'request': request}).data
            data.update({"token": token.key})
            return Response(data)

serializes.py

class ProfessionalRegistrationSerializer(serializers.HyperlinkedModelSerializer):

    password = serializers.CharField(max_length=20, write_only=True)
    experiences = ExperienceSerializer(required=False)
    email = serializers.EmailField()
    first_name = serializers.CharField(max_length=30)
    last_name = serializers.CharField(max_length=30)

    class Meta:
        model = User
        fields = ('url', 'id', 'first_name', 'last_name', 'email', 'password',
        'experiences', 'headline')

    def validate_email(self, value):
        from validate_email_address import validate_email
        if User.all_objects.filter(email=value.lower()).exists():
            raise serializers.ValidationError('User with this email already exists.')
        # if not validate_email(value.lower(), check_mx=True):
        #     raise serializers.ValidationError('It looks like you may have entered an incorrect email address.')
        return value.lower()

    def create(self, validated_data):
        experiences = validated_data.pop('experiences')
        password = validated_data.pop('password')
        email = validated_data.pop('email')
        user = User.objects.create(
            username=email.lower(),
            email=email.lower(),
            role_id=1)
        user.set_password(password)
        user.save()
        user_location = experiences.pop('user_location')
        if hasattr(user, 'location'):
            user.location.location = user_location
            user.save()
        else:
            UserLocation.objects.create(user=user, location=user_location)
            Experience.objects.create(user=user)
        return user

Another serializes.py for Experiance

class ExperienceSerializer(serializers.HyperlinkedModelSerializer):

    user_location = LocationField()
    location = LocationField()

    class Meta:
        model = Experience
        fields = ('id', 'company_name', 'company', 'description', 'location',
        'title', 'start_date', 'end_date', 'is_current', 'user_location')

I want to Remove Validation from company_name, company, description, location, title, start_date, end_date, user_location

actually these fields are second page means after complete the first step users move on second step so second step fields are optional

class ExperienceSerializer(serializers.HyperlinkedModelSerializer):

    user_location = LocationField()
    location = LocationField()

    class Meta:
        model = Experience
        fields = ('id', 'company_name', 'company', 'description', 'location',
            'title', 'start_date', 'end_date', 'is_current', 'user_location')

        def create(self, validated_data):

            return Experience.objects.create(field_a='value', field_b='value')

in the above class, what should be do to remove validation of

"error_msg": {
        "location": [
            "Expected a dictionary of items but got type \"str\"."
        ],
        "start_date": [
            "Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]."
        ],
        "end_date": [
            "Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]."
        ],
        "user_location": [
            "Expected a dictionary of items but got type \"str\"."
        ]
    }

Experience Model

class Experience(models.Model):

    """
    """

    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='experiences')
    company_name = models.CharField(max_length=200, db_index=True, blank=True)
    company = models.ForeignKey('organisations.Organisation', null=True, blank=True, on_delete=models.SET_NULL)
    description = models.TextField(null=True, blank=True)
    location = models.ForeignKey('regions.Location', null=True, blank=True, on_delete=models.SET_NULL)
    start_date = models.DateField(null=True, blank=True)
    end_date = models.DateField(null=True, blank=True)
    title = models.CharField(max_length=200, db_index=True, blank=True)
    is_current = models.BooleanField(default=False)
    is_associated = models.BooleanField(default=False)
    created_at = models.DateTimeField(_('created at'), auto_now_add=True)
    modified_at = models.DateTimeField(_('modified at'), auto_now=True)

    class Meta:
        db_table = 'experience'
        verbose_name = _('experience')
        verbose_name_plural = _('experiences')
        ordering = ('-start_date',)

    def __str__(self):
        return getattr(self, 'title', '')

    @property
    def experience(self):
        if self.end_date:
            return (self.end_date - self.start_date).days
        else:
            return (datetime.datetime.now().date() - self.start_date).days

    def get_formated_experience(self):
        days = self.experience
        total_months = round(days/30)
        years = int(total_months/12)
        months = round(((total_months/12)%1)*12)
        year_txt = 'years' if years > 1 else 'year'
        month_txt = 'months' if months > 1 else 'month'
        return "%s %s %s %s" %(years, year_txt, months, month_txt)

Location Model

class Location(models.Model):
    """
    """
    id = models.TextField(primary_key=True)
    display_name = models.TextField(null=True, blank=True)
    latitude = models.DecimalField(max_digits=15, decimal_places=10, null=True, blank=True)
    longitude = models.DecimalField(max_digits=15, decimal_places=10, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = LocationManager()

Body:
You are getting Two types of validation error according to snapshot.

Field  is required

Expected a dictionary and got a string

The required field error occurs when you have set field as required in your model. You can change this by adding blank=True in your model for that field.
For second error, your serializer is expecting a dictionary and you are sending a string. You can remove this validation by writing your custom create method.

class ExperienceSerializer(serializers.HyperlinkedModelSerializer):

    user_location = LocationField()
    location = LocationField()

    class Meta:
        model = Experience
        fields = ('id', 'company_name', 'company', 'description', 'location',
                'title', 'start_date', 'end_date', 'is_current', 'user_location')

    def create(self, validated_data):
        # you create code for that models.

Your seriailzers will be like this

class ProfessionalRegistrationSerializer(serializers.HyperlinkedModelSerializer):

    password = serializers.CharField(max_length=20, write_only=True)
    experiences = ExperienceSerializer(required=False)
    email = serializers.EmailField()
    first_name = serializers.CharField(max_length=30)
    last_name = serializers.CharField(max_length=30)

    class Meta:
        model = User
        fields = ('url', 'id', 'first_name', 'last_name', 'email', 'password',
        'experiences', 'headline')

    def validate_email(self, value):
        from validate_email_address import validate_email
        if User.all_objects.filter(email=value.lower()).exists():
            raise serializers.ValidationError('User with this email already exists.')
        # if not validate_email(value.lower(), check_mx=True):
        #     raise serializers.ValidationError('It looks like you may have entered an incorrect email address.')
        return value.lower()

    def create(self, validated_data):
        experiences = validated_data.get('experiences')
        password = validated_data.get('password')
        email = validated_data.get('email')
        user = User.objects.create(
            username=email.lower(),
            email=email.lower(),
            role_id=1)
        user.set_password(password)
        user.save()
        user_location = experiences.get('user_location')
        location_object = None
        if user_location:
            location_object, created = Location.objects.get_or_create(display_name=user_location.get('display_name'), latitude= user_location.get('latitude'), longitude=user_location.get('longitude'))
        user_experience = Experience.objects.create(user=user, company_name=experiences.get('company_name'), location=location_object)
        return user

class ExperienceSerializer(serializers.HyperlinkedModelSerializer):

    user_location = LocationField()
    location = LocationField()

    class Meta:
        model = Experience
        fields = ('id', 'company_name', 'company', 'description', 'location',
                'title', 'start_date', 'end_date', 'is_current', 'user_location')


问:
How can I define the parameters of a query using string values?
The query below should have only returned the numbers 0 through 8. However, the result are 0 thru 87. and 88 thru 99 are not shown. The next numbers shown are 100 thru 799. 800 thru 999 are not shown. So I see a pattern here, and it is that if the first number is within the range specified it is returned.

```<code> public Cursor getList(String user) {
    String zero = "0";
    String query = ("SELECT * FROM flavors WHERE inventory >= "+zero+" AND inventory <= "+user);
    return mDb.rawQuery(query, null);
</code>```

How can I keep the expected results withing the query parameters?

Thanks for all your efforts.

EDIT

For anyone that are looking for an answer as I was. Here is the final working statement.
Thanks to @FAT I was able to learn more about the sql query process from the links that where provided. Googling is an art it seems. I changed my code to meet my needs as follows.

```<code> public Cursor getList(String user) {
    String zero = "0";
    String query = ("SELECT * FROM flavors WHERE inventory != '' AND (cast(inventory as real)) >= " + zero + " AND (cast(inventory as real)) <= " + user);
    return mDb.rawQuery(query, null);
}
</code>```

The "cast" was the key to getting the string to be used to compare the two numbers. I also learned that you can exclude all null items. By adding "!= '', only the items that had an entry where returned in accordance with the statement. This even works for decimal numbers such as 5.5 or .5 etc.

答:
You can use BETWEEN like the following:

```<code>SELECT * FROM flavors WHERE inventory BETWEEN X AND Y
</code>```

Body:
The query below should have only returned the numbers 0 through 8. However, the result are 0 thru 87. and 88 thru 99 are not shown. The next numbers shown are 100 thru 799. 800 thru 999 are not shown. So I see a pattern here, and it is that if the first number is within the range specified it is returned.

 public Cursor getList(String user) {
    String zero = "0";
    String query = ("SELECT * FROM flavors WHERE inventory >= "+zero+" AND inventory <= "+user);
    return mDb.rawQuery(query, null);

How can I keep the expected results withing the query parameters?

Thanks for all your efforts.

EDIT

For anyone that are looking for an answer as I was. Here is the final working statement.
Thanks to @FAT I was able to learn more about the sql query process from the links that where provided. Googling is an art it seems. I changed my code to meet my needs as follows.

 public Cursor getList(String user) {
    String zero = "0";
    String query = ("SELECT * FROM flavors WHERE inventory != '' AND (cast(inventory as real)) >= " + zero + " AND (cast(inventory as real)) <= " + user);
    return mDb.rawQuery(query, null);
}

The "cast" was the key to getting the string to be used to compare the two numbers. I also learned that you can exclude all null items. By adding "!= '', only the items that had an entry where returned in accordance with the statement. This even works for decimal numbers such as 5.5 or .5 etc.

Body:
You can use BETWEEN like the following:

SELECT * FROM flavors WHERE inventory BETWEEN X AND Y