问:
Ionic 3 make promise funtion in constructor
How can we make a promise function in constructor that run line by line and wait for it's result then go to next line. Currently my promise function is not running and it runs in last.

```<code>constructor(){
    console.log("Start");
    this.getData();
    console.log("End");
}

getData() {
   return new Promise(data => {
     this.db.database.ref().child('/category').orderByChild('parent_id').
       equalTo(this.idn).once('value').then(function (snapshot) {
         console.log("Mid")
       })
   });
}
</code>```

output of above is

```<code>Start
End
Mid
</code>```

Expected output is

```<code>Start
Mid
End
</code>```

答:
Just to clarify, your promise function does not run last. It starts after "Start" and before "End", as expected. It just happens to finish last. This is because it is an "async" call by design. (Async == non-blocking means the program does not wait for it to finish. It just moves on to the next statement, console.log("End"), in your example.)

BTW, calling methods like "getData()" in Ctor is not a good practice. You may want to do it in an Angular lifecycle method like ngOnInit().

Body:
How can we make a promise function in constructor that run line by line and wait for it's result then go to next line. Currently my promise function is not running and it runs in last.

constructor(){
    console.log("Start");
    this.getData();
    console.log("End");
}

getData() {
   return new Promise(data => {
     this.db.database.ref().child('/category').orderByChild('parent_id').
       equalTo(this.idn).once('value').then(function (snapshot) {
         console.log("Mid")
       })
   });
}

output of above is

Start
End
Mid

Expected output is

Start
Mid
End


来源: stackexchange

问:
How to validate date field with format MMM/DD/YY or MMM/DD/YYYY?
My field contains the string values like JUL/11/2017, JAN/11/17. Though it is a valid field, i am not able to validate it using is_date function

```<code>SET DATEFORMAT MDY;
if isdate('JUL/11/2017')=1
print 'VALID_DATE'
else
print 'invalid date'
</code>```

If the field value is DD/MMM/YY or DD/MMM/YYYY , it works fine. Any one can help me validating this field.

Note:I have tried using set language option too.

答:
You can try the following too:

```<code>DECLARE @DATE_FIELD VARCHAR(15) = 'JUL/11/2017' --'JAN/11/17'
    IF (ISDATE(REVERSE(LEFT(REVERSE(@DATE_FIELD),CHARINDEX('/',REVERSE(@DATE_FIELD),1)-1))+'-'+ LEFT(@DATE_FIELD,CHARINDEX('/',@DATE_FIELD,1)-1)+'-'+SUBSTRING(@DATE_FIELD,CHARINDEX('/',@DATE_FIELD,1)+1,LEN(@DATE_FIELD)-CHARINDEX('/',@DATE_FIELD,1)-CHARINDEX('/',REVERSE(@DATE_FIELD),1))) = 1)
    PRINT 'VALID_DATE'
    ELSE
    PRINT 'INVALID_DATE'
</code>```

Thanks.

ContentLicense: CC BY-SA 3.0

Body:
My field contains the string values like JUL/11/2017, JAN/11/17. Though it is a valid field, i am not able to validate it using is_date function

SET DATEFORMAT MDY;
if isdate('JUL/11/2017')=1
print 'VALID_DATE'
else
print 'invalid date'

If the field value is DD/MMM/YY or DD/MMM/YYYY , it works fine. Any one can help me validating this field.

Note:I have tried using set language option too.

Body:
You can try the following too:

DECLARE @DATE_FIELD VARCHAR(15) = 'JUL/11/2017' --'JAN/11/17'
    IF (ISDATE(REVERSE(LEFT(REVERSE(@DATE_FIELD),CHARINDEX('/',REVERSE(@DATE_FIELD),1)-1))+'-'+ LEFT(@DATE_FIELD,CHARINDEX('/',@DATE_FIELD,1)-1)+'-'+SUBSTRING(@DATE_FIELD,CHARINDEX('/',@DATE_FIELD,1)+1,LEN(@DATE_FIELD)-CHARINDEX('/',@DATE_FIELD,1)-CHARINDEX('/',REVERSE(@DATE_FIELD),1))) = 1)
    PRINT 'VALID_DATE'
    ELSE
    PRINT 'INVALID_DATE'

Thanks.


问:
Find out string array lengthand each string length
Consider the following array of "strings" in C:

```<code>const char* const animals[] =
{
    "",
    "Cat",
    "Dawg",
    "Elephant",
    "Tiger",
};
</code>```

Is it possible to obtain:

The number of elements (char pointers) in the animals array?

The length of each array member, ie. size = 1 for element 0, size = 4 for element 1 and so on?

I tried using sizeof of course, but it doesnt seem to return anything that makes sense. I think it should be possible for the precompiler to figureout the amount of elements in the array as well as size of each element. For the latter, one could serach of \0 character as well do define length. I wonder however why I cant get proper array size (ie. number of elements in animals array) when using sizeof?

I would appreciate all suggestions.

Edit:

Yes I meant preprocessor, not precompiller, sorry.

Why do I need this functionality?
I am parsing incoming strings from a serial port. I need to figure out either the received string matches any string in my preconfigured table. If it does, I need the index of that item. I need the searching algorithm to be fast. Because of that, I first want to check the string size and all bytes after that, only if size matches. Because of that I thought maybe the length of each string is known at compile time.

This is my current checking function:

```<code>static int32_t  getStringIndex(const uint8_t* const buf, const uint32_t len)
{
    if (!len)
        return -1;

    int32_t arraySize = sizeof(animals) /  sizeof(animals[0]);
    uint32_t elementSize;

    // The algorithm 1st checks if the length matches. If yes, it compares the strings.
    for (int32_t i = 0; i < arraySize; i++)
    {
        elementSize = strlen(animals[i]);

        if (elementSize == len)
        {
            if (0 == memcmp(animals[i], buf, len))
            {
                return i;
            }
        }
    }

    return -1;
}
</code>```

I dont use strcmp because buf doesnt have \0 at the end.

答:
sizeof animals / sizeof *animals (total size in bytes divided by the size of a single element)

