问:
Get drawable from 3d gallery an pass it to other activity into an imageview saving into sharedpreferences
I'm making an app. I have a 3d gallery with an imageAdapter, galleryView, gallery3dActivity and the mainactivity.

ImageAdapter:

```<code>public class ImageAdapter extends BaseAdapter
{
private ImageView[] mImages;

private Context mContext;
public List<Map<String, Object>> list;

public Integer[] imgs = { R.drawable.cat, R.drawable.dog, R.drawable.bird,
    R.drawable.chicken, R.drawable.cow, R.drawable.rabbit, R.drawable.pig,
    R.drawable.sheep, R.drawable.donkey, R.drawable.deer, R.drawable.fox,
    R.drawable.helephant, R.drawable.tiger, R.drawable.leopard, R.drawable.lion,
    R.drawable.monquey, R.drawable.owl, R.drawable.panda, R.drawable.pinguin, R.drawable.zebra,};
public String[] titles = { "The Cat.", "The Dog", "The Bird", "The Chicken", "The Cow", "The Rabbit",
"The Pig", "The Sheep", "The Donkey", "The Deer","The Fox", "The Helephant", "The Tiger", "The Leopard",
"The Lion", "The Monquey", "The Owl", "The Panda", "The Pinguin", "The Zebra"};

public ImageAdapter(Context c)
{
    this.mContext = c;
    list = new ArrayList<Map<String, Object>>();
    for (int i = 0; i < imgs.length; i++) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("image", imgs[i]);
        list.add(map);
    }
    mImages = new ImageView[list.size()];
}

public boolean createReflectedImages()
{
    final int reflectionGap = 0;
    final int Height = 350;
    int index = 0;
    for (Map<String, Object> map : list) {
        Integer id = (Integer) map.get("image");

        Bitmap originalImage = BitmapFactory.decodeResource(mContext.getResources(), id);
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        float scale = Height / (float)height;

        Matrix sMatrix = new Matrix();
        sMatrix.postScale(scale, scale);
        Bitmap miniBitmap = Bitmap.createBitmap(originalImage, 0, 0,
                originalImage.getWidth(), originalImage.getHeight(), sMatrix, true);

        originalImage.recycle();

        int mwidth = miniBitmap.getWidth();
        int mheight = miniBitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);
        Bitmap reflectionImage = Bitmap.createBitmap(miniBitmap, 0, mheight/2, mwidth, mheight/2, matrix, false);
        Bitmap bitmapWithReflection = Bitmap.createBitmap(mwidth, (mheight + mheight / 2), Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmapWithReflection);
        canvas.drawBitmap(miniBitmap, 0, 0, null);
        Paint paint = new Paint();
        canvas.drawRect(0, mheight, mwidth, mheight + reflectionGap, paint);
        canvas.drawBitmap(reflectionImage, 0, mheight + reflectionGap, null);

        paint = new Paint();
        LinearGradient shader = new LinearGradient(0, miniBitmap.getHeight(), 0, bitmapWithReflection.getHeight()
                + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);
        paint.setShader(shader);
        paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
        canvas.drawRect(0, mheight, mwidth, bitmapWithReflection.getHeight() + reflectionGap, paint);

        ImageView imageView = new ImageView(mContext);
        imageView.setImageBitmap(bitmapWithReflection);
        imageView.setLayoutParams(new GalleryView.LayoutParams((int)(width * scale),
                (int)(mheight * 3 / 2.0 + reflectionGap)));
        imageView.setScaleType(ScaleType.MATRIX);
        mImages[index++] = imageView;
    }
    return true;
}

@Override
public int getCount() {
    return imgs.length;
}

@Override
public Object getItem(int position) {
    return mImages[position];
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    return mImages[position];
}

public float getScale(boolean focused, int offset) {
    return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
}

}
</code>```

GalleryView:

```<code>public class GalleryView extends Gallery
{
private Camera mCamera = new Camera();
private int mMaxRotationAngle = 45;
private int mMaxZoom = -120;
private int mCoveflowCenter;

public GalleryView(Context context)
{
    super(context);
    this.setStaticTransformationsEnabled(true);
}

public GalleryView(Context context, AttributeSet attrs)
{
    super(context, attrs);
    this.setStaticTransformationsEnabled(true);
}

public GalleryView(Context context, AttributeSet attrs, int defStyle)
{
    super(context, attrs, defStyle);
    this.setStaticTransformationsEnabled(true);
}

public int getMaxRotationAngle()
{
    return mMaxRotationAngle;
}

public void setMaxRotationAngle(int maxRotationAngle)
{
    mMaxRotationAngle = maxRotationAngle;
}

public int getMaxZoom()
{
    return mMaxZoom;
}

public void setMaxZoom(int maxZoom)
{
    mMaxZoom = maxZoom;
}

private int getCenterOfCoverflow()
{
    return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft();
}

private static int getCenterOfView(View view) {
    return view.getLeft() + view.getWidth() / 2;
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
    mCoveflowCenter = getCenterOfCoverflow();
    super.onSizeChanged(w, h, oldw, oldh);
}

@Override
protected boolean getChildStaticTransformation(View child, Transformation trans)
{
    final int childCenter = getCenterOfView(child);
    final int childWidth = child.getWidth();
    int rotationAngle = 0;

    trans.clear();
    trans.setTransformationType(Transformation.TYPE_BOTH);

    if (childCenter == mCoveflowCenter)
    {
        transformImageBitmap((ImageView) child, trans, 0);
    }
    else
    {
        rotationAngle = (int) ( ( (float) (mCoveflowCenter - childCenter) / childWidth ) * mMaxRotationAngle );
        if (Math.abs(rotationAngle) > mMaxRotationAngle)
        {
            rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle : mMaxRotationAngle;
        }
        transformImageBitmap((ImageView) child, trans, rotationAngle);
    }

    return true;
}

private void transformImageBitmap(ImageView child, Transformation trans, int rotationAngle)
{
    mCamera.save();

    final Matrix imageMatrix = trans.getMatrix();
    final int imageHeight = child.getLayoutParams().height;
    final int imageWidth = child.getLayoutParams().width;
    final int rotation = Math.abs(rotationAngle);

    mCamera.translate(0.0f, 0.0f, -20.0f);

    // As the angle of the view gets less, zoom in
    if (rotation < mMaxRotationAngle)
    {
        float zoomAmount = (float) (mMaxZoom + (rotation * 1.0));
        mCamera.translate(0.0f, 0.0f, zoomAmount);
    }

    mCamera.rotateY(rotationAngle);
    mCamera.getMatrix(imageMatrix);
    imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));
    imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));

    mCamera.restore();
}
}
</code>```

Gallery3DActivity:

```<code>public class Gallery3DActivity extends Activity {

private TextView tvTitle;
private GalleryView gallery;
private ImageAdapter adapter;
private ImageView Avatar;

@Override
public void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.grallery_layout);

    initRes();
}

private void initRes(){
    tvTitle = (TextView) findViewById(R.id.tvTitle);
    gallery = (GalleryView) findViewById(R.id.mygallery);
    Avatar = (ImageView) findViewById(R.id.imageAvatar);
    adapter = new ImageAdapter(this);
    adapter.createReflectedImages();
    gallery.setAdapter(adapter);

    gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            tvTitle.setText(adapter.titles[position]);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    gallery.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent i = new Intent(Gallery3DActivity.this, MainActivity.class);
            int grallery_layout = 0;
            Avatar.setImageResource(R.layout.grallery_layout);
            startActivity(i);
            Toast.makeText(Gallery3DActivity.this, "img " + (position+1) + " selected", Toast.LENGTH_SHORT).show();
        }
    });
}
}
</code>```

In the gallery.setOnItemClickListener I try to get the drawable and show it on the main activity in the imageview with id imageAvatar but it does't work. I tried a lot of methods without luck. Grid type doesn't work, after I wanted to save the imageview new drawable using shared preferences.

答:
here is the solution i got working...
My intent of gallery3dActivity is:

```<code>@Override
public void onItemClick(AdapterView<?> parent, View  view, int position, long id) {
int selectedId = imgs[position];
Intent intent = new Intent(Gallery3DActivity.this,MainActivity.class);
intent.putExtra("imageId", selectedId);
startActivity(intent);
}
</code>```

this will send the selected drawable inside the intent to my main activity,
in the main activity i receive the intent and set it on the imageview:

```<code>Intent avatar = getIntent();
int imageId = avatar.getIntExtra("imageId", -0);
// -0 would be a default value
// -1 will crash with a missing resource

if (getIntent().getExtras() != null)
{Avatar.setImageResource(imageId);
savedAvatar.setImageResource(imageId);
update.setVisibility(View.GONE);
}
else
{Avatar.setImageResource(R.mipmap.ic_launcher);
}
</code>```

i have a button with id update on my main activity, that onclick calls setProfilePhoto:

```<code>public void setProfilePhoto(View view){
//code image to string
savedAvatar.buildDrawingCache();
Bitmap bitmap = savedAvatar.getDrawingCache();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image=stream.toByteArray();
String img_str = Base64.encodeToString(image, 0);

//decode string to image
String base=img_str;
byte[] imageAsBytes = Base64.decode(base.getBytes(), Base64.DEFAULT);
Avatar.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) );

//save in sharedpreferences
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("userphoto",img_str);
editor.commit();
update.setVisibility(View.GONE);
}
</code>```

this will get the imageview drawingcache converting it bitmao them to string, the string back to image to be able to display it on the imageview and i save the string in the sharedpreferences.
After i retrieve the image back on the oncreate method calling 2 methods:

```<code>checkFirstLogin();
prepareForm();
</code>```

wich are like this:

```<code>private void prepareForm() {
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
// If value for key not exist then return second param value - In this case "..."
String img_str=preferences.getString("userphoto", "");
if (!img_str.equals("")){
//decode string to image
String base=img_str;
byte[] imageAsBytes = Base64.decode(base.getBytes(), Base64.DEFAULT);
        Avatar.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) );
        savedAvatar.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) );
    }
}

private void checkFirstLogin() {
    SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
    // If value for key not exist then return second param value - In this case true
    if (preferences.getBoolean("firstLogin", true)) {
        initProfile();
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("firstLogin", false);
        editor.commit();
    }
}
</code>```

and finaly inside the method chechfirstlogin i call initProfile method:

```<code>private void initProfile() {
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.commit();
}
</code>```

that will call sharedpreferences.

thats it, it works perfectly the code, i hope this can help someone, sorry for making such a hard question and make such big answer. have a good day.

Body:
I'm making an app. I have a 3d gallery with an imageAdapter, galleryView, gallery3dActivity and the mainactivity.

ImageAdapter:

