问:
httpServer.listen() firing before http.createServer(). Why? How?
```<code>const http = require('http');
const hostname = 'localhost';
const port = 3000;

http.createServer((req, res) => {
  console.log(`http.createServer..`);
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
}).listen(port, hostname, () => {
  console.log(`Server listening at http://${hostname}:${port}/`);
});
</code>```

"Server running at http://localhost:3000/" logged to console immediately after running the module.

"http.createServer.." logged to console on request to port 3000.

I would expect both console.logs to execute right away, in opposite order. In other words, for createServer() to run first, including the callback function and then to .listen().

What is happening here?

EDIT: Documentation says the function within .createServer() is not a callback, but a requestListener - a function which is automatically added to the 'request' event. So, how does this work?

答:
This is because the request listener function (which you pass to createServer) is executed only when a request event is emitted.

From the  docs

The requestListener is a function which is automatically added to the 'request' event.

The request event

Emitted each time there is a request. Note that there may be multiple requests per connection (in the case of HTTP Keep-Alive connections).

Body:
const http = require('http');
const hostname = 'localhost';
const port = 3000;

http.createServer((req, res) => {
  console.log(`http.createServer..`);
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
}).listen(port, hostname, () => {
  console.log(`Server listening at http://${hostname}:${port}/`);
});

"Server running at http://localhost:3000/" logged to console immediately after running the module.

"http.createServer.." logged to console on request to port 3000.

I would expect both console.logs to execute right away, in opposite order. In other words, for createServer() to run first, including the callback function and then to .listen().

What is happening here?

EDIT: Documentation says the function within .createServer() is not a callback, but a requestListener - a function which is automatically added to the 'request' event. So, how does this work?


来源: stackexchange

问:
Layout in list tile - flutter
Current output:

Expected output:

Code:

```<code>SizedBox(
      width: 380,
      height: 180,
      child: Swiper(
        itemCount: items.length,
        itemBuilder: (context, index) {
          return Column(
            children: <Widget>[
              Expanded(
                child: Card(
                  child: ListTile(
                    title: Text(
                      '${items[index].title}',
                    ),
                    subtitle: Text(
                      '${items[index].body}',
                    ),
                    trailing: Column(
                      children: <Widget>[
                        CircleAvatar(
                          backgroundColor: HexColor("#0087a8"),
                          child: IconButton(
                            icon: Icon(Icons.add),
                      ],
                    ),
                  ),
                ),
              )
            ],
          );
        },
        viewportFraction: 0.8,
        scale: 0.9,
        control: SwiperControl(color: Colors.white),
      ),
    );
</code>```

I am unable to create the icon button to be that way. As when i put in padding, it says that the pixels overflowed. I need to get the add button on the bottom right hand side.

答:
Try this code

```<code>Container(
        height: 180,
        width: double.infinity,
        child: Card(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      'EUR/USD',
                      style: TextStyle(fontSize: 40),
                    ),
                    Text('FOREX', style: TextStyle(fontSize: 20)),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    CircleAvatar(
                        backgroundColor: Colors.blueAccent,
                        child: IconButton(
                          onPressed: () {
                            print('On Pressed');
                          },
                          icon: Icon(Icons.add),
                        )),
                  ],
                )
              ],
            ),
          ),
        ),
      )
</code>```

ContentLicense: CC BY-SA 4.0

Title: Layout in list tile - flutter

Body:
Current output:

Expected output:

Code:

SizedBox(
      width: 380,
      height: 180,
      child: Swiper(
        itemCount: items.length,
        itemBuilder: (context, index) {
          return Column(
            children: <Widget>[
              Expanded(
                child: Card(
                  child: ListTile(
                    title: Text(
                      '${items[index].title}',
                    ),
                    subtitle: Text(
                      '${items[index].body}',
                    ),
                    trailing: Column(
                      children: <Widget>[
                        CircleAvatar(
                          backgroundColor: HexColor("#0087a8"),
                          child: IconButton(
                            icon: Icon(Icons.add),
                      ],
                    ),
                  ),
                ),
              )
            ],
          );
        },
        viewportFraction: 0.8,
        scale: 0.9,
        control: SwiperControl(color: Colors.white),
      ),
    );

I am unable to create the icon button to be that way. As when i put in padding, it says that the pixels overflowed. I need to get the add button on the bottom right hand side.

Body:
Try this code

Container(
        height: 180,
        width: double.infinity,
        child: Card(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      'EUR/USD',
                      style: TextStyle(fontSize: 40),
                    ),
                    Text('FOREX', style: TextStyle(fontSize: 20)),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    CircleAvatar(
                        backgroundColor: Colors.blueAccent,
                        child: IconButton(
                          onPressed: () {
                            print('On Pressed');
                          },
                          icon: Icon(Icons.add),
                        )),
                  ],
                )
              ],
            ),
          ),
        ),
      )


问:
How to filter array to match array
I have list of permissions :

```<code>const all_permissions = [
    {
        permission_id: 1,
        permission_name: "Getting User List",
        permission_method: "GET",
        permission_url: /^\/panel\/user$/
    },
    {
        permission_id: 2,
        permission_name: "Getting User Info",
        permission_method: "GET",
        permission_url: /^\/panel\/user\/[0-9]+$/
    },
    {
        permission_id: 3,
        permission_name: "Testing",
        permission_method: "GET",
        permission_url: /^\/panel\/test\/[a-z]+$/
    }
]

const my_permissions = [1,2]
</code>```

How to filter all_permissions to match only the id inside my_permissions?
Thanks

答:
Use filter and includes like so:

const all_permissions = [{permission_id:1,permission_name:"Getting User List",permission_method:"GET",permission_url:/^\/panel\/user$/},{permission_id:2,permission_name:"Getting User Info",permission_method:"GET",permission_url:/^\/panel\/user\/[0-9]+$/},{permission_id:3,permission_name:"Testing",permission_method:"GET",permission_url:/^\/panel\/test\/[a-z]+$/}];
const my_permissions = [1,2];

const res = all_permissions.filter(({ permission_id }) => my_permissions.includes(permission_id));

console.log(res);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

ES5 syntax:

var all_permissions = [{permission_id:1,permission_name:"Getting User List",permission_method:"GET",permission_url:/^\/panel\/user$/},{permission_id:2,permission_name:"Getting User Info",permission_method:"GET",permission_url:/^\/panel\/user\/[0-9]+$/},{permission_id:3,permission_name:"Testing",permission_method:"GET",permission_url:/^\/panel\/test\/[a-z]+$/}];
var my_permissions = [1,2];

var res = all_permissions.filter(function(item) {
  return my_permissions.indexOf(item.permission_id) > -1;
});

console.log(res);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

Title: How to filter array to match array

Body:
I have list of permissions :

const all_permissions = [
    {
        permission_id: 1,
        permission_name: "Getting User List",
        permission_method: "GET",
        permission_url: /^\/panel\/user$/
    },
    {
        permission_id: 2,
        permission_name: "Getting User Info",
        permission_method: "GET",
        permission_url: /^\/panel\/user\/[0-9]+$/
    },
    {
        permission_id: 3,
        permission_name: "Testing",
        permission_method: "GET",
        permission_url: /^\/panel\/test\/[a-z]+$/
    }
]

const my_permissions = [1,2]

How to filter all_permissions to match only the id inside my_permissions?
Thanks

Body:
Use filter and includes like so:

const all_permissions = [{permission_id:1,permission_name:"Getting User List",permission_method:"GET",permission_url:/^\/panel\/user$/},{permission_id:2,permission_name:"Getting User Info",permission_method:"GET",permission_url:/^\/panel\/user\/[0-9]+$/},{permission_id:3,permission_name:"Testing",permission_method:"GET",permission_url:/^\/panel\/test\/[a-z]+$/}];
const my_permissions = [1,2];

const res = all_permissions.filter(({ permission_id }) => my_permissions.includes(permission_id));

console.log(res);

.as-console-wrapper { max-height: 100% !important; top: auto; }

ES5 syntax:

var all_permissions = [{permission_id:1,permission_name:"Getting User List",permission_method:"GET",permission_url:/^\/panel\/user$/},{permission_id:2,permission_name:"Getting User Info",permission_method:"GET",permission_url:/^\/panel\/user\/[0-9]+$/},{permission_id:3,permission_name:"Testing",permission_method:"GET",permission_url:/^\/panel\/test\/[a-z]+$/}];
var my_permissions = [1,2];

var res = all_permissions.filter(function(item) {
  return my_permissions.indexOf(item.permission_id) > -1;
});

console.log(res);

.as-console-wrapper { max-height: 100% !important; top: auto; }


问:
yield return IEnumerator or IEnumerable
I'm new to C#, just a question on yield keyword which confuses me a lot.
It seems that yield  can return an IEnumerator  and IEnumerable

```<code>//case 1
static IEnumerator YieldReturn()
{
   yield return 1;
   yield return 2;
   yield return 3;
}
</code>```

and

```<code>//case 2
static IEnumerable YieldReturn()
{
   yield return 1;
   yield return 2;
   yield return 3;
}
</code>```

how come one thing can return two different return types?

答:
A method using yield is rebuilt by the compiler. It creates a state machine with a whole new compiler-generated class.

This state-machine-class is an IEnumerator as well as an IEnumerable whose GetEnumerator method returns itself.

So depending on how you declare your method, the compiler emits code that either returns the IEnumerable or an already initialized IEnumerator.

As always, Jon Skeet has a good article about what happens under the hood with the yield keyword.

Title: yield return IEnumerator or IEnumerable

Body:
I'm new to C#, just a question on yield keyword which confuses me a lot.
It seems that yield  can return an IEnumerator  and IEnumerable

//case 1
static IEnumerator YieldReturn()
{
   yield return 1;
   yield return 2;
   yield return 3;
}

and

//case 2
static IEnumerable YieldReturn()
{
   yield return 1;
   yield return 2;
   yield return 3;
}