strlen(animals[0]) + 1 (the string length doesn't include the 0 terminator)

Body:
Consider the following array of "strings" in C:

const char* const animals[] =
{
    "",
    "Cat",
    "Dawg",
    "Elephant",
    "Tiger",
};

Is it possible to obtain:

The number of elements (char pointers) in the animals array?

The length of each array member, ie. size = 1 for element 0, size = 4 for element 1 and so on?

I tried using sizeof of course, but it doesnt seem to return anything that makes sense. I think it should be possible for the precompiler to figureout the amount of elements in the array as well as size of each element. For the latter, one could serach of \0 character as well do define length. I wonder however why I cant get proper array size (ie. number of elements in animals array) when using sizeof?

I would appreciate all suggestions.

Edit:

Yes I meant preprocessor, not precompiller, sorry.

Why do I need this functionality?
I am parsing incoming strings from a serial port. I need to figure out either the received string matches any string in my preconfigured table. If it does, I need the index of that item. I need the searching algorithm to be fast. Because of that, I first want to check the string size and all bytes after that, only if size matches. Because of that I thought maybe the length of each string is known at compile time.

This is my current checking function:

static int32_t  getStringIndex(const uint8_t* const buf, const uint32_t len)
{
    if (!len)
        return -1;

    int32_t arraySize = sizeof(animals) /  sizeof(animals[0]);
    uint32_t elementSize;

    // The algorithm 1st checks if the length matches. If yes, it compares the strings.
    for (int32_t i = 0; i < arraySize; i++)
    {
        elementSize = strlen(animals[i]);

        if (elementSize == len)
        {
            if (0 == memcmp(animals[i], buf, len))
            {
                return i;
            }
        }
    }

    return -1;
}

I dont use strcmp because buf doesnt have \0 at the end.


问:
Displaying custom Select field in Dokan Vendor Dashboard
This is question have already been asked here How Add Custom Meta Fields to Dokan in New Product

But no one answered that question. What I am trying to achieve is following:

Need to display custom field in Dokan Vendor Dashboard, plugin author have answer with this "You have to customize Dokan plugin to add an extra field on the product upload form. Please open dokan-lite/templates/products/new-product.php and in this file, you have to add an extra field. As we do not provide support to customize our plugin for that reason, I am unable to provide more specific instruction :)"

I have created custom field already using Fields Factory Plugin and it's displaying fine in Add Single Product page.

But I am unable to add that field in Dokan Plugin screenshot below for the location.

答: You need to override your dokan plugin templates. First, you need to create 'dokan' folder in the root of your active theme, after that, you need to find dokan template file in /plugins/dokan/templates/ and recreate it in your theme folder and add additional field. After that you need to save your new variable via update_user_meta function in functions.php</p>


答:
```<code>sizeof animals / sizeof animals[0]
</code>```

Returns the number of elements in the array.

And also you can use strlen() to get length of each of the elements of the array.

From standard §7.24.6.3

The strlen function returns the number of characters that precede
  the terminating null character.

Also sizeof is an operator.

From standard §6.5.3.4

Another use of the sizeof operator is to compute the number of
  elements in an array:

```<code>     sizeof array / sizeof array[0]
</code>```

Title: Find out string array lengthand each string length

Body:
sizeof animals / sizeof animals[0]

Returns the number of elements in the array.

And also you can use strlen() to get length of each of the elements of the array.

From standard §7.24.6.3

The strlen function returns the number of characters that precede
  the terminating null character.

Also sizeof is an operator.

From standard §6.5.3.4

Another use of the sizeof operator is to compute the number of
  elements in an array:

     sizeof array / sizeof array[0]


问:
Getting current Cart Id in Bigcommerce
So, I am using the cart API of Bigcommerce for adding items to the cart from a different domain which is working fine. However, when I try to repeat adding other items to the same cart it does not work. So, is there a way I can get the cart ID for an instance so that I can update my items to the existing cart?

答: When you created your first item, the response will include Cart ID. Use this Cart ID to add more items to the same cart.</p>

Title: Getting current Cart Id in Bigcommerce


问:
How to convert Bitmap to HBITMAP with alpha via Bitmap::GetHBITMAP?
I need to draw PNG images with transparency. I use GDI, GDI+, and WinApi.

To load and draw images, I always used GDI+, but now I'm using more "native" GDI algorithms (StretchBlt, etc).

The problem is that GDI can't load PNG. I searched the internet and found 2 ways:

loading via GDI+

using WIC.

WIC seems to be too difficult (but what did I expect?), so I choose the first one.

It's easy to load a PNG image using GDI+, just create a Bitmap object passing the file path to the constructor, then call the  getHBITMAP() method to receive an HBITMAP handle, and that's all.

The problem is that the HBITMAP produced by Bitmap loses transparency.

I searched how to fix it. There are different ways - like passing Color::Black as first argument, etc. But it doesn't work.

So, how can I Ioad a PNG image and convert it to HBITMAP with transparency?

I don't use DrawImage method, because it's slow, GDI is faster

I pinned the code:

I understood my mistake: I have to blit hdc_mem to hdcc firstly, and then blit the image. I've did it, but i have a new problem¬_¬

I made a class to manage uploaded images, here the code:

```<code>class Imagee
{
HDC hdc; HBITMAP bm;
Imagee(HDC hdc, HBITMAP bm, another args)
{
this->hdc=CreateCompatibleDC(hdc);
this->bm=bm;
SelectObject(this->hdc,this->bm);
}
void draw(int hdcc, int x,int y, int cx, int cy)
{
**StretchBlt(this->hdc,0,0,cx,cy,hdcc,x,y,cx,cy,SRCCOPY); //I'VE ADDED THIS
SelectObject(this->hdc,this->bm); //AND THIS **

StretchBlt(this->hdcc,x,y,cx,cy,hdc,0,0,cx,cy,SRCCOPY);
};
};
Imagee *image;

void render()
{
for(;;)
{
//some draws

//Loading a bitmap via Gdi+, calling a GetHBITMAP function, HBITMAP variable named hbm

if(image==0)
image=new Imagee(hdc_mem, hbm, x, y etc..);

image->draw(hdc_mem, x, y etc..);

StretchBlt(hdc_main,0,0,1920,1080,hdc_mem,0,0,1920,1080,SRCCOPY);
}
</code>```

I have a black screen. It seems I can't call     SelectObject again, yes?

答:
From: https://ru.stackoverflow.com/questions/743530

```<code>class Imagee
{
   HDC hdc; HBITMAP bm;

   Imagee(HDC hdc, HBITMAP bm, another args)
   {
      this->hdc=CreateCompatibleDC(hdc);
      this->bm=bm;
      SelectObject(this->hdc,this->bm);
   }

   void draw(int hdcc, int x,int y, int cx, int cy)
   {
      BITMAP btm;
      GetObject(bm,sizeof(BITMAP),&btm);

      BLENDFUNCTION bf;
      //initialize bf
      AlphaBlend(hdcc,x,y,cx,cy,his->hdcc,0,0,btm.bmWidth,btm.bmHeight,bf);
   };
};
</code>```

Usage

```<code>Imagee *image;

void render()
{
   for(;;)
   {
      //here I am downloading via gdi+ bitmap, converting it to hbitmap, writing it to the variable HBITMAP hbm

      if(image==0)
         image = new Image(hdc_mem, hbm, x, y и т.д.);

      image->draw(hdc_mem, x, y и т.д.);

      StretchBlt(hdc_main,0,0,1920,1080,hdc_mem,0,0,1920,1080,SRCCOPY);
      //hdc_main главный дс, hdc_mem буфер
   }
}
</code>```

Body:
I need to draw PNG images with transparency. I use GDI, GDI+, and WinApi.

To load and draw images, I always used GDI+, but now I'm using more "native" GDI algorithms (StretchBlt, etc).

The problem is that GDI can't load PNG. I searched the internet and found 2 ways:

loading via GDI+

using WIC.

WIC seems to be too difficult (but what did I expect?), so I choose the first one.

It's easy to load a PNG image using GDI+, just create a Bitmap object passing the file path to the constructor, then call the  getHBITMAP() method to receive an HBITMAP handle, and that's all.

The problem is that the HBITMAP produced by Bitmap loses transparency.

I searched how to fix it. There are different ways - like passing Color::Black as first argument, etc. But it doesn't work.

So, how can I Ioad a PNG image and convert it to HBITMAP with transparency?

I don't use DrawImage method, because it's slow, GDI is faster

I pinned the code:

I understood my mistake: I have to blit hdc_mem to hdcc firstly, and then blit the image. I've did it, but i have a new problem¬_¬

I made a class to manage uploaded images, here the code:

class Imagee
{
HDC hdc; HBITMAP bm;
Imagee(HDC hdc, HBITMAP bm, another args)
{
this->hdc=CreateCompatibleDC(hdc);
this->bm=bm;
SelectObject(this->hdc,this->bm);
}
void draw(int hdcc, int x,int y, int cx, int cy)
{
**StretchBlt(this->hdc,0,0,cx,cy,hdcc,x,y,cx,cy,SRCCOPY); //I'VE ADDED THIS
SelectObject(this->hdc,this->bm); //AND THIS **

StretchBlt(this->hdcc,x,y,cx,cy,hdc,0,0,cx,cy,SRCCOPY);
};
};
Imagee *image;

void render()
{
for(;;)
{
//some draws

//Loading a bitmap via Gdi+, calling a GetHBITMAP function, HBITMAP variable named hbm

if(image==0)
image=new Imagee(hdc_mem, hbm, x, y etc..);

image->draw(hdc_mem, x, y etc..);

StretchBlt(hdc_main,0,0,1920,1080,hdc_mem,0,0,1920,1080,SRCCOPY);
}

I have a black screen. It seems I can't call     SelectObject again, yes?

Body:
From: https://ru.stackoverflow.com/questions/743530

class Imagee
{
   HDC hdc; HBITMAP bm;

   Imagee(HDC hdc, HBITMAP bm, another args)
   {
      this->hdc=CreateCompatibleDC(hdc);
      this->bm=bm;
      SelectObject(this->hdc,this->bm);
   }

   void draw(int hdcc, int x,int y, int cx, int cy)
   {
      BITMAP btm;
      GetObject(bm,sizeof(BITMAP),&btm);

      BLENDFUNCTION bf;
      //initialize bf
      AlphaBlend(hdcc,x,y,cx,cy,his->hdcc,0,0,btm.bmWidth,btm.bmHeight,bf);
   };
};

Usage

Imagee *image;

void render()
{
   for(;;)
   {
      //here I am downloading via gdi+ bitmap, converting it to hbitmap, writing it to the variable HBITMAP hbm

      if(image==0)
         image = new Image(hdc_mem, hbm, x, y и т.д.);

      image->draw(hdc_mem, x, y и т.д.);

      StretchBlt(hdc_main,0,0,1920,1080,hdc_mem,0,0,1920,1080,SRCCOPY);
      //hdc_main главный дс, hdc_mem буфер
   }
}

ContentLicense: CC BY-SA 4.0


问:
React Router v4 - How to prevent redirect loops?
What I'm trying to accomplish is to have my App component redirect to the "/login" route if the state's uid is null. The redirect works correctly and will always redirect you to "/login" if there is a null uid, however the problem is it doesn't stop redirecting once you're on the "/login" route.

The error being thrown is:

Warning: You tried to redirect to the same route you're currently on: "/login"

One last constraint is I need the uid to be null until after a login event fires from the LoginScreen component. So the user needs to be able to view the "/login" route with a null uid in the top-level App component.

My code is as follows:

```<code>class App extends Component {
  constructor() {
    super();
    this.state = {
      uid: null
    }
  }
  render() {
    // Redirect to login if no user
    if (this.state.uid == null) {
      return (
        <Router>
          <Redirect to="/login" />
        </Router>
      );
    }

    return (
      <Router>
        <div>
          <Route path="/login" component={LoginScreen} />
          <Route path="/dashboard" component={DashboardScreen} />
          <Route path="/profile" component={ProfileScreen} />
        </div>
      </Router>
    );
  }
}
</code>```

I hope I explained the situation well. Thanks in advance!

答:
Its because when it redirects to /login it goes from '/' i.e App component and render function calls again which indeed redirects to /login and goes in the loop so on.
So instead to prevent this update the state in login component and pass it to the parent component.

So if you are not using any store like redux, just set the state in the window.localStorage.

Body:
What I'm trying to accomplish is to have my App component redirect to the "/login" route if the state's uid is null. The redirect works correctly and will always redirect you to "/login" if there is a null uid, however the problem is it doesn't stop redirecting once you're on the "/login" route.

The error being thrown is:

Warning: You tried to redirect to the same route you're currently on: "/login"

One last constraint is I need the uid to be null until after a login event fires from the LoginScreen component. So the user needs to be able to view the "/login" route with a null uid in the top-level App component.

My code is as follows:

class App extends Component {
  constructor() {
    super();
    this.state = {
      uid: null
    }
  }
  render() {
    // Redirect to login if no user
    if (this.state.uid == null) {
      return (
        <Router>
          <Redirect to="/login" />
        </Router>
      );
    }

    return (
      <Router>

          <Route path="/login" component={LoginScreen} />
          <Route path="/dashboard" component={DashboardScreen} />
          <Route path="/profile" component={ProfileScreen} />

      </Router>
    );
  }
}

I hope I explained the situation well. Thanks in advance!


问:
NetSuite: Populate custom item field value on transaction custom column field
I have 3 free-text custom fields on inventory item record. they contain different information based on location so my fields names are "XXXX Location1", "XXXX Location2" and "XXXX Location3". Across all transactions in the system we need to populate the information in a custom column field of these 3 fields based on the main location we choose on that transaction.

For example if on an Invoice the Main location is Location1 then our line custom column field should show information from "XXXX Location1" when user choose that item on the line; if Main location is Location2 on that Invoice then the line custom column field should show information from "XXXX Location2" when select that item on the line.

I understand this needs to be done thru scripts but i don't know how to write the script, could someone help?

Appreciate!!!

答:
You don't need a script for that.
On the colmn field, set the field to be a formula.
In the formula, write the followin statement(change to real location names and real item custom field ids):</p>

```<code>Case  {location}
When "location1 name" then {item.custitem... }
When "location2 name" then {item.custitem.. }
When "location3 name" then {item.custitem...}
End
</code>```

Body:
You don't need a script for that.
On the colmn field, set the field to be a formula.
In the formula, write the followin statement(change to real location names and real item custom field ids):

Case  {location}
When "location1 name" then {item.custitem... }
When "location2 name" then {item.custitem.. }
When "location3 name" then {item.custitem...}
End


问:
Why and how to fix? IIS Express "The specified port is in use"
We know a random port number is assigned to a web application in Visual Studio. It works fine in my office desktop. But when I pull the code onto my laptop (from VisualStudio.com) and run the web app. I got a message, saying,

The specified port is in use

Port 10360 is already being used by another application.

Recommendations

Try switching to port other than 10360 and higher than 1024.

Stop the application that is using port 10360.

I can fix it using Recommendation #1 by changing the port into something else like 13333. But I am very curious what happened to port 10360. How can I check what application is using port 10360? How can I stop that application?

答: Running visual studio in administrative mode solved my issue</p>


问:
How to sets the process title in Go?
How to sets the process title in Go?
Such as node.js </p>

```<code>process.title=""
</code>```

答:
I don't think there is any currently. As its implementation would be OS dependent. Nodejs did it through libuv which on linux, it uses prctl syscall with PR_SET_NAME see source code.

You can accomplish the same result using the syscall package. And make sure you suffix your go source code with _linux as it would be OS dependant code.

Similar question with answer here

Title: How to sets the process title in Go?

Body:
How to sets the process title in Go?
Such as node.js

process.title=""


问:
Unable to execute file_get_contents in component
I am trying to insert the data from file into database using file_get_contents through jobline component. But i am unable to execute the function inside the component when i had written the code outside the joomla it is working fine below is the working code. Can anyone suggest me what should i do?</p>

答: Go on are there mechanisms, to disable file_get_contents() function working?</p>

ContentLicense: CC BY-SA 2.5


问:
Xamarin.Forms Entry.Height is bigger than Label.Height
I have a Xamarin.Forms grid that I'm setting up and I've noticed that the Entry fields are a lot higher (3 - 4 times) than label fields. I can't see any obvious reason why this would be the case.

```<code><Grid RowSpacing="0" ColumnSpacing="0">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>

    <Label Grid.Row="0" Grid.Column="0" Text="G/C" FontSize="Small"/>
    <Entry Grid.Row="1" Grid.Column="0" FontSize="Small" BackgroundColor="Red"/>
</Grid>
</code>```

This results in something like this (on the default Android Emulator, installed 2 days ago);

Does anyone have any suggestions as to why the Entry height is so much bigger and what I can do to reduce it (obviously HeightRequest, but I'd rather avoid if possible)?

答:
Based on your comments here is a suggestion to do what you want in XAML. You can bind Entry.HeightRequest to Label.Height to avoid setting it manually.

```<code><Grid RowSpacing="0" ColumnSpacing="0">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>

    <Label Grid.Row="0" Grid.Column="0" Text="G/C" FontSize="Small" x:Name="MyLabel" />
    <Entry Grid.Row="1" Grid.Column="0" FontSize="Small" BackgroundColor="Red" HeightRequest="{Binding Source={x:Reference MyLabel}, Path=Height}"/>
</Grid>
</code>```

Body:
I have a Xamarin.Forms grid that I'm setting up and I've noticed that the Entry fields are a lot higher (3 - 4 times) than label fields. I can't see any obvious reason why this would be the case.

<Grid RowSpacing="0" ColumnSpacing="0">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>

    <Entry Grid.Row="1" Grid.Column="0" FontSize="Small" BackgroundColor="Red"/>
</Grid>

This results in something like this (on the default Android Emulator, installed 2 days ago);

Does anyone have any suggestions as to why the Entry height is so much bigger and what I can do to reduce it (obviously HeightRequest, but I'd rather avoid if possible)?

Body:
Based on your comments here is a suggestion to do what you want in XAML. You can bind Entry.HeightRequest to Label.Height to avoid setting it manually.

<Grid RowSpacing="0" ColumnSpacing="0">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>

    <Label Grid.Row="0" Grid.Column="0" Text="G/C" FontSize="Small" x:Name="MyLabel" />
    <Entry Grid.Row="1" Grid.Column="0" FontSize="Small" BackgroundColor="Red" HeightRequest="{Binding Source={x:Reference MyLabel}, Path=Height}"/>
</Grid>


问:
JS & CSS - How to Randomly generate a colour and have it apply to an element on an event?
I know this question has been asked before, but I can never seem to find it in the right context.

For my website, I want, upon loading the page, a random colour to be generated (1 of the rainbow). Then, whenever I hover over a div, (it is one that is repeated), that div(s) will become the specified colour.

```<code>.shape:hover {
        background-color: green;
        transition-duration: 0.1s;
    }
</code>```

That's the CSS. The current background colour is green, but that's the property I want to be randomly selected upon the page loading. Thanks.

答:
Using jquery something like this can be done.

$(document).ready(function() {
  var colors = ["#ff0000", "#0000ff", "#00ff00"];
  var rand = Math.floor(Math.random() * colors.length);
  $('.bgcolor').css("background-color", colors[rand]);
  $('div').css("color", colors[rand]);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bgcolor{
  height: 500px;
  width: 500px;

}</code>```

```

Body:
I know this question has been asked before, but I can never seem to find it in the right context.

For my website, I want, upon loading the page, a random colour to be generated (1 of the rainbow). Then, whenever I hover over a div, (it is one that is repeated), that div(s) will become the specified colour.

.shape:hover {
        background-color: green;
        transition-duration: 0.1s;
    }

That's the CSS. The current background colour is green, but that's the property I want to be randomly selected upon the page loading. Thanks.

Body:
Using jquery something like this can be done.

$(document).ready(function() {
  var colors = ["#ff0000", "#0000ff", "#00ff00"];
  var rand = Math.floor(Math.random() * colors.length);
  $('.bgcolor').css("background-color", colors[rand]);
  $('div').css("color", colors[rand]);
});

.bgcolor{
  height: 500px;
  width: 500px;

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<body>
  <div class="bgcolor"></div>
</body>


问:
store an array of files in an already existing session array
i have a session array called $_SESSION['CART'] i already use it to store details of cart items
now i want to store multiple uploaded files names of files that user uploads while adding this item to cart as part of the session cart.i want to store them with key files. this is what am doing but its not working. is there a way for me to achieve this </p>

```<code>$_SESSION['cart'][] =
    array(
            'id'=>$productid,
            'quantity'=>$quantity,
            'detail'=>$detail,
            'files'=>$files
    );
</code>```

答:
You can't use $_SESSION array like this way, try to use buffer variable to prepare data for session:</p>

```<code>$cart = $_SESSION['cart'];
$cart[] = array(
        'id'       => $productid,
        'quantity' => $quantity,
        'detail'   => $detail,
        'files'    => $files
);
$_SESSION['cart'] = $cart;
</code>```

Body:
i have a session array called $_SESSION['CART'] i already use it to store details of cart items
now i want to store multiple uploaded files names of files that user uploads while adding this item to cart as part of the session cart.i want to store them with key files. this is what am doing but its not working. is there a way for me to achieve this

$_SESSION['cart'][] =
    array(
            'id'=>$productid,
            'quantity'=>$quantity,
            'detail'=>$detail,
            'files'=>$files
    );

Body:
You can't use $_SESSION array like this way, try to use buffer variable to prepare data for session:

$cart = $_SESSION['cart'];
$cart[] = array(
        'id'       => $productid,
        'quantity' => $quantity,
        'detail'   => $detail,
        'files'    => $files
);
$_SESSION['cart'] = $cart;


问:
Error during installing of module in odoo
I am currently encountering an error in Odoo. I am using Odoo v.10 and I am looking for loan management module for FREE and I found a module in lower version which is 8 and when I'm installing the module, it gives me an error. Why is this?

but I checked it and the model name is perfectly declared on its dunder init and the views are declared on its manifest or dunder openerp.

答: In odoo v10 using new api. So you must be upgrade that module v8 to v10. As per your screen shot this code are written in V8 and using old API. In v10, osv package is not available, also i think you don't use any cr, self, context type parameter in funtion, also don't use self.pool.get(). You should be use self.env[] for v10.


问:
fwrite, fread - problems with fread
I have following code:

```<code>int main()
{
    char* pedal[20];
    char* pedal2[20];
    for (int i = 0; i < 20; i++)
    {
        pedal[i] = "Pedal";
    }
    FILE* plik;
    plik = fopen("teraz.txt","wb");
    for (int i = 0; i < 20; i++)
    {
       fwrite(pedal[i],strlen(pedal[i]),1,plik);
    }
    system("pause");
    fclose(plik);
    plik = fopen("teraz.txt","rb");
    for (int i = 0; i < 20; i++)
    {
        fread(pedal2[i],5,1,plik); //I know for now that every element has 5 bytes
    }
    for (int i = 0; i < 20; i++)
    {
        std::cout << pedal2[i] << std::endl;
    }
    fclose(plik);
    system("pause");
    return 0;
}
</code>```

It's crashing at reading and second question let's assume that I have structure where I keep like integers, floats and also char* array and how can I easly write whole structure to the file? Normal fwrite with sizeof structure is not working

答:
You can't read into pedal2 without first having allocated space for it.

You need something like this:

```<code>for (int i = 0; i < 20; ++i) {
    pedal[i] = malloc(100); //allocate some space
}
</code>```

Title: fwrite, fread - problems with fread

Body:
I have following code:

int main()
{
    char* pedal[20];
    char* pedal2[20];
    for (int i = 0; i < 20; i++)
    {
        pedal[i] = "Pedal";
    }
    FILE* plik;
    plik = fopen("teraz.txt","wb");
    for (int i = 0; i < 20; i++)
    {
       fwrite(pedal[i],strlen(pedal[i]),1,plik);
    }
    system("pause");
    fclose(plik);
    plik = fopen("teraz.txt","rb");
    for (int i = 0; i < 20; i++)
    {
        fread(pedal2[i],5,1,plik); //I know for now that every element has 5 bytes
    }
    for (int i = 0; i < 20; i++)
    {
        std::cout << pedal2[i] << std::endl;
    }
    fclose(plik);
    system("pause");
    return 0;
}

It's crashing at reading and second question let's assume that I have structure where I keep like integers, floats and also char* array and how can I easly write whole structure to the file? Normal fwrite with sizeof structure is not working

Body:
You can't read into pedal2 without first having allocated space for it.

You need something like this:

for (int i = 0; i < 20; ++i) {
    pedal[i] = malloc(100); //allocate some space
}


问:
How set button position relatively in code behind on WPF
In WPF , i create button on canvas. like this.

```<code>private void DrawBtnTag( List<ValPosCrt> tagPos)
    {
        int posNum = tagPos.Count;

        StackPanel[] temp = new StackPanel[ posNum ];
        Button[] btn = new Button[posNum];

        for ( int i = 0 ; i < posNum ; i++ )
        {
            var btntemp = CheckButton(i);
            Canvas.SetLeft( btntemp , tagPos [ i ].X );
            Canvas.SetTop( btntemp , tagPos [ i ].Y );
            cvsMap.Children.Add( btntemp );
            btn [ i ] = btntemp;
        }
    }

    private Button CheckButton( int i ) // done
    {
        var btn = new Button();
        btn.Name = "btn" + i.ToString();
        btn.Width = 20;
        btn.Height = 20;
        btn.VerticalAlignment = VerticalAlignment.Stretch;
        btn.HorizontalAlignment = HorizontalAlignment.Stretch;
        btn.Click += ClickIdx;
        return btn;
    }
</code>```

but when i run this code and expand application size, button position is not updated.

Second image is expanded application size and small button that i created is act anchored object.
 I want to this button follow background Image.

Xaml code is just only this

```<code>     <DockPanel Name="dckPanel" Margin="5" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
    <Border CornerRadius="6" BorderThickness="2" BorderBrush="RoyalBlue" DockPanel.Dock="Top" >
        <Grid>
            <Canvas Name="cvsMap" Grid.Column="0" ClipToBounds="True" Margin="15">
                <Canvas.Background>
                    <ImageBrush x:Name="imgMap" Stretch="Uniform"  RenderOptions.BitmapScalingMode="Fant"   />
                </Canvas.Background>
            </Canvas>
        </Grid>
    </Border>
</DockPanel>
</code>```

How can i fix this?

** update : Add TestCode , Fix Xaml Code.

This is test code for wpf project

Code Behind -

```<code>public partial class MainWindow : Window
</code>```

{
    public MainWindow()
    {
        InitializeComponent();

```<code>    List<Point> inputdata = new List<Point>();
    inputdata.Add( new Point( 250 , 250 ) );
    inputdata.Add( new Point( 250 , 300 ) );
    inputdata.Add( new Point( 300 , 250 ) );
    inputdata.Add( new Point( 250 , 200 ) );
    inputdata.Add( new Point( 200 , 250 ) );
    DrawBtnTag( inputdata );

    imgMap.ImageSource = createImg();
}

private void DrawBtnTag( List<Point> tagPos ) // done
{
    int posNum = tagPos.Count;

    StackPanel[] temp = new StackPanel[ posNum ];
    Button[] btn = new Button[posNum];

    for ( int i = 0 ; i < posNum ; i++ )
    {
        var btntemp = CheckButton(i);
        Canvas.SetLeft( btntemp , tagPos [ i ].X );
        Canvas.SetTop( btntemp , tagPos [ i ].Y );
        cvsMap.Children.Add( btntemp );
        btn [ i ] = btntemp;
    }
}

private Button CheckButton( int i ) // done
{
    var btn = new Button();
    btn.Name = "btn" + i.ToString();
    btn.Width = 20;
    btn.Height = 20;
    btn.VerticalAlignment = VerticalAlignment.Stretch;
    btn.HorizontalAlignment = HorizontalAlignment.Stretch;
    return btn;
}

public BitmapSource createImg()
{
    List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>();
    colors.Add( System.Windows.Media.Colors.Red );
    colors.Add( System.Windows.Media.Colors.Blue );

    BitmapPalette palette = new BitmapPalette(colors);
    System.Windows.Media.PixelFormat pf =
        System.Windows.Media.PixelFormats.Indexed1;
    int width = 128;
    int height = width;
    int stride = width/pf.BitsPerPixel;

    byte[] pixels = new byte[height*stride];

    for ( int i = 0 ; i < height * stride ; ++i )
    {
        if ( i < height * stride / 2 )
        {
            pixels [ i ] = 0x00;
        }
        else
        {
            pixels [ i ] = 0xff;
        }
    }

    return  BitmapSource.Create(
        width,
        height,
        96,
        96,
        pf,
        palette,
        pixels,
        stride);

}
</code>```

}

xaml code -
=> same as xaml code abaove. just put that dockpanel after window. like this window> .. here ../window>

答:
The answer might be a bit long but it should work without modifications.

Basically:

I added a SizeChanged event for your Canvas

It computes the size and position (old and new) for your background image

For each button, it computes the relative position (old and new) from the background image and modifies it

There is a lot of things around aspect ratio (to ensure a proper behavior), and this code can work only with a uniform behavior (Stretch="Uniform")

Here is the modified XAML code:

```<code><Canvas Name="cvsMap" Grid.Column="0" ClipToBounds="True" Margin="15" SizeChanged="cvsMap_SizeChanged">
    <Canvas.Background>
        <ImageBrush x:Name="imgMap" Stretch="Uniform"  RenderOptions.BitmapScalingMode="Fant"   />
    </Canvas.Background>
</Canvas>
</code>```

And then the code behind (copy/paste after your createImg function):

```<code>    private void cvsMap_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        double ratio = imgMap.ImageSource.Width / imgMap.ImageSource.Height;

        foreach (Control ctrl in cvsMap.Children)
        {
            if (ctrl is Button)
            {
                newBtnPosition((Button)ctrl, ratio, e);
            }
        }
    }
    /// <summary>
    /// Assign a new position to a ctrl contained into a canvas
    /// </summary>
    /// <param name="ctrl">control to modify</param>
    /// <param name="ratio">ratio of the reference element</param>
    /// <param name="e">SizeChanged of the container</param>
    private void newBtnPosition(Control ctrl, double ratio, SizeChangedEventArgs e)
    {

        //Everythong is computed according to the reference element (ImageBrush)
        Size oldImgSize, newImgSize;

        //Avoid dividing by 0
        if (e.PreviousSize.Width * e.PreviousSize.Height * e.NewSize.Width * e.NewSize.Height == 0) { return; }

        oldImgSize = RefSize(ratio, e.PreviousSize);
        newImgSize = RefSize(ratio, e.NewSize);

        Point oldImgPos, newImgPos;
        oldImgPos = new Point((e.PreviousSize.Width - oldImgSize.Width) / 2, (e.PreviousSize.Height - oldImgSize.Height) / 2);
        newImgPos = new Point((e.NewSize.Width - newImgSize.Width) / 2, (e.NewSize.Height - newImgSize.Height) / 2);

        //Retrieve the position of the control according to the ref element
        Point ctrlPos = new Point((double)ctrl.GetValue(Canvas.LeftProperty) - oldImgPos.X,
                                 (double)ctrl.GetValue(Canvas.TopProperty) - oldImgPos.Y);

        //Compute the new position according to the reference element
        ctrlPos.X*=newImgSize.Width / oldImgSize.Width;
        ctrlPos.Y *= newImgSize.Height / oldImgSize.Height;

        //Assign the new position according to the Canvas
        ctrl.SetValue(Canvas.LeftProperty, ctrlPos.X + newImgPos.X);
        ctrl.SetValue(Canvas.TopProperty, ctrlPos.Y + newImgPos.Y);
    }

    /// <summary>
    /// Compute a element size, given a aspect ratio, a container size, and a Stretch="Uniform" behavior
    /// </summary>
    /// <param name="ratio">aspect ratio of the control</param>
    /// <param name="containerSize">container size of the control</param>
    /// <returns>new size</returns>
    private Size RefSize(double ratio, Size containerSize)
    {
        double cH, cW;
        cW = containerSize.Width;
        cH = containerSize.Height;

        if (cH * cW == 0) { return new Size(0, 0); }

        if (cW / cH  > ratio)
        {
            return new Size(cH * ratio, cH);
        }
        else
        {
            return new Size(cW, cW/ratio);
        }

    }
</code>```

Body:
In WPF , i create button on canvas. like this.

private void DrawBtnTag( List<ValPosCrt> tagPos)
    {
        int posNum = tagPos.Count;

        StackPanel[] temp = new StackPanel[ posNum ];
        Button[] btn = new Button[posNum];

        for ( int i = 0 ; i < posNum ; i++ )
        {
            var btntemp = CheckButton(i);
            Canvas.SetLeft( btntemp , tagPos [ i ].X );
            Canvas.SetTop( btntemp , tagPos [ i ].Y );
            cvsMap.Children.Add( btntemp );
            btn [ i ] = btntemp;
        }
    }

    private Button CheckButton( int i ) // done
    {
        var btn = new Button();
        btn.Name = "btn" + i.ToString();
        btn.Width = 20;
        btn.Height = 20;
        btn.VerticalAlignment = VerticalAlignment.Stretch;
        btn.HorizontalAlignment = HorizontalAlignment.Stretch;
        btn.Click += ClickIdx;
        return btn;
    }

but when i run this code and expand application size, button position is not updated.

Second image is expanded application size and small button that i created is act anchored object.
 I want to this button follow background Image.

Xaml code is just only this

     <DockPanel Name="dckPanel" Margin="5" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
    <Border CornerRadius="6" BorderThickness="2" BorderBrush="RoyalBlue" DockPanel.Dock="Top" >
        <Grid>
            <Canvas Name="cvsMap" Grid.Column="0" ClipToBounds="True" Margin="15">
                <Canvas.Background>
                    <ImageBrush x:Name="imgMap" Stretch="Uniform"  RenderOptions.BitmapScalingMode="Fant"   />
                </Canvas.Background>
            </Canvas>
        </Grid>
    </Border>
</DockPanel>

How can i fix this?

** update : Add TestCode , Fix Xaml Code.

This is test code for wpf project

Code Behind -

public partial class MainWindow : Window

{
    public MainWindow()
    {
        InitializeComponent();

    List<Point> inputdata = new List<Point>();
    inputdata.Add( new Point( 250 , 250 ) );
    inputdata.Add( new Point( 250 , 300 ) );
    inputdata.Add( new Point( 300 , 250 ) );
    inputdata.Add( new Point( 250 , 200 ) );
    inputdata.Add( new Point( 200 , 250 ) );
    DrawBtnTag( inputdata );

    imgMap.ImageSource = createImg();
}

private void DrawBtnTag( List<Point> tagPos ) // done
{
    int posNum = tagPos.Count;

    StackPanel[] temp = new StackPanel[ posNum ];
    Button[] btn = new Button[posNum];

    for ( int i = 0 ; i < posNum ; i++ )
    {
        var btntemp = CheckButton(i);
        Canvas.SetLeft( btntemp , tagPos [ i ].X );
        Canvas.SetTop( btntemp , tagPos [ i ].Y );
        cvsMap.Children.Add( btntemp );
        btn [ i ] = btntemp;
    }
}

private Button CheckButton( int i ) // done
{
    var btn = new Button();
    btn.Name = "btn" + i.ToString();
    btn.Width = 20;
    btn.Height = 20;
    btn.VerticalAlignment = VerticalAlignment.Stretch;
    btn.HorizontalAlignment = HorizontalAlignment.Stretch;
    return btn;
}

public BitmapSource createImg()
{
    List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>();
    colors.Add( System.Windows.Media.Colors.Red );
    colors.Add( System.Windows.Media.Colors.Blue );

    BitmapPalette palette = new BitmapPalette(colors);
    System.Windows.Media.PixelFormat pf =
        System.Windows.Media.PixelFormats.Indexed1;
    int width = 128;
    int height = width;
    int stride = width/pf.BitsPerPixel;

    byte[] pixels = new byte[height*stride];

    for ( int i = 0 ; i < height * stride ; ++i )
    {
        if ( i < height * stride / 2 )
        {
            pixels [ i ] = 0x00;
        }
        else
        {
            pixels [ i ] = 0xff;
        }
    }

    return  BitmapSource.Create(
        width,
        height,
        96,
        96,
        pf,
        palette,
        pixels,
        stride);

}

}

xaml code -
=> same as xaml code abaove. just put that dockpanel after window. like this window> .. here ../window>

Body:
The answer might be a bit long but it should work without modifications.

Basically:

I added a SizeChanged event for your Canvas

It computes the size and position (old and new) for your background image

For each button, it computes the relative position (old and new) from the background image and modifies it

There is a lot of things around aspect ratio (to ensure a proper behavior), and this code can work only with a uniform behavior (Stretch="Uniform")

Here is the modified XAML code:

<Canvas Name="cvsMap" Grid.Column="0" ClipToBounds="True" Margin="15" SizeChanged="cvsMap_SizeChanged">
    <Canvas.Background>
        <ImageBrush x:Name="imgMap" Stretch="Uniform"  RenderOptions.BitmapScalingMode="Fant"   />
    </Canvas.Background>
</Canvas>

And then the code behind (copy/paste after your createImg function):

    private void cvsMap_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        double ratio = imgMap.ImageSource.Width / imgMap.ImageSource.Height;

        foreach (Control ctrl in cvsMap.Children)
        {
            if (ctrl is Button)
            {
                newBtnPosition((Button)ctrl, ratio, e);
            }
        }
    }
    /// <summary>
    /// Assign a new position to a ctrl contained into a canvas
    /// </summary>
    /// <param name="ctrl">control to modify</param>
    /// <param name="ratio">ratio of the reference element</param>
    /// <param name="e">SizeChanged of the container</param>
    private void newBtnPosition(Control ctrl, double ratio, SizeChangedEventArgs e)
    {

        //Everythong is computed according to the reference element (ImageBrush)
        Size oldImgSize, newImgSize;

        //Avoid dividing by 0
        if (e.PreviousSize.Width * e.PreviousSize.Height * e.NewSize.Width * e.NewSize.Height == 0) { return; }

        oldImgSize = RefSize(ratio, e.PreviousSize);
        newImgSize = RefSize(ratio, e.NewSize);

        Point oldImgPos, newImgPos;
        oldImgPos = new Point((e.PreviousSize.Width - oldImgSize.Width) / 2, (e.PreviousSize.Height - oldImgSize.Height) / 2);
        newImgPos = new Point((e.NewSize.Width - newImgSize.Width) / 2, (e.NewSize.Height - newImgSize.Height) / 2);

        //Retrieve the position of the control according to the ref element
        Point ctrlPos = new Point((double)ctrl.GetValue(Canvas.LeftProperty) - oldImgPos.X,
                                 (double)ctrl.GetValue(Canvas.TopProperty) - oldImgPos.Y);

        //Compute the new position according to the reference element
        ctrlPos.X*=newImgSize.Width / oldImgSize.Width;
        ctrlPos.Y *= newImgSize.Height / oldImgSize.Height;

        //Assign the new position according to the Canvas
        ctrl.SetValue(Canvas.LeftProperty, ctrlPos.X + newImgPos.X);
        ctrl.SetValue(Canvas.TopProperty, ctrlPos.Y + newImgPos.Y);
    }

    /// <summary>
    /// Compute a element size, given a aspect ratio, a container size, and a Stretch="Uniform" behavior
    /// </summary>
    /// <param name="ratio">aspect ratio of the control</param>
    /// <param name="containerSize">container size of the control</param>
    /// <returns>new size</returns>
    private Size RefSize(double ratio, Size containerSize)
    {
        double cH, cW;
        cW = containerSize.Width;
        cH = containerSize.Height;

        if (cH * cW == 0) { return new Size(0, 0); }

        if (cW / cH  > ratio)
        {
            return new Size(cH * ratio, cH);
        }
        else
        {
            return new Size(cW, cW/ratio);
        }

    }


问:
Modify variables inside self-invoking functions
I have been hung up on this for a while. I am wondering if there is any way to modify a variable inside an anonymous self-invoking function from outside of its scope?

Here's some sample code to help clarify:

```<code>(function(x, y, z) {
var annoyances = "normal functions";
console.log(annoyances);
})(window, document, undefined);
</code>```

What I am hoping to do is to change the value of annoyances to:

```<code>annoyances = "self-invoking functions";
</code>```

答:
Functions create a scope for the variables, so the variables are not visible outside of it. But you can do vice versa. Create a variable outside of the self invoked function and use it inside it. Functions can access the variables in the scope where it was defined.</p>

```<code>let annoyances;

(function(x, y, z) {
   annoyances = "normal functions";
   console.log(annoyances);
})(window, document, undefined);
</code>```

Body:
I have been hung up on this for a while. I am wondering if there is any way to modify a variable inside an anonymous self-invoking function from outside of its scope?

Here's some sample code to help clarify:

(function(x, y, z) {
var annoyances = "normal functions";
console.log(annoyances);
})(window, document, undefined);

What I am hoping to do is to change the value of annoyances to:

annoyances = "self-invoking functions";

Body:
Functions create a scope for the variables, so the variables are not visible outside of it. But you can do vice versa. Create a variable outside of the self invoked function and use it inside it. Functions can access the variables in the scope where it was defined.

let annoyances;

(function(x, y, z) {
   annoyances = "normal functions";
   console.log(annoyances);
})(window, document, undefined);


问:
JSX Component + dangerouslySetInnerHTML?
So I am having trouble implementing this scenario:

From the backend server, I am receving an html string, something along like this:

```<code><ul><li><strong>Title1</strong> <br/> <a class=\"title1" href="title1-link">Title 1</a></li><li><strong>Title2</strong> <a class="title2" href="/title2-link">Title 2</a>
</code>```

Normally, that would be fine when just using dangerouslySetInnerHTML.

However, around the a href tags in the html, I need to wrap those in component like so:

```<code><ModalLink href={'title'}>
    {Title}
</ModalLink>
</code>```

This is because when wrapping  the a tags, the component essentially adds functionality on creating a new child window.

I figured this is something you would need to implement on Regex, but I dont have the slightest idea where to begin.

答:
You can deconstruct and extract the necessary values from your html string with regex and then use JSX instead of dangerouslySetInnerHtml. This component shows how to render your sample html string.

```<code>import React, { Component } from 'react'

export default class App extends Component {
    render() {
        const html = `<ul><li><strong>Title1</strong><br/><a class="title1" href="/title1-link">Title 1</a></li><li><strong>Title2</strong><br/><a class="title2" href="/title2-link">Title 2</a></li></ul>`

        return (
            <div>
                <ul>
                {html.match(/(<li>.*?<\/li>)/g).map( li => {
                    const title =  li.match(/<strong>(.*?)<\/strong>/)[1]
                    const aTag = li.match(/<a.*?\/a>/)[0]
                    const aClass = aTag.match(/class="(.*?)"/)[1]
                    const href = aTag.match(/href="(.*?)"/)[1]
                    const aText = aTag.match(/>(.*?)</)[1]
                    return (
                        <li>
                            <strong>{title}</strong>
                            <br/>
                            <a className={aClass} href={href}>{aText}</a>
                        </li>
                    )
                })}
                </ul>
            </div>
        )
    }
}
</code>```

From there you can simply wrap the a tag in your ModalLink component. I'm not sure this is exactly how you want to do that, but here is an example.

```<code>return (
    <li>
        <strong>{title}</strong>
        <br/>
        <ModalLink href={href}>
            <a className={aClass} href={href}>{aText}</a>
        </ModalLink>
    </li>
)
</code>```

html.match(/(
.*?<\/li>)/g) matches each
...
 within the html string in an array, which can then be mapped. Then I extract the title, href, etc. out of each
...
 using captures (the part within parentheses), which can then be used in JSX. This answer provides more detail on the regular expressions used.

Body:
So I am having trouble implementing this scenario:

From the backend server, I am receving an html string, something along like this:

Title1
 Title 1

Title2 Title 2

Normally, that would be fine when just using dangerouslySetInnerHTML.

However, around the a href tags in the html, I need to wrap those in component like so:

<ModalLink href={'title'}>
    {Title}
</ModalLink>

This is because when wrapping  the a tags, the component essentially adds functionality on creating a new child window.

I figured this is something you would need to implement on Regex, but I dont have the slightest idea where to begin.

Body:
You can deconstruct and extract the necessary values from your html string with regex and then use JSX instead of dangerouslySetInnerHtml. This component shows how to render your sample html string.

import React, { Component } from 'react'

export default class App extends Component {
    render() {
        const html = `<ul><li><strong>Title1</strong><br/><a class="title1" href="/title1-link">Title 1</a></li><li><strong>Title2</strong><br/><a class="title2" href="/title2-link">Title 2</a></li></ul>`

        return (
            <div>
                <ul>
                {html.match(/(<li>.*?<\/li>)/g).map( li => {
                    const title =  li.match(/<strong>(.*?)<\/strong>/)[1]
                    const aTag = li.match(/<a.*?\/a>/)[0]
                    const aClass = aTag.match(/class="(.*?)"/)[1]
                    const href = aTag.match(/href="(.*?)"/)[1]
                    const aText = aTag.match(/>(.*?)</)[1]
                    return (
                        <li>
                            <strong>{title}</strong>
                            <br/>
                            <a className={aClass} href={href}>{aText}</a>
                        </li>
                    )
                })}
                </ul>
            </div>
        )
    }
}

From there you can simply wrap the a tag in your ModalLink component. I'm not sure this is exactly how you want to do that, but here is an example.

return (
    <li>
        <strong>{title}</strong>
        <br/>
        <ModalLink href={href}>
            <a className={aClass} href={href}>{aText}</a>
        </ModalLink>
    </li>
)

html.match(/(<li>.*?<\/li>)/g) matches each <li>...</li> within the html string in an array, which can then be mapped. Then I extract the title, href, etc. out of each <li>...</li> using captures (the part within parentheses), which can then be used in JSX. This answer provides more detail on the regular expressions used.


问:
Qlik Sense and JWT authentication
I am trying to get Qlik Sense to work using JWT auth, instead of our current header based auth. Has anyone been successful with this? Would anyone who's gotten this working be able to help me out? Even a sample working example is fine. I can try to follow through the process there to get it to work in mine.

Server Version: November 2017 release

Note: I am still pretty a newbie to Qlik, so hoping for considerate answers.

答: You can check the example provided in enigma.js repo</p>

Title: Qlik Sense and JWT authentication


问:
stateChangeStart - AngularJS
I am working with $stateChangeStart for login.

In my site I have some pages where user can go when he is not logged.

I write this code for logout and for check access on some page.

But I have problem when user go to page about (there is no need for user validation)

```<code>$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            console.log('TS', toState, 'TP', toParams, 'FS', fromState, 'FP', fromParams)
            if (!$rootScope.currentUser) {
                console.log('NO USER')
                if (toState.name !== 'login') {
                    event.preventDefault();
                    console.log('SOME ROUTE');
                    $state.go("login");
                }
                else if (toState.name !== 'about' ) {
                    console.log("about no user")
                    $state.go("about");
                }

            }
        });
</code>```

Any idea how can I do that with $stateChangeStart

This with else if doesn't work.

Thanks!

答:
The best practice is to specify on each route (at config time) if it requires a login,

```<code>.state("users", {
   url: "/users",
   data: {
      requiresLogin: true
   }
})
</code>```

then you will able to check if the state requires login on each navigation, something like that:

```<code>$rootScope.$on('$stateChangeStart', (event, toState, toParams, fromState, fromParams, options) => {
    if(toState.data && toState.data.requiresLogin) {
       // validate the user here, if not valid navigate to Login
    }
});
</code>```

As a bonus, you can take advantage of data inheritance and specify a scope of routes that requires a login with an abstract state.

```<code>e.state("users", {
    abstract: true,
    url: "/users",
    data: {
        requiresLogin: true
    }
})
.state("users.main", {
    url: "/",
    template: '<users-main></users-main>'
})
.state("users.page2", {
    url: "/page2",
    template: '<users-page2></users-page2>'
})
</code>```

In the example above, each state that is a child state of users (has users. prefix at its name) will inherit the data prop, therefore will require login.

Title: stateChangeStart - AngularJS

Body:
I am working with $stateChangeStart for login.

In my site I have some pages where user can go when he is not logged.

I write this code for logout and for check access on some page.

But I have problem when user go to page about (there is no need for user validation)

$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            console.log('TS', toState, 'TP', toParams, 'FS', fromState, 'FP', fromParams)
            if (!$rootScope.currentUser) {
                console.log('NO USER')
                if (toState.name !== 'login') {
                    event.preventDefault();
                    console.log('SOME ROUTE');
                    $state.go("login");
                }
                else if (toState.name !== 'about' ) {
                    console.log("about no user")
                    $state.go("about");
                }

            }
        });

Any idea how can I do that with $stateChangeStart

This with else if doesn't work.

Thanks!

Body:
The best practice is to specify on each route (at config time) if it requires a login,

.state("users", {
   url: "/users",
   data: {
      requiresLogin: true
   }
})

then you will able to check if the state requires login on each navigation, something like that:

$rootScope.$on('$stateChangeStart', (event, toState, toParams, fromState, fromParams, options) => {
    if(toState.data && toState.data.requiresLogin) {
       // validate the user here, if not valid navigate to Login
    }
});

As a bonus, you can take advantage of data inheritance and specify a scope of routes that requires a login with an abstract state.

e.state("users", {
    abstract: true,
    url: "/users",
    data: {
        requiresLogin: true
    }
})
.state("users.main", {
    url: "/",
    template: '<users-main></users-main>'
})
.state("users.page2", {
    url: "/page2",
    template: '<users-page2></users-page2>'
})

In the example above, each state that is a child state of users (has users. prefix at its name) will inherit the data prop, therefore will require login.


问:
Reading two matrices
I have a text file with two matrices in the format shown in the figure, the figure is just an example the matrices size may vary.

please help me read the two matrices.

(the first and the second matrices are separated by a blank line)

1 2 3 4
5 6 7 8
0 1 5 6

5 6 9
6 4 3
9 7 5
9 8 0
```

答:
To parse a file to 2d matrices, you have to read file line by line, split a line to get member of matrix row, each time you meet blank line, add new matrix to matrices list.

Following code represent how to do it. int[][][] matrices stores all read matrices from file (of cause, this code does not validate file content, and is not optimized code, just show how to do)

```<code>int[][][] matrices = new int[][][] {}; //array of matrix
try (BufferedReader reader = new BufferedReader(
    new FileReader(new File("test.txt"))))
{
    String line;
    int index = 0; //current matrix
    while ((line = reader.readLine()) != null)
    {
        if (!line.trim().equals(""))
        {
            // parse line to int array
            String[] memb = line.split(" ");
            int[] arr = new int[memb.length];
            for (int i = 0; i < memb.length; i++)
                arr[i] = Integer.parseInt(memb[i]);

            // add new matrix
            if (index == matrices.length)
                matrices = Arrays.copyOf(matrices, matrices.length + 1);

            int[][] matrix = matrices[index];
            if (matrix == null)
                matrix = new int[][] {};

            // add int array to matrix (line)
            matrix = Arrays.copyOf(matrix, matrix.length + 1);
            matrix[matrix.length - 1] = arr;
            matrices[index] = matrix;
        }
        else
        {
            // flag to increase matrices size
            index++;
        }
    }
}

// test output
for (int i = 0; i < matrices.length; i++)
{
    for (int j = 0; j < matrices[i].length; j++)
    {
        for (int k = 0; k < matrices[i][j].length; k++)
        {
            System.out.print(matrices[i][j][k]);
            System.out.print(" ");
        }
        System.out.print("\r\n");
    }
    System.out.print("\r\n");
}
</code>```

Title: Reading two matrices

Body:
To parse a file to 2d matrices, you have to read file line by line, split a line to get member of matrix row, each time you meet blank line, add new matrix to matrices list.

Following code represent how to do it. int[][][] matrices stores all read matrices from file (of cause, this code does not validate file content, and is not optimized code, just show how to do)

int[][][] matrices = new int[][][] {}; //array of matrix
try (BufferedReader reader = new BufferedReader(
    new FileReader(new File("test.txt"))))
{
    String line;
    int index = 0; //current matrix
    while ((line = reader.readLine()) != null)
    {
        if (!line.trim().equals(""))
        {
            // parse line to int array
            String[] memb = line.split(" ");
            int[] arr = new int[memb.length];
            for (int i = 0; i < memb.length; i++)
                arr[i] = Integer.parseInt(memb[i]);

            // add new matrix
            if (index == matrices.length)
                matrices = Arrays.copyOf(matrices, matrices.length + 1);

            int[][] matrix = matrices[index];
            if (matrix == null)
                matrix = new int[][] {};

            // add int array to matrix (line)
            matrix = Arrays.copyOf(matrix, matrix.length + 1);
            matrix[matrix.length - 1] = arr;
            matrices[index] = matrix;
        }
        else
        {
            // flag to increase matrices size
            index++;
        }
    }
}

// test output
for (int i = 0; i < matrices.length; i++)
{
    for (int j = 0; j < matrices[i].length; j++)
    {
        for (int k = 0; k < matrices[i][j].length; k++)
        {
            System.out.print(matrices[i][j][k]);
            System.out.print(" ");
        }
        System.out.print("\r\n");
    }
    System.out.print("\r\n");
}


问:
Zero number is always omitted in day section of Kendo-datepicker
I am trying to input the following date:

```<code>5/01/2017
</code>```

But the first zero of days is always omitted by kendo-date-picker and my date becomes the following:

```<code>5/12/17
</code>```

HTML:

```<code>        <kendo-datepicker
            [min]="min"
            [max]="max"
            [(ngModel)]="value"
            #dateModel="ngModel"
        ></kendo-datepicker>
</code>```

What I can do to not omit zero in days section to input days with zero?

This behavior can be seen if you see DatePicker overview.

答:
This is a known issue that is addressed in the 1.4.1 release of the @progress/kendo-angular-dateinputs. More details can be found in the corresponding issue:

https://github.com/telerik/kendo-angular/issues/910

The site is still using 1.3.1, which has the described issue. Once the new release is used,

```<code>map: {
  ...,
  "@progress/kendo-angular-dateinputs": "https://unpkg.com/@progress/kendo-angular-dateinputs@1.4.1"
},
</code>```

the component behaves as expected.

http://plnkr.co/edit/HonarK6ICLxhs221YHiY?p=preview

Body:
I am trying to input the following date:

5/01/2017

But the first zero of days is always omitted by kendo-date-picker and my date becomes the following:

5/12/17

HTML:

        <kendo-datepicker
            [min]="min"
            [max]="max"
            [(ngModel)]="value"
            #dateModel="ngModel"
        ></kendo-datepicker>

What I can do to not omit zero in days section to input days with zero?

This behavior can be seen if you see DatePicker overview.

Body:
This is a known issue that is addressed in the 1.4.1 release of the @progress/kendo-angular-dateinputs. More details can be found in the corresponding issue:

https://github.com/telerik/kendo-angular/issues/910

The site is still using 1.3.1, which has the described issue. Once the new release is used,

map: {
  ...,
  "@progress/kendo-angular-dateinputs": "https://unpkg.com/@progress/kendo-angular-dateinputs@1.4.1"
},

the component behaves as expected.

http://plnkr.co/edit/HonarK6ICLxhs221YHiY?p=preview


问:
Build NuGet package for .Net Standard 2.0 lib with Cake
I have created a class library based on .Net Standard 2.0 and I build the project/solution with Cake, but I cannot find how to build NuGet package for that library. NuGetPack doesn't work.</p>

答:
NuGetPack requires nuget.exe 4.4.x or newer for .NET Standard to work properly, that said there's also alternatives to using nuget.exe.

If you're using the .NET Core Cli then you use the DotNetCorePack alias.

If you're using MSBuild to build, MSBuild now for new SDK csproj has a Pack target, which could look something like this:

```<code>var configuration           = Argument("configuration", "Release");
FilePath solution           = MakeAbsolute(File("./src/MySolution.sln"));
DirectoryPath artifacts     = MakeAbsolute(Directory("./artifacts"));
var version = //some version login i.e. GitVersion
var semVersion = //some version login i.e. GitVersion

Func<MSBuildSettings,MSBuildSettings>
    commonSettings         = settings => settings
                                .UseToolVersion(MSBuildToolVersion.VS2017)
                                .SetConfiguration(configuration)
                                .SetVerbosity(Verbosity.Minimal)
                                .WithProperty("PackageOutputPath", artifacts.FullPath)
                                .WithProperty("VisualStudioVersion", "15.0")
                                .WithProperty("Version", semVersion)
                                .WithProperty("AssemblyVersion", version)
                                .WithProperty("FileVersion", version);

Task("Clean")
  .Does(() =>
  {
    //some clean logic
  });

Task("Restore-NuGet-Packages")
    .IsDependentOn("Clean")
    .Does(() =>
{
    NuGetRestore(solution,
        new NuGetRestoreSettings {
            Verbosity = NuGetVerbosity.Quiet
            });
});

Task("Build")
    .IsDependentOn("Restore-NuGet-Packages")
    .Does(() =>
{
    MSBuild(solution, settings => commonSettings(settings).WithTarget("Build"));
});

Task("Create-NuGet-Package")
    .IsDependentOn("Build")
    .Does(() =>
{
     MSBuild(project,
        settings => commonSettings(settings)
                        .WithTarget("Pack")
                        .WithProperty("IncludeSymbols","true"));
});
</code>```

Body:
NuGetPack requires nuget.exe 4.4.x or newer for .NET Standard to work properly, that said there's also alternatives to using nuget.exe.

If you're using the .NET Core Cli then you use the DotNetCorePack alias.

If you're using MSBuild to build, MSBuild now for new SDK csproj has a Pack target, which could look something like this:

var configuration           = Argument("configuration", "Release");
FilePath solution           = MakeAbsolute(File("./src/MySolution.sln"));
DirectoryPath artifacts     = MakeAbsolute(Directory("./artifacts"));
var version = //some version login i.e. GitVersion
var semVersion = //some version login i.e. GitVersion

Func<MSBuildSettings,MSBuildSettings>
    commonSettings         = settings => settings
                                .UseToolVersion(MSBuildToolVersion.VS2017)
                                .SetConfiguration(configuration)
                                .SetVerbosity(Verbosity.Minimal)
                                .WithProperty("PackageOutputPath", artifacts.FullPath)
                                .WithProperty("VisualStudioVersion", "15.0")
                                .WithProperty("Version", semVersion)
                                .WithProperty("AssemblyVersion", version)
                                .WithProperty("FileVersion", version);

Task("Clean")
  .Does(() =>
  {
    //some clean logic
  });

Task("Restore-NuGet-Packages")
    .IsDependentOn("Clean")
    .Does(() =>
{
    NuGetRestore(solution,
        new NuGetRestoreSettings {
            Verbosity = NuGetVerbosity.Quiet
            });
});

Task("Build")
    .IsDependentOn("Restore-NuGet-Packages")
    .Does(() =>
{
    MSBuild(solution, settings => commonSettings(settings).WithTarget("Build"));
});

Task("Create-NuGet-Package")
    .IsDependentOn("Build")
    .Does(() =>
{
     MSBuild(project,
        settings => commonSettings(settings)
                        .WithTarget("Pack")
                        .WithProperty("IncludeSymbols","true"));
});


问:
How to handle uppercase and lowercase characters when using UIKeyCommand
We are in the process of receiving and processing keyboard input.

Among my source code,

```<code>UIKeyCommand *menuKey = [UIKeyCommand keyCommandWithInput:[NSString stringWithFormat:@"%c", 77]
                                                modifierFlags:0
                                                       action:@selector(menuKey:)];
</code>```

There is this part.

However, if you process it like this, it will only react when it is an uppercase 'M', and it does not respond when it is a lowercase 'm'.

Is there a way to handle UIKeyCommand with all uppercase and lowercase characters?

答: You can add command for both Upper case Character and lowercase character</p>

Body:
We are in the process of receiving and processing keyboard input.

Among my source code,

UIKeyCommand *menuKey = [UIKeyCommand keyCommandWithInput:[NSString stringWithFormat:@"%c", 77]
                                                modifierFlags:0
                                                       action:@selector(menuKey:)];

There is this part.

However, if you process it like this, it will only react when it is an uppercase 'M', and it does not respond when it is a lowercase 'm'.

Is there a way to handle UIKeyCommand with all uppercase and lowercase characters?


问:
DryIoc: Register with a different Dependency of a Dependency
How can I override a Dependency of a Dependency in a Register-Statement?

For Example:

```<code>class A {
  public A(IB b) {}
}

class MyService {
  public MyService(A a) {}
}

cnt.Register<MyService>(made: Parameters.Of.Type<IB>(serviceKey: "otherIB")); // ignored by dryioc, because it's a Dependency of Dependency A
cnt.Register<IB, OtherB>(serviceKey: "otherIB");
</code>```

I think it's a simple question, if other explanation needed, I will edit the question.

答:
Dependency of dependency is a nested thing which is not visible to the first dependency owner. Otherwise it will break an isolation - why should I know about my dependencies implementation details (their dependencies)?

To fix the code you need to add registration for A:

```<code>cnt.Register<MyService>();
cnt.Register<A>(made: Parameters.Of.Type<IB>(serviceKey: "otherIB"));
cnt.Register<IB, OtherB>(serviceKey: "otherIB");
</code>```

Update:

From the other hand, if you want a context based dependency, you can register it with condition:

```<code>cnt.Register<IB, OtherB>(setup: Setup.With(condition:
    req => req.Parent.Enumerate().Any(p => p.ServiceType == typeof(MyService)));

cnt.Register<IB, DefaultB>(setup: Setup.With(condition:
    req => req.Parent.Enumerate().All(p => p.ServiceType != typeof(MyService)));
</code>```

Body:
How can I override a Dependency of a Dependency in a Register-Statement?

For Example:

class A {
  public A(IB b) {}
}

class MyService {
  public MyService(A a) {}
}

cnt.Register<MyService>(made: Parameters.Of.Type<IB>(serviceKey: "otherIB")); // ignored by dryioc, because it's a Dependency of Dependency A
cnt.Register<IB, OtherB>(serviceKey: "otherIB");

I think it's a simple question, if other explanation needed, I will edit the question.

Body:
Dependency of dependency is a nested thing which is not visible to the first dependency owner. Otherwise it will break an isolation - why should I know about my dependencies implementation details (their dependencies)?

To fix the code you need to add registration for A:

cnt.Register<MyService>();
cnt.Register<A>(made: Parameters.Of.Type<IB>(serviceKey: "otherIB"));
cnt.Register<IB, OtherB>(serviceKey: "otherIB");

Update:

From the other hand, if you want a context based dependency, you can register it with condition:

cnt.Register<IB, OtherB>(setup: Setup.With(condition:
    req => req.Parent.Enumerate().Any(p => p.ServiceType == typeof(MyService)));

cnt.Register<IB, DefaultB>(setup: Setup.With(condition:
    req => req.Parent.Enumerate().All(p => p.ServiceType != typeof(MyService)));


问:
button1.PerformClick() in wpf
Why this code in WPF does not work ?

```<code>private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("yes");
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        button1.PerformClick();
    }
</code>```

I need to command.

答:
Because PerformClick is a method on WindowsForms Button control:

http://msdn.microsoft.com/en-us/library/system.windows.forms.button.performclick.aspx

Not on the WPF Button control:

http://msdn.microsoft.com/en-us/library/system.windows.controls.button_methods.aspx

To automate a button click, you might like to take a look at the UI automation framework:

http://msdn.microsoft.com/en-us/library/ms747327.aspx

Title: button1.PerformClick() in wpf

Body:
Why this code in WPF does not work ?

private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("yes");
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        button1.PerformClick();
    }

I need to command.


问:
Need to display 2 input text after selecting a specific value in drop down in angular 4
I have a specific requirement. I need to display 2 input text fields after selecting a specific value from a drop down which is 'Add New...'
My code snippet is below -

```<code>    <td>
    <div *ngIf="item.showOperationField">
        <p-checkbox
            value ="inflationaryImpactCheck"
            label="Save for Inflationary Impact"
            name = "calculationSaveInflation"
            [(ngModel)]="item.inflationaryImpact"
            pTooltip="Check the Inflationary Impact box to map this calculation to an index for Inflationary Pressure calculation."
            binary="true">
        </p-checkbox>
    </div>
    </td>
    <td>
    <div *ngIf="item.inflationaryImpact">
        <p-dropdown
            [style]="{'width':'200px'}"
            [options]="inflation"
            name = "calculationInflation"
            [(ngModel)]="item.selectedInflation">
        </p-dropdown>
    </div>
    </td>
<td>
<div *ngIf="item.selectedInflation=='Add New...'">
   <input
    [style]="{'width':'200px'}"
    type="text"
    name="catValue"
    pInputText
    [(ngModel)]="item.catValue"
    />
</div>
</td>
</code>```

Now I need to display 2 input boxes while selecting a specific value from the drop down "inflation" which is 'Add New...'. I have tried with the above  code snippet but nothing happened.
Please help me.

答:
Just use the ngIf condition

```<code><td>
<div *ngIf="item.inflationaryImpact">
    <p-dropdown
        [style]="{'width':'200px'}"
        [options]="inflation"
        name = "calculationInflation"
        [(ngModel)]="item.selectedInflation">
    </p-dropdown>
</div>
</td>
<td *ngIf="item.selectedInflation === 'Add New...'">
<div>
    <input type="text" name="txt 1"/>
    <input type="text" name="txt 2"/>
</div>
</td>
</code>```

Body:
I have a specific requirement. I need to display 2 input text fields after selecting a specific value from a drop down which is 'Add New...'
My code snippet is below -

   <input
    [style]="{'width':'200px'}"
    type="text"
    name="catValue"
    pInputText
    [(ngModel)]="item.catValue"
    />

Now I need to display 2 input boxes while selecting a specific value from the drop down "inflation" which is 'Add New...'. I have tried with the above  code snippet but nothing happened.
Please help me.

Body:
Just use the ngIf condition

<td>
<div *ngIf="item.inflationaryImpact">
    <p-dropdown
        [style]="{'width':'200px'}"
        [options]="inflation"
        name = "calculationInflation"
        [(ngModel)]="item.selectedInflation">
    </p-dropdown>
</div>
</td>
<td *ngIf="item.selectedInflation === 'Add New...'">
<div>
    <input type="text" name="txt 1"/>
    <input type="text" name="txt 2"/>
</div>
</td>


问:
Mysql master-slave replication breaks when issuing commands from master's phpmyadmin
I have successfully configured MYSQL slave from existing master SQL server using this https://www.digitalocean.com/community/tutorials/how-to-set-up-master-slave-replication-in-mysql

The setup works fine and changes made to master through MySQL shell are perfectly reflected on the slave. But if I issue commands from PHPMyAdmin, the system breaks down. it shows following error

```<code>mysql> show slave status \G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: ***.***.***.***
                  Master_User: *****
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.0000**
          Read_Master_Log_Pos: 107
               Relay_Log_File: mysql-relay-bin.00000*
                Relay_Log_Pos: 2407
        Relay_Master_Log_File: mysql-bin.000**
             Slave_IO_Running: Yes
            Slave_SQL_Running: No
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 1146
                   Last_Error: Error 'Table 'phpmyadmin.pma_table_uiprefs' doesn't exist' on query. Default database: ''. Query: 'REPLACE INTO `phpmyadmin`.`pma_table_uiprefs` VALUES ('**', '******', '******', '{"sorted_col":"`******`.`date` DESC","CREATE_TIME":"2016-12-19 09:35:35","col_order":["1","2","3","4","5","0","6","7","8","9"]}', NULL)'
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 2261
              Relay_Log_Space: 8323
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: NULL
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 1146
               Last_SQL_Error: Error 'Table 'phpmyadmin.pma_table_uiprefs' doesn't exist' on query. Default database: ''. Query: 'REPLACE INTO `phpmyadmin`.`pma_table_uiprefs` VALUES ('******', '******', '******', '{"sorted_col":"`******`.`date` DESC","******":"2016-12-19 09:35:35","col_order":["1","2","3","4","5","0","6","7","8","9"]}', NULL)'
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 1
1 row in set (0.00 sec)
</code>```

Phpmyadmin is not configured on the slave(I installed it without configuring it to slave parameters) and in the master configuration, I've explicitly set PHPmyadmin to not get replicated on slave through the following command.

```<code>binlog_ignore_db    = phpmyadmin
</code>```

How to remove this error

'phpmyadmin.pma_table_uiprefs' doesn't exist'

please guide.

答:
The problem it's that the system it's trying to replicate the phpadmin tables that doesn't exist in your replica. To make it work, you need to exclude the phpmyadmin db.

In the slave mysqld.cnf file, you need to add this:

```<code>replicate-ignore-db=phpmyadmin
</code>```

and restart the replica

Body:
I have successfully configured MYSQL slave from existing master SQL server using this https://www.digitalocean.com/community/tutorials/how-to-set-up-master-slave-replication-in-mysql

The setup works fine and changes made to master through MySQL shell are perfectly reflected on the slave. But if I issue commands from PHPMyAdmin, the system breaks down. it shows following error

mysql> show slave status \G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: ***.***.***.***
                  Master_User: *****
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.0000**
          Read_Master_Log_Pos: 107
               Relay_Log_File: mysql-relay-bin.00000*
                Relay_Log_Pos: 2407
        Relay_Master_Log_File: mysql-bin.000**
             Slave_IO_Running: Yes
            Slave_SQL_Running: No
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 1146
                   Last_Error: Error 'Table 'phpmyadmin.pma_table_uiprefs' doesn't exist' on query. Default database: ''. Query: 'REPLACE INTO `phpmyadmin`.`pma_table_uiprefs` VALUES ('**', '******', '******', '{"sorted_col":"`******`.`date` DESC","CREATE_TIME":"2016-12-19 09:35:35","col_order":["1","2","3","4","5","0","6","7","8","9"]}', NULL)'
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 2261
              Relay_Log_Space: 8323
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: NULL
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 1146
               Last_SQL_Error: Error 'Table 'phpmyadmin.pma_table_uiprefs' doesn't exist' on query. Default database: ''. Query: 'REPLACE INTO `phpmyadmin`.`pma_table_uiprefs` VALUES ('******', '******', '******', '{"sorted_col":"`******`.`date` DESC","******":"2016-12-19 09:35:35","col_order":["1","2","3","4","5","0","6","7","8","9"]}', NULL)'
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 1
1 row in set (0.00 sec)

Phpmyadmin is not configured on the slave(I installed it without configuring it to slave parameters) and in the master configuration, I've explicitly set PHPmyadmin to not get replicated on slave through the following command.

binlog_ignore_db    = phpmyadmin

How to remove this error

'phpmyadmin.pma_table_uiprefs' doesn't exist'

please guide.

Body:
The problem it's that the system it's trying to replicate the phpadmin tables that doesn't exist in your replica. To make it work, you need to exclude the phpmyadmin db.

In the slave mysqld.cnf file, you need to add this:

replicate-ignore-db=phpmyadmin

and restart the replica


问:
Use function in replace for preg_replace()
I need to use a function in preg_replace() like this:

```<code>$out = preg_replace($regex, "[ ".$this->ToMobileFormatt("$0")." ]", $input);
</code>```

but it doesn't work true.

The fuction and regex .

$regex = '~((?:\+?989|09)|(?:\+?98 9|09)|(?:\+?9|09))(\s|-)*\d{1}(\s|-)*\d{1}(\s|-)*\d{1}(\s|-)*\d{1}(\s|-)*\d{1}(\s|-)*\d{1}(\s|-)*\d{1}(\s|-)*\d{1}(\s|-)*\d{1}~';

```<code>function ToMobileFormatt($string)
{

    $string = str_replace(" ","",$string);
    $string = str_replace(" ","",$string);

    if ( preg_match('/^\0\d{10}/', $string) AND count($string) == '11' )
    {
        return $string ;
    }
    elseif( preg_match('/^\98\d{10}/', $string) )
    {
        $string = substr($string,2);
        $string = '0'.$string ;
        return $string ;
    }

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

Any suggestions?

答:
you have to use preg_replace_callback ;)
something like this (may vary depending on your regex):</p>

```<code>$out = preg_replace_callback($regex, 'ToMobileFormatt', $input);

function ToMobileFormatt($matches)
{

    $string = str_replace(" ","",$matches[0]);
    $string = str_replace(" ","",$string);

    if ( preg_match('/^\0\d{10}/', $string) AND count($string) == '11' )
    {
        return $string ;
    }
    elseif( preg_match('/^\98\d{10}/', $string) )
    {
        $string = substr($string,2);
        $string = '0'.$string ;
        return $string ;
    }

    return "[ ".$string."]";
}
</code>```

Body:
I need to use a function in preg_replace() like this:

$out = preg_replace($regex, "[ ".$this->ToMobileFormatt("$0")." ]", $input);

but it doesn't work true.

The fuction and regex .

$regex = '~((?:\+?989|09)|(?:\+?98 9|09)|(?:\+?9|09))(\s|-)*\d{1}(\s|-)*\d{1}(\s|-)*\d{1}(\s|-)*\d{1}(\s|-)*\d{1}(\s|-)*\d{1}(\s|-)*\d{1}(\s|-)*\d{1}(\s|-)*\d{1}~';

function ToMobileFormatt($string)
{

    $string = str_replace(" ","",$string);
    $string = str_replace(" ","",$string);

    if ( preg_match('/^\0\d{10}/', $string) AND count($string) == '11' )
    {
        return $string ;
    }
    elseif( preg_match('/^\98\d{10}/', $string) )
    {
        $string = substr($string,2);
        $string = '0'.$string ;
        return $string ;
    }

    return $string;
}

Any suggestions?

Body:
you have to use preg_replace_callback ;)
something like this (may vary depending on your regex):

$out = preg_replace_callback($regex, 'ToMobileFormatt', $input);

function ToMobileFormatt($matches)
{

    $string = str_replace(" ","",$matches[0]);
    $string = str_replace(" ","",$string);

    if ( preg_match('/^\0\d{10}/', $string) AND count($string) == '11' )
    {
        return $string ;
    }
    elseif( preg_match('/^\98\d{10}/', $string) )
    {
        $string = substr($string,2);
        $string = '0'.$string ;
        return $string ;
    }

    return "[ ".$string."]";
}


问:
Why visual studio delete non-related assemblies from Bin folder when rebuild
I have an asp.net mvc web application, and i have a reference to SharpArch.Web (one of the Sharp Architecture assemblies)

When i rebuild the project, and run it, an exception is thrown telling me that the (Newtonsoft.Json.dll) is missing from the Bin folder which is used by (SharpArch.Web), so it's ok, i copied it, and every thing worked well.

When i try to rebuild the project again, the exception is thrown again, and the (Newtonsoft.Json.dll) assembly is deleted ??

Why did that happen? what does visual studio have to do with non-referenced assembly ?
and FYI, VS doesn't delete everything from Bin, just a specific assemblies !!!

and BTW i don't want to add a reference to (Newtonsoft.Json.dll), i don't like to reference an unused assembly.

答: I suppose that the Bin\ directory is reserved for mangling by Visual Studio. You'll have to put your assembly in a different location.</p>


问:
Get Json_encode to a different jQuery page
I am working on a little project to learn more about JSON, but I am kinda stuck. I did a PHP query to get content from my database and I want to pass that data to a different jQuery page with JSON (optional).

Here is my process.php file:

```<code><div id="msg" class="msg">
<?php
    $query = "SELECT id, d_prijs, code, artikelNL FROM artikel";
    $json =  array();
    $result= $conn->query($query);
    while($row = $result->fetch_assoc()){
        $json[]= $row;
    }
    echo json_encode($json);
?>
</div>
</code>```

This echo works fine and it gives a result, but I want to pass that result to another page and show it on that page.

Here is my jQuery file:

```<code><script>
 $(document).ready(function(){
  $("button").click(function(){
    var mycontent  = $('div.msg').text();
    console.log(mycontent);
  });
 });
</script>
</code>```

But this doesn't seem to work, it doesn't give an error either. Any ideas on how I can improve?

答: If you have a single page application and when you say page you mean hidden/displayed content, your code should work. But if you have actual pages, this will never work because your source div does not exist in the DOM once you have switched pages</p>

Body:
I am working on a little project to learn more about JSON, but I am kinda stuck. I did a PHP query to get content from my database and I want to pass that data to a different jQuery page with JSON (optional).

Here is my process.php file:

<?php
    $query = "SELECT id, d_prijs, code, artikelNL FROM artikel";
    $json =  array();
    $result= $conn->query($query);
    while($row = $result->fetch_assoc()){
        $json[]= $row;
    }
    echo json_encode($json);
?>

This echo works fine and it gives a result, but I want to pass that result to another page and show it on that page.

Here is my jQuery file:

But this doesn't seem to work, it doesn't give an error either. Any ideas on how I can improve?


问:
How to display Chinese in matplotlib plot
Here, I have a plot work to do with pandas, like this :

```<code>most_active_posts.plot(x = 'title',y = 'active_span',kind = 'barh')
</code>```

most_active_posts is an object of dataframe with index, I want a simple two-dimensional plot with two columns, one is 'title' and the other is 'active_span'.

title is type of string, which contains Chinese characters, while active_span is type of integer .

How can I display Chinese characters normally?

答:
I find a python library designed for fixing Chinese display in pip. You can download it using the command in your terminal:

```<code>pip install pyplotz
</code>```

And you can write the following code instead(full code):

```<code>from pyplotz.pyplotz import PyplotZ
pltz = PyplotZ()
pltz.enable_chinese()
most_active_posts.plot(x='title',y='active_span',kind='bar')
pltz.xticks(np.arange(len(df.cn)),df.cn,rotation=360)
pltz.legend()
pltz.show()
</code>```

The result is like this

And it can help you handle matplotlib Chinese font for you! This is the github page:

https://github.com/201528015329004/pyplotz

And there are some handy examples:

https://github.com/201528015329004/pyplotz/blob/master/examples/quick_start.ipynb

Body:
Here, I have a plot work to do with pandas, like this :

most_active_posts.plot(x = 'title',y = 'active_span',kind = 'barh')

most_active_posts is an object of dataframe with index, I want a simple two-dimensional plot with two columns, one is 'title' and the other is 'active_span'.

title is type of string, which contains Chinese characters, while active_span is type of integer .

How can I display Chinese characters normally?

Body:
I find a python library designed for fixing Chinese display in pip. You can download it using the command in your terminal:

pip install pyplotz

And you can write the following code instead(full code):

from pyplotz.pyplotz import PyplotZ
pltz = PyplotZ()
pltz.enable_chinese()
most_active_posts.plot(x='title',y='active_span',kind='bar')
pltz.xticks(np.arange(len(df.cn)),df.cn,rotation=360)
pltz.legend()
pltz.show()

The result is like this

And it can help you handle matplotlib Chinese font for you! This is the github page:

https://github.com/201528015329004/pyplotz

And there are some handy examples:

https://github.com/201528015329004/pyplotz/blob/master/examples/quick_start.ipynb


问:
How can I generate a parser with Jison which deals with grammar ambiguity?
I am trying to generate a parser in JavaScript via Jison for the language ChucK, and have got off to a good start except that there are ambiguities in the language which the generated parser is unable to handle. The original ChucK compiler is generated by Bison, and that must somehow be able to resolve these ambiguities.

For the purposes of this question I've simplified the problem to a construed grammar which presents only one ambiguity. For reference I've put up a gist of all the involved files (including the generated parser). The project structure is as follows:

language/lexer.js: The lexer.

language/grammar.js: The grammar definition as well as a function (generate) to generate the parser via Jison.

language/helpers.js: Helper functions

src/parser.js: The generated parser.

testparse.js: A program that tests the parser with the following source code: Type var => out;.

The grammar itself looks as follows:

```<code>grammar = {
    Program: [
        ['ProgramSection', '$$ = new yy.Program($1);']
    ],
    ProgramSection: [
        ['Expression SEMICOLON', '$$ = new yy.ExpressionStatement($1);']
    ],
    Expression: [
        ['DeclExpression', '$$ = $1;'],
        ['Expression OP DeclExpression', '$$ = new yy.ExpFromBinary($1, $2, $3);']
    ],
    DeclExpression: [
        ['TypeDecl VarDeclList', '$$ = new yy.DeclExp($1, $2, 0);'],
        ['PrimaryExpression', '$$ = $1;']
    ],
    VarDeclList: [
        ['VarDecl', '$$ = new yy.VarDeclList($1);']
    ],
    VarDecl: [
        ['ID', '$$ = new yy.VarDecl($1);']
    ],
    TypeDecl: [
        ['ID', '$$ = new yy.TypeDecl(new yy.IdList($1), 0);']
    ],
    PrimaryExpression: [
        ['ID', '$$ = new yy.ExpFromId($1);']
    ]
};
</code>```

The ambiguity is that the non-terminal DeclExpression can match either TypeDecl VarDeclList or PrimaryExpression. This makes Jison emit the following warning:

```<code>States with conflicts:
State 7
  TypeDecl -> ID . #lookaheads= ID SEMICOLON OP
  PrimaryExpression -> ID . #lookaheads= ID SEMICOLON OP
</code>```

And the generated parser fails to parse the test code (Type var => out;) like so:

```<code>Error: Parse error on line 1: Unexpected 'SEMICOLON'
</code>```

To my understanding, it's the part after the => operator that the parser tries to match against the rule TypeDecl VarDeclList.

So, how can I generate a parser that is able to deal with this ambiguity?

答:
The reason your grammer doesn't work with a LALR(1) parser is because your is ambiguous for a LALR(1) parser in the DeclExpression state on the TypeDecl and PrimaryExpression states.

Let me try to explain. As stated by the error message the parser detects a conflict on TypeDecl and PrimaryExpression. Both have ID as token but since the LALR(1) parser can only look one token ahead it means that the parser doesn't know what to do when it is in the DeclExpression state. SLR on the other hand has a kind of dynamic look-a-head which will resolve the conflict at the expense of some memory.

If you want to make it work on a LALR(1) parser, just refactor your DeclExpression rule to be like ID VarDeclList | ID, this way the parser doesn't have to look-a-head in order to find the correct rule.

Body:
I am trying to generate a parser in JavaScript via Jison for the language ChucK, and have got off to a good start except that there are ambiguities in the language which the generated parser is unable to handle. The original ChucK compiler is generated by Bison, and that must somehow be able to resolve these ambiguities.

For the purposes of this question I've simplified the problem to a construed grammar which presents only one ambiguity. For reference I've put up a gist of all the involved files (including the generated parser). The project structure is as follows:

language/lexer.js: The lexer.

language/grammar.js: The grammar definition as well as a function (generate) to generate the parser via Jison.

language/helpers.js: Helper functions

src/parser.js: The generated parser.

testparse.js: A program that tests the parser with the following source code: Type var => out;.

The grammar itself looks as follows:

grammar = {
    Program: [
        ['ProgramSection', '$$ = new yy.Program($1);']
    ],
    ProgramSection: [
        ['Expression SEMICOLON', '$$ = new yy.ExpressionStatement($1);']
    ],
    Expression: [
        ['DeclExpression', '$$ = $1;'],
        ['Expression OP DeclExpression', '$$ = new yy.ExpFromBinary($1, $2, $3);']
    ],
    DeclExpression: [
        ['TypeDecl VarDeclList', '$$ = new yy.DeclExp($1, $2, 0);'],
        ['PrimaryExpression', '$$ = $1;']
    ],
    VarDeclList: [
        ['VarDecl', '$$ = new yy.VarDeclList($1);']
    ],
    VarDecl: [
        ['ID', '$$ = new yy.VarDecl($1);']
    ],
    TypeDecl: [
        ['ID', '$$ = new yy.TypeDecl(new yy.IdList($1), 0);']
    ],
    PrimaryExpression: [
        ['ID', '$$ = new yy.ExpFromId($1);']
    ]
};

The ambiguity is that the non-terminal DeclExpression can match either TypeDecl VarDeclList or PrimaryExpression. This makes Jison emit the following warning:

States with conflicts:
State 7
  TypeDecl -> ID . #lookaheads= ID SEMICOLON OP
  PrimaryExpression -> ID . #lookaheads= ID SEMICOLON OP

And the generated parser fails to parse the test code (Type var => out;) like so:

Error: Parse error on line 1: Unexpected 'SEMICOLON'

To my understanding, it's the part after the => operator that the parser tries to match against the rule TypeDecl VarDeclList.

So, how can I generate a parser that is able to deal with this ambiguity?