public class ImageAdapter extends BaseAdapter
{
private ImageView[] mImages;

private Context mContext;
public List<Map<String, Object>> list;

public Integer[] imgs = { R.drawable.cat, R.drawable.dog, R.drawable.bird,
    R.drawable.chicken, R.drawable.cow, R.drawable.rabbit, R.drawable.pig,
    R.drawable.sheep, R.drawable.donkey, R.drawable.deer, R.drawable.fox,
    R.drawable.helephant, R.drawable.tiger, R.drawable.leopard, R.drawable.lion,
    R.drawable.monquey, R.drawable.owl, R.drawable.panda, R.drawable.pinguin, R.drawable.zebra,};
public String[] titles = { "The Cat.", "The Dog", "The Bird", "The Chicken", "The Cow", "The Rabbit",
"The Pig", "The Sheep", "The Donkey", "The Deer","The Fox", "The Helephant", "The Tiger", "The Leopard",
"The Lion", "The Monquey", "The Owl", "The Panda", "The Pinguin", "The Zebra"};

public ImageAdapter(Context c)
{
    this.mContext = c;
    list = new ArrayList<Map<String, Object>>();
    for (int i = 0; i < imgs.length; i++) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("image", imgs[i]);
        list.add(map);
    }
    mImages = new ImageView[list.size()];
}

public boolean createReflectedImages()
{
    final int reflectionGap = 0;
    final int Height = 350;
    int index = 0;
    for (Map<String, Object> map : list) {
        Integer id = (Integer) map.get("image");

        Bitmap originalImage = BitmapFactory.decodeResource(mContext.getResources(), id);
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        float scale = Height / (float)height;

        Matrix sMatrix = new Matrix();
        sMatrix.postScale(scale, scale);
        Bitmap miniBitmap = Bitmap.createBitmap(originalImage, 0, 0,
                originalImage.getWidth(), originalImage.getHeight(), sMatrix, true);

        originalImage.recycle();

        int mwidth = miniBitmap.getWidth();
        int mheight = miniBitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);
        Bitmap reflectionImage = Bitmap.createBitmap(miniBitmap, 0, mheight/2, mwidth, mheight/2, matrix, false);
        Bitmap bitmapWithReflection = Bitmap.createBitmap(mwidth, (mheight + mheight / 2), Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmapWithReflection);
        canvas.drawBitmap(miniBitmap, 0, 0, null);
        Paint paint = new Paint();
        canvas.drawRect(0, mheight, mwidth, mheight + reflectionGap, paint);
        canvas.drawBitmap(reflectionImage, 0, mheight + reflectionGap, null);

        paint = new Paint();
        LinearGradient shader = new LinearGradient(0, miniBitmap.getHeight(), 0, bitmapWithReflection.getHeight()
                + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);
        paint.setShader(shader);
        paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
        canvas.drawRect(0, mheight, mwidth, bitmapWithReflection.getHeight() + reflectionGap, paint);

        ImageView imageView = new ImageView(mContext);
        imageView.setImageBitmap(bitmapWithReflection);
        imageView.setLayoutParams(new GalleryView.LayoutParams((int)(width * scale),
                (int)(mheight * 3 / 2.0 + reflectionGap)));
        imageView.setScaleType(ScaleType.MATRIX);
        mImages[index++] = imageView;
    }
    return true;
}

@Override
public int getCount() {
    return imgs.length;
}

@Override
public Object getItem(int position) {
    return mImages[position];
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    return mImages[position];
}

public float getScale(boolean focused, int offset) {
    return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
}

}

GalleryView:

public class GalleryView extends Gallery
{
private Camera mCamera = new Camera();
private int mMaxRotationAngle = 45;
private int mMaxZoom = -120;
private int mCoveflowCenter;

public GalleryView(Context context)
{
    super(context);
    this.setStaticTransformationsEnabled(true);
}

public GalleryView(Context context, AttributeSet attrs)
{
    super(context, attrs);
    this.setStaticTransformationsEnabled(true);
}

public GalleryView(Context context, AttributeSet attrs, int defStyle)
{
    super(context, attrs, defStyle);
    this.setStaticTransformationsEnabled(true);
}

public int getMaxRotationAngle()
{
    return mMaxRotationAngle;
}

public void setMaxRotationAngle(int maxRotationAngle)
{
    mMaxRotationAngle = maxRotationAngle;
}

public int getMaxZoom()
{
    return mMaxZoom;
}

public void setMaxZoom(int maxZoom)
{
    mMaxZoom = maxZoom;
}

private int getCenterOfCoverflow()
{
    return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft();
}

private static int getCenterOfView(View view) {
    return view.getLeft() + view.getWidth() / 2;
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
    mCoveflowCenter = getCenterOfCoverflow();
    super.onSizeChanged(w, h, oldw, oldh);
}

@Override
protected boolean getChildStaticTransformation(View child, Transformation trans)
{
    final int childCenter = getCenterOfView(child);
    final int childWidth = child.getWidth();
    int rotationAngle = 0;

    trans.clear();
    trans.setTransformationType(Transformation.TYPE_BOTH);

    if (childCenter == mCoveflowCenter)
    {
        transformImageBitmap((ImageView) child, trans, 0);
    }
    else
    {
        rotationAngle = (int) ( ( (float) (mCoveflowCenter - childCenter) / childWidth ) * mMaxRotationAngle );
        if (Math.abs(rotationAngle) > mMaxRotationAngle)
        {
            rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle : mMaxRotationAngle;
        }
        transformImageBitmap((ImageView) child, trans, rotationAngle);
    }

    return true;
}

private void transformImageBitmap(ImageView child, Transformation trans, int rotationAngle)
{
    mCamera.save();

    final Matrix imageMatrix = trans.getMatrix();
    final int imageHeight = child.getLayoutParams().height;
    final int imageWidth = child.getLayoutParams().width;
    final int rotation = Math.abs(rotationAngle);

    mCamera.translate(0.0f, 0.0f, -20.0f);

    // As the angle of the view gets less, zoom in
    if (rotation < mMaxRotationAngle)
    {
        float zoomAmount = (float) (mMaxZoom + (rotation * 1.0));
        mCamera.translate(0.0f, 0.0f, zoomAmount);
    }

    mCamera.rotateY(rotationAngle);
    mCamera.getMatrix(imageMatrix);
    imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));
    imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));

    mCamera.restore();
}
}

Gallery3DActivity:

public class Gallery3DActivity extends Activity {

private TextView tvTitle;
private GalleryView gallery;
private ImageAdapter adapter;
private ImageView Avatar;

@Override
public void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.grallery_layout);

    initRes();
}

private void initRes(){
    tvTitle = (TextView) findViewById(R.id.tvTitle);
    gallery = (GalleryView) findViewById(R.id.mygallery);
    Avatar = (ImageView) findViewById(R.id.imageAvatar);
    adapter = new ImageAdapter(this);
    adapter.createReflectedImages();
    gallery.setAdapter(adapter);

    gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            tvTitle.setText(adapter.titles[position]);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    gallery.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent i = new Intent(Gallery3DActivity.this, MainActivity.class);
            int grallery_layout = 0;
            Avatar.setImageResource(R.layout.grallery_layout);
            startActivity(i);
            Toast.makeText(Gallery3DActivity.this, "img " + (position+1) + " selected", Toast.LENGTH_SHORT).show();
        }
    });
}
}

In the gallery.setOnItemClickListener I try to get the drawable and show it on the main activity in the imageview with id imageAvatar but it does't work. I tried a lot of methods without luck. Grid type doesn't work, after I wanted to save the imageview new drawable using shared preferences.

Body:
here is the solution i got working...
My intent of gallery3dActivity is:

@Override
public void onItemClick(AdapterView<?> parent, View  view, int position, long id) {
int selectedId = imgs[position];
Intent intent = new Intent(Gallery3DActivity.this,MainActivity.class);
intent.putExtra("imageId", selectedId);
startActivity(intent);
}

this will send the selected drawable inside the intent to my main activity,
in the main activity i receive the intent and set it on the imageview:

Intent avatar = getIntent();
int imageId = avatar.getIntExtra("imageId", -0);
// -0 would be a default value
// -1 will crash with a missing resource

if (getIntent().getExtras() != null)
{Avatar.setImageResource(imageId);
savedAvatar.setImageResource(imageId);
update.setVisibility(View.GONE);
}
else
{Avatar.setImageResource(R.mipmap.ic_launcher);
}

i have a button with id update on my main activity, that onclick calls setProfilePhoto:

public void setProfilePhoto(View view){
//code image to string
savedAvatar.buildDrawingCache();
Bitmap bitmap = savedAvatar.getDrawingCache();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image=stream.toByteArray();
String img_str = Base64.encodeToString(image, 0);

//decode string to image
String base=img_str;
byte[] imageAsBytes = Base64.decode(base.getBytes(), Base64.DEFAULT);
Avatar.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) );

//save in sharedpreferences
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("userphoto",img_str);
editor.commit();
update.setVisibility(View.GONE);
}

this will get the imageview drawingcache converting it bitmao them to string, the string back to image to be able to display it on the imageview and i save the string in the sharedpreferences.
After i retrieve the image back on the oncreate method calling 2 methods:

checkFirstLogin();
prepareForm();

wich are like this:

private void prepareForm() {
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
// If value for key not exist then return second param value - In this case "..."
String img_str=preferences.getString("userphoto", "");
if (!img_str.equals("")){
//decode string to image
String base=img_str;
byte[] imageAsBytes = Base64.decode(base.getBytes(), Base64.DEFAULT);
        Avatar.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) );
        savedAvatar.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) );
    }
}

private void checkFirstLogin() {
    SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
    // If value for key not exist then return second param value - In this case true
    if (preferences.getBoolean("firstLogin", true)) {
        initProfile();
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("firstLogin", false);
        editor.commit();
    }
}

and finaly inside the method chechfirstlogin i call initProfile method:

private void initProfile() {
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.commit();
}

that will call sharedpreferences.

thats it, it works perfectly the code, i hope this can help someone, sorry for making such a hard question and make such big answer. have a good day.


来源: stackexchange

问:
Error handling in C code
What do you consider "best practice" when it comes to error handling errors in a consistent way in a C library.

There are two ways I've been thinking of:

Always return error code. A typical function would look like this:

```<code>MYAPI_ERROR getObjectSize(MYAPIHandle h, int* returnedSize);
</code>```

The always provide an error pointer approach:

```<code>int getObjectSize(MYAPIHandle h, MYAPI_ERROR* returnedError);
</code>```

When using the first approach it's possible to write code like this where the error handling check is directly placed on the function call:

```<code>int size;
if(getObjectSize(h, &size) != MYAPI_SUCCESS) {
  // Error handling
}
</code>```

Which looks better than the error handling code here.

```<code>MYAPIError error;
int size;
size = getObjectSize(h, &error);
if(error != MYAPI_SUCCESS) {
    // Error handling
}
</code>```

However, I think using the return value for returning data makes the code more readable, It's obvious that something was written to the size variable in the second example.

Do you have any ideas on why I should prefer any of those approaches or perhaps mix them or use something else? I'm not a fan of global error states since it tends to make multi threaded use of the library way more painful.

EDIT:
C++ specific ideas on this would also be interesting to hear about as long as they are not involving exceptions since it's not an option for me at the moment...