how come one thing can return two different return types?


答:
You can use filter and includes

Loop through all_permission array using filter

inside filter check for permission_id in my_permission array if it's there return true else return false

const all_permissions = [{permission_id: 1,permission_name: "Getting User List",permission_method: "GET",permission_url: /^\/panel\/user$/},{permission_id: 2,permission_name: "Getting User Info",permission_method: "GET",permission_url: /^\/panel\/user\/[0-9]+$/},{permission_id: 3,permission_name: "Testing",permission_method: "GET",permission_url: /^\/panel\/test\/[a-z]+$/}]
const my_permissions = [1,2]

let op = all_permissions.filter(({permission_id})=> my_permissions.includes(permission_id))

console.log(op)```

Title: How to filter array to match array


问:
Can we run a current Jenkins with older slaves?
We've been using Jenkins to run our builds and (some) of our deploys, for some time. We're planning the move from SVN to Git for our VC.

The current Git plugin for Jenkins requires Jenkins 1.625. We're running 1.612.

1.625 requires Java 7. I've noticed that more current releases require Java 8, and support Java 11.

Our problem is that we have some projects that still build (God help us) on Windows XP, so we have a Jenkins slave running on an XP build machine.

And, of course, Windows XP doesn't support Java 8.

So, can a current version of Jenkins control an older version of the Jenkins slave? Could we install Jenkins 2.164+ on the master, leave the slave on the XP machine running the Jenkins 1.612 slave, and have them successfully talk to each other?

答:
Apparently, you cannot run a master against an older slave.

We haven't entirely decided what to do, but it looks like we're probably going to configure a new build machine with a current Jenkins install, and leave the old machines alone until we finally get rid of the old XP projects


Title: Select rows based on index

Body:
I tried to use

data = data.loc['bids:']

to get all rows corresponding to the index.

SAMPLE DATA FROM TEXT FILE:

 {"offset":"14726172634","bids":[["871094.22000","0.00200000","0.00200000","0","1081537351","29194","5","14726172633","1"],["871076.11000","0.00808000","0.00808000","0","1081537130","623964","5","14726172043","1"],["871073.96500","0.00100000","0.00100000","0","1081537185","29194","5","14726172231","1"]]],
"asks":[["875644.72000","0.00200000","0.00200000","0","1081606189","29194","5","14726356256","1"],["875669.77637","0.01000000","0.01000000","0","1081606227","29194","5","14726356379","1"],["875678.92000","0.00600000","0.00600000","0","1081606263","29194","5","14726356488","1"],["875731.74364","0.03000000","0.03000000","0","1081606233","29194","5","14726356393","1"],

CODE SAMPLE:

 data = pd.read_csv('20190523-012523_product_5_snapshot_14726172634_14728561053.txt', lineterminator= str(']'), low_memory= False, error_bad_lines=False, header= None)#, names= ['a','d','f','r','y','h','n','m','k'])

 new = data[1].str.split("[", n = 1, expand = True)
 data[1]= new[0]
 data[10]= new[1]
 data.drop(data.index[-1], inplace=True)
 data[10]= new[1].str.strip('[').str.strip('"')

 data = data.set_index([1,2])
 data = data.loc[:,[10]]
 data = data.loc['bids:']

DATA SAMPLE:

bids:  0.002000   871094.22000
       0.008080   871076.11000
       0.001000   871073.96500
bids:  0.005000   871042.87000
       0.005000   871038.55000
       0.001000   871032.90156

CODE OUTPUT:

bids:  0.002000   871094.22000
bids:  0.005000   871042.87000

How to get the 6 rows please? The purpose is to filter among other index labels.

The index output is :

Index(['bids:', '', '', '', '', '', '', '', '', '',
       ...
       'asks:', '', '', '', '', '', '', '', '', '',
       ...
       'bids:', '', '', '', '', '', '', '', '', '',
       ...'],
      dtype='object', name=1, length=505148)

Body:
I believe you need:

print (data)
                           10
1    2
bids 0.00200000  871094.22000
     0.00808000  871076.11000
     0.00100000  871073.96500
asks 0.00200000  875644.72000
     0.01000000  875669.77637
     0.00600000  875678.92000
     0.03000000  875731.74364
bids 0.00200000  871094.22000
     0.00808000  871076.11000
     0.00100000  871073.96500

print (data.index)
MultiIndex(levels=[['asks', 'bids'],
                   ['0.00100000', '0.00200000', '0.00600000',
                    '0.00808000', '0.01000000', '0.03000000']],
           codes=[[1, 1, 1, 0, 0, 0, 0, 1, 1, 1], [1, 3, 0, 1, 4, 2, 5, 1, 3, 0]],
           names=[1, 2])

Solution for first values by first level of MultiIndex, with duplicated values:

s = data.index.get_level_values(0).to_series()
mask = s.ne(s.shift())
print (mask)
1
bids     True
bids    False
bids    False
asks     True
asks    False
asks    False
asks    False
bids     True
bids    False
bids    False
Name: 1, dtype: bool

df = data[mask.values]
print (df)
                           10
1    2
bids 0.00200000  871094.22000
asks 0.00200000  875644.72000
bids 0.00200000  871094.22000

df = df.xs('bids', drop_level=False)
print (df)
                           10
1    2
bids 0.00200000  871094.22000
     0.00200000  871094.22000

If there is no MultiIndex:

print (data)
              2             10
1
bids  0.00200000  871094.22000
bids  0.00808000  871076.11000
bids  0.00100000  871073.96500
asks  0.00200000  875644.72000
asks  0.01000000  875669.77637
asks  0.00600000  875678.92000
asks  0.03000000  875731.74364
bids  0.00200000  871094.22000
bids  0.00808000  871076.11000
bids  0.00100000  871073.96500

print (data.index)
Index(['bids', 'bids', 'bids', 'asks', 'asks', 'asks', 'asks', 'bids', 'bids',
       'bids'],
      dtype='object', name=1)

s = data.index.to_series()
mask = s.ne(s.shift())
print (mask)
1
bids     True
bids    False
bids    False
asks     True
asks    False
asks    False
asks    False
bids     True
bids    False
bids    False
Name: 1, dtype: bool

df = data[mask.values].loc['bids']
print (df)
              2             10
1
bids  0.00200000  871094.22000
bids  0.00200000  871094.22000


答:
You can try with Array.prototype.filter() and Array.prototype.includes()

const all_permissions = [
    {
        permission_id: 1,
        permission_name: "Getting User List",
        permission_method: "GET",
        permission_url: /^\/panel\/user$/
    },
    {
        permission_id: 2,
        permission_name: "Getting User Info",
        permission_method: "GET",
        permission_url: /^\/panel\/user\/[0-9]+$/
    },
    {
        permission_id: 3,
        permission_name: "Testing",
        permission_method: "GET",
        permission_url: /^\/panel\/test\/[a-z]+$/
    }
]

const my_permissions = [1,2];
const match = all_permissions.filter(p => my_permissions.includes(p.permission_id));
console.log(match);```

Title: How to filter array to match array


问:
Ripple Animation on a Bitmap instead of View
I have been using bitmap to render small colored circles inside a View. Now I want to show custom Ripples Animation around those circles when tapped.

After searching for sometime through StackOverflow's answers, it is being mostly suggested to wrap those bitmaps inside a VIEW and apply Animations to those views using Android's animation framework.

But problem is, I am already drawing those bitmaps inside a view using the canvas of that view via

canvas.drawBitmap()

function. I just want to show ripples centered around those bitmaps when clicked. My Question is, Is there anyway that I can provide ripple or any animation to a bitmap without wrapping them as a View?

```<code>protected void fill(ILineDataSet set, boolean drawCircleHole,
        boolean drawTransparentCircleHole, int selectedEntryIndex) {

        int colorCount = set.getCircleColorCount();
        int holeColorCount = set.getCircleHoleColorCount();
        circleRadius = set.getCircleRadius();
        circleHoleRadius = set.getCircleHoleRadius();

        for (int i = 0; i < (colorCount > holeColorCount ? colorCount: holeColorCount); i++) {

            Bitmap.Config conf = Bitmap.Config.ARGB_4444;
            Bitmap circleBitmap = Bitmap.createBitmap((int) (circleRadius * 2.1),
                (int) (circleRadius * 2.1), conf);

            Canvas canvas = new Canvas(circleBitmap);
            circleBitmaps[i] = circleBitmap;

            //fill colors in the values' circles
            mRenderPaint.setColor(set.getCircleColor(i < colorCount ? i : 0));
            mCirclePaintInner.setColor(set.getCircleHoleColor(i < holeColorCount ? i : 0));

            if (drawTransparentCircleHole) {
                // Begin path for circle with hole
                mCirclePathBuffer.reset();

                mCirclePathBuffer.addCircle(
                        circleRadius,
                        circleRadius,
                        circleRadius,
                        Path.Direction.CW);

                // Cut hole in path
                mCirclePathBuffer.addCircle(
                        circleRadius,
                        circleRadius,
                        circleHoleRadius,
                        Path.Direction.CCW);

                // Fill in-between
                canvas.drawPath(mCirclePathBuffer, mRenderPaint);
            } else {

                canvas.drawCircle(
                        circleRadius,
                        circleRadius,
                        circleRadius,
                        mRenderPaint);

                if (drawCircleHole) {
                    canvas.drawCircle(
                            circleRadius,
                            circleRadius,
                            circleHoleRadius,
                            mCirclePaintInner);
                }
            }

            if (i == selectedEntryIndex) {
                circleBitmaps[i] = getScaledUpBitmap(circleBitmaps[i]);
            }
        }
    }

    private Bitmap getScaledUpBitmap(Bitmap bm) {
        //scale bitmap as twice its size
        int width = bm.getWidth();
        int height = bm.getHeight();

        Matrix matrix = new Matrix();
        matrix.postScale(1.5f, 1.5f);

        Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
        bm.recycle();
        return resizedBitmap;
    }
</code>```

答:
An Android Ripple animation is a combination of a growing animation + a fade animation.
In other words, this is a drawing process and that's why it's not recommended to do it directly on a bitmap.

I have written a class which is a layout that you can use as a touch panel.
This layout, called RippleLayout, is extended from RelativeLayout. You can use this layout to draw your circles and manage onTouchListener event to show a ripple animation on a given point.

RippleLayout.java

```<code>import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.List;

public class RippleLayout extends RelativeLayout {

    private AnimatorSet mAnimatorSet;
    private Paint mPaint;
    private boolean mStarted;
    private float mX, mY;
    private int mCount = 1;
    private int mDuration = 300;
    private float mRadius = 300;
    private IntRippleView rippleView;

    public RippleLayout(Context context) {
        this(context, null, 0);
    }

    public RippleLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RippleLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void build() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(Color.GRAY);
        List<Animator> animators = new ArrayList<>();
        rippleView = new IntRippleView(getContext());
        rippleView.setCircleRadius(0);
        rippleView.setCircleAlpha(1);
        addView(rippleView);

        ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(rippleView, "CircleRadius", 0f, 1f);
        scaleXAnimator.setRepeatCount(0);
        animators.add(scaleXAnimator);

        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(rippleView, "CircleAlpha", 1f, 0f);
        alphaAnimator.setRepeatCount(0);
        animators.add(alphaAnimator);

        mAnimatorSet = new AnimatorSet();
        mAnimatorSet.setInterpolator(new LinearInterpolator());
        mAnimatorSet.playTogether(animators);
        mAnimatorSet.setDuration(mDuration);
        mAnimatorSet.addListener(mAnimatorListener);
    }

    public void doRipple(float x, float y) {
        doRipple(x, y, mRadius, mPaint.getColor());
    }

    public synchronized void doRipple(float x, float y, float radius, int acolor) {
        if (mStarted)
            mAnimatorSet.end();
        mX = x;
        mY = y;
        mRadius = radius;
        rippleView.bringToFront();
        mPaint.setColor(acolor);
        mAnimatorSet.start();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        build();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mAnimatorSet != null) {
            mAnimatorSet.cancel();
            mAnimatorSet = null;
        }
        mPaint = null;
    }

    private final Animator.AnimatorListener mAnimatorListener = new Animator.AnimatorListener() {

        @Override
        public void onAnimationStart(Animator animator) {
            mStarted = true;
        }

        @Override
        public void onAnimationEnd(Animator animator) {
            mStarted = false;
        }

        @Override
        public void onAnimationCancel(Animator animator) {
            mStarted = false;
        }

        @Override
        public void onAnimationRepeat(Animator animator) {
        }

    };

    private class IntRippleView extends View {

        public IntRippleView(Context context) {
            super(context);
        }

        private float CircleRadius = 0;

        public void setCircleRadius(float value) {
            CircleRadius = value;
            invalidate();
        }

        public float getCircleRadius() {
            return CircleRadius;
        }

        private float CircleAlpha = 1;

        public void setCircleAlpha(float value) {
            CircleAlpha = value;
            invalidate();
        }

        public float getCircleAlpha() {
            return CircleAlpha;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            int aColor = Color.RED;
            mPaint.setAlpha((int)(255 * CircleAlpha));
            canvas.drawCircle(mX, mY, mRadius * CircleRadius, mPaint);
        }

    }

}
</code>```

How to use

In an XML layout

```<code><android.support.constraint.ConstraintLayout
    android:id="@+id/mainlayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="0dp"
    >

    <com.mcblau.pacerblue.components.RippleLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
    >

    </com.mcblau.pacerblue.components.RippleLayout>

</android.support.constraint.ConstraintLayout>
</code>```

In your Activity

```<code>    container = findViewById(R.id.container);
    container.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // detect here which circle was touch
            // get the center of the circle => mCenterX, mCenterY
            container.doRipple(mCenterX, mCenterY); // ripple animation
            return true;
        }
    });
</code>```

You can draw your circles directly on RippleLayout or in another one. If you put the RippleLayout exactly over your bitmap layout, you can use it as a touch panel. In this case, use the setOnTouchListener of your circle's layout.

Use doRipple(x, y); or  doRipple(x, y, radius, acolor); to set circle radius an ripple color.

Body:
I have been using bitmap to render small colored circles inside a View. Now I want to show custom Ripples Animation around those circles when tapped.

After searching for sometime through StackOverflow's answers, it is being mostly suggested to wrap those bitmaps inside a VIEW and apply Animations to those views using Android's animation framework.

But problem is, I am already drawing those bitmaps inside a view using the canvas of that view via

canvas.drawBitmap()

function. I just want to show ripples centered around those bitmaps when clicked. My Question is, Is there anyway that I can provide ripple or any animation to a bitmap without wrapping them as a View?

protected void fill(ILineDataSet set, boolean drawCircleHole,
        boolean drawTransparentCircleHole, int selectedEntryIndex) {

        int colorCount = set.getCircleColorCount();
        int holeColorCount = set.getCircleHoleColorCount();
        circleRadius = set.getCircleRadius();
        circleHoleRadius = set.getCircleHoleRadius();

        for (int i = 0; i < (colorCount > holeColorCount ? colorCount: holeColorCount); i++) {

            Bitmap.Config conf = Bitmap.Config.ARGB_4444;
            Bitmap circleBitmap = Bitmap.createBitmap((int) (circleRadius * 2.1),
                (int) (circleRadius * 2.1), conf);

            Canvas canvas = new Canvas(circleBitmap);
            circleBitmaps[i] = circleBitmap;

            //fill colors in the values' circles
            mRenderPaint.setColor(set.getCircleColor(i < colorCount ? i : 0));
            mCirclePaintInner.setColor(set.getCircleHoleColor(i < holeColorCount ? i : 0));

            if (drawTransparentCircleHole) {
                // Begin path for circle with hole
                mCirclePathBuffer.reset();

                mCirclePathBuffer.addCircle(
                        circleRadius,
                        circleRadius,
                        circleRadius,
                        Path.Direction.CW);

                // Cut hole in path
                mCirclePathBuffer.addCircle(
                        circleRadius,
                        circleRadius,
                        circleHoleRadius,
                        Path.Direction.CCW);

                // Fill in-between
                canvas.drawPath(mCirclePathBuffer, mRenderPaint);
            } else {

                canvas.drawCircle(
                        circleRadius,
                        circleRadius,
                        circleRadius,
                        mRenderPaint);

                if (drawCircleHole) {
                    canvas.drawCircle(
                            circleRadius,
                            circleRadius,
                            circleHoleRadius,
                            mCirclePaintInner);
                }
            }

            if (i == selectedEntryIndex) {
                circleBitmaps[i] = getScaledUpBitmap(circleBitmaps[i]);
            }
        }
    }

    private Bitmap getScaledUpBitmap(Bitmap bm) {
        //scale bitmap as twice its size
        int width = bm.getWidth();
        int height = bm.getHeight();

        Matrix matrix = new Matrix();
        matrix.postScale(1.5f, 1.5f);

        Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
        bm.recycle();
        return resizedBitmap;
    }

Body:
An Android Ripple animation is a combination of a growing animation + a fade animation.
In other words, this is a drawing process and that's why it's not recommended to do it directly on a bitmap.

I have written a class which is a layout that you can use as a touch panel.
This layout, called RippleLayout, is extended from RelativeLayout. You can use this layout to draw your circles and manage onTouchListener event to show a ripple animation on a given point.

RippleLayout.java

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.List;

public class RippleLayout extends RelativeLayout {

    private AnimatorSet mAnimatorSet;
    private Paint mPaint;
    private boolean mStarted;
    private float mX, mY;
    private int mCount = 1;
    private int mDuration = 300;
    private float mRadius = 300;
    private IntRippleView rippleView;

    public RippleLayout(Context context) {
        this(context, null, 0);
    }

    public RippleLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RippleLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void build() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(Color.GRAY);
        List<Animator> animators = new ArrayList<>();
        rippleView = new IntRippleView(getContext());
        rippleView.setCircleRadius(0);
        rippleView.setCircleAlpha(1);
        addView(rippleView);

        ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(rippleView, "CircleRadius", 0f, 1f);
        scaleXAnimator.setRepeatCount(0);
        animators.add(scaleXAnimator);

        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(rippleView, "CircleAlpha", 1f, 0f);
        alphaAnimator.setRepeatCount(0);
        animators.add(alphaAnimator);

        mAnimatorSet = new AnimatorSet();
        mAnimatorSet.setInterpolator(new LinearInterpolator());
        mAnimatorSet.playTogether(animators);
        mAnimatorSet.setDuration(mDuration);
        mAnimatorSet.addListener(mAnimatorListener);
    }

    public void doRipple(float x, float y) {
        doRipple(x, y, mRadius, mPaint.getColor());
    }

    public synchronized void doRipple(float x, float y, float radius, int acolor) {
        if (mStarted)
            mAnimatorSet.end();
        mX = x;
        mY = y;
        mRadius = radius;
        rippleView.bringToFront();
        mPaint.setColor(acolor);
        mAnimatorSet.start();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        build();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mAnimatorSet != null) {
            mAnimatorSet.cancel();
            mAnimatorSet = null;
        }
        mPaint = null;
    }

    private final Animator.AnimatorListener mAnimatorListener = new Animator.AnimatorListener() {

        @Override
        public void onAnimationStart(Animator animator) {
            mStarted = true;
        }

        @Override
        public void onAnimationEnd(Animator animator) {
            mStarted = false;
        }

        @Override
        public void onAnimationCancel(Animator animator) {
            mStarted = false;
        }

        @Override
        public void onAnimationRepeat(Animator animator) {
        }

    };

    private class IntRippleView extends View {

        public IntRippleView(Context context) {
            super(context);
        }

        private float CircleRadius = 0;

        public void setCircleRadius(float value) {
            CircleRadius = value;
            invalidate();
        }

        public float getCircleRadius() {
            return CircleRadius;
        }

        private float CircleAlpha = 1;

        public void setCircleAlpha(float value) {
            CircleAlpha = value;
            invalidate();
        }

        public float getCircleAlpha() {
            return CircleAlpha;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            int aColor = Color.RED;
            mPaint.setAlpha((int)(255 * CircleAlpha));
            canvas.drawCircle(mX, mY, mRadius * CircleRadius, mPaint);
        }

    }

}