答:
What you could do instead of returning your error, and thus forbidding you from returning data with your function, is using a wrapper for your return type:

```<code>typedef struct {
    enum {SUCCESS, ERROR} status;
    union {
        int errCode;
        MyType value;
    } ret;
} MyTypeWrapper;
</code>```

Then, in the called function:

```<code>MyTypeWrapper MYAPIFunction(MYAPIHandle h) {
    MyTypeWrapper wrapper;
    // [...]
    // If there is an error somewhere:
    wrapper.status = ERROR;
    wrapper.ret.errCode = MY_ERROR_CODE;

    // Everything went well:
    wrapper.status = SUCCESS;
    wrapper.ret.value = myProcessedData;
    return wrapper;
}
</code>```

Please note that with the following method, the wrapper will have the size of MyType plus one byte (on most compilers), which is quite profitable; and you won't have to push another argument on the stack when you call your function (returnedSize or returnedError in both of the methods you presented).

OwnerDisplayName: Laserallan

ContentLicense: CC BY-SA 3.0

Title: Error handling in C code

Body:
What do you consider "best practice" when it comes to error handling errors in a consistent way in a C library.

There are two ways I've been thinking of:

Always return error code. A typical function would look like this:

MYAPI_ERROR getObjectSize(MYAPIHandle h, int* returnedSize);

The always provide an error pointer approach:

int getObjectSize(MYAPIHandle h, MYAPI_ERROR* returnedError);

When using the first approach it's possible to write code like this where the error handling check is directly placed on the function call:

int size;
if(getObjectSize(h, &size) != MYAPI_SUCCESS) {
  // Error handling
}

Which looks better than the error handling code here.

MYAPIError error;
int size;
size = getObjectSize(h, &error);
if(error != MYAPI_SUCCESS) {
    // Error handling
}

However, I think using the return value for returning data makes the code more readable, It's obvious that something was written to the size variable in the second example.

Do you have any ideas on why I should prefer any of those approaches or perhaps mix them or use something else? I'm not a fan of global error states since it tends to make multi threaded use of the library way more painful.

EDIT:
C++ specific ideas on this would also be interesting to hear about as long as they are not involving exceptions since it's not an option for me at the moment...

LastEditorDisplayName: Laserallan

Body:
What you could do instead of returning your error, and thus forbidding you from returning data with your function, is using a wrapper for your return type:

typedef struct {
    enum {SUCCESS, ERROR} status;
    union {
        int errCode;
        MyType value;
    } ret;
} MyTypeWrapper;

Then, in the called function:

MyTypeWrapper MYAPIFunction(MYAPIHandle h) {
    MyTypeWrapper wrapper;
    // [...]
    // If there is an error somewhere:
    wrapper.status = ERROR;
    wrapper.ret.errCode = MY_ERROR_CODE;

    // Everything went well:
    wrapper.status = SUCCESS;
    wrapper.ret.value = myProcessedData;
    return wrapper;
}

Please note that with the following method, the wrapper will have the size of MyType plus one byte (on most compilers), which is quite profitable; and you won't have to push another argument on the stack when you call your function (returnedSize or returnedError in both of the methods you presented).


问:
Regular expression for bounce email message
I am looking for a regular expression (or other method if there is such a thing) for detecting bounce email messages. So far I have been going through our unattended mail box and adding strings that I find into a regex. I figured someone would have something that is already complete rather than me re-inventing the wheel.

Here is an example of what I have so far:

```<code>/reason: 550|permanent fatal errors|Error 550|Action: Failed|Mailbox does not exist|Delivery to the following recipients failed/i
</code>```

答:
This works for me and covers pretty much all hard bounces. This is Perl, but you can roll your own using this Regex pretty safely.</p>