How to use

In an XML layout

<android.support.constraint.ConstraintLayout
    android:id="@+id/mainlayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="0dp"
    >

    <com.mcblau.pacerblue.components.RippleLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
    >

    </com.mcblau.pacerblue.components.RippleLayout>

</android.support.constraint.ConstraintLayout>

In your Activity

    container = findViewById(R.id.container);
    container.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // detect here which circle was touch
            // get the center of the circle => mCenterX, mCenterY
            container.doRipple(mCenterX, mCenterY); // ripple animation
            return true;
        }
    });

You can draw your circles directly on RippleLayout or in another one. If you put the RippleLayout exactly over your bitmap layout, you can use it as a touch panel. In this case, use the setOnTouchListener of your circle's layout.

Use doRipple(x, y); or  doRipple(x, y, radius, acolor); to set circle radius an ripple color.


问:
deepCss is failing to identify an element inside the shadow root in Protractor
Can not identify button which inside the ShadowRoot in protractor.

I have tried using deepCss as follows,

this.startNowButton = element(by.deepCss('button[class="apply-now"]'));

But I am getting

NoSuchElementError: No element found using locator: By(css selector, * /deep/ button[class="apply-now"])

Is this the correct way to identify the elements inside the ShadowRoot for Protractor? Thanks

my HTML page is similar to as follows,

```<code><div id="modal">
<div class="push-wrap">
   <header id ="site-header">
      <hmy-cms-header class="hydrated">
         #shadow-root (open)
           <header>
               <div class=notification-banner> ... </div>
               <div class="ca">
                  <button class="apply-now">"Apply"<span>now</span>
</code>```

答:
Try the below locator options

```<code>1. const ele = element(by.css(div.ca>button.apply-now));
2. const ele = element(by.buttonText('Apply'));
</code>```

If normal click does not works for you, Try the below executor to perform click on the button

await browser.executeScript("arguments[0].click()", ele);

Body:
Can not identify button which inside the ShadowRoot in protractor.

I have tried using deepCss as follows,

this.startNowButton = element(by.deepCss('button[class="apply-now"]'));

But I am getting

NoSuchElementError: No element found using locator: By(css selector, * /deep/ button[class="apply-now"])

Is this the correct way to identify the elements inside the ShadowRoot for Protractor? Thanks

my HTML page is similar to as follows,

      <hmy-cms-header class="hydrated">
         #shadow-root (open)

 ...

                  <button class="apply-now">"Apply"now

Body:
Try the below locator options

1. const ele = element(by.css(div.ca>button.apply-now));
2. const ele = element(by.buttonText('Apply'));

If normal click does not works for you, Try the below executor to perform click on the button

await browser.executeScript("arguments[0].click()", ele);


问:
Extracting nested value from an RDD Tuple
EDITED.

I appear a little rusty it appears.

The following snippet:

```<code>import org.apache.spark.sql.functions.input_file_name

val inputPath: String = "/FileStore/tables/g1.txt" //does work
val rdd = spark.read.text(inputPath)
   .select(input_file_name, $"value")
   .as[(String, String)]
   .rdd
val rdd2 = rdd.map(line => (line._1, line._2.split(",")))
</code>```

returns:

```<code>rdd2: org.apache.spark.rdd.RDD[(String, Array[String])] = MapPartitionsRDD[52] at map at command-2326393392121655:9
res13: Array[(String, Array[String])] = Array((dbfs:/FileStore/tables/g1.txt,Array(0, 5, 10)), (dbfs:/FileStore/tables/g1.txt,Array(202008, 5, 10)), (dbfs:/FileStore/tables/g1.txt,Array(202009, 10, 20)))
</code>```

I want to get the 2nd element of the Array remaining in RDD domain. Somehow, cannot do it.

Selecting as per below having converted to a DF, I can get the Int value out no worries. But I am interested in the RDD approach. E.g.:

```<code>df.select($"value".getField("_2")).show(false)
</code>```

returns correctly:

```<code>5,5,10
</code>```

However, I cannot achieve the same with an RDD. Things like:

```<code>val rddx = rddx-1.map(x => (x._2._2))
</code>```

DF works easier, curious as to what the easiest way with an RDD would be.

答:
From your ask to extract only the second element of the array fixing your code below:</p>
```<code>import org.apache.spark.sql.functions.input_file_name

val inputPath: String = "/FileStore/tables/g1.txt" //does work
val rdd = spark.read.text(inputPath)
    .select(input_file_name, $"value")
    .as[(String, String)]
    .rdd
val rdd2 = rdd.map(line => (line._1, line._2.split(",").lift(1).getOrElse("0").toInt))
</code>```

Body:
EDITED.

I appear a little rusty it appears.

The following snippet:

import org.apache.spark.sql.functions.input_file_name

val inputPath: String = "/FileStore/tables/g1.txt" //does work
val rdd = spark.read.text(inputPath)
   .select(input_file_name, $"value")
   .as[(String, String)]
   .rdd
val rdd2 = rdd.map(line => (line._1, line._2.split(",")))

returns:

rdd2: org.apache.spark.rdd.RDD[(String, Array[String])] = MapPartitionsRDD[52] at map at command-2326393392121655:9
res13: Array[(String, Array[String])] = Array((dbfs:/FileStore/tables/g1.txt,Array(0, 5, 10)), (dbfs:/FileStore/tables/g1.txt,Array(202008, 5, 10)), (dbfs:/FileStore/tables/g1.txt,Array(202009, 10, 20)))

I want to get the 2nd element of the Array remaining in RDD domain. Somehow, cannot do it.

Selecting as per below having converted to a DF, I can get the Int value out no worries. But I am interested in the RDD approach. E.g.:

df.select($"value".getField("_2")).show(false)

returns correctly:

5,5,10

However, I cannot achieve the same with an RDD. Things like:

val rddx = rddx-1.map(x => (x._2._2))

DF works easier, curious as to what the easiest way with an RDD would be.

Body:
From your ask to extract only the second element of the array fixing your code below:

import org.apache.spark.sql.functions.input_file_name

val inputPath: String = "/FileStore/tables/g1.txt" //does work
val rdd = spark.read.text(inputPath)
    .select(input_file_name, $"value")
    .as[(String, String)]
    .rdd
val rdd2 = rdd.map(line => (line._1, line._2.split(",").lift(1).getOrElse("0").toInt))


问:
React Native - Fetch POST request is sending as GET request
I'm having issues when using FETCH.

I am trying to make a POST request using FETCH in react-native.

```<code>    fetch("http://www.example.co.uk/login", {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username: 'test',
            password: 'test123',
        })
    })

        .then((response) => response.json())
        .then((responseData) => {
            console.log(
                "POST Response",
                "Response Body -> " + JSON.stringify(responseData)
            )
        })
        .done();
}
</code>```

When I inspect this call using Charles it is recorded as a GET request and the username and password that should be in the body are not there.

Can anyone help with this issue?

答:
In my case, the redirect was caused by wrongly formed url for the POST request:
http://localhost:90/Worx/drupal/d8/www//jsonapi
double slash before jsonapi

Because of the wrong url, the browser was redirecting the request and changing the method from POST to GET.

I was able to debug it after reading this:
https://serverfault.com/questions/434205/nginx-https-rewrite-turns-post-to-get

ContentLicense: CC BY-SA 3.0

Body:
I'm having issues when using FETCH.

I am trying to make a POST request using FETCH in react-native.

    fetch("http://www.example.co.uk/login", {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username: 'test',
            password: 'test123',
        })
    })

        .then((response) => response.json())
        .then((responseData) => {
            console.log(
                "POST Response",
                "Response Body -> " + JSON.stringify(responseData)
            )
        })
        .done();
}

When I inspect this call using Charles it is recorded as a GET request and the username and password that should be in the body are not there.

Can anyone help with this issue?


问:
Can`t use custom restClient for replacing id to _id. Parsing error: Unexpected token
I`m trying to change restClient to support mongoDB(replace id to _id).

This is documantation https://marmelab.com/admin-on-rest/FAQ.html#can-i-have-custom-identifiers-primary-keys-for-my-resources. I tried different variants, but with this one it shows "Unexpected token"

This is the screenshot of error

```<code>const convertHTTPResponseToREST = (response, type, resource, params) => {
        const { headers, json } = response;
        switch (type) {
            case GET_LIST:
                return {
                    data: json.map(resource => { ...resource, id: resource._id } ), // here an error with "...resource"
                    total: parseInt(headers.get('content-range').split('/').pop(), 10),
                };
            case UPDATE:
            case DELETE:
            case GET_ONE:
                return { ...json, id: json._id };
            case CREATE:
                return { ...params.data, id: json._id };
            default:
                return json;
        }
    };

 <Admin
         title="Dashboard"
         restClient={convertHTTPResponseToREST('/api')}>
 </Admin>
</code>```

When I use jsonServerRestClient() it works. Maybe there is other way to change id to _id?

答:
Edited answer:

You need to replace:

```<code>data: json.map(resource => { ...resource, id: resource._id }),
</code>```

by

```<code>data: json.map(resource => ({ ...resource, id: resource._id })),
</code>```

Note the additional parenthesis around the returned object

Body:
I`m trying to change restClient to support mongoDB(replace id to _id).

This is documantation https://marmelab.com/admin-on-rest/FAQ.html#can-i-have-custom-identifiers-primary-keys-for-my-resources. I tried different variants, but with this one it shows "Unexpected token"

This is the screenshot of error

const convertHTTPResponseToREST = (response, type, resource, params) => {
        const { headers, json } = response;
        switch (type) {
            case GET_LIST:
                return {
                    data: json.map(resource => { ...resource, id: resource._id } ), // here an error with "...resource"
                    total: parseInt(headers.get('content-range').split('/').pop(), 10),
                };
            case UPDATE:
            case DELETE:
            case GET_ONE:
                return { ...json, id: json._id };
            case CREATE:
                return { ...params.data, id: json._id };
            default:
                return json;
        }
    };

 <Admin
         title="Dashboard"
         restClient={convertHTTPResponseToREST('/api')}>
 </Admin>

When I use jsonServerRestClient() it works. Maybe there is other way to change id to _id?

Body:
Edited answer:

You need to replace:

data: json.map(resource => { ...resource, id: resource._id }),

by

data: json.map(resource => ({ ...resource, id: resource._id })),

Note the additional parenthesis around the returned object


问:
Importing S3FileUpload from react-s3 causes Unexpected Identifier error
I am new to Javascript programming and have been learning React. The situtation is I am trying to upload an image to AWS S3 bucket. As the title says, when I try to import S3FileUpload from 'react-s3' SyntaxError: Unexpected identifier occurs

I have tried googling the problem but the only result I found with the same error was in another language which is unanswered: http://qaru.site/questions/17278232/syntaxerror-unexpected-token-import-while-transpiling-reactjs-app-using-babel

```<code>import S3FileUpload from 'react-s3';
</code>```

This is the log from terminal that appears:

```<code>(function (exports, require, module, __filename, __dirname) { import Signature from "./Signature";
                                                                     ^^^^^^^^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:83:7)
    at createScript (vm.js:267:10)
    at Object.runInThisContext (vm.js:319:10)
    at Module._compile (internal/modules/cjs/loader.js:684:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Module.require (internal/modules/cjs/loader.js:657:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (C:\Users\Me\Documents\GitHub\myrepo\node_modules\react-s3\index.js:1:80)
    at Module._compile (internal/modules/cjs/loader.js:721:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
</code>```

Any tips would be greatly appreciated!

答: My mistake, I just went to the Github repo of the module and it appears that the name of the module has been changed to aws-S3 6 days ago. Working now!</p>

Body:
I am new to Javascript programming and have been learning React. The situtation is I am trying to upload an image to AWS S3 bucket. As the title says, when I try to import S3FileUpload from 'react-s3' SyntaxError: Unexpected identifier occurs

I have tried googling the problem but the only result I found with the same error was in another language which is unanswered: http://qaru.site/questions/17278232/syntaxerror-unexpected-token-import-while-transpiling-reactjs-app-using-babel

import S3FileUpload from 'react-s3';

This is the log from terminal that appears:

(function (exports, require, module, __filename, __dirname) { import Signature from "./Signature";
                                                                     ^^^^^^^^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:83:7)
    at createScript (vm.js:267:10)
    at Object.runInThisContext (vm.js:319:10)
    at Module._compile (internal/modules/cjs/loader.js:684:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Module.require (internal/modules/cjs/loader.js:657:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (C:\Users\Me\Documents\GitHub\myrepo\node_modules\react-s3\index.js:1:80)
    at Module._compile (internal/modules/cjs/loader.js:721:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)

Any tips would be greatly appreciated!


问:
php variable scope
i'm confused about the php variable scope.
such as:

```<code>while(true){
    $var = "yes , it is a test!";
  }
  printf($var)
</code>```

the $var is defined in while statement scope , how could we get it outside it's scope ? and i can't find explanation on the document .

i wonder how php deal with it's scope .

答: In PHP, a while loop doesn't create a new scope. So it will be available in the function</p>

Title: php variable scope

Body:
i'm confused about the php variable scope.
such as:

while(true){
    $var = "yes , it is a test!";
  }
  printf($var)

the $var is defined in while statement scope , how could we get it outside it's scope ? and i can't find explanation on the document .

i wonder how php deal with it's scope .


问:
What is the effect of increasing partition key count on read performance for azure cosmos db
I'm working with cosmos db and I am trying to wisely choose a partition key. I'm wondering what the effect of having a high partition key count will have on read time and indexing. I'm talking 10 keys vs 10000 keys.</p>

答:
The number of Partition Keys usually does not matter. All you need to make sure is to select the right Partition key, so that the Read & Write queries are evenly distributed across the partitions.

See here for more details about selecting the right key for partitioning.


问:
how to get details of all the running apps in a pcf space after login to pcf via cli mode
```<code>cf login -a api_end_point -u -p -o org -s space
</code>```

Once logged in i need to get the running apps info under a particular space. I tried below but no luck

```<code>cf services
</code>```

Please suggest

答:
try with

cf apps

instead of services... cf apps will show you all the applications name, requested state   instances   memory   disk   urls details

Body:
cf login -a api_end_point -u -p -o org -s space

Once logged in i need to get the running apps info under a particular space. I tried below but no luck

cf services

Please suggest


问:
How to avoid PyCharm console crash "WARNING: QApplication was not created in the main() thread" when plotting with matplotlib?
In PyCharm, when I try to plot something using its interactive console, such as:

```<code>In[2]: from matplotlib.pyplot import *
In[3]: x = range(5)
In[4]: y = range(5,10)
In[5]: plot(x,y)
WARNING: QApplication was not created in the main() thread.
Out[5]: [<matplotlib.lines.Line2D at 0x7fade916a438>]
In[6]: show()
</code>```

It opens a window and crashes. I have to stop the console and start a new one.

It works fine when I run anything like that in an ipython console in my terminal, the error happens only in Pycharm, it seems.

On the other hand, if import matplotlib with import matplotlib.pyplot as plt it works fine:

```<code>In[2]: import matplotlib.pyplot as plt
In[3]: x = range(5)
In[4]: y = range(5,10)
In[5]: plt.plot(x,y)
Out[5]: [<matplotlib.lines.Line2D at 0x7fd3453b72e8>]
In[6]: plt.show()
</code>```

But if I do both, it crashes too (even calling the plot function using plt.plot):

```<code>In[2]: from matplotlib.pyplot import *
In[3]: import matplotlib.pyplot as plt
In[4]: x = range(5)
In[5]: y = range(5,10)
In[6]: plt.plot(x,y)
WARNING: QApplication was not created in the main() thread.
Out[6]: [<matplotlib.lines.Line2D at 0x7fade916a438>]
In[7]: plt.show()
</code>```

Furthermore, when I run it all in one command, it works the first time. But if I try to plot another time, it crashes:

```<code>In[2]: from matplotlib.pyplot import *
  ...: x = range(5)
  ...: y = range(5,10)
  ...: plot(x,y)
  ...: show()
In[3]: plot(x,y)
WARNING: QApplication was not created in the main() thread.
Out[3]: [<matplotlib.lines.Line2D at 0x7fc68a3009e8>]
In[4]: show()
</code>```

So it is something related with using the matplotlib library with the import using * and with running in the interactive console after the first time it was imported. I know the wildcard import is not recommended, but sometimes it is useful to do it for a sake of testing things faster and being less verbose.

Looking for this warning online, I have only found these

https://github.com/matplotlib/matplotlib/issues/13296
But my case doesn't seem to be related to multiprocessing. And even if pycharm is doing something behind the scenes, I wonder why it has changed, as I had no problems with this like a month ago;

Suppress warning "QApplication was not created in main() thread"
and other posts related to C++, which is not my case;

WARNING: QApplication was not created in main() thread -> related to pycharm, but has an additional error different than mine

Which didn't help much. Anyone knows what is happening and how to solve it?

SPECS:

PyCharm 2019.1.2 (Professional Edition)

Build #PY-191.7141.48, built on May 7, 2019

JRE: 11.0.2+9-b159.56 amd64

JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

Linux 4.15.0-50-generic

conda 4.6.14, with Python 3.7.3

Qt5

答:
There several things you can try:

First, you can try to update the Qt. You may have some older version. Run

```<code>print(plt.get_backend())
</code>```

to verify which backend you are using. If you are using Qt4, try Qt5 back end.

Next, update Qt5 to the latest version via

```<code>pip install --upgrade PyQt5
</code>```

Also, you can try ditching Qt and switch to Tk back end: add

```<code>import matplotlib
matplotlib.use('TkAgg')
</code>```

before importing pyplot

Body:
In PyCharm, when I try to plot something using its interactive console, such as:

In[2]: from matplotlib.pyplot import *
In[3]: x = range(5)
In[4]: y = range(5,10)
In[5]: plot(x,y)
WARNING: QApplication was not created in the main() thread.
Out[5]: [<matplotlib.lines.Line2D at 0x7fade916a438>]
In[6]: show()

It opens a window and crashes. I have to stop the console and start a new one.

It works fine when I run anything like that in an ipython console in my terminal, the error happens only in Pycharm, it seems.

On the other hand, if import matplotlib with import matplotlib.pyplot as plt it works fine:

In[2]: import matplotlib.pyplot as plt
In[3]: x = range(5)
In[4]: y = range(5,10)
In[5]: plt.plot(x,y)
Out[5]: [<matplotlib.lines.Line2D at 0x7fd3453b72e8>]
In[6]: plt.show()

But if I do both, it crashes too (even calling the plot function using plt.plot):

In[2]: from matplotlib.pyplot import *
In[3]: import matplotlib.pyplot as plt
In[4]: x = range(5)
In[5]: y = range(5,10)
In[6]: plt.plot(x,y)
WARNING: QApplication was not created in the main() thread.
Out[6]: [<matplotlib.lines.Line2D at 0x7fade916a438>]
In[7]: plt.show()

Furthermore, when I run it all in one command, it works the first time. But if I try to plot another time, it crashes:

In[2]: from matplotlib.pyplot import *
  ...: x = range(5)
  ...: y = range(5,10)
  ...: plot(x,y)
  ...: show()
In[3]: plot(x,y)
WARNING: QApplication was not created in the main() thread.
Out[3]: [<matplotlib.lines.Line2D at 0x7fc68a3009e8>]
In[4]: show()

So it is something related with using the matplotlib library with the import using * and with running in the interactive console after the first time it was imported. I know the wildcard import is not recommended, but sometimes it is useful to do it for a sake of testing things faster and being less verbose.

Looking for this warning online, I have only found these

https://github.com/matplotlib/matplotlib/issues/13296
But my case doesn't seem to be related to multiprocessing. And even if pycharm is doing something behind the scenes, I wonder why it has changed, as I had no problems with this like a month ago;

Suppress warning "QApplication was not created in main() thread"
and other posts related to C++, which is not my case;

WARNING: QApplication was not created in main() thread -> related to pycharm, but has an additional error different than mine

Which didn't help much. Anyone knows what is happening and how to solve it?

SPECS:

PyCharm 2019.1.2 (Professional Edition)

Build #PY-191.7141.48, built on May 7, 2019

JRE: 11.0.2+9-b159.56 amd64

JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

Linux 4.15.0-50-generic

conda 4.6.14, with Python 3.7.3

Qt5

Body:
There several things you can try:

First, you can try to update the Qt. You may have some older version. Run

print(plt.get_backend())

to verify which backend you are using. If you are using Qt4, try Qt5 back end.

Next, update Qt5 to the latest version via

pip install --upgrade PyQt5

Also, you can try ditching Qt and switch to Tk back end: add

import matplotlib
matplotlib.use('TkAgg')

before importing pyplot


问:
reading matrices from a file and retriving their dimension
I have a text file containing two matrices in this form:

```
1 2 3
4 5 6
1 2 3
*
4 5 6
1 2 3]
```

I want to be able to read the dimension of the two matrices and the type of operation * + / -. I'd like to retrieve the dimension and read data at the same time.

In my code the get_dim() function goes through the data in the file to get the dimension of the two matrices. I don't know if there is a way to store the values of the matrices already at this point with dynamic memory allocation. With the function read_matrix() one that I know the dimension of the matrices I'm reading again the same data.

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>

#define IN 1
#define OUT 0

struct matrix{
    int rows;
    int cols;
    double *data;
};

void f(double x); /*truncate a double */
int get_dim(char *file, int *r, int *col);
void read_matrix(char *file, struct matrix *A, struct matrix *B);
void print_matrix(struct matrix *A);
void multiply(struct matrix *A, struct matrix *B, struct matrix *C);

int main (int argc, char *argv[])
{
    int rows[2]= {0,0};
    int cols[2]= {0,0};
    int operation; /*type of operation 1 for * and 2 for + */

    operation = get_dim(argv[1], rows, cols);

    struct matrix A;
    struct matrix B;
    struct matrix C;

    A.rows = rows[0];
    A.cols = cols[0];

    B.rows = rows[1];
    B.cols = cols[1];

    C.rows = rows[0];
    C.cols = cols[1];

    A.data = malloc(sizeof(double) * A.rows * A.cols);
    B.data = malloc(sizeof(double) * B.rows * B.cols);
    C.data = malloc(sizeof(double) * A.rows * B.cols);

    read_matrix(argv[1],&A,&B);

    print_matrix(&A);

    printf("\n*\n");

    print_matrix(&B);
    printf("\n=\n");

    multiply(&A,&B,&C);
    print_matrix(&C);

    free(A.data);
    free(B.data);
    free(C.data);

    return 0;
}

void read_matrix(char *file, struct matrix *A, struct matrix *B){

    int i,j;
    FILE *fp;
    int c=1;

    if((fp = fopen(file, "r")) != NULL ){

        for(i=0; i < A->rows; i++)
            for(j=0; j < A->cols; j++)
                fscanf(fp, "%lf", (A->data + (i * A->cols + j)));

        /*skip the character operator line */

        while(!isdigit(c))
            c=fgetc(fp);

        ungetc(c,fp);

        for(i=0; i < B->rows; i++)
           for(j=0; j < B->cols; j++)
                fscanf(fp, "%lf", (B->data + (i * B->cols + j)));
    }
    fclose(fp);
}

int get_dim(char *file, int *rows, int *cols){

    FILE *fp;
    double a;
    int c =1;
    int n = OUT;
    int op=0;

    if((fp = fopen(file, "r")) == NULL ){
        fprintf(stderr, "matrix: I cannot open %s\n",file);
        exit(1);
    }

    while(fscanf(fp,"%lf",&a)){

            if(n==OUT)
                cols[0]++;

            c=fgetc(fp);

            if(isdigit(c))
                ungetc(c,fp);

            else if(c =='\n'){
                rows[0]++;
                n=IN;
            }

            else if(c=='*'){
                op=1;
                break;
            }
    }

    n=OUT;
    printf("\n");

    while(!isdigit(c))
        c=fgetc(fp);

    ungetc(c,fp);

    while(fscanf(fp,"%lf",&a)){

        if(n==OUT)
            cols[1]++;

        c=fgetc(fp);

        if(isdigit(c))
            ungetc(c,fp);

        else if(c =='\n'){
            rows[1]++;
            n=IN;
        }

        else if(c == ']'){
                rows[1]++;
                break;
        }
    }
    fclose(fp);
    return op;
}

void print_matrix(struct matrix *A){

    int i,j;

/*printing the matrices*/

     double *tmp = A->data;

     for(i=0; i < A->rows; i++){
        for(j=0; j < A->cols; j++){
                f(*(tmp++));
        }
        printf("\n");
    }
}

void multiply(struct matrix *A, struct matrix *B, struct matrix *C)
{
    int i, j, k;

    /*initialize C to 0*/

   for (i=0; i< C->rows; i++){
    for (j=0; j < C->cols; j++)
        C->data[i * C->cols + j]=0;
   }
// Multiplying matrix A and B and storing in C.
   for(i = 0; i < A->rows; ++i)
        for(j = 0; j < B->cols; ++j)
            for(k=0; k < A->cols; ++k)
                C->data[i * C->cols + j] += A->data[i * A->cols + k] * B->data[k * B->cols + j];
}

void f(double x)
{
    double i,f= modf(x,&i);

    if(f<.00001)
        printf("%.f ",i);
    else printf("%f ",x);
}
</code>```

答:
I don't know if there is a way to store the values of the matrices
  already at this point with dynamic memory allocation.

There is, but understand that even is you assume there are only two matricies separated by a single operator, to truly do a dynamic read of matricies of an unknown number of columns and rows takes being able to track the number of rows and columns for each matrix encountered in the file and careful attention to allocation and reallocation throughout the read process.

To simplify the approach you can first assume there will be less than or equal to 512 columns per-row (or some reasonable number that fits your data). This allows you to read a row of integer values into a temporary array before having to allocate storage for the row. (you can of course dynamically allocate and reallocate the temporary array to get to that point, but for purposes here, that just adds an additional set of conditional checks and reallocation -- where there are plenty already).

Now knowing the number of columns-per-row, (which you save in a variable to validate subsequent rows against), you can allocate storage for that row (and the remainder in that matrix until a row begins with a non-digit)

One way to simplify the storage of rows and columns of the matrix along with variables that store the number of rows and columns as a single using is to use a struct to hold the matrix and it's size. (this lends itself to 2 matricies, or any number you like) This allows you to allocate for an array of struct for any number of arrays to be read (or you can simply declare an array of 2 of them for your case and avoid the allocation/reallocation checks). For example:

```<code>typedef struct {
    int **a;
    size_t row, col;
} arr_t;
</code>```

Where a is a pointer-to-pointer-to int and row and col hold the number of rows and columns in the allocated and filled a. The choice of pointer-to-pointer allows native indexing as a[i][j] in normal 2D fashion without having to map 2D indexing into a single offset. (you can do it either way, choice is yours)

The base storage scheme is simple, you allocate (or statically declare) some number of struct, then allocate some initial number of pointers for a, and as you read and convert each line into your temporary array, you allocate storage for each row, copy your temporary row to that block of memory, and assign the starting address of that block to the next available pointer. When the number of pointers used equals the number you initially allocated, you realloc more pointers and keep going. (when you are done with the arrays, make sure you free() everything you have allocated.

That's basically it. The rest is just dotting your i's and crossing your t's on tracking what is allocated, and when a reallocation needs to occur. It's not complicated, it just takes careful attention to detail. The following implementation allocates (and will reallocate) for the structs (number of arrays) as well as the arrays themselves. It reads each line with fgets() assuming each will fit into a 1024 byte buffer (that too can be allocated and reallocated as required, but just as with the temporary array, that additional layer of allocation/reallocation has been omitted for example purposes).

Each line is then converted into integers using sscanf into the temporary array tmp (you would ideally use strtol for the error detecting benefit, but that was omitted to simplify the example). A block of memory is then allocated and the integer from tmp are copied to the new block of memory and its address assigned as the next pointer in the current array. aidx is used as your array of struct index (e.g. for arr[0], arr[1], ...) When a non-digit is encountered as the first character in the line, it is taken as the operator between arrays and it is stored in an array of char, the array index aidx is increment and filling of the next array proceeds.

At the end, the arrays are printed out and all memory previous allocated is freed. Take the time to work through it and understand what is happening at each point and why. (use a piece of paper and pencil to track the iteration logic through -- often much better than staring at a computer screen)

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MINA    2   /* if you need a constant, #define one (or more) */
#define MAXC 1024

typedef struct {
    int **a;
    size_t row, col;
} arr_t;

int main (int argc, char **argv) {

    arr_t *arr;                     /* pointer to array type */
    size_t  aidx = 0, maxa = MINA,  /* arr index, max no. allocated */
            nrow = 0, ncol = 0,     /* current row/col count */
            maxrow = MINA, nop = 0; /* alloc'ed rows current array, no. op */
    char buf[MAXC],                 /* buffer to hold each line */
        op[MAXC];                   /* array to hold operators */
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }
    /* allocate/validate maxa no. of arr_t */
    if (!(arr = calloc (maxa, sizeof *arr))) {
        perror ("calloc-arr");
        return 1;
    }

    while (fgets (buf, MAXC, fp)) { /* read each line info buf */
        int off = 0, n;         /* offset from start of line, n for "%n" */
        size_t tidx = 0;        /* temporary array index */
        char *p = buf;          /* pointer to advance in sscanf */
        int tmp[MAXC / 2 + 1];  /* temporary array, sized for max no. ints */

        if (!isdigit(*buf)) {   /* if 1st char non-digit, end of array */
            op[nop++] = *buf;   /* store operator */
            if (nrow)           /* if rows stored */
                arr[aidx++].row = nrow; /* set final number of rows */
            nrow = ncol = 0;    /* reset nrow/ncol counters */
            maxrow = MINA;      /* reset allocate rows */
            continue;           /* get next line of data */
        }
        if (aidx == maxa) {     /* check if no. of structs need realloc */
            void *atmp = realloc (arr, 2 * maxa * sizeof *arr);  /* realloc */
            if (!atmp) {        /* validate */
                perror ("realloc-arr");
                return 1;
            }
            arr = atmp;         /* assign new block to arr */
            /* set all new bytes zero (realloc doesn't initialize) */
            memset (arr + maxa, 0, maxa * sizeof *arr);
            maxa *= 2;      /* update struct count */
        }

        /* read all integers in line into tmp array */
        while (sscanf (p + off, "%d%n", &tmp[tidx], &n) == 1) {
            off +=  n;
            tidx++;
        }
        if (tidx) { /* if integers stored in tmp */
            if (nrow == 0) {   /* if first row in array */
                /* allocate/validate maxrow pointers */
                if (!(arr[aidx].a = malloc (maxrow * sizeof *arr[aidx].a))) {
                    perror ("malloc-arr[aidx].a");
                    return 1;
                }
                arr[aidx].col = tidx;   /* fix no. cols on 1st row */
            }
            else if (nrow == maxrow) {  /* realloc of row ptrs req'd? */
                void *atmp =            /* always realloc with temp ptr */
                    realloc (arr[aidx].a, 2 * maxrow * sizeof *arr[aidx].a);
                if (!atmp) {            /* validate every alloc/realloc */
                    perror ("realloc-arr[aidx].a");
                    return 1;
                }
                arr[aidx].a = atmp;     /* assign realloced block to ptr */
                maxrow *= 2;            /* update maxrow to current alloc */
            }
            if (tidx != arr[aidx].col) {    /* validate no. of columns */
                fprintf (stderr, "error: invalid number of columns "
                        "arr[%zu].a[%zu]\n", aidx, nrow);
                return 1;
            }
            if (!(arr[aidx].a[nrow] =   /* allocate storagre for integers */
                            malloc (tidx * sizeof *arr[aidx].a[nrow]))) {
                perror ("malloc-arr[aidx].a[nrow]");
                return 1;
            }
            /* copy integers from tmp to row, increment row count */
            memcpy (arr[aidx].a[nrow++], tmp, tidx * sizeof *tmp);
        }
    }
    if (nrow)   /* handle final array */
        arr[aidx++].row = nrow; /* set final number of rows */

    if (fp != stdin) fclose (fp);   /* close file if not stdin */

    for (size_t i = 0; i < aidx; i++) {     /* for each struct */
        printf ("\narray %zu:\n(%zu x %zu)\n",      /* output no. and size */
                i + 1, arr[i].row, arr[i].col);
        for (size_t j = 0; j < arr[i].row; j++) {   /* for each row */
            for (size_t k = 0; k < arr[i].col; k++) /* for each col */
                printf ("%4d", arr[i].a[j][k]);     /* output int */
            putchar ('\n');         /* tidy up with '\n' */
            free (arr[i].a[j]);     /* free row */
        }
        free (arr[i].a);    /* free pointers */
        if (i < nop)
            printf ("\noperator: '%c'\n", op[i]);
    }
    free (arr);     /* free structs */

    return 0;
}
</code>```

Example Input File

```<code>$ cat dat/unknown_arrays.txt
1 2 3
4 5 6
1 2 3
*
4 5 6
1 2 3
</code>```

Example Use/Output

```<code>$ ./bin/read_unknown_arrays dat/unknown_arrays.txt

array 1:
(3 x 3)
   1   2   3
   4   5   6
   1   2   3

operator: '*'

array 2:
(2 x 3)
   4   5   6
   1   2   3
</code>```

Memory Use/Error Check

In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.

It is imperative that you use a memory error checking program to insure you do not attempt to access memory or write beyond/outside the bounds of your allocated block, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.

For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.

```<code>$ valgrind ./bin/read_unknown_arrays dat/unknown_arrays.txt
==7714== Memcheck, a memory error detector
==7714== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==7714== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==7714== Command: ./bin/read_unknown_arrays dat/unknown_arrays.txt
==7714==

array 1:
(3 x 3)
   1   2   3
   4   5   6
   1   2   3

  operator: '*'

array 2:
(2 x 3)
   4   5   6
   1   2   3
==7714==
==7714== HEAP SUMMARY:
==7714==     in use at exit: 0 bytes in 0 blocks
==7714==   total heap usage: 10 allocs, 10 frees, 724 bytes allocated
==7714==
==7714== All heap blocks were freed -- no leaks are possible
==7714==
==7714== For counts of detected and suppressed errors, rerun with: -v
==7714== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</code>```

Always confirm that you have freed all memory you have allocated and that there are no memory errors.

Work through the example. Understand that it doesn't matter whether you are allocating/reallocating for a 2x2 or 150x150 array, the validation and reallocation checks are the same which is what makes short input files like your seem deceptively over-complicated. They aren't, it just takes the same code to handle a 2x2 or 150x150. Let me know if you have further questions.

Body:
I have a text file containing two matrices in this form:

1 2 3
4 5 6
1 2 3
*
4 5 6
1 2 3]

I want to be able to read the dimension of the two matrices and the type of operation * + / -. I'd like to retrieve the dimension and read data at the same time.

In my code the get_dim() function goes through the data in the file to get the dimension of the two matrices. I don't know if there is a way to store the values of the matrices already at this point with dynamic memory allocation. With the function read_matrix() one that I know the dimension of the matrices I'm reading again the same data.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>

#define IN 1
#define OUT 0

struct matrix{
    int rows;
    int cols;
    double *data;
};

void f(double x); /*truncate a double */
int get_dim(char *file, int *r, int *col);
void read_matrix(char *file, struct matrix *A, struct matrix *B);
void print_matrix(struct matrix *A);
void multiply(struct matrix *A, struct matrix *B, struct matrix *C);

int main (int argc, char *argv[])
{
    int rows[2]= {0,0};
    int cols[2]= {0,0};
    int operation; /*type of operation 1 for * and 2 for + */

    operation = get_dim(argv[1], rows, cols);

    struct matrix A;
    struct matrix B;
    struct matrix C;

    A.rows = rows[0];
    A.cols = cols[0];

    B.rows = rows[1];
    B.cols = cols[1];

    C.rows = rows[0];
    C.cols = cols[1];

    A.data = malloc(sizeof(double) * A.rows * A.cols);
    B.data = malloc(sizeof(double) * B.rows * B.cols);
    C.data = malloc(sizeof(double) * A.rows * B.cols);

    read_matrix(argv[1],&A,&B);

    print_matrix(&A);

    printf("\n*\n");

    print_matrix(&B);
    printf("\n=\n");

    multiply(&A,&B,&C);
    print_matrix(&C);

    free(A.data);
    free(B.data);
    free(C.data);

    return 0;
}

void read_matrix(char *file, struct matrix *A, struct matrix *B){

    int i,j;
    FILE *fp;
    int c=1;

    if((fp = fopen(file, "r")) != NULL ){

        for(i=0; i rows; i++)
            for(j=0; j cols; j++)
                fscanf(fp, "%lf", (A->data + (i * A->cols + j)));

        /*skip the character operator line */

        while(!isdigit(c))
            c=fgetc(fp);

        ungetc(c,fp);

        for(i=0; i rows; i++)
           for(j=0; j cols; j++)
                fscanf(fp, "%lf", (B->data + (i * B->cols + j)));
    }
    fclose(fp);
}

int get_dim(char *file, int *rows, int *cols){

    FILE *fp;
    double a;
    int c =1;
    int n = OUT;
    int op=0;

    if((fp = fopen(file, "r")) == NULL ){
        fprintf(stderr, "matrix: I cannot open %s\n",file);
        exit(1);
    }

    while(fscanf(fp,"%lf",&a)){

            if(n==OUT)
                cols[0]++;

            c=fgetc(fp);

            if(isdigit(c))
                ungetc(c,fp);

            else if(c =='\n'){
                rows[0]++;
                n=IN;
            }

            else if(c=='*'){
                op=1;
                break;
            }
    }

    n=OUT;
    printf("\n");

    while(!isdigit(c))
        c=fgetc(fp);

    ungetc(c,fp);

    while(fscanf(fp,"%lf",&a)){

        if(n==OUT)
            cols[1]++;

        c=fgetc(fp);

        if(isdigit(c))
            ungetc(c,fp);

        else if(c =='\n'){
            rows[1]++;
            n=IN;
        }

        else if(c == ']'){
                rows[1]++;
                break;
        }
    }
    fclose(fp);
    return op;
}

void print_matrix(struct matrix *A){

    int i,j;

/*printing the matrices*/

     double *tmp = A->data;

     for(i=0; i rows; i++){
        for(j=0; j cols; j++){
                f(*(tmp++));
        }
        printf("\n");
    }
}

void multiply(struct matrix *A, struct matrix *B, struct matrix *C)
{
    int i, j, k;

    /*initialize C to 0*/

   for (i=0; i< C->rows; i++){
    for (j=0; j < C->cols; j++)
        C->data[i * C->cols + j]=0;
   }
// Multiplying matrix A and B and storing in C.
   for(i = 0; i rows; ++i)
        for(j = 0; j cols; ++j)
            for(k=0; k cols; ++k)
                C->data[i * C->cols + j] += A->data[i * A->cols + k] * B->data[k * B->cols + j];
}

void f(double x)
{
    double i,f= modf(x,&i);

    if(f<.00001)
        printf("%.f ",i);
    else printf("%f ",x);
}

Body:
I don't know if there is a way to store the values of the matrices
  already at this point with dynamic memory allocation.

There is, but understand that even is you assume there are only two matricies separated by a single operator, to truly do a dynamic read of matricies of an unknown number of columns and rows takes being able to track the number of rows and columns for each matrix encountered in the file and careful attention to allocation and reallocation throughout the read process.

To simplify the approach you can first assume there will be less than or equal to 512 columns per-row (or some reasonable number that fits your data). This allows you to read a row of integer values into a temporary array before having to allocate storage for the row. (you can of course dynamically allocate and reallocate the temporary array to get to that point, but for purposes here, that just adds an additional set of conditional checks and reallocation -- where there are plenty already).

Now knowing the number of columns-per-row, (which you save in a variable to validate subsequent rows against), you can allocate storage for that row (and the remainder in that matrix until a row begins with a non-digit)

One way to simplify the storage of rows and columns of the matrix along with variables that store the number of rows and columns as a single using is to use a struct to hold the matrix and it's size. (this lends itself to 2 matricies, or any number you like) This allows you to allocate for an array of struct for any number of arrays to be read (or you can simply declare an array of 2 of them for your case and avoid the allocation/reallocation checks). For example:

typedef struct {
    int **a;
    size_t row, col;
} arr_t;

Where a is a pointer-to-pointer-to int and row and col hold the number of rows and columns in the allocated and filled a. The choice of pointer-to-pointer allows native indexing as a[i][j] in normal 2D fashion without having to map 2D indexing into a single offset. (you can do it either way, choice is yours)

The base storage scheme is simple, you allocate (or statically declare) some number of struct, then allocate some initial number of pointers for a, and as you read and convert each line into your temporary array, you allocate storage for each row, copy your temporary row to that block of memory, and assign the starting address of that block to the next available pointer. When the number of pointers used equals the number you initially allocated, you realloc more pointers and keep going. (when you are done with the arrays, make sure you free() everything you have allocated.

That's basically it. The rest is just dotting your i's and crossing your t's on tracking what is allocated, and when a reallocation needs to occur. It's not complicated, it just takes careful attention to detail. The following implementation allocates (and will reallocate) for the structs (number of arrays) as well as the arrays themselves. It reads each line with fgets() assuming each will fit into a 1024 byte buffer (that too can be allocated and reallocated as required, but just as with the temporary array, that additional layer of allocation/reallocation has been omitted for example purposes).

Each line is then converted into integers using sscanf into the temporary array tmp (you would ideally use strtol for the error detecting benefit, but that was omitted to simplify the example). A block of memory is then allocated and the integer from tmp are copied to the new block of memory and its address assigned as the next pointer in the current array. aidx is used as your array of struct index (e.g. for arr[0], arr[1], ...) When a non-digit is encountered as the first character in the line, it is taken as the operator between arrays and it is stored in an array of char, the array index aidx is increment and filling of the next array proceeds.

At the end, the arrays are printed out and all memory previous allocated is freed. Take the time to work through it and understand what is happening at each point and why. (use a piece of paper and pencil to track the iteration logic through -- often much better than staring at a computer screen)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MINA    2   /* if you need a constant, #define one (or more) */
#define MAXC 1024

typedef struct {
    int **a;
    size_t row, col;
} arr_t;

int main (int argc, char **argv) {

    arr_t *arr;                     /* pointer to array type */
    size_t  aidx = 0, maxa = MINA,  /* arr index, max no. allocated */
            nrow = 0, ncol = 0,     /* current row/col count */
            maxrow = MINA, nop = 0; /* alloc'ed rows current array, no. op */
    char buf[MAXC],                 /* buffer to hold each line */
        op[MAXC];                   /* array to hold operators */
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }
    /* allocate/validate maxa no. of arr_t */
    if (!(arr = calloc (maxa, sizeof *arr))) {
        perror ("calloc-arr");
        return 1;
    }

    while (fgets (buf, MAXC, fp)) { /* read each line info buf */
        int off = 0, n;         /* offset from start of line, n for "%n" */
        size_t tidx = 0;        /* temporary array index */
        char *p = buf;          /* pointer to advance in sscanf */
        int tmp[MAXC / 2 + 1];  /* temporary array, sized for max no. ints */

        if (!isdigit(*buf)) {   /* if 1st char non-digit, end of array */
            op[nop++] = *buf;   /* store operator */
            if (nrow)           /* if rows stored */
                arr[aidx++].row = nrow; /* set final number of rows */
            nrow = ncol = 0;    /* reset nrow/ncol counters */
            maxrow = MINA;      /* reset allocate rows */
            continue;           /* get next line of data */
        }
        if (aidx == maxa) {     /* check if no. of structs need realloc */
            void *atmp = realloc (arr, 2 * maxa * sizeof *arr);  /* realloc */
            if (!atmp) {        /* validate */
                perror ("realloc-arr");
                return 1;
            }
            arr = atmp;         /* assign new block to arr */
            /* set all new bytes zero (realloc doesn't initialize) */
            memset (arr + maxa, 0, maxa * sizeof *arr);
            maxa *= 2;      /* update struct count */
        }

        /* read all integers in line into tmp array */
        while (sscanf (p + off, "%d%n", &tmp[tidx], &n) == 1) {
            off +=  n;
            tidx++;
        }
        if (tidx) { /* if integers stored in tmp */
            if (nrow == 0) {   /* if first row in array */
                /* allocate/validate maxrow pointers */
                if (!(arr[aidx].a = malloc (maxrow * sizeof *arr[aidx].a))) {
                    perror ("malloc-arr[aidx].a");
                    return 1;
                }
                arr[aidx].col = tidx;   /* fix no. cols on 1st row */
            }
            else if (nrow == maxrow) {  /* realloc of row ptrs req'd? */
                void *atmp =            /* always realloc with temp ptr */
                    realloc (arr[aidx].a, 2 * maxrow * sizeof *arr[aidx].a);
                if (!atmp) {            /* validate every alloc/realloc */
                    perror ("realloc-arr[aidx].a");
                    return 1;
                }
                arr[aidx].a = atmp;     /* assign realloced block to ptr */
                maxrow *= 2;            /* update maxrow to current alloc */
            }
            if (tidx != arr[aidx].col) {    /* validate no. of columns */
                fprintf (stderr, "error: invalid number of columns "
                        "arr[%zu].a[%zu]\n", aidx, nrow);
                return 1;
            }
            if (!(arr[aidx].a[nrow] =   /* allocate storagre for integers */
                            malloc (tidx * sizeof *arr[aidx].a[nrow]))) {
                perror ("malloc-arr[aidx].a[nrow]");
                return 1;
            }
            /* copy integers from tmp to row, increment row count */
            memcpy (arr[aidx].a[nrow++], tmp, tidx * sizeof *tmp);
        }
    }
    if (nrow)   /* handle final array */
        arr[aidx++].row = nrow; /* set final number of rows */

    if (fp != stdin) fclose (fp);   /* close file if not stdin */

    for (size_t i = 0; i < aidx; i++) {     /* for each struct */
        printf ("\narray %zu:\n(%zu x %zu)\n",      /* output no. and size */
                i + 1, arr[i].row, arr[i].col);
        for (size_t j = 0; j < arr[i].row; j++) {   /* for each row */
            for (size_t k = 0; k < arr[i].col; k++) /* for each col */
                printf ("%4d", arr[i].a[j][k]);     /* output int */
            putchar ('\n');         /* tidy up with '\n' */
            free (arr[i].a[j]);     /* free row */
        }
        free (arr[i].a);    /* free pointers */
        if (i < nop)
            printf ("\noperator: '%c'\n", op[i]);
    }
    free (arr);     /* free structs */

    return 0;
}

Example Input File

$ cat dat/unknown_arrays.txt
1 2 3
4 5 6
1 2 3
*
4 5 6
1 2 3

Example Use/Output

$ ./bin/read_unknown_arrays dat/unknown_arrays.txt

array 1:
(3 x 3)
   1   2   3
   4   5   6
   1   2   3

operator: '*'

array 2:
(2 x 3)
   4   5   6
   1   2   3

Memory Use/Error Check

In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.

It is imperative that you use a memory error checking program to insure you do not attempt to access memory or write beyond/outside the bounds of your allocated block, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.

For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.

$ valgrind ./bin/read_unknown_arrays dat/unknown_arrays.txt
==7714== Memcheck, a memory error detector
==7714== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==7714== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==7714== Command: ./bin/read_unknown_arrays dat/unknown_arrays.txt
==7714==

array 1:
(3 x 3)
   1   2   3
   4   5   6
   1   2   3

  operator: '*'

array 2:
(2 x 3)
   4   5   6
   1   2   3
==7714==
==7714== HEAP SUMMARY:
==7714==     in use at exit: 0 bytes in 0 blocks
==7714==   total heap usage: 10 allocs, 10 frees, 724 bytes allocated
==7714==
==7714== All heap blocks were freed -- no leaks are possible
==7714==
==7714== For counts of detected and suppressed errors, rerun with: -v
==7714== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Always confirm that you have freed all memory you have allocated and that there are no memory errors.

Work through the example. Understand that it doesn't matter whether you are allocating/reallocating for a 2x2 or 150x150 array, the validation and reallocation checks are the same which is what makes short input files like your seem deceptively over-complicated. They aren't, it just takes the same code to handle a 2x2 or 150x150. Let me know if you have further questions.