```<code>my $content = 'EMAIL MESSAGE HEADER AND BODY';
if (
$content =~ m/Status: 5\.\d\.\d/i || # Any 5xx error
$content =~ m/Action: Failed/i ||
$content =~ m/Reason: 5\.\d\.\d/i || # Any 5xx error
$content =~ m/MAILER-DAEMON/i ||
$content =~ m/Mailbox does not exist/i ||
$content =~ m/No Such User/i ||
$content =~ m/Delivery to the following recipients failed/i ||
$content =~ m/Recipient address rejected/i ||
$content =~ m/Host or domain name not found/i ||
$content =~ m/mailbox unavailable/i
){

# Extract email address from FINAL-RECIPIENT header:
$content =~ s/^.*?final-recipient:\s?rfc822;?\s?([^\n]+).*?$/$1/is;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am looking for a regular expression (or other method if there is such a thing) for detecting bounce email messages. So far I have been going through our unattended mail box and adding strings that I find into a regex. I figured someone would have something that is already complete rather than me re-inventing the wheel.

Here is an example of what I have so far:

/reason: 550|permanent fatal errors|Error 550|Action: Failed|Mailbox does not exist|Delivery to the following recipients failed/i

Body:
This works for me and covers pretty much all hard bounces. This is Perl, but you can roll your own using this Regex pretty safely.

my $content = 'EMAIL MESSAGE HEADER AND BODY';
if (
$content =~ m/Status: 5\.\d\.\d/i || # Any 5xx error
$content =~ m/Action: Failed/i ||
$content =~ m/Reason: 5\.\d\.\d/i || # Any 5xx error
$content =~ m/MAILER-DAEMON/i ||
$content =~ m/Mailbox does not exist/i ||
$content =~ m/No Such User/i ||
$content =~ m/Delivery to the following recipients failed/i ||
$content =~ m/Recipient address rejected/i ||
$content =~ m/Host or domain name not found/i ||
$content =~ m/mailbox unavailable/i
){

# Extract email address from FINAL-RECIPIENT header:
$content =~ s/^.*?final-recipient:\s?rfc822;?\s?([^\n]+).*?$/$1/is;
}


问:
Github Linguist overrides with wildcard
I want to set some GitHub's Linguist overrides in my .gitattributes file, more specifically I want to remove some ".vb" files from being taken into an account for determining the language statistics:

```<code>Solution 1/Vb/My Project/AssemblyInfo.vb
Solution 1/Vb/My Project/Resources.Designer.vb
Solution 1/Vb/My Project/Settings.Designer.vb
Solution 2/Vb/My Project/AssemblyInfo.vb
Solution 2/Vb/My Project/Resources.Designer.vb
Solution 2/Vb/My Project/Settings.Designer.vb
...
</code>```

It's mentioned here that we can:

use standard git-style path matchers for the files you want to override

So I tried the followings, but they're not working:

```<code>*/*/My Project/*.vb linguist-generated=true

*/*/My[[:space:]]Project/*.vb linguist-generated=true

**/My Project/* linguist-generated=true

**/My[[:space:]]Project/* linguist-generated=true
</code>```

答:
The following path matches your files:

```<code>*/*/My?Project/*.vb linguist-generated
</code>```

Note that this also works:

```<code>**/My?Project/*.vb linguist-generated
</code>```

Unfortunately, git does not support white space escaping in .gitattributes' paths. [[:space:]] is only for regular expressions (wordRegex). ? will match any character and not only spaces, but it might be enough in your case.

Title: Github Linguist overrides with wildcard

Body:
I want to set some GitHub's Linguist overrides in my .gitattributes file, more specifically I want to remove some ".vb" files from being taken into an account for determining the language statistics:

Solution 1/Vb/My Project/AssemblyInfo.vb
Solution 1/Vb/My Project/Resources.Designer.vb
Solution 1/Vb/My Project/Settings.Designer.vb
Solution 2/Vb/My Project/AssemblyInfo.vb
Solution 2/Vb/My Project/Resources.Designer.vb
Solution 2/Vb/My Project/Settings.Designer.vb
...

It's mentioned here that we can:

use standard git-style path matchers for the files you want to override

So I tried the followings, but they're not working:

*/*/My Project/*.vb linguist-generated=true

*/*/My[[:space:]]Project/*.vb linguist-generated=true

**/My Project/* linguist-generated=true

**/My[[:space:]]Project/* linguist-generated=true

Body:
The following path matches your files:

*/*/My?Project/*.vb linguist-generated

Note that this also works:

**/My?Project/*.vb linguist-generated

Unfortunately, git does not support white space escaping in .gitattributes' paths. [[:space:]] is only for regular expressions (wordRegex). ? will match any character and not only spaces, but it might be enough in your case.


问:
getting warning with this link of code
```<code> -(CLLocationCoordinate2D) addressLocation {

    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv",
   [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
    NSLog(@"locationString %@",locationString);
    NSArray *listItems = [locationString componentsSeparatedByString:@","];

    double latitude = 0.0;
    double longitude = 0.0;

    if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) {
        latitude = [[listItems objectAtIndex:2] doubleValue];
        longitude = [[listItems objectAtIndex:3] doubleValue];
        NSLog(@"listItems %@",[listItems objectAtIndex:2]);
    }
    else {
        //Show error
    }
    CLLocationCoordinate2D location;
    location.latitude = latitude;
    location.longitude = longitude;

    return location;
}
</code>```

<p>StringWithContentsOfURL is deprecated.... </p>

答:
try instead of:
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];

```<code>NSData *locationData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
NSString *locationString = [[NSString alloc] initWithData:locationData encoding:NSASCIIStringEncoding];
</code>```

the good thing about this way is that you can use NSURLConnection instead to get the data (asynchronously).

Title: getting warning with this link of code

Body:
 -(CLLocationCoordinate2D) addressLocation {

    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv",
   [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
    NSLog(@"locationString %@",locationString);
    NSArray *listItems = [locationString componentsSeparatedByString:@","];

    double latitude = 0.0;
    double longitude = 0.0;

    if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) {
        latitude = [[listItems objectAtIndex:2] doubleValue];
        longitude = [[listItems objectAtIndex:3] doubleValue];
        NSLog(@"listItems %@",[listItems objectAtIndex:2]);
    }
    else {
        //Show error
    }
    CLLocationCoordinate2D location;
    location.latitude = latitude;
    location.longitude = longitude;

    return location;
}

StringWithContentsOfURL is deprecated....

Body:
try instead of:
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];

NSData *locationData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
NSString *locationString = [[NSString alloc] initWithData:locationData encoding:NSASCIIStringEncoding];

the good thing about this way is that you can use NSURLConnection instead to get the data (asynchronously).


问:
Find path to pdf-reader and open file with it
OS : Linux.

What I want to do: Compile a file with TikZ-commands and open it with a certain pdf-viewer (I have to work only with the name of the viewer!). If the viewer does not exist, I have to return an exception.

My approach: I search for a file with the name of the viewer. This then should be the viewer itself. Next, I want to determine the path to this file. tikz_commands. Then I want to use its value via subprocess.call([viewer_path] + ['tikz_commands.pdf']. The following is part of a class:

```<code>import subprocess
import os
import tempfile
import fnmatch

def visualize(self,viewername):

    temp = tempfile.mkdtemp()
    os.chdir(temp)

    file = open('tikz_commands.tex', 'w')
    file.write(tikz_commands)
    file.close()

    proc=subprocess.Popen(['pdflatex','tikz_commands.tex'])
    proc.communicate()

    subprocess.call([str(self.set_viewer(viewername)), 'tikz_commands.pdf'])

 def set_viewer(self,viewername):
    try:
        for root, dirs, files in os.walk(os.path.join('path', 'to', 'file')):
            for file in files:
                if str(viewername) in file.lower():
                    return(os.path.join(root, file))
    except NameError:
        print('No such viewer')
</code>```

Can this work?

Have I overlooked a much easier approach?

Any help is much appreciated!

EDIT: Thanks to @Roland Smith and @Robb I could work everything out and it works perfectly now. Comment if you want to see the final code.

答: On UNIX-like operating systems (like Linux) it is generally expected that such a program is installed in a location that is contained in the environment variable PATH. In that case you should just be able to call the program without any location and it should just work.

Body:
OS : Linux.

What I want to do: Compile a file with TikZ-commands and open it with a certain pdf-viewer (I have to work only with the name of the viewer!). If the viewer does not exist, I have to return an exception.

My approach: I search for a file with the name of the viewer. This then should be the viewer itself. Next, I want to determine the path to this file. tikz_commands. Then I want to use its value via subprocess.call([viewer_path] + ['tikz_commands.pdf']. The following is part of a class:

import subprocess
import os
import tempfile
import fnmatch

def visualize(self,viewername):

    temp = tempfile.mkdtemp()
    os.chdir(temp)

    file = open('tikz_commands.tex', 'w')
    file.write(tikz_commands)
    file.close()

    proc=subprocess.Popen(['pdflatex','tikz_commands.tex'])
    proc.communicate()

    subprocess.call([str(self.set_viewer(viewername)), 'tikz_commands.pdf'])

 def set_viewer(self,viewername):
    try:
        for root, dirs, files in os.walk(os.path.join('path', 'to', 'file')):
            for file in files:
                if str(viewername) in file.lower():
                    return(os.path.join(root, file))
    except NameError:
        print('No such viewer')

Can this work?

Have I overlooked a much easier approach?

Any help is much appreciated!

EDIT: Thanks to @Roland Smith and @Robb I could work everything out and it works perfectly now. Comment if you want to see the final code.


问:
How to remove the padding on a dropdown-menu
I am looking for a way to remove a padding on "dropdown-menu"
 tag when the list is empty, so nothing shows instead of narrow space corresponding to the padding.
I don't want to do .dropdown{padding: 0}, because it will remove the necessary padding when it's not empty. But .dropdown:empty{padding:0} doesn't work since the content is not empty, only filtered by an *ngIf (I guess, though I know that Angular removes the element from the DOM).

```<code><ul role="menu" class="dropdown-menu">
    <li *ngFor="let option of options">
      <span *ngIf="option.condition;then template1 else template2">
      </span>
      <ng-template #template1>some content</ng-template>
      <ng-template #template2>some content</ng-template>
  </li>
</ul>
</code>```

答:
Just replace the padding on parent with margins on first and last child:

.dropdown-menu {
   padding-top: 0;
   padding-bottom: 0;
}
.dropdown-menu > li:first-child {
   margin-top: 15px;
}
.dropdown-menu > li:last-child {
   margin-bottom: 15px;
}
```

Note the selectors here are generic. You'll need to change them to apply to your specific example and not affect other instances of .dropdown-menu that perhaps should not be affected.

Also, 15px is a generic size. You should use the same value and unit you now have in .dropdown-menu top and bottom padding.

Body:
I am looking for a way to remove a padding on "dropdown-menu"
 tag when the list is empty, so nothing shows instead of narrow space corresponding to the padding.
I don't want to do .dropdown{padding: 0}, because it will remove the necessary padding when it's not empty. But .dropdown:empty{padding:0} doesn't work since the content is not empty, only filtered by an *ngIf (I guess, though I know that Angular removes the element from the DOM).

      <ng-template #template1>some content</ng-template>
      <ng-template #template2>some content</ng-template>

Body:
Just replace the padding on parent with margins on first and last child:

.dropdown-menu {
   padding-top: 0;
   padding-bottom: 0;
}
.dropdown-menu > li:first-child {
   margin-top: 15px;
}
.dropdown-menu > li:last-child {
   margin-bottom: 15px;
}

Note the selectors here are generic. You'll need to change them to apply to your specific example and not affect other instances of .dropdown-menu that perhaps should not be affected.

Also, 15px is a generic size. You should use the same value and unit you now have in .dropdown-menu top and bottom padding.


答:
You can use the linux which command to find a program:

```<code>viewer = subprocess.check_output(["which", viewer_name])
</code>```

It will raise an CalledProcessError if it doesn't find the program viewer_name and return the full path if it does

Title: Find path to pdf-reader and open file with it

Body:
You can use the linux which command to find a program:

viewer = subprocess.check_output(["which", viewer_name])

It will raise an CalledProcessError if it doesn't find the program viewer_name and return the full path if it does


问:
Angular2 Final release Http Post not working in MVC
I am not able to call a MVC APIController from the Angular Service. Can anybody help. Thank you.

My Route.Config is as shown below.I am allowing all routes.

```<code>public class RouteConfig
  {
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{*anything}",     //"{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
</code>```

When i am calling the post from the Application its not working not throwing any error also.

Code from forms.service.ts file

```<code>    createForm(post: myForm) {

    console.log('Actual object: ' + JSON.stringify(post));
    console.log(JSON.stringify(post));
    return this._http.post(this._posturl, JSON.stringify(post)).map(response => response.json());
    }
</code>```

Code from API Controller

```<code>  public class MinPostController : ApiController
{
   public MinPostController()
    {

    }

    [System.Web.Http.HttpPost]
    public ActionResult CreateForm([FromBody] PostFormModel input)
    {
         //Check if the post is hitting.
         bool status = false;
    }

}
</code>```

When i post the Json using the Fiddler it works fine as shown below.Please find the images below.

答:
Could you add Content-Type in header, and see any different?

```<code>return this._http.post(this._posturl, JSON.stringify(post), this.getRequestOptions())
   .map(response => response.json())
   .catch(this.handleError);

private getRequestOptions() {
   return new RequestOptions({
      headers: new Headers({
         "Content-Type": "application/json"
      })
  });
}

private handleError(error: Response) {
   console.error(error);
}
</code>```

Body:
I am not able to call a MVC APIController from the Angular Service. Can anybody help. Thank you.

My Route.Config is as shown below.I am allowing all routes.

public class RouteConfig
  {
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{*anything}",     //"{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

When i am calling the post from the Application its not working not throwing any error also.

Code from forms.service.ts file

    createForm(post: myForm) {

    console.log('Actual object: ' + JSON.stringify(post));
    console.log(JSON.stringify(post));
    return this._http.post(this._posturl, JSON.stringify(post)).map(response => response.json());
    }

Code from API Controller

  public class MinPostController : ApiController
{
   public MinPostController()
    {

    }

    [System.Web.Http.HttpPost]
    public ActionResult CreateForm([FromBody] PostFormModel input)
    {
         //Check if the post is hitting.
         bool status = false;
    }

}

When i post the Json using the Fiddler it works fine as shown below.Please find the images below.

Body:
Could you add Content-Type in header, and see any different?

return this._http.post(this._posturl, JSON.stringify(post), this.getRequestOptions())
   .map(response => response.json())
   .catch(this.handleError);

private getRequestOptions() {
   return new RequestOptions({
      headers: new Headers({
         "Content-Type": "application/json"
      })
  });
}

private handleError(error: Response) {
   console.error(error);
}


问:
How to change @color in a application
I have a source code for an application. I try to change the colors in it.After i find the color background (i think it is) so  i see this tag @color/material_grey_800 . Can you tell me how to change it?
Thanks.
Picture

答:
You can change the color profile of a color by simply changing the value (color hex codes or color profiles that come packaged with Android) in-between the color tags. For instance:

```<code><color name="colorBlack">#000000</color>
</code>```

... or:

```<code><color name="colorBlack">@android:color/black</color>
</code>```

... and then a sample implementation of referencing a color profile in say, a View's background, is as follows:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@color/colorBlack"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    ...

</RelativeLayout>
</code>```

Title: How to change @color in a application

Body:
You can change the color profile of a color by simply changing the value (color hex codes or color profiles that come packaged with Android) in-between the color tags. For instance:

<color name="colorBlack">#000000</color>

... or:

<color name="colorBlack">@android:color/black</color>

... and then a sample implementation of referencing a color profile in say, a View's background, is as follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@color/colorBlack"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    ...

</RelativeLayout>


问:
Is it possible to increase the max columns of an Oracle database to store huge arrays?
For reasons that are beyond my control I need to store huge arrays (10000+ entries) in database rows, and it has to be easy to access each index of the array individually, which means I'd rather avoid serialization/blobs, if at all possible.

So my first idea, and the actual question here, is can I increase max columns for Oracle in anyway?

Or is there an easy way to say store the array over a few rows and hide the implementation below the surface (I'm thinking stored procedure here).

Any other suggestions are also welcome!

答:
The maximum number of columns is a constraint of the database engine. So no luck there.

I don't know how many rows your database will contain, but it could be a solution to use a table that stores three fields: ArrayId, FieldIndex, Contents. Each array field is a single row in the database. If you put a combined index on ArrayId and FieldIndex, access should be pretty fast.

This solution would also allow for variable-length arrays.

OwnerDisplayName: Robert Gould

OwnerDisplayName: Sebastian Dietz


问:
Delphi 10.1 doesn't find the units added with an installed package
I use Delphi 10.1 Berlin Starter and have the following problem:

Is added some packages by opening them, and installing them by right-clicking on the package in the project manager and choosing "install". The compiled packages are now in the same folder as the other packages Delphi uses, so I think that there cannot be a problem with the library or search path.

The packages also added some Components that are now accessible in the tool palette. If I add one of these components to my program, Delphi automatically adds the unit name of the component to the "uses" section of the unit containing the component. But if I want to compile, Delphi throws the fatal error "could not find unit_name.pas".

How can I fix this? Does the units required to build and install the packages have to be included in a library path?

Maybe this is a compatibility problem. The packages were written in 2008 (Are Namespaces in Delphi younger?), so maybe the way the package wants to tell the compiler what to do does not work anymore.

This question might be difficult to understand (I had some problems to explain it...), so please comment, if you need more information.

答: Quite easy, I just had to add the units of the package to the library path (Tools->Options->Delphi Options->Library). Worked. Thanks to KenWhite.</p>


问:
Jquery UI Datepicker beforeShowDay tooltip
I found this thread about adding tooltip to disabled days on StackOverflow and could not figure out how to add it to my code.

I would be pleased if somebody could help me out.

My code so far:

```<code>beforeShowDay: function(disabledDates) {
  //Concatenating All dates before they are sent in to beforeShowDay
  var localDateArray = parsedDates.concat(addWeekendToDisabled(), disableToday(), disableTomorrow());

  var string = jQuery.datepicker.formatDate('yy-mm-dd', disabledDates);
  return [localDateArray.indexOf(string) === -1];

},
</code>```

Here is from Jquery UI Datepicker official docs beforeShowDay here

beforeShowDay

  Type: Function( Date date )

  Default: null

  A function that takes a date as a parameter and must return an array with:

  [0]: true/false indicating whether or not this date is selectable

  [1]: a CSS class name to add to the date's cell or "" for the default presentation

  [2]: an optional popup tooltip for this date

答:
Here is an old CodePen I made for another question...

The relevant code for your question is below.

CSS to re-enable pointer events on disabled dates:

```<code>pointer-events:initial !important;
</code>```

Then, on beforeShowDay, when you return a false to disable a date, you also can return a class (for background-colors, for example AND the pointer-events).

You can use that class to attach the right tooltip message, from an array, to the disabled dates.

So to attach the message, which has to be in the title attribute of the element, do something like this after the datepicker is instantiated:

```<code>$(document).find(".ui-state-disabled.red").attr("title",disabledReason[0]).tooltip();
</code>```

Edit

It looks like after a date is selected, my trick doesn't work...

Because the DatePicker is re-drawn.

So here is the walk-around, using onSelect ans a setTimeout():

```<code>onSelect: function(){
    setTimeout(function(){
        $(document).find(".ui-state-disabled.red").attr("title",disabledReason[0]).tooltip();
        $(document).find(".ui-state-disabled.green").attr("title",disabledReason[1]).tooltip();
    },10);
}
</code>```

It is working in this second CodePen.

Body:
I found this thread about adding tooltip to disabled days on StackOverflow and could not figure out how to add it to my code.

I would be pleased if somebody could help me out.

My code so far:

beforeShowDay: function(disabledDates) {
  //Concatenating All dates before they are sent in to beforeShowDay
  var localDateArray = parsedDates.concat(addWeekendToDisabled(), disableToday(), disableTomorrow());

  var string = jQuery.datepicker.formatDate('yy-mm-dd', disabledDates);
  return [localDateArray.indexOf(string) === -1];

},

Here is from Jquery UI Datepicker official docs beforeShowDay here

beforeShowDay

  Type: Function( Date date )

  Default: null

  A function that takes a date as a parameter and must return an array with:

  [0]: true/false indicating whether or not this date is selectable

  [1]: a CSS class name to add to the date's cell or "" for the default presentation

  [2]: an optional popup tooltip for this date

Body:
Here is an old CodePen I made for another question...

The relevant code for your question is below.

CSS to re-enable pointer events on disabled dates:

pointer-events:initial !important;

Then, on beforeShowDay, when you return a false to disable a date, you also can return a class (for background-colors, for example AND the pointer-events).

You can use that class to attach the right tooltip message, from an array, to the disabled dates.

So to attach the message, which has to be in the title attribute of the element, do something like this after the datepicker is instantiated:

$(document).find(".ui-state-disabled.red").attr("title",disabledReason[0]).tooltip();

Edit

It looks like after a date is selected, my trick doesn't work...

Because the DatePicker is re-drawn.

So here is the walk-around, using onSelect ans a setTimeout():

onSelect: function(){
    setTimeout(function(){
        $(document).find(".ui-state-disabled.red").attr("title",disabledReason[0]).tooltip();
        $(document).find(".ui-state-disabled.green").attr("title",disabledReason[1]).tooltip();
    },10);
}

It is working in this second CodePen.


问:
React: creating a href inside

I have this component:

```<code>const Candidate = ({candidate}) => {
    return(
        <li href='http://www.google.com' key={candidate.id}>{candidate.first} {candidate.last} ({candidate.company}) </li>
    )
}
</code>```

but it looks like I can't make a
 into a clickable link? I change it to href=''> and it worked.

What is the best way to go about making this work?

答:
Why dont you do

? I would make better since you are making a link. Add the href to the  tag.

Title: React: creating a href inside <li>

Body:
I have this component:

const Candidate = ({candidate}) => {
    return(

{candidate.first} {candidate.last} ({candidate.company})

    )
}

but it looks like I can't make a
 into a clickable link? I change it to  and it worked.

What is the best way to go about making this work?

Body: Why dont you do <li><a href=""> </a> </li>? I would make better since you are making a link. Add the href to the <a> tag.


问:
Why cannot load the js/css file?
I download the project in here

Then I opened the index.html, got these error. I checked, url for files are correct.

Updated: I often faced this problem, but I do not know why. I believe the url for the files are correct. I hope someone can download that project and run and let me know the reason. And how to solve the problem I have. I appreciate, so I know how to fix in the future.

I think angularJS's project do not need the localhost server, right?

I followed this tutorial: https://www.sitepoint.com/creating-crud-app-minutes-angulars-resource/

答: Try running a localhost server instead of directly loading the html from your file browser on your computer (in terminal run a localhost with http-simple server )see if you still get that error. also double check your code to make sure the directory pointing are correct.</p>

Title: Why cannot load the js/css file?


答:
You can use a simple anchor tag

```<code>const Candidate = ({candidate}) => {
    return(
        <li key={candidate.id}>
          <a href='http://www.google.com'>{candidate.first} {candidate.last} ({candidate.company})</a>
        </li>
    )
}
</code>```

Or if you're using react-router have a look at documentation for the Link component: https://reacttraining.com/react-router/web/example/custom-link

Title: React: creating a href inside <li>

Body:
You can use a simple anchor tag

const Candidate = ({candidate}) => {
    return(
        <li key={candidate.id}>
          <a href='http://www.google.com'>{candidate.first} {candidate.last} ({candidate.company})</a>
        </li>
    )
}

Or if you're using react-router have a look at documentation for the Link component: https://reacttraining.com/react-router/web/example/custom-link


问:
Why does this method consume so much memory? Or rather, why isn't GC freeing the memory?
I'm building some software that requires image panning, zooming, and brightness controls. I set up a small project to to build a simple brightness control after finding a lot of examples online, so please ignore that I'm doing everything in the main form

When I start to use the trackbar controller, which fires the event below when the value (-100 to 100) is changed, memory usage stacks up into the Gigabytes in seconds. It'll then sit there and never free the memory. Moving the trackbar again eats up even more memory

```<code>private void trackBarBrightness_EditValueChanged(object sender, EventArgs e)
    {
        float value = trackBarBrightness.Value * 0.01f;
        float[][] colorMatrixElements =
        {
            new float[] {
                1,
                0,
                0,
                0,
                0
            },
            new float[] {
                0,
                1,
                0,
                0,
                0
            },
            new float[] {
                0,
                0,
                1,
                0,
                0
            },
            new float[] {
                0,
                0,
                0,
                1,
                0
            },
            new float[] {
                value,
                value,
                value,
                0,
                1
            }
        };

        ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
        ImageAttributes imageAttributes = new ImageAttributes();

        imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

        //Image img = this.pictureEdit.Image;
        Image img = originalImage;
        Graphics g = default(Graphics);
        Bitmap bm = new Bitmap(Convert.ToInt32(img.Width), Convert.ToInt32(img.Height));
        g = Graphics.FromImage(bm);
        g.DrawImage(img, new Rectangle(0, 0, bm.Width, bm.Height), 0, 0, bm.Width, bm.Height, GraphicsUnit.Pixel, imageAttributes);
        pictureEdit.Image = bm;
    }
</code>```

Any guidance would be much appreciated

答:
Don't see you are using any loops and so not sure but you can consider using a memory profiler and see but I see you are not disposing off the created Image object all. I mean the below two lines. You should explicitly call Dispose() on them or use a Using(...) { ... } construct for better disposal

```<code>Image img = originalImage;
Graphics g = default(Graphics);
</code>```

Body:
I'm building some software that requires image panning, zooming, and brightness controls. I set up a small project to to build a simple brightness control after finding a lot of examples online, so please ignore that I'm doing everything in the main form

When I start to use the trackbar controller, which fires the event below when the value (-100 to 100) is changed, memory usage stacks up into the Gigabytes in seconds. It'll then sit there and never free the memory. Moving the trackbar again eats up even more memory

private void trackBarBrightness_EditValueChanged(object sender, EventArgs e)
    {
        float value = trackBarBrightness.Value * 0.01f;
        float[][] colorMatrixElements =
        {
            new float[] {
                1,
                0,
                0,
                0,
                0
            },
            new float[] {
                0,
                1,
                0,
                0,
                0
            },
            new float[] {
                0,
                0,
                1,
                0,
                0
            },
            new float[] {
                0,
                0,
                0,
                1,
                0
            },
            new float[] {
                value,
                value,
                value,
                0,
                1
            }
        };

        ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
        ImageAttributes imageAttributes = new ImageAttributes();

        imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

        //Image img = this.pictureEdit.Image;
        Image img = originalImage;
        Graphics g = default(Graphics);
        Bitmap bm = new Bitmap(Convert.ToInt32(img.Width), Convert.ToInt32(img.Height));
        g = Graphics.FromImage(bm);
        g.DrawImage(img, new Rectangle(0, 0, bm.Width, bm.Height), 0, 0, bm.Width, bm.Height, GraphicsUnit.Pixel, imageAttributes);
        pictureEdit.Image = bm;
    }

Any guidance would be much appreciated

Body:
Don't see you are using any loops and so not sure but you can consider using a memory profiler and see but I see you are not disposing off the created Image object all. I mean the below two lines. You should explicitly call Dispose() on them or use a Using(...) { ... } construct for better disposal

Image img = originalImage;
Graphics g = default(Graphics);


问:
Map object support in Google Apps Script
Does Google Apps Script supports the Map object?

When I try to use it I get:

```<code>ReferenceError: "Map" is not defined. (line 21, file "Code")
</code>```

答: No. Map was introduced in ES6. Google Apps Script roughly corresponds to ES 5.1. It runs on Rhino, which is not so actively developed, and it's not clear if Google will ever want to pull in newer Rhino releases anyway. </p>

Body:
Does Google Apps Script supports the Map object?

When I try to use it I get:

ReferenceError: "Map" is not defined. (line 21, file "Code")


问:
Making 3d models in flash
hy!

I have to make a animation for my school.

My cencept:

Make 4 Pictures from a person's head and wire them together to a cube.
Then i want to import this into Adobe flash professional cs5.

My Question:

Is this possible?
If not, are there any other rudiments to solve my problem?

Thanks for helping

答:
I strongly recommend to use Away 3D. It's the only flash 3d engine which has a dedicated (and free) editor.

The editor is called Prefab http://www.closier.nl/prefab.
It lets you create and texture simple 3d objects previewing results in realtime right inside the Away 3D renderer (this editor is built on top of it) then you can export your model into the Away 3D compatible format. I had a hard experience trying to export textured 3d from different 3d packages to different flash 3d engines. Prefab and Away 3d is the easiest way to do the task.

To make coding in Flash IDE easier you should install syntax highlighting extension from http://away3d.com/downloads.

Pass through the beginner's tutorials at http://away3d.com/tutorials up to the "Manipulating 3D objects". You won't need to learn anything else 'cause Prefab will handle 3d object setup for you.

Title: Making 3d models in flash


问:
View more than one project/solution in Visual Studio
I am new to visual studio and I am experimenting around with some Windows Services. I have created two solutions and I would like to view both of them at once. Without having to click file->recent projects to switch back and forth.

Ideally this could take place in the solution explorer and just nest the projects, but I am only able to view one solution/project at a time there.

Is there anyway to view multiple solutions/projects in Visual Studio?

答:
There is a way to store multiple solutions in one instance of VS.

Attempt the following steps:

File > Open > Project/Solution

This will bring up the open project window, notice at the bottom where it says options, select add to solution

Then select the file you want to add and click open

This will then add the solution to your project. You still won't be able to run the same project in a single instance of VS, but you can have all your code organized in one place.

NOTE:
This worked for Visual Studio 2013 Professional


问:
Firebase DataSnapshot Not Filling Object
I have an object in a firebase database that I am trying to extract from a snapshot.

The JSON object from firebase is:

```<code>"-KoVHZ8YVll0RiI2GwKb" : {
    "name" : "Name 1",
    "phone_number" : "4443335555"
}
</code>```

I am trying to safe it in an object that looks like this

```<code>public class Contact {
    private String mName;
    private String mPhoneNumber;

    public Contact() {
        mName = "";
        mPhoneNumber = "";
    }

    public String getName() { return mName; }
    public String getPhoneNumber() { return mPhoneNumber; }
    public void setName(final String name) { mName = name; }
    public void setPhoneNumber(final String phoneNumber) { mPhoneNumber = phoneNumber; }
}
</code>```

I am calling

```<code>Contact contact = snapshot.getValue(Contact.class);
</code>```

The contact object only has the name populated and not the phone number. The documentation just states that there must be public getters and an empty constructor in order for this to work. My guess is something is wrong with my naming convention anyone have any ideas?

EDIT

I am aware that I can extract the data out by doing this:

```<code>mName = (String) snapshot.child("nane").getValue();
mPhoneNumber = (String) snapshot.child("phone_number").getValue();
</code>```

But then what is the point of creating the P.O.J.O.?

答:
Make your Contact.java like this:

```<code>@IgnoreExtraProperties
public class Contact {

   private String name;
   private String phone_number;

   public Contact() {
   }

   public String getName() {
       return name;
   }

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

   public String getPhone_number() {
       return phone_number;
   }

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

}

Body:
I have an object in a firebase database that I am trying to extract from a snapshot.

The JSON object from firebase is:

"-KoVHZ8YVll0RiI2GwKb" : {
    "name" : "Name 1",
    "phone_number" : "4443335555"
}

I am trying to safe it in an object that looks like this

public class Contact {
    private String mName;
    private String mPhoneNumber;

    public Contact() {
        mName = "";
        mPhoneNumber = "";
    }

    public String getName() { return mName; }
    public String getPhoneNumber() { return mPhoneNumber; }
    public void setName(final String name) { mName = name; }
    public void setPhoneNumber(final String phoneNumber) { mPhoneNumber = phoneNumber; }
}

I am calling

Contact contact = snapshot.getValue(Contact.class);

The contact object only has the name populated and not the phone number. The documentation just states that there must be public getters and an empty constructor in order for this to work. My guess is something is wrong with my naming convention anyone have any ideas?

EDIT

I am aware that I can extract the data out by doing this:

mName = (String) snapshot.child("nane").getValue();
mPhoneNumber = (String) snapshot.child("phone_number").getValue();

But then what is the point of creating the P.O.J.O.?

Body:
Make your Contact.java like this:

@IgnoreExtraProperties
public class Contact {

   private String name;
   private String phone_number;

   public Contact() {
   }

   public String getName() {
       return name;
   }

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

   public String getPhone_number() {
       return phone_number;
   }

   public void setPhone_number(String phone_number) {
       this.phone_number = phone_number;
   }

}


问:
R: Global assignment of vector element works only inside a function
I'm working on a project where there are some global assignments, and I ran into something sort of odd. I was hoping someone could help me with it.

I wrote this toy example to demonstrate the problem:

```<code>x <-  1:3 ; x <-  c(1, 2, 5) # this works fine
x <-  1:3 ; x[3] <- 5        # this works fine

x <<- 1:3 ; x <<- c(1, 2, 5) # this works fine
x <<- 1:3 ; x[3] <<- 5       # this does not work
# Error in x[3] <<- 5 : object 'x' not found

same.thing.but.in.a.function = function() {
  x <<- 1:3
  x[3] <<- 5
}
same.thing.but.in.a.function(); x
# works just fine
</code>```

So, it seems it's not possible to change part of a vector using a global assignment -- unless that assignment is contained within a function. Can anyone explain why this is the case?

答:
I figured out the problem.

Basically, in this manifestation of <<- (which is more accurately called the "superassignment operator" rather than the "global assignment operator"), it actually skips checking the global environment when trying to access the variable.

On page 19 of R Language Definition, it states the following:

```<code>x <<- data.frame(0, 0, 0) # (I added this so the code can be run)
names(x)[3] <<- "Three"
</code>```

is equivalent to

```<code>x <<- data.frame(0, 0, 0) # (I added this so the code can be run)
`*tmp*` <<- get(x, envir=parent.env(), inherits=TRUE)
names(`*tmp*`)[3] <- "Three"
x <<- `*tmp*`
rm(`*tmp*`)
</code>```

When I tried to run those four lines, it threw an error -- parent.env requires an argument and has no default. I can only assume that the documentation was written at a time when parent.env() contained a default value for its first argument. But I can safely guess that the default would have been environment() which returns the current environment. It then throws an error again -- x needs to be in quotes. So I fixed that too. Now, when I run the first line, it throws the same error message as I encountered originally, but with more detail:

```<code># Error in get("x", envir = parent.env(environment()), inherits = TRUE) :
#   object 'x' not found
</code>```

This makes sense -- environment() itself returns .GlobalEnv, so parent.env(.GlobalEnv) misses out on the global environment entirely, instead returning the most recently loaded package environment. Then, since inherits is set to TRUE, the get() function keeps going up the levels, searching through each of the loaded package environments before eventually reaching the empty environment, and at that point it has still not found x. Thus the error.

Since parent.env(environment()) will return .GlobalEnv (or another environment below it) as long as you start inside a local environment, this same problem does not occur when the same lines are run from inside a local environment:*

```<code>local({
  x <<- data.frame(0, 0, 0) # (I added this so the code can be run)
  `tmp` <<- get("x", envir=parent.env(environment()), inherits=TRUE)
  names(`tmp`)[3] <- "Three"
  x <<- `tmp`
  rm(`tmp`)
})
x
#   X0 X0.1 Three
# 1  0    0     0

# so, it works properly
</code>```

In contrast, when <<- is used in general, there is no extra subsetting code that occurs behind the scenes, and it first attempts to access the value in the current environment (which might be the global environment), before moving upwards. So in that situation, it doesn't run into the problem where it skips the global environment.

 * I had to change the variable from *tmp* to tmp because one of the behind-the-scenes operations in the code uses the *tmp* variable and then removes it, so *tmp* disappears in the middle of line 3 and so it throws an error when I then try to access it.

Body:
I'm working on a project where there are some global assignments, and I ran into something sort of odd. I was hoping someone could help me with it.

I wrote this toy example to demonstrate the problem:

x <-  1:3 ; x <-  c(1, 2, 5) # this works fine
x <-  1:3 ; x[3] <- 5        # this works fine

x <<- 1:3 ; x <<- c(1, 2, 5) # this works fine
x <<- 1:3 ; x[3] <<- 5       # this does not work
# Error in x[3] <<- 5 : object 'x' not found

same.thing.but.in.a.function = function() {
  x <<- 1:3
  x[3] <<- 5
}
same.thing.but.in.a.function(); x
# works just fine

So, it seems it's not possible to change part of a vector using a global assignment -- unless that assignment is contained within a function. Can anyone explain why this is the case?

Body:
I figured out the problem.

Basically, in this manifestation of <<- (which is more accurately called the "superassignment operator" rather than the "global assignment operator"), it actually skips checking the global environment when trying to access the variable.

On page 19 of R Language Definition, it states the following:

x <<- data.frame(0, 0, 0) # (I added this so the code can be run)
names(x)[3] <<- "Three"

is equivalent to

x <<- data.frame(0, 0, 0) # (I added this so the code can be run)
`*tmp*` <<- get(x, envir=parent.env(), inherits=TRUE)
names(`*tmp*`)[3] <- "Three"
x <<- `*tmp*`
rm(`*tmp*`)

When I tried to run those four lines, it threw an error -- parent.env requires an argument and has no default. I can only assume that the documentation was written at a time when parent.env() contained a default value for its first argument. But I can safely guess that the default would have been environment() which returns the current environment. It then throws an error again -- x needs to be in quotes. So I fixed that too. Now, when I run the first line, it throws the same error message as I encountered originally, but with more detail:

# Error in get("x", envir = parent.env(environment()), inherits = TRUE) :
#   object 'x' not found

This makes sense -- environment() itself returns .GlobalEnv, so parent.env(.GlobalEnv) misses out on the global environment entirely, instead returning the most recently loaded package environment. Then, since inherits is set to TRUE, the get() function keeps going up the levels, searching through each of the loaded package environments before eventually reaching the empty environment, and at that point it has still not found x. Thus the error.

Since parent.env(environment()) will return .GlobalEnv (or another environment below it) as long as you start inside a local environment, this same problem does not occur when the same lines are run from inside a local environment:*

local({
  x <<- data.frame(0, 0, 0) # (I added this so the code can be run)
  `tmp` <<- get("x", envir=parent.env(environment()), inherits=TRUE)
  names(`tmp`)[3] <- "Three"
  x <<- `tmp`
  rm(`tmp`)
})
x
#   X0 X0.1 Three
# 1  0    0     0

# so, it works properly

In contrast, when <<- is used in general, there is no extra subsetting code that occurs behind the scenes, and it first attempts to access the value in the current environment (which might be the global environment), before moving upwards. So in that situation, it doesn't run into the problem where it skips the global environment.

 * I had to change the variable from *tmp* to tmp because one of the behind-the-scenes operations in the code uses the *tmp* variable and then removes it, so *tmp* disappears in the middle of line 3 and so it throws an error when I then try to access it.


问:
Hooking up React Native to back-end (with Express)
I made a UI with React Native, as well as a Cheerio.js scraper (with Cron Job to activate it once every day) I'll use to grab certain data from the web, so it can render in the UI. However, I have no idea how to link the two of them.

I am pretty sure I can do this with Express (which I am most comfortable with for the back-end), but can someone tell me exactly what I need to do to connect my front-end to a back-end?

Just in case, I am a junior dev (better on the front-end than the back-end) so please keep your answers simple. Even if your answers are more conceptual, rather than code-based, I'd really appreciate it.

答: Assuming you're communicating with an API built with Express then use fetch as described in the docs: https://facebook.github.io/react-native/docs/network.html


问:
Comparing elements of an array in Google Apps Script
Basic Example data

I cannot figure out why the if statement I have marked as "If statement in question", never evaluates to true and its commands never execute.

```<code>  function setDuplicatesArray () {
  var sheet = SpreadsheetApp.getActive().getActiveSheet();

  var compareFromCol = "A";
  var compareToCol = "E";
  var compareFromIndex = sheet.getRange(compareFromCol+"1").getColumn();
  var compareToIndex = sheet.getRange(compareToCol+"1").getColumn();
  var maxRows = sheet.getMaxRows();

  var FromValues = sheet.getRange(4,compareFromIndex,maxRows,1).getValues();
  var ToValues   = sheet.getRange(4,compareToIndex,maxRows,1).getValues();

  var count = 0
  for (i=0; i <= maxRows; i++) {
    var from = FromValues[i];
    if (from == "") { break; }
       for ( j=0; j <= maxRows; j++) {
         var to = ToValues[j];

         if (to == "") {break; }

         Logger.log("\n"+from+"\n"+to+"\n\n");

         if (from === to) { //IF STATEMENT IN QUESTION
           count = count++;
           sheet.getRange(i+4,compareFromIndex,1,4).setBackgroundRGB(255,255,0);
           break;
         }
       }
  }
</code>```

Here is the log to confirm that some elements are the same:

```<code>[17-07-08 12:27:57:899 PDT]
Desk
Cats

[17-07-08 12:27:57:900 PDT]
Desk
Dogs

[17-07-08 12:27:57:900 PDT]
Desk
Pigs

[17-07-08 12:27:57:900 PDT]
Desk
Fish

[17-07-08 12:27:57:900 PDT]
Cats
Cats

[17-07-08 12:27:57:901 PDT]
Cats
Dogs

[17-07-08 12:27:57:901 PDT]
Cats
Pigs

[17-07-08 12:27:57:901 PDT]
Cats
Fish

[17-07-08 12:27:57:902 PDT]
Fish
Cats

[17-07-08 12:27:57:902 PDT]
Fish
Dogs

[17-07-08 12:27:57:902 PDT]
Fish
Pigs

[17-07-08 12:27:57:903 PDT]
Fish
Fish

[17-07-08 12:27:57:903 PDT]
Pencils
Cats

[17-07-08 12:27:57:903 PDT]
Pencils
Dogs

[17-07-08 12:27:57:904 PDT]
Pencils
Pigs

[17-07-08 12:27:57:904 PDT]
Pencils
Fish

[17-07-08 12:27:57:904 PDT] 0.0
</code>```

答:
I figured it out.

.getValues() creates a two dimensional array despite there being only one column in its range.

So I changed:

```<code>var from = FromValues[i];
</code>```

to

```<code>var from = FromValues[i][0];
</code>```

and

```<code>var from = ToValues[j];
</code>```

to

```<code>var from = ToValues[j][0];
</code>```

Body:
Basic Example data

I cannot figure out why the if statement I have marked as "If statement in question", never evaluates to true and its commands never execute.

  function setDuplicatesArray () {
  var sheet = SpreadsheetApp.getActive().getActiveSheet();

  var compareFromCol = "A";
  var compareToCol = "E";
  var compareFromIndex = sheet.getRange(compareFromCol+"1").getColumn();
  var compareToIndex = sheet.getRange(compareToCol+"1").getColumn();
  var maxRows = sheet.getMaxRows();

  var FromValues = sheet.getRange(4,compareFromIndex,maxRows,1).getValues();
  var ToValues   = sheet.getRange(4,compareToIndex,maxRows,1).getValues();

  var count = 0
  for (i=0; i <= maxRows; i++) {
    var from = FromValues[i];
    if (from == "") { break; }
       for ( j=0; j <= maxRows; j++) {
         var to = ToValues[j];

         if (to == "") {break; }

         Logger.log("\n"+from+"\n"+to+"\n\n");

         if (from === to) { //IF STATEMENT IN QUESTION
           count = count++;
           sheet.getRange(i+4,compareFromIndex,1,4).setBackgroundRGB(255,255,0);
           break;
         }
       }
  }

Here is the log to confirm that some elements are the same:

[17-07-08 12:27:57:899 PDT]
Desk
Cats

[17-07-08 12:27:57:900 PDT]
Desk
Dogs

[17-07-08 12:27:57:900 PDT]
Desk
Pigs

[17-07-08 12:27:57:900 PDT]
Desk
Fish

[17-07-08 12:27:57:900 PDT]
Cats
Cats

[17-07-08 12:27:57:901 PDT]
Cats
Dogs

[17-07-08 12:27:57:901 PDT]
Cats
Pigs

[17-07-08 12:27:57:901 PDT]
Cats
Fish

[17-07-08 12:27:57:902 PDT]
Fish
Cats

[17-07-08 12:27:57:902 PDT]
Fish
Dogs

[17-07-08 12:27:57:902 PDT]
Fish
Pigs

[17-07-08 12:27:57:903 PDT]
Fish
Fish

[17-07-08 12:27:57:903 PDT]
Pencils
Cats

[17-07-08 12:27:57:903 PDT]
Pencils
Dogs

[17-07-08 12:27:57:904 PDT]
Pencils
Pigs

[17-07-08 12:27:57:904 PDT]
Pencils
Fish

[17-07-08 12:27:57:904 PDT] 0.0

Body:
I figured it out.

.getValues() creates a two dimensional array despite there being only one column in its range.

So I changed:

var from = FromValues[i];

to

var from = FromValues[i][0];

and

var from = ToValues[j];

to

var from = ToValues[j][0];


问:
GND Servo and Arduino
I was working in a little project with Arduino and two Servomotors

Why is it necessary to putting the GND from external source (necessary to power the servomotor) and Arduino GND together?

Why is not able to work properly with separated GND?

答:
Whenever you interface your Arduino to a separate device -- or several -- you must establish a common ground.  Perhaps your servos run off their own power of a small breadboard, or you have a sensor or a bunch of LEDs... in all cases you'll need to make a common ground for all components of the circuit.

If I'm hooking up more than a single LED or single sensor to my Arduino, I prototype on a breadboard and the first thing I do is connect the power GND pin of the Arduino to the blue/black ground rail of the breadboard.  That ensures a common ground, which is vitally important as a reference 0V in any circuit you build.

In many well-designed multi-layer circuit boards for example, often one layer of copper is devoted entirely to GND so that every component will be able to have a solid connection to GND.  Then it's referred to as a "ground plane" and is a common goal in good circuit board design.

Title: GND Servo and Arduino


问:
Divide string into words
I'm now having a headache solving this issue.

I have this line :-

```<code>$quote = "Success consists of going from failure to failure without loss of enthusiasm.";
</code>```

How do I break this line such that each broken line would have max 27 characters?

My Desired output would be

```<code>array(line 1) --> Success consists of going
array(line 2) --> from failure to failure
array(line 3) --> without loss of enthusiasm
</code>```

This is what I've tried :-

```<code>$final_lines = array();
      //conver to string array
      $string_arrray_line = str_split($string_line);
      $a = "";
      $b=0;
      $counter = 0;
      for($i=0;$i<strlen($string_line);$i++)
      {
        // echo $i;
        if($counter == 27)
        {
          //insert into array now
          $final_lines[$b] = $a;
          $b++;
          $a = "";
          $counter = 0;
        }
        $a .= $string_arrray_line[$i];
        $counter++;
        // var_dump($string_arrray_line[$i]);
      }
</code>```

^^  This doesn't work and dozen other solutions that I tried.
What could I possibly do to achieve what I want?

Any solution would be helpful.

答:
Use wordwrap():</p>

```<code><?php
$quote = "Success consists of going from failure to failure without loss of enthusiasm.";
$result = explode("\n", wordwrap($quote, 27));
var_dump($result);
</code>```

Title: Divide string into words

Body:
I'm now having a headache solving this issue.

I have this line :-

$quote = "Success consists of going from failure to failure without loss of enthusiasm.";

How do I break this line such that each broken line would have max 27 characters?

My Desired output would be

array(line 1) --> Success consists of going
array(line 2) --> from failure to failure
array(line 3) --> without loss of enthusiasm

This is what I've tried :-

$final_lines = array();
      //conver to string array
      $string_arrray_line = str_split($string_line);
      $a = "";
      $b=0;
      $counter = 0;
      for($i=0;$i<strlen($string_line);$i++)
      {
        // echo $i;
        if($counter == 27)
        {
          //insert into array now
          $final_lines[$b] = $a;
          $b++;
          $a = "";
          $counter = 0;
        }
        $a .= $string_arrray_line[$i];
        $counter++;
        // var_dump($string_arrray_line[$i]);
      }

^^  This doesn't work and dozen other solutions that I tried.
What could I possibly do to achieve what I want?

Any solution would be helpful.

Body:
Use wordwrap():

<?php
$quote = "Success consists of going from failure to failure without loss of enthusiasm.";
$result = explode("\n", wordwrap($quote, 27));
var_dump($result);


问:
Check if an array is descending, ascending or not sorted?
I'm just beginning with programming using javascript and I need to practice some questions to get EXP with the logic of code build.
I got this question for homework but I can't make it work for some reason, even though it seems "logic" to me.
Check if an array is descending, ascending or not sorted using loops.

I'm just a noob so please try and help me figure this out as I only got to loops in my studies (:
 this is the code I wrote:

```<code>        var array = [1, 2, 3, 7 ];
        var d = 0;
        var c =0 ;
        var b = 1;
        var a = 0;
        for (var i = 1; i <= array.length; i++)
            {
                if (array[c]<array[b] && a!== -1  ){
                   d = -1;
                   c =c+1;
                   b = b+1;
                   if(c==array.length){
                    console.log("asc");
                     break;
                   }else{
                     continue;
                }

                } else if (array[c]>array[b] && d!==-1 ){
                           a = -1;
                           d= d+1;
                           b = b+1;
                    if(i=array.length){
                    console.log("dsc");
                    break;
               }else{continue;}

               } else{

                    console.log("unsorted array");
                    break;
                }

            }
</code>```

答:
This is a question that requires some sort of loop, with several if statements because there are several cases you need to tackle:

Array is empty or has only one element.

All items in the array are equal

Array is ascending - delta between 2 elements > 0, but some deltas may be 0

Array is descending - delta between 2 elements < 0, but some deltas may be 0

Not sorted - some deltas are > 0, and some are < 0

Depending on how the sorted is defined in the question, cases 1 & 2 might be regarded as unsorted as well.

function findSortOrder(arr) {
  if(arr.length < 2) { // case 1
    return 'not enough items'; // can also be 'unsorted'
  }

  var ascending = null;
  var nextArr = arr.slice(1); // create an array that starts from the 2nd element of the original array

  for(var i = 0; i < nextArr.length; i++) {
    if (nextArr[i] === arr[i]) { // neutral - do nothing
    } else if(ascending === null) { // define the the direction by the 1st delta encountered
      ascending = nextArr[i] > arr[i];
    } else if (ascending !== nextArr[i] > arr[i]) { // case 5
      return 'unsorted';
    }
  }

  if(ascending === null) { // case 2
    return 'all items are equal'; // can also be 'unsorted'
  }

  return ascending ? 'ascending' : 'descending'; // cases 3 & 4
}

console.log(findSortOrder([1])); // case 1

console.log(findSortOrder([1, 1, 1, 1])); // case 2

console.log(findSortOrder([1, 1, 2, 3, 7, 7])); // case 3

console.log(findSortOrder([7, 2, 2, 1])); // case 4

console.log(findSortOrder([7, 2, 1, 3, 2, 1])); // case 5```

Body:
I'm just beginning with programming using javascript and I need to practice some questions to get EXP with the logic of code build.
I got this question for homework but I can't make it work for some reason, even though it seems "logic" to me.
Check if an array is descending, ascending or not sorted using loops.

I'm just a noob so please try and help me figure this out as I only got to loops in my studies (:
 this is the code I wrote:

        var array = [1, 2, 3, 7 ];
        var d = 0;
        var c =0 ;
        var b = 1;
        var a = 0;
        for (var i = 1; i <= array.length; i++)
            {
                if (array[c]<array[b] && a!== -1  ){
                   d = -1;
                   c =c+1;
                   b = b+1;
                   if(c==array.length){
                    console.log("asc");
                     break;
                   }else{
                     continue;
                }

                } else if (array[c]>array[b] && d!==-1 ){
                           a = -1;
                           d= d+1;
                           b = b+1;
                    if(i=array.length){
                    console.log("dsc");
                    break;
               }else{continue;}

               } else{

                    console.log("unsorted array");
                    break;
                }

            }


问:
Responsive image aspect ratio of height
I have an image of 768px x 432px. I make it responsive, but I want the aspect ratio to be calculated based on the value of 350px x 250px.

I can do this with the width but not with the height.

How could I do it?

What am I using for width:

```<code>.thumb {
    width: 100%;
    max-width: 350px;
}
</code>```

.thumb {
  width: 100%;
  max-width: 350px;
  max-height: 250px;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">
    <div class="col col-md-4">
      <img src="http://lorempixel.com/768/432/technics/" class="thumb">
    </div>
  </div>
</div></code>```

答:
try in the css using  the vh /vw tags for responsive cross platform page fitting.

for example:
vh - view-height
vw - viewwidth

```<code>.thumb {
  width: 100%;
  max-width: 30vw;
  max-height: 25vh;
  height: 10vh;
}
</code>```

Just a side note, When your thinking of page width -- imagine the full page width being 100vw so 30vw would basically be a bit less than a third of the page no matter the size of a page. same idea with the height.

Title: Responsive image aspect ratio of height

Body:
I have an image of 768px x 432px. I make it responsive, but I want the aspect ratio to be calculated based on the value of 350px x 250px.

I can do this with the width but not with the height.

How could I do it?

What am I using for width:

.thumb {
    width: 100%;
    max-width: 350px;
}

.thumb {
  width: 100%;
  max-width: 350px;
  max-height: 250px;
  height: 100%;
}

Body:
try in the css using  the vh /vw tags for responsive cross platform page fitting.

for example:
vh - view-height
vw - viewwidth

.thumb {
  width: 100%;
  max-width: 30vw;
  max-height: 25vh;
  height: 10vh;
}

Just a side note, When your thinking of page width -- imagine the full page width being 100vw so 30vw would basically be a bit less than a third of the page no matter the size of a page. same idea with the height.

ContentLicense: CC BY-SA 4.0


答:
I called your dataframe Data, then:

```<code>test <- with(Data,
   data.frame(
     Loc = rep(Loc,2),
     est = rep(c("A","B"),each=nrow(Data)),
     value = c(get("est A"),get("est B")),
     lb = c(get("A lb"),get("B lb")),
     ub = c(get("A ub"),get("B ub"))
   )
)
ggplot(test,aes(x=Loc,y=value,color=est))+geom_point()+
     geom_errorbar(aes(ymax=ub,ymin=lb))
</code>```

And please, never ever use variable names with a space if possible. If you didn't, you could just have done:

```<code>test <- with(Data,
   data.frame(
     Loc = rep(Loc,2),
     est = rep(c("A","B"),each=nrow(Data)),
     value = c(estA,estB),
     lb = c(Alb,Blb),
     ub = c(Aub,Bub)
   )
)
ggplot(test,aes(x=Loc,y=value,color=est))+geom_point()+
    geom_errorbar(aes(ymax=ub,ymin=lb))
</code>```

Title: ggplot and errorbars

Body:
I'm trying to create a plot with errorbars from the following data (dput of the dataframe in the end). I'd like to create errorbars for the "est A" and "est B" variables for each "loc", but I cannot figure out the right way to melt/cast the data so that each "loc" would have two rows with several columns.

I.e. I'd like to convert the dataframe into

loc est value  lb     ub

a    A   0.56   0.26  1.20

a    B   0.26   0.11  0.60

b    A   0.13

b    B   0.03

c    A

c    B

ggplot(test,aes(x=Loc,y=value,color=est))+geom_point()+geom_errorbar(aes(ymax=ub,ymin=lb))

> dput(test)
structure(list(Loc = c("a", "b", "c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s"), `est A` = c(0.563270934055709,
0.137109873453407, 0.0946514679398302, 0.185103062070327, 0.0322566231880829,
0.122509922923046, 0.120243043198876, 0.496530499385046, 0.469200921538171,
0.0605252215342125, 0.102364314964088, 0.115500654388976, 0.226320301860998,
0.553299923910439, 0.0284461712437990, 0.161231809656951, 0.129270683014873,
0.0691902563736868, 4.22775563209408e-10), `est B` = c(0.261222076585074,
0.0361169058045732, 0.0389295009573361, 0.0341489915400374, 0.00722206105211422,
0.0756192543690879, 0.0638910584951127, 0.112923798991901, 0.169215410079679,
0.0235142527703486, 0.0347964005083873, 0.0485649792804626, 0.057534910753763,
0.142573116854277, 0.0221769276223588, 0.104198059736499, 0.0234801538140553,
0.072563099770018, 1.93211916678252e-10), `A lb` = c(0.262976608413878,
0.0724138165552355, 0.0496821188642757, 0.083935851825787, 0.00630380846921399,
0.0490562081838664, 0.0467393615329014, 0.20284436584412, 0.178474018619480,
0.0171506568665928, 0.0503363150211533, 0.0600281091658352, 0.0747597162489745,
0.276929613768523, 0.00665167561787145, 0.0580348444006193, 0.0516432163190537,
0.0228220757228112, 0), `A ub` = c(1.20647287629726, 0.259606775235633,
0.180324442434493, 0.408206300913301, 0.165057321233572, 0.305948661143090,
0.309340756132258, 1.21542708762748, 1.23351010121895, 0.213595459944227,
0.208168853315217, 0.222235904972905, 0.685140094216929, 1.10548237017075,
0.121651250740107, 0.447932560408103, 0.323583825296458, 0.209765826526966,
Inf), `B lb` = c(0.111866193520147, 0.0169169666997800, 0.0186761266424921,
0.0121471488870159, 0.00126380823047679, 0.0279532804037691,
0.0225442254744942, 0.0369377660459994, 0.0509571176650792, 0.00592607390737984,
0.0157043256006381, 0.0231925392578512, 0.0153998561264800, 0.0612241780775462,
0.00507024995333768, 0.0364091610491575, 0.00745586930827693,
0.0243798413908829, 0), `B ub` = c(0.609987442570209, 0.0771078472899858,
0.0811466999446844, 0.0960022499146318, 0.0412706331409062, 0.204565315724654,
0.181069310198491, 0.345223486522794, 0.561920617187038, 0.0933029341161755,
0.0770991075408484, 0.101694652159027, 0.214954342966326, 0.332010886676128,
0.0970003694676995, 0.298200654450461, 0.0739441103828987, 0.215973654783605,
Inf)), .Names = c("Loc", "est A", "est B", "A lb", "A ub", "B lb",
"B ub"), row.names = c(NA, -19L), class = "data.frame")

Body:
I called your dataframe Data, then:

test <- with(Data,
   data.frame(
     Loc = rep(Loc,2),
     est = rep(c("A","B"),each=nrow(Data)),
     value = c(get("est A"),get("est B")),
     lb = c(get("A lb"),get("B lb")),
     ub = c(get("A ub"),get("B ub"))
   )
)
ggplot(test,aes(x=Loc,y=value,color=est))+geom_point()+
     geom_errorbar(aes(ymax=ub,ymin=lb))

And please, never ever use variable names with a space if possible. If you didn't, you could just have done:

test <- with(Data,
   data.frame(
     Loc = rep(Loc,2),
     est = rep(c("A","B"),each=nrow(Data)),
     value = c(estA,estB),
     lb = c(Alb,Blb),
     ub = c(Aub,Bub)
   )
)
ggplot(test,aes(x=Loc,y=value,color=est))+geom_point()+
    geom_errorbar(aes(ymax=ub,ymin=lb))


问:
python 3.6 put number is str
```<code>def binary(n):
    if n>0:
        return binary(n//2)*10 + (n%2)
    else:
        return 0
</code>```

The answer is 10000000 but it have to be "10000000". How can I put str on the answer?

答:
I will suggest that you use nested/inner functions as shown below to solve you problem. This allows you to compute the result using integers, and then convert the result to a string, or any other type, before returning it.

```<code>def binary(n):
    def inner(m):
        if m>0:
            return inner(m//2)*10 + (m%2)
        else:
            return 0
    return str(inner(n))
</code>```

Alternatively you can cast n to the correct type whenever you use it. This is, in my opinion, a horrible to solve the problem, but it should still do the trick.

```<code>def binary(n):
    if int(n) > 0:
        return str(int(binary(n//2))*10 + n%2)
    else:
        return "0"
</code>```

Title: python 3.6 put number is str

Body:
def binary(n):
    if n>0:
        return binary(n//2)*10 + (n%2)
    else:
        return 0

The answer is 10000000 but it have to be "10000000". How can I put str on the answer?

Body:
I will suggest that you use nested/inner functions as shown below to solve you problem. This allows you to compute the result using integers, and then convert the result to a string, or any other type, before returning it.

def binary(n):
    def inner(m):
        if m>0:
            return inner(m//2)*10 + (m%2)
        else:
            return 0
    return str(inner(n))

Alternatively you can cast n to the correct type whenever you use it. This is, in my opinion, a horrible to solve the problem, but it should still do the trick.

def binary(n):
    if int(n) > 0:
        return str(int(binary(n//2))*10 + n%2)
    else:
        return "0"