问:
Radio livestream does not play on android webview but plays on the browser
I have a number of radio live stream embedded on a website. They are playing on the website but not on android web-view. I am not sure what i am missing in my code. Please help. Below is the code i am using:</p>

```<code>   webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setAppCacheEnabled(true);
    swipe.setRefreshing(true);
    webView.loadUrl(getString(url));

    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setAllowContentAccess(true);
    webView.getSettings().supportZoom();
    webView.getSettings().setBuiltInZoomControls(true);

    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webView.setSoundEffectsEnabled(true);
</code>```

答:
My Project code   </p>

```<code>public class RoiFragment extends AbstractBaseFragment {

        @BindView(R.id.web_roi)
        WebView webViewRoi;
        private String url = FORMS;

        public static RoiFragment newInstance(Bundle bundle) {
            RoiFragment fragment = new RoiFragment();
            if (bundle != null)
                fragment.setArguments(bundle);
            return fragment;
        }

        @Override
        public int getContentView() {
            return R.layout.roi_fragment;
        }

        @Override
        protected void onViewReady(Bundle savedInstanceState) {
            super.onViewReady(savedInstanceState);
            Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
            for (int i = 0; i < toolbar.getChildCount(); i++) {
                if (i != 0)
                    toolbar.removeViewAt(i);
            }

            Bundle bundle = getArguments();
            if (bundle != null) {
                if (bundle.getInt("FORM") == 1) {
                    url += "roi";
                    toolbar.setTitle(getString(R.string.roi));
                } else if (bundle.getInt("FORM") == 2) {
                    url += "selfassesment";
                    toolbar.setTitle(getString(R.string.self_ass));
                }

            }

            try {
                getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                WebSettings settings = webViewRoi.getSettings();
                settings.setJavaScriptEnabled(true);
                settings.setJavaScriptCanOpenWindowsAutomatically(true);
                settings.setSupportZoom(true);
                settings.setBuiltInZoomControls(true);
                settings.setDatabaseEnabled(true);
                String databasePath = getActivity().getDir("database", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setAppCacheEnabled(true);

                webViewRoi.setWebChromeClient(new WebChromeClient() {
                    @Override
                    public void onExceededDatabaseQuota(String url, String databaseIdentifier,
                                                        long currentQuota, long estimatedSize, long totalUsedQuota,
                                                        WebStorage.QuotaUpdater quotaUpdater) {
                        // try to keep quota size as big as possible else database will not get created in HTML 5 app
                        quotaUpdater.updateQuota(estimatedSize * 2);
                    }
                });
                webViewRoi.setWebViewClient(new WebViewClient());
                JsonObject object = new JsonObject();
                object.addProperty("token", LoginActivity.loginInfoDTO.getToken());
                String outputT = object.toString();

                Gson gson = new Gson();
                String a1 = gson.toJson(LoginActivity.loginInfoDTO.getProfile());

                String auth1 = URLEncoder.encode(a1, "UTF-8");
                String auth2 = URLEncoder.encode(outputT, "UTF-8");

                String a = "Radius.PROFILE=" + auth1;
                String q = "Radius.AUTH=" + auth2;
                CookieManager cookieManager = CookieManager.getInstance();
                cookieManager.setAcceptCookie(true);
                clearcookies(cookieManager);
                cookieManager.setCookie(url, q);
                cookieManager.setCookie(url, a);
                settings.setAllowUniversalAccessFromFileURLs(true);
                settings.setAllowFileAccessFromFileURLs(true);
                settings.setBuiltInZoomControls(true);
                webViewRoi.setWebChromeClient(new WebChromeClient());
                webViewRoi.loadUrl(url);

            } catch (Exception e) {
                Log.e("ROI", "error", e);
                Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
            }

        }

        @SuppressWarnings("deprecation")
        void clearcookies(CookieManager cookieManager) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1)
                cookieManager.removeAllCookies(null);
            else
                cookieManager.removeAllCookie();
        }

    }
</code>```

Body:
I have a number of radio live stream embedded on a website. They are playing on the website but not on android web-view. I am not sure what i am missing in my code. Please help. Below is the code i am using:

   webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setAppCacheEnabled(true);
    swipe.setRefreshing(true);
    webView.loadUrl(getString(url));

    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setAllowContentAccess(true);
    webView.getSettings().supportZoom();
    webView.getSettings().setBuiltInZoomControls(true);

    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webView.setSoundEffectsEnabled(true);

Body:
My Project code

public class RoiFragment extends AbstractBaseFragment {

        @BindView(R.id.web_roi)
        WebView webViewRoi;
        private String url = FORMS;

        public static RoiFragment newInstance(Bundle bundle) {
            RoiFragment fragment = new RoiFragment();
            if (bundle != null)
                fragment.setArguments(bundle);
            return fragment;
        }

        @Override
        public int getContentView() {
            return R.layout.roi_fragment;
        }

        @Override
        protected void onViewReady(Bundle savedInstanceState) {
            super.onViewReady(savedInstanceState);
            Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
            for (int i = 0; i < toolbar.getChildCount(); i++) {
                if (i != 0)
                    toolbar.removeViewAt(i);
            }

            Bundle bundle = getArguments();
            if (bundle != null) {
                if (bundle.getInt("FORM") == 1) {
                    url += "roi";
                    toolbar.setTitle(getString(R.string.roi));
                } else if (bundle.getInt("FORM") == 2) {
                    url += "selfassesment";
                    toolbar.setTitle(getString(R.string.self_ass));
                }

            }

            try {
                getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                WebSettings settings = webViewRoi.getSettings();
                settings.setJavaScriptEnabled(true);
                settings.setJavaScriptCanOpenWindowsAutomatically(true);
                settings.setSupportZoom(true);
                settings.setBuiltInZoomControls(true);
                settings.setDatabaseEnabled(true);
                String databasePath = getActivity().getDir("database", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setAppCacheEnabled(true);

                webViewRoi.setWebChromeClient(new WebChromeClient() {
                    @Override
                    public void onExceededDatabaseQuota(String url, String databaseIdentifier,
                                                        long currentQuota, long estimatedSize, long totalUsedQuota,
                                                        WebStorage.QuotaUpdater quotaUpdater) {
                        // try to keep quota size as big as possible else database will not get created in HTML 5 app
                        quotaUpdater.updateQuota(estimatedSize * 2);
                    }
                });
                webViewRoi.setWebViewClient(new WebViewClient());
                JsonObject object = new JsonObject();
                object.addProperty("token", LoginActivity.loginInfoDTO.getToken());
                String outputT = object.toString();

                Gson gson = new Gson();
                String a1 = gson.toJson(LoginActivity.loginInfoDTO.getProfile());

                String auth1 = URLEncoder.encode(a1, "UTF-8");
                String auth2 = URLEncoder.encode(outputT, "UTF-8");

                String a = "Radius.PROFILE=" + auth1;
                String q = "Radius.AUTH=" + auth2;
                CookieManager cookieManager = CookieManager.getInstance();
                cookieManager.setAcceptCookie(true);
                clearcookies(cookieManager);
                cookieManager.setCookie(url, q);
                cookieManager.setCookie(url, a);
                settings.setAllowUniversalAccessFromFileURLs(true);
                settings.setAllowFileAccessFromFileURLs(true);
                settings.setBuiltInZoomControls(true);
                webViewRoi.setWebChromeClient(new WebChromeClient());
                webViewRoi.loadUrl(url);

            } catch (Exception e) {
                Log.e("ROI", "error", e);
                Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
            }

        }

        @SuppressWarnings("deprecation")
        void clearcookies(CookieManager cookieManager) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1)
                cookieManager.removeAllCookies(null);
            else
                cookieManager.removeAllCookie();
        }

    }


来源: stackexchange

问:
how to assign the value of match expression to a 2-dim array's elements in scala?
```<code>def longestPalindrome(s: String): String = {
    val f = Array.ofDim[Boolean](1001,1001);
    var len = s.length();
    for (i<-0 to len-1; j<-i to len-1) {
        f(i,j) = i match {
            case j => true ;
            case x if x==j-1 => if (s(i) == s(j)) true else false;
            case y if y<j-1 => if (s(i) == s(j)) f(i+1,j-1) else false;
        }
    }
}
</code>```

It complains about this line f(i,j) = i match { :

Line 5: error: too many arguments for method update: (i: Int, x: Array[Boolean])Unit

What does it means? I just assign the value of match expression to a 2-dim array, what error happens?

答:
Your problem is that you are trying to access the elements of the array with f(i,j).

You should use f(i)(j)

```<code>scala> val f = Array.ofDim[Boolean](1001,1001);
    f: Array[Array[Boolean]] = Array(Array(false, false, false, false....
scala> f(1,1)
<console>:13: error: too many arguments for method apply: (i: Int)Array[Boolean] in class Array
     f(1,1)
       ^

scala> f(1)(1)
res1: Boolean = false
</code>```

ContentLicense: CC BY-SA 3.0

Body:
def longestPalindrome(s: String): String = {
    val f = Array.ofDim[Boolean](1001,1001);
    var len = s.length();
    for (i<-0 to len-1; j<-i to len-1) {
        f(i,j) = i match {
            case j => true ;
            case x if x==j-1 => if (s(i) == s(j)) true else false;
            case y if y<j-1 => if (s(i) == s(j)) f(i+1,j-1) else false;
        }
    }
}

It complains about this line f(i,j) = i match { :

Line 5: error: too many arguments for method update: (i: Int, x: Array[Boolean])Unit

What does it means? I just assign the value of match expression to a 2-dim array, what error happens?

Body:
Your problem is that you are trying to access the elements of the array with f(i,j).

You should use f(i)(j)

scala> val f = Array.ofDim[Boolean](1001,1001);
    f: Array[Array[Boolean]] = Array(Array(false, false, false, false....
scala> f(1,1)
<console>:13: error: too many arguments for method apply: (i: Int)Array[Boolean] in class Array
     f(1,1)
       ^

scala> f(1)(1)
res1: Boolean = false


问:
React Native components name with point parameter

Is it possible to create custom component in React Native with parameters, ex. : transform <PageHeader /> to <Page.Header /> or <PageContent /> to <Page.Content />.

I've see this syntaxe with Picker component in React Native.

<Picker
  selectedValue={this.state.lang}
  onValueChange={(itemValue, itemIndex) => this.switchLang(itemValue)}
  style={Styles.picker}
>
  <Picker.Item label="EN" value="en-EN" />
  <Picker.Item label="FR" value="fr-FR" />
</Picker>
```

Thank you community :)

答:
You would write your components exposing the other components as static class variables which you can access from the class Instance  for example you define your components like

```<code>class PageContent extends React.Component {}

class PageHeader extends React.Component {}
</code>```

and then declare your page component like

```<code>class Page extends React.Component {
   static Content = PageContent;
   static Header = PageHeader;

}

export default Page
</code>```

Now if your import Page , you could access Header and Content like <Page.Content/> and <Page.Header/>

Now if the Page component doesn't do any React stuff, you could instead write it a basic class

Body:
Is it possible to create custom component in React Native with parameters, ex. : transform <PageHeader /> to <Page.Header /> or <PageContent /> to <Page.Content />.

I've see this syntaxe with Picker component in React Native.

<Picker
  selectedValue={this.state.lang}
  onValueChange={(itemValue, itemIndex) => this.switchLang(itemValue)}
  style={Styles.picker}
>
  <Picker.Item label="EN" value="en-EN" />
  <Picker.Item label="FR" value="fr-FR" />
</Picker>

Thank you community :)

Body:
You would write your components exposing the other components as static class variables which you can access from the class Instance  for example you define your components like

class PageContent extends React.Component {}

class PageHeader extends React.Component {}

and then declare your page component like

class Page extends React.Component {
   static Content = PageContent;
   static Header = PageHeader;

}

export default Page

Now if your import Page , you could access Header and Content like <Page.Content/> and <Page.Header/>

Now if the Page component doesn't do any React stuff, you could instead write it a basic class


问:
How to create a variable hyperlink in an R Shiny App
In my shiny app, I'm trying to create a hyperlink that opens an html file, created from an R Markdown file, to a certain section based on the current tab of the app the user is on.

Here's an excerpt from the ui and server code I'm using.

```<code>ui <- fluidPage(title = "App Title",
                dashboardPage(title = "App Title",
                              dashboardHeader(tags$li(a(href = paste0('Help_File.html', textOutput(page), target="_blank", icon("question"), title = "Help"), class = "dropdown")),
                              dashboardSidebar(sidebarMenu(id = "tabs",
                                                           menuItem(text = 'Tab 1', tabName = 'tab1'),
                                                           menuItem(text = 'Tab 2', tabName = 'tab2'),
                                                           menuItem(text = 'Tab 3', tabName = 'tab3')
                                                           )
                                               )

server <- function(input, output, session) {

                   output$page <- renderText({
                                  if(input$tabs == 'tab1') {'#page_1'}
                                  else if (input$tabs == 'tab2') {'#page_2'}
                                  else if (input$tabs == 'tab3') {'#page_3'}
                                  else ''
                                             })
                                            }
</code>```

When I run the app, I get the error "ERROR: cannot coerce type 'closure' to vector of type 'character'".  If I put single quotes around page in the textOutput function in the ui, the app runs but the file doesn't open.  I think either the textOuput function is wrong or the renderText function in the server is wrong but I'm not sure what the correct syntax is.

答:
Your problem is that renderText doesn't just have  text as output but rather a complete html object. In this case you want to use renderUI for the complete a object. And let the href be dynamicly generated within this. Like this

```<code>library(shiny)
library(shinydashboard)
ui <- fluidPage(title = "App Title",
                dashboardPage(title = "App Title",
                              header = dashboardHeader(tags$li(uiOutput("page"), class = "dropdown")),
                              sidebar = dashboardSidebar(sidebarMenu(id = "tabs",
                                                           menuItem(text = 'Tab 1', tabName = 'tab1'),
                                                           menuItem(text = 'Tab 2', tabName = 'tab2'),
                                                           menuItem(text = 'Tab 3', tabName = 'tab3')
                                                           )
                                               ),
                              body = dashboardBody(div())
                )
)
server <- function(input, output, session) {
  output$page <- renderUI({
    a(href = paste0(
      'Help_File.html',
      if(input$tabs == 'tab1') {'#page_1'}
      else if (input$tabs == 'tab2') {'#page_2'}
      else if (input$tabs == 'tab3') {'#page_3'}
      else ''),
      target="_blank",
      style = "color:#FFF;",
      icon("question"),
      title = "Help",
      "Help")
  })
}

shinyApp(ui,server)
</code>```

Hope this helps!

Body:
In my shiny app, I'm trying to create a hyperlink that opens an html file, created from an R Markdown file, to a certain section based on the current tab of the app the user is on.

Here's an excerpt from the ui and server code I'm using.

ui <- fluidPage(title = "App Title",
                dashboardPage(title = "App Title",
                              dashboardHeader(tags$li(a(href = paste0('Help_File.html', textOutput(page), target="_blank", icon("question"), title = "Help"), class = "dropdown")),
                              dashboardSidebar(sidebarMenu(id = "tabs",
                                                           menuItem(text = 'Tab 1', tabName = 'tab1'),
                                                           menuItem(text = 'Tab 2', tabName = 'tab2'),
                                                           menuItem(text = 'Tab 3', tabName = 'tab3')
                                                           )
                                               )

server <- function(input, output, session) {

                   output$page <- renderText({
                                  if(input$tabs == 'tab1') {'#page_1'}
                                  else if (input$tabs == 'tab2') {'#page_2'}
                                  else if (input$tabs == 'tab3') {'#page_3'}
                                  else ''
                                             })
                                            }

When I run the app, I get the error "ERROR: cannot coerce type 'closure' to vector of type 'character'".  If I put single quotes around page in the textOutput function in the ui, the app runs but the file doesn't open.  I think either the textOuput function is wrong or the renderText function in the server is wrong but I'm not sure what the correct syntax is.

Body:
Your problem is that renderText doesn't just have  text as output but rather a complete html object. In this case you want to use renderUI for the complete a object. And let the href be dynamicly generated within this. Like this

library(shiny)
library(shinydashboard)
ui <- fluidPage(title = "App Title",
                dashboardPage(title = "App Title",
                              header = dashboardHeader(tags$li(uiOutput("page"), class = "dropdown")),
                              sidebar = dashboardSidebar(sidebarMenu(id = "tabs",
                                                           menuItem(text = 'Tab 1', tabName = 'tab1'),
                                                           menuItem(text = 'Tab 2', tabName = 'tab2'),
                                                           menuItem(text = 'Tab 3', tabName = 'tab3')
                                                           )
                                               ),
                              body = dashboardBody(div())
                )
)
server <- function(input, output, session) {
  output$page <- renderUI({
    a(href = paste0(
      'Help_File.html',
      if(input$tabs == 'tab1') {'#page_1'}
      else if (input$tabs == 'tab2') {'#page_2'}
      else if (input$tabs == 'tab3') {'#page_3'}
      else ''),
      target="_blank",
      style = "color:#FFF;",
      icon("question"),
      title = "Help",
      "Help")
  })
}

shinyApp(ui,server)

Hope this helps!


问:
Property getter simplification via delegation
I have many properties that follow this pattern, basically the only things that change from the template below are:

the initialized value

the property name

code

```<code>var foo: Double = 0.0
    get() {
        update()
        return field
    }

var foo2: Double = 1.23
    get() {
        update()
        return field
    }
</code>```

question

is there any way that I can use delegation to to simplify (reduce the verbosity of) the code?

答:
Sure</p>

```<code>private fun <T> publishingDelegate(value: T): ReadWriteProperty<Any?, T> = object: ReadWriteProperty<Any?, T> {
    private var initValue = value

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        update()
        return initValue
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        update()
        initValue = value
    }
}

var foo: Double by publishingDelegate(0.0)
var foo2: Double by publishingDelegate(1.23)
</code>```

Body:
I have many properties that follow this pattern, basically the only things that change from the template below are:

the initialized value

the property name

code

var foo: Double = 0.0
    get() {
        update()
        return field
    }

var foo2: Double = 1.23
    get() {
        update()
        return field
    }

question

is there any way that I can use delegation to to simplify (reduce the verbosity of) the code?

Body:
Sure

private fun <T> publishingDelegate(value: T): ReadWriteProperty<Any?, T> = object: ReadWriteProperty<Any?, T> {
    private var initValue = value

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        update()
        return initValue
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        update()
        initValue = value
    }
}

var foo: Double by publishingDelegate(0.0)
var foo2: Double by publishingDelegate(1.23)


问:
Highlight menu item and its submenu item
I have this css code and I need to do this:
I have a dropdown menu with 5 items.
Item1 (root)
-Item2
-Item3
-Item4
-Item5

When I'm inside the page for example "Item4" I need that the "Item4" menu item and the "Item1 (root)" menu item are highlighted with a same color.

Thanks so much.

.menu-container{
}

.de-menu {
  color:#333;
  font-family:'Ovo';
  font-weight:400;
  font-size:13px;
  letter-spacing:3px;
  text-transform:uppercase;
  float:right;
}

.de-menu {
  display:inline-block;
   padding:0px 0px 0px 0px;
 margin:10px 0px 0px 0px;
   height:93px;
}

.de-menu li {
  padding:0px 0px 0px 0px;
  margin:0px 0px 0px 0px;
  float:left;
  display:inline;
  list-style:none;
  position:relative;
}

.de-menu a {
  display:block;
  padding:35px 14px 34px 14px;
  line-height:30px;
  text-decoration:none;
  color:#fff;
}

.de-menu .current-menu-item a{
  color:#e8c694;
}

.de-menu .current-menu-parent a{
  color:#e8c694;
}

/*.de-menu .active a {
  color:#red;
}*/

.de-menu li ul{
 box-shadow: 0 1px 8px 0 rgba(0, 0, 0, 0.3);
 -moz-box-shadow: 0 1px 8px 0 rgba(0, 0, 0, 0.3);
 -webkit-box-shadow: 0 1px 8px 0 rgba(0, 0, 0, 0.3);
 margin-left:25px;
 padding:0;
}

.de-menu li li {
 font-size:12px;
 letter-spacing:normal;
 text-transform:uppercase;
}

.de-menu li li a{
 padding:5px 15px 5px 15px;
 background:#64483E;
 border-top:none;
}

.de-menu a:hover {
  background:#64483E;
}

.de-menu li li a:hover{
 border-top:none;
}

.de-menu li li a:hover {
  background:url(../images/dotblack30.png) #513D32;
}

.de-menu li ul {
  width:170px;
  height:auto;
  position:absolute;
  top:100%;
  left:-25px;
  z-index:10;
  display:none;
  text-align:left;
}

.de-menu li li {
  display:block;
  float:none;
}

.de-menu li li ul{
 margin-left:0;
}

.de-menu li:hover > ul {
  display:block;
}

.de-menu li ul ul {
  left:100%;
  top:0px;
}

.de-menu li:hover a {
 background:#64483E;
}

.de-menu select {padding:10px; height:36px; font-size:14px; border:none; background:#513D32; color:#fff;}
.de-menu select option{padding:10px;}```

答:
In my CSS file, "active" class has highlighting css values like

```<code>"background-color: #FFFFFF"
</code>```

I'm using these in each page:

```<code><script>
    document.getElementById("PAGE_MENU_NAME_1").className = "active";
</script>
</code>```

OR

```<code><script>
    document.getElementById("PAGE_MENU_NAME_2").className = "active";
</script>
</code>```

OR

```<code><script>
    document.getElementById("PAGE_MENU_NAME_3").className = "active";
</script>
</code>```

Use one of above for which page you are viewing.

This is my master page like "Menu.php"

```<code><ul id="menu">
   <li id="PAGE_MENU_NAME_1"><a href="page1.php">PAGEMENUNAME1"</a></li>
   <li id="PAGE_MENU_NAME_1"><a href="page2.php">PAGEMENUNAME2"</a></li>
   <li id="PAGE_MENU_NAME_3"><a href="page3.php">PAGEMENUNAME3"</a></li>
</ul>
</code>```

I hope you get what I said.

Body:
In my CSS file, "active" class has highlighting css values like

"background-color: #FFFFFF"

I'm using these in each page:

<script>
    document.getElementById("PAGE_MENU_NAME_1").className = "active";
</script>

OR

<script>
    document.getElementById("PAGE_MENU_NAME_2").className = "active";
</script>

OR

<script>
    document.getElementById("PAGE_MENU_NAME_3").className = "active";
</script>

Use one of above for which page you are viewing.

This is my master page like "Menu.php"

<ul id="menu">
   <li id="PAGE_MENU_NAME_1"><a href="page1.php">PAGEMENUNAME1"</a></li>
   <li id="PAGE_MENU_NAME_1"><a href="page2.php">PAGEMENUNAME2"</a></li>
   <li id="PAGE_MENU_NAME_3"><a href="page3.php">PAGEMENUNAME3"</a></li>
</ul>

I hope you get what I said.


答:
The error you are experiencing is due to the fact that you are not using the right syntax to access a 2D array.

To put it into context, the syntax to access an arbitrary nth element in the array is

```<code>array(n)
</code>```

and if you think about it, a 2D array is just an array of arrays, meaning that to access the inner array you could do something like

```<code>val inner = nested(n)
inner(m)
</code>```

Or in short

```<code>nested(n)(m)
</code>```

Title: how to assign the value of match expression to a 2-dim array's elements in scala?

Body:
The error you are experiencing is due to the fact that you are not using the right syntax to access a 2D array.

To put it into context, the syntax to access an arbitrary nth element in the array is

array(n)

and if you think about it, a 2D array is just an array of arrays, meaning that to access the inner array you could do something like

val inner = nested(n)
inner(m)

Or in short

nested(n)(m)


问:
How to use single print function to print multiple lines?
I just started learning Python3 and I got to the part where I started using arithmetic operations, I am trying to break the result into multiple lines, I used sep='/n' and /n, but I gives this error (positional argument follows keyword argument) I know it maybe a noob question but I can't figure out how to do it or what to search for in Google.

```<code>x=22
y=18
print('x+y=', x+y, 'x-y=', x-y)
</code>```

The result I get is this:
x+y= 40 x-y= 4.

I want it to be displayed like this:

x+y= 40

x-y= 4

答:
Why not use format instead:

```<code>x=22
y=18
print("x+y= {}\nx-y= {}".format(x+y, x-y))
</code>```

Output:

```<code>x+y= 40
x-y= 4
</code>```

Body:
I just started learning Python3 and I got to the part where I started using arithmetic operations, I am trying to break the result into multiple lines, I used sep='/n' and /n, but I gives this error (positional argument follows keyword argument) I know it maybe a noob question but I can't figure out how to do it or what to search for in Google.

x=22
y=18
print('x+y=', x+y, 'x-y=', x-y)

The result I get is this:
x+y= 40 x-y= 4.

I want it to be displayed like this:

x+y= 40

x-y= 4

Body:
Why not use format instead:

x=22
y=18
print("x+y= {}\nx-y= {}".format(x+y, x-y))

Output:

x+y= 40
x-y= 4


问:
Linq Where clause with two conditions, not working
I have three tables:

```<code>[Products]
    Id
    Title
    Info
    Price

[ProductCategories]
    Id
    Title
    ParentId

[ProductsInCategories]
    Id
    ProductId
    ProductCategoryId
</code>```

I'm trying to read a selection of products in a certain category. The code I have doesn't concider the ProductCategoryId, and just loads all products from the Product table. Where's my mistake?:

The id-variable is a method argument. The value coming in is correct.

```<code>var ProdInCat = from p in _context.Products
                from pc in _context.ProductsInCategories
                    .Where(x => p.Id == x.ProductId && x.ProductCategoryId == id)
                    .DefaultIfEmpty()
                select new
                {
                    p.Id,
                    p.Title,
                    p.Info,
                    p.Price
                };
</code>```

答:
Use Inner join expression</p>

```<code>var ProdInCat = from p in _context.Products
                from pc in _context.ProductsInCategories.Where(x => x.ProductCategoryId == id).DefaultIfEmpty()
                on p.Id equals pc.ProductID
                select new {
                    p.Id,
                    p.Title,
                    p.Info,
                    p.Price
                };
</code>```

Body:
I have three tables:

[Products]
    Id
    Title
    Info
    Price

[ProductCategories]
    Id
    Title
    ParentId

[ProductsInCategories]
    Id
    ProductId
    ProductCategoryId

I'm trying to read a selection of products in a certain category. The code I have doesn't concider the ProductCategoryId, and just loads all products from the Product table. Where's my mistake?:

The id-variable is a method argument. The value coming in is correct.

var ProdInCat = from p in _context.Products
                from pc in _context.ProductsInCategories
                    .Where(x => p.Id == x.ProductId && x.ProductCategoryId == id)
                    .DefaultIfEmpty()
                select new
                {
                    p.Id,
                    p.Title,
                    p.Info,
                    p.Price
                };

Body:
Use Inner join expression

var ProdInCat = from p in _context.Products
                from pc in _context.ProductsInCategories.Where(x => x.ProductCategoryId == id).DefaultIfEmpty()
                on p.Id equals pc.ProductID
                select new {
                    p.Id,
                    p.Title,
                    p.Info,
                    p.Price
                };


问:
Eclipse CDT Oxygen + DevStyle no build error highlighting
I recently switch to eclipse CDT(Oxygen.1a Release (4.7.1a)). I also installed the DevStyle Plugin. Since then I don't get error/warning highlighting in the build console. It seems that the error is parsed correctly, because it shows up in the problem window.

Here are some pictures:

Error in Build

Problem Window

Settings

Thanks

答:
Ok found the problem. Devstyle used black color in default for highlighting warnings and errors. With the new settings it is working.

console settings


问:
How to access a JSON object that is inside an object having no name
I have this JSON

```<code>{
    "success": true,
    "shippingMethod": [
        {
            "flat": {
                "code": "flat.flat",
                "title": "Flat Shipping Rate",
                "cost": "5.00",
                "tax_class_id": "9",
                "text": "$5.00"
            }
        },
        {
            "zajil": {
                "code": "zajil.zajil",
                "title": "Zajil Shipping",
                "cost": "26",
                "tax_class_id": "0",
                "text": "$26.00"
            }
        }
    ]
}
</code>```

Notice that every real object in array is within an unnecessary object that has no name i.e. flat and zajil in the above code are in another object.

I just need the data within those nested objects flat and zajil. When I try this code

```<code>JSONArray shippingMethods = response.optJSONArray("shippingMethod");
          for (int i = 0; i < shippingMethods.length(); i++) {
          JSONObject shippingObj = shippingMethods.optJSONObject(i);
          JSONObject shippingMethod = shippingObj.optJSONObject("");
          Iterator<?> keys = shippingObj.keys();
             shippingMethod.optString("title");
             shippingMethod.optString("cost");
       }
</code>```

I supposed I can get the Object that has no name like

```<code>JSONObject shippingMethod = shippingObj.optJSONObject("");
</code>```

But it does not work and throw NullPointerException when getting something from it. Then I try to iterate for keys like

```<code>Iterator<?> keys = shippingObj.keys();
</code>```

It does not show anything as this object does not contain any key directly. So My question is how can I get the required data title and cost from the above JSON.
I can't change JSON as it is the default structure of the customer's website.

Any help would be appreciated.

答:
Try like this, may help you</p>

```<code>//get response
JSONObject jsonObject = new JSONObject("response");

//get status
boolean success = jsonObject.getBoolean("success");

if(success){
    //get jsonarray from response
    JSONArray shippingMethodArray = jsonObject.getJSONArray("shippingMethod");

    //iterate array
    for(int i=0; i<shippingMethodArray.length(); i++){

        jsonObject = shippingMethodArray.getJSONObject(i);

        //get all keys from jsonObject
        List<String> allKeys = getAllKeys(jsonObject);

        //iterate all keys
        for(String key: allKeys) {

            //get jsonObject by key
            jsonObject = jsonObject.getJSONObject(key);

            //get data
            String title = jsonObject.getString("title");
            String cost = jsonObject.getString("cost");
        }
    }
}else {
    //do if not success...
}

//returns all keys from jsonobjects
private List<String> getAllKeys(JSONObject jsonObject) throws JSONException{
    List<String> keys = new ArrayList<String>();

    Iterator<?> iterator = jsonObject.keys();
    while( iterator.hasNext() ) {
        String key = (String)iterator.next();
        keys.add(key);
    }
    return keys;
}
</code>```

Body:
I have this JSON

{
    "success": true,
    "shippingMethod": [
        {
            "flat": {
                "code": "flat.flat",
                "title": "Flat Shipping Rate",
                "cost": "5.00",
                "tax_class_id": "9",
                "text": "$5.00"
            }
        },
        {
            "zajil": {
                "code": "zajil.zajil",
                "title": "Zajil Shipping",
                "cost": "26",
                "tax_class_id": "0",
                "text": "$26.00"
            }
        }
    ]
}

Notice that every real object in array is within an unnecessary object that has no name i.e. flat and zajil in the above code are in another object.

I just need the data within those nested objects flat and zajil. When I try this code

JSONArray shippingMethods = response.optJSONArray("shippingMethod");
          for (int i = 0; i < shippingMethods.length(); i++) {
          JSONObject shippingObj = shippingMethods.optJSONObject(i);
          JSONObject shippingMethod = shippingObj.optJSONObject("");
          Iterator<?> keys = shippingObj.keys();
             shippingMethod.optString("title");
             shippingMethod.optString("cost");
       }

I supposed I can get the Object that has no name like

JSONObject shippingMethod = shippingObj.optJSONObject("");

But it does not work and throw NullPointerException when getting something from it. Then I try to iterate for keys like

Iterator<?> keys = shippingObj.keys();

It does not show anything as this object does not contain any key directly. So My question is how can I get the required data title and cost from the above JSON.
I can't change JSON as it is the default structure of the customer's website.

Any help would be appreciated.

Body:
Try like this, may help you

//get response
JSONObject jsonObject = new JSONObject("response");

//get status
boolean success = jsonObject.getBoolean("success");

if(success){
    //get jsonarray from response
    JSONArray shippingMethodArray = jsonObject.getJSONArray("shippingMethod");

    //iterate array
    for(int i=0; i<shippingMethodArray.length(); i++){

        jsonObject = shippingMethodArray.getJSONObject(i);

        //get all keys from jsonObject
        List<String> allKeys = getAllKeys(jsonObject);

        //iterate all keys
        for(String key: allKeys) {

            //get jsonObject by key
            jsonObject = jsonObject.getJSONObject(key);

            //get data
            String title = jsonObject.getString("title");
            String cost = jsonObject.getString("cost");
        }
    }
}else {
    //do if not success...
}

//returns all keys from jsonobjects
private List<String> getAllKeys(JSONObject jsonObject) throws JSONException{
    List<String> keys = new ArrayList<String>();

    Iterator<?> iterator = jsonObject.keys();
    while( iterator.hasNext() ) {
        String key = (String)iterator.next();
        keys.add(key);
    }
    return keys;
}


问:
Select the values in pop dataframe which its index in index_par dataframe
I'm buliding genetic algorithm for feature selection. And I'm having some difficulties.

I have pop dataframe (population), consist of 20 individus and 9 features:

```<code>    0   1   2   3   4   5   6   7   8
0   0   1   1   1   0   0   0   0   1
1   0   0   1   1   1   0   0   1   0
2   0   1   0   0   1   0   0   0   1
3   0   0   0   1   1   0   0   1   1
4   1   0   0   1   1   1   1   1   0
5   1   1   0   0   0   1   0   1   1
6   0   0   1   1   0   1   1   1   1
7   1   1   0   0   1   1   1   1   1
8   0   0   0   0   1   0   0   1   1
9   1   0   1   1   1   1   1   1   1
10  0   0   1   1   0   1   0   1   1
11  1   1   1   0   1   1   0   0   0
12  0   0   1   0   0   0   1   1   0
13  0   0   1   1   1   1   1   1   0
14  1   1   1   1   0   0   0   1   0
15  1   1   0   1   1   1   0   1   1
16  1   0   1   0   1   1   1   0   0
17  1   1   0   0   1   1   0   0   1
18  1   0   1   0   0   0   1   0   0
19  1   1   1   1   1   1   1   0   0
</code>```

And I have index_par dataframe, consist of index number:

```<code>    0
0   0
1   1
2   4
3   5
4   8
5   10
6   11
7   13
8   14
9   19
</code>```

The index_par dataframe is the indexes of selected parent for crossover.

How can I select the values in pop dataframe which its index in index_par dataframe? Thanks in advance.

Body:
I'm buliding genetic algorithm for feature selection. And I'm having some difficulties.

I have pop dataframe (population), consist of 20 individus and 9 features:

    0   1   2   3   4   5   6   7   8
0   0   1   1   1   0   0   0   0   1
1   0   0   1   1   1   0   0   1   0
2   0   1   0   0   1   0   0   0   1
3   0   0   0   1   1   0   0   1   1
4   1   0   0   1   1   1   1   1   0
5   1   1   0   0   0   1   0   1   1
6   0   0   1   1   0   1   1   1   1
7   1   1   0   0   1   1   1   1   1
8   0   0   0   0   1   0   0   1   1
9   1   0   1   1   1   1   1   1   1
10  0   0   1   1   0   1   0   1   1
11  1   1   1   0   1   1   0   0   0
12  0   0   1   0   0   0   1   1   0
13  0   0   1   1   1   1   1   1   0
14  1   1   1   1   0   0   0   1   0
15  1   1   0   1   1   1   0   1   1
16  1   0   1   0   1   1   1   0   0
17  1   1   0   0   1   1   0   0   1
18  1   0   1   0   0   0   1   0   0
19  1   1   1   1   1   1   1   0   0

And I have index_par dataframe, consist of index number:

    0
0   0
1   1
2   4
3   5
4   8
5   10
6   11
7   13
8   14
9   19

The index_par dataframe is the indexes of selected parent for crossover.

How can I select the values in pop dataframe which its index in index_par dataframe? Thanks in advance.

Body:
I think you need loc by column 0 of index_par:

index_par = pd.DataFrame({0:[0,1,4,5,8,10,11,13,14,19]})

df3 = pop.loc[index_par[0]]
print (df3)
    0  1  2  3  4  5  6  7  8
0   0  1  1  1  0  0  0  0  1
1   0  0  1  1  1  0  0  1  0
4   1  0  0  1  1  1  1  1  0
5   1  1  0  0  0  1  0  1  1
8   0  0  0  0  1  0  0  1  1
10  0  0  1  1  0  1  0  1  1
11  1  1  1  0  1  1  0  0  0
13  0  0  1  1  1  1  1  1  0
14  1  1  1  1  0  0  0  1  0
19  1  1  1  1  1  1  1  0  0


问:
Insert to list with variable names in python
I have three lists, named list0, list1 and list2.

Here is what i want to do

```<code>for n in range(10):
    x = n%3
    listx.append(n)
</code>```

where x can be 0, 1 or 2. How can I do this? Basically, I don't want to create 3 if/elif cases but just change the third line in above program

PS - I know this not the best method for this problem but my project is quite different from this

答:
Why not a list of lists?

```<code>lists = [[],[],[]]
for n in range(10):
    list[n%3].append(n)

list1,list2,list3 = lists
</code>```

or just use lists[i], which would scale better to bigger primes.

Body:
I have three lists, named list0, list1 and list2.

Here is what i want to do

for n in range(10):
    x = n%3
    listx.append(n)

where x can be 0, 1 or 2. How can I do this? Basically, I don't want to create 3 if/elif cases but just change the third line in above program

PS - I know this not the best method for this problem but my project is quite different from this

Body:
Why not a list of lists?

lists = [[],[],[]]
for n in range(10):
    list[n%3].append(n)

list1,list2,list3 = lists

or just use lists[i], which would scale better to bigger primes.


问:
Having a block of code wait to run at a certain time in iOS
Let's say I have a view controller with code that I want to execute at a certain time, say 2:00pm. What I want to happen is that if the user opens the view controller at 1:58pm, that the code will wait and continuously check the time, executing itself at exactly 2:00pm. Is there a way to do this in Swift 4, perhaps with a timer?</p>

答:
You can add a timer with a fire date to the runloop:

```<code>{
    let dateOfExecution = Date(timeIntervalSince1970: <number of seconds from 1970-01-01-00:00:00 to your date of execution>)
    let timer = Timer(fireAt: dateOfExecution, interval: 0, target: self, selector: #selector(codeToExecute), userInfo: nil, repeats: false)
    RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
}

@objc func codeToExecute() {
    <Your code to run>
}
</code>```

See Apple docs: https://developer.apple.com/documentation/foundation/timer/1415700-init

Body:
You can add a timer with a fire date to the runloop:

{
    let dateOfExecution = Date(timeIntervalSince1970: <number of seconds from 1970-01-01-00:00:00 to your date of execution>)
    let timer = Timer(fireAt: dateOfExecution, interval: 0, target: self, selector: #selector(codeToExecute), userInfo: nil, repeats: false)
    RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
}

@objc func codeToExecute() {
    <Your code to run>
}

See Apple docs: https://developer.apple.com/documentation/foundation/timer/1415700-init


问:
Python: ValueError: invalid literal for int() with base 10: '"'
I'm creating code to get the average score in a CSV file.

CSV file looks like this:

```<code>5 Ser15

4 Ser15

3 Ser15
</code>```

1st column are the scores, the second are the usernames.

This is my code so far:

```<code>   def av():
    with open("SciMedreport.csv","r") as f:
        average = 0
        Sum = 0
        row_count = 0
        for row in f:
            column = row.split(',')
            i=(int(column[0]))
            Sum += i
            row_count += 1
        average = Sum / row_count
        return 'The average is:', average
  av()
</code>```

But this error appears...

```<code>  i=int(column[0])
ValueError: invalid literal for int() with base 10: '"'
</code>```

When I print the whole row to check, this appears:

```<code>def av():
with open("SciMedreport.csv","r") as f:
    average = 0
    Sum = 0
    row_count = 0
    for row in f:
        print(row)
av()
</code>```

This is the result:

```<code>5,Ser15
""

5,Ser15

""

4,Ser15
</code>```

Anyone know of a way to fix this, or an alternative way to work out the average??

答:
I am able to see a couple of errors in the code.

```<code>for row in f:
(1)    for column in row.split(','):
(2)            i=(int(column))
            Sum += i
        row_count += 1
(3)    average = Sum / len(column)
</code>```

(1) When you split the row, what you get back is basically an array/list. In your case, it would be ['5', 'Ser15]. And instead of a for loop, you might want to change the code as follows:

```<code>for row in f:
    columns_list = row.split(',')
    i=(int(columns_list[0]))
    Sum += i
    row_count += 1
average = Sum / row_count
</code>```

(2) Now you can't convert a list to an integer. What you might be interested in is i = int(column[0]) i.e. first number in the list i.e. first column of your CSV file.

(3) You want to find the average of all rows, right? Souldn't it be average = Sum / row_count?

```<code>def av():
    with open("SciMedreport.csv","r") as f:
        average = 0
        Sum = 0
        row_count = 0
        divisor = 0
        for row in f:
            row_count += 1
            if row_count%2 == 0: # if it doesn't work, try changing to 1
                # print(row.split(','))
                divisor += 1
                # write rest of the code here, Sum += i etc.
                columns_list = row.split(',')
                i = int(columns_list[0])
                Sum += i
        average = Sum / divisor
</code>```

Body:
I'm creating code to get the average score in a CSV file.

CSV file looks like this:

5 Ser15

4 Ser15

3 Ser15

1st column are the scores, the second are the usernames.

This is my code so far:

   def av():
    with open("SciMedreport.csv","r") as f:
        average = 0
        Sum = 0
        row_count = 0
        for row in f:
            column = row.split(',')
            i=(int(column[0]))
            Sum += i
            row_count += 1
        average = Sum / row_count
        return 'The average is:', average
  av()

But this error appears...

  i=int(column[0])
ValueError: invalid literal for int() with base 10: '"'

When I print the whole row to check, this appears:

def av():
with open("SciMedreport.csv","r") as f:
    average = 0
    Sum = 0
    row_count = 0
    for row in f:
        print(row)
av()

This is the result:

5,Ser15
""

5,Ser15

""

4,Ser15

Anyone know of a way to fix this, or an alternative way to work out the average??

Body:
I am able to see a couple of errors in the code.

for row in f:
(1)    for column in row.split(','):
(2)            i=(int(column))
            Sum += i
        row_count += 1
(3)    average = Sum / len(column)

(1) When you split the row, what you get back is basically an array/list. In your case, it would be ['5', 'Ser15]. And instead of a for loop, you might want to change the code as follows:

for row in f:
    columns_list = row.split(',')
    i=(int(columns_list[0]))
    Sum += i
    row_count += 1
average = Sum / row_count

(2) Now you can't convert a list to an integer. What you might be interested in is i = int(column[0]) i.e. first number in the list i.e. first column of your CSV file.

(3) You want to find the average of all rows, right? Souldn't it be average = Sum / row_count?

def av():
    with open("SciMedreport.csv","r") as f:
        average = 0
        Sum = 0
        row_count = 0
        divisor = 0
        for row in f:
            row_count += 1
            if row_count%2 == 0: # if it doesn't work, try changing to 1
                # print(row.split(','))
                divisor += 1
                # write rest of the code here, Sum += i etc.
                columns_list = row.split(',')
                i = int(columns_list[0])
                Sum += i
        average = Sum / divisor


答:
You can join products with a filtered list of products in categories based on your external (computed) id.

```<code>from p in _context.Products
join pc in _context.ProductsInCategories.Where(pic => pic.ProductCategoryId == id).DefaultIfEmpty()
on p.Id equals pc.ProductId
</code>```

More about how can you achieve this at the following link: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/join-clause

Title: Linq Where clause with two conditions, not working

Body:
You can join products with a filtered list of products in categories based on your external (computed) id.

from p in _context.Products
join pc in _context.ProductsInCategories.Where(pic => pic.ProductCategoryId == id).DefaultIfEmpty()
on p.Id equals pc.ProductId

More about how can you achieve this at the following link: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/join-clause


问:
How to ignore the fail case and continues to next value
I am looping values from an Excel file by using ${txnExcel} to search and compare the value. But sometimes ${txnExcel} is doesn't exist in the system. In that case I want to ignore the fail (as there is no need to compare value) and continue to the next ${txnExcel} by skipping the error.

```<code>open excel      ${PATH_EXCEL}
    ${exp_row_count}    get row count   Sheet1
    :For    ${i}    in range     1       ${exp_row_count}
    \   ${excel_index}      evaluate  ${i}+1
    \   ${txnExcel}    Read Cell Data By Name    Sheet1    B${excel_index}
    \   ${ServiceTypeExcel}    Read Cell Data By Name    Sheet1    C${excel_index}
    \   ${TransferAmountExcelOrigin}    Read Cell Data By Name    Sheet1    D${excel_index}
    \   ${CurrencyExcel}    Read Cell Data By Name    Sheet1    E${excel_index}
    \   ${TransferAmountExcel}  set variable    ${TransferAmountExcelOrigin} ${CurrencyExcel}
#=======================================================================================
    \   input text       name=id_or_tsn     ${txnExcel}
    \   click button    name=Submit
    \   wait until element is visible   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]    5s

   #===========================Compare Transaction Element================================================
   \   ${txnCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]
   \   ${ServiceTypeCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[3]/div[2]/span
   \   ${TransferAmountCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[5]/div[2]/span
   \   ${CurrencyCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[4]/div[2]
   \   should be equal as strings    ${txnExcel}    ${txnCompare}       invalid TXN comparison[${i}]
   \   should be equal as strings    ${ServiceTypeExcel}    ${ServiceTypeCompare}       invalid ServiceType comparison[${i}]
   \   should be equal as strings    ${TransferAmountExcel}    ${TransferAmountCompare}       invalid Transfer Amount comparison[${i}]
   \   should be equal as strings    ${CurrencyExcel}    ${CurrencyCompare}       invalid Currency comparison[${i}]
#============================End Compare Transaction Element====================================================
</code>```

答:
Here the solution that work for me now .</p>

```<code>open excel      ${PATH_EXCEL}
    ${exp_row_count}    get row count   Sheet1
    :For    ${i}    in range     1       ${exp_row_count}
    \   ${excel_index}      evaluate  ${i}+1
    \   ${txnExcel}    Read Cell Data By Name    Sheet1    B${excel_index}
    \   ${ServiceTypeExcel}    Read Cell Data By Name    Sheet1    C${excel_index}
    \   ${TransferAmountExcelOrigin}    Read Cell Data By Name    Sheet1    D${excel_index}
    \   ${CurrencyExcel}    Read Cell Data By Name    Sheet1    E${excel_index}
    \   ${TransferAmountExcel}  set variable    ${TransferAmountExcelOrigin} ${CurrencyExcel}
    #=======================================================================================
    \   input text       name=id_or_tsn     ${txnExcel}
    \   click button    name=Submit
    \   ${found_txn}    run keyword and return status   wait until element is visible   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]    5s
    \   ${error_message}    run keyword unless  ${found_txn}    get text    xpath=/html/body/div[2]/div[2]
    \   run keyword and continue on failure     element should be visible       xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]
    \   run keyword unless      ${found_txn}        continue for loop
    #===========================Compare Transaction Element================================================
    \   ${txnCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]
    \   ${ServiceTypeCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[3]/div[2]/span
    \   ${TransferAmountCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[5]/div[2]/span
    \   ${CurrencyCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[4]/div[2]
    \   should be equal as strings    ${txnExcel}    ${txnCompare}       invalid TXN comparison[${i}]
    \   should be equal as strings    ${ServiceTypeExcel}    ${ServiceTypeCompare}       invalid ServiceType comparison[${i}]
    \   should be equal as strings    ${TransferAmountExcel}    ${TransferAmountCompare}       invalid Transfer Amount comparison[${i}]
    \   should be equal as strings    ${CurrencyExcel}    ${CurrencyCompare}       invalid Currency comparison[${i}]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am looping values from an Excel file by using ${txnExcel} to search and compare the value. But sometimes ${txnExcel} is doesn't exist in the system. In that case I want to ignore the fail (as there is no need to compare value) and continue to the next ${txnExcel} by skipping the error.

open excel      ${PATH_EXCEL}
    ${exp_row_count}    get row count   Sheet1
    :For    ${i}    in range     1       ${exp_row_count}
    \   ${excel_index}      evaluate  ${i}+1
    \   ${txnExcel}    Read Cell Data By Name    Sheet1    B${excel_index}
    \   ${ServiceTypeExcel}    Read Cell Data By Name    Sheet1    C${excel_index}
    \   ${TransferAmountExcelOrigin}    Read Cell Data By Name    Sheet1    D${excel_index}
    \   ${CurrencyExcel}    Read Cell Data By Name    Sheet1    E${excel_index}
    \   ${TransferAmountExcel}  set variable    ${TransferAmountExcelOrigin} ${CurrencyExcel}
#=======================================================================================
    \   input text       name=id_or_tsn     ${txnExcel}
    \   click button    name=Submit
    \   wait until element is visible   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]    5s

   #===========================Compare Transaction Element================================================
   \   ${txnCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]
   \   ${ServiceTypeCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[3]/div[2]/span
   \   ${TransferAmountCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[5]/div[2]/span
   \   ${CurrencyCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[4]/div[2]
   \   should be equal as strings    ${txnExcel}    ${txnCompare}       invalid TXN comparison[${i}]
   \   should be equal as strings    ${ServiceTypeExcel}    ${ServiceTypeCompare}       invalid ServiceType comparison[${i}]
   \   should be equal as strings    ${TransferAmountExcel}    ${TransferAmountCompare}       invalid Transfer Amount comparison[${i}]
   \   should be equal as strings    ${CurrencyExcel}    ${CurrencyCompare}       invalid Currency comparison[${i}]
#============================End Compare Transaction Element====================================================

Body:
Here the solution that work for me now .

open excel      ${PATH_EXCEL}
    ${exp_row_count}    get row count   Sheet1
    :For    ${i}    in range     1       ${exp_row_count}
    \   ${excel_index}      evaluate  ${i}+1
    \   ${txnExcel}    Read Cell Data By Name    Sheet1    B${excel_index}
    \   ${ServiceTypeExcel}    Read Cell Data By Name    Sheet1    C${excel_index}
    \   ${TransferAmountExcelOrigin}    Read Cell Data By Name    Sheet1    D${excel_index}
    \   ${CurrencyExcel}    Read Cell Data By Name    Sheet1    E${excel_index}
    \   ${TransferAmountExcel}  set variable    ${TransferAmountExcelOrigin} ${CurrencyExcel}
    #=======================================================================================
    \   input text       name=id_or_tsn     ${txnExcel}
    \   click button    name=Submit
    \   ${found_txn}    run keyword and return status   wait until element is visible   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]    5s
    \   ${error_message}    run keyword unless  ${found_txn}    get text    xpath=/html/body/div[2]/div[2]
    \   run keyword and continue on failure     element should be visible       xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]
    \   run keyword unless      ${found_txn}        continue for loop
    #===========================Compare Transaction Element================================================
    \   ${txnCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]
    \   ${ServiceTypeCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[3]/div[2]/span
    \   ${TransferAmountCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[5]/div[2]/span
    \   ${CurrencyCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[4]/div[2]
    \   should be equal as strings    ${txnExcel}    ${txnCompare}       invalid TXN comparison[${i}]
    \   should be equal as strings    ${ServiceTypeExcel}    ${ServiceTypeCompare}       invalid ServiceType comparison[${i}]
    \   should be equal as strings    ${TransferAmountExcel}    ${TransferAmountCompare}       invalid Transfer Amount comparison[${i}]
    \   should be equal as strings    ${CurrencyExcel}    ${CurrencyCompare}       invalid Currency comparison[${i}]


问:
Securing Laravel application code
Im installing my Laravel projects in the servers of the clients to use in Local Networks.. can you ofuscate the code or protect it with tools like Homestead / Vagrant or something like that ?? Or only at the Windows user levels I can protect the code from being stolen.. </p>

答:
If your applications run on local networks you don't really need to protect something because your app can't be call from internet.

You could use a proxy access from the local network but i'm not sure if it's really useful.

Best

Title: Securing Laravel application code


问:
How to toggle a UITextField secure text entry (hide password) in Swift?
I currently have a UITextfield with an eye icon in it that when pressed is supposed to toggle the secure text entry on and off.

I know you can check mark the "secure text entry" box in the attributes inspector but how to do it so it toggles whenever the icon is pressed?

答:
First you need to set image(visible or hide) of button of eye for different state (selected or normal)

than connect IBAction and write code like

```<code>@IBAction func btnPasswordVisiblityClicked(_ sender: Any) {
        (sender as! UIButton).isSelected = !(sender as! UIButton).isSelected
        if (sender as! UIButton).isSelected {
            txtfPassword.isSecureTextEntry = false
        } else {
            txtfPassword.isSecureTextEntry = true
        }
    }
</code>```

Body:
First you need to set image(visible or hide) of button of eye for different state (selected or normal)

than connect IBAction and write code like

@IBAction func btnPasswordVisiblityClicked(_ sender: Any) {
        (sender as! UIButton).isSelected = !(sender as! UIButton).isSelected
        if (sender as! UIButton).isSelected {
            txtfPassword.isSecureTextEntry = false
        } else {
            txtfPassword.isSecureTextEntry = true
        }
    }


问:
How to create Performance testing framework in jmeter?
For functional automation we use to create a framework which is reusable for automating application. Is there any way to create Performance testing framework in jmeter. So that we can use same framework for Performance testing of different applications.

Please help if any one knows and provide more information regarding it.

答:
You can consider JMeter as a "framework" which already comes with test elements to build requests via different protocols/transports, applying assertions, generating reports, etc.

It is highly unlikely you will be able to re-use existing script for another application as JMeter acts on protocol level therefore there will be different requests for different applications.

There is a mechanism in JMeter allowing to re-use pieces of test plan as modules so you won't have to duplicate your code, check out Test Fragments and Module Controller, however it is more applicable for a single application.

The only "framework-like" approach I can think of is adding your JMeter tests into continuous integration process so you will have a build step which will execute performance tests and publish reports, basically you will be able to re-use the same test setup and reporting routine and the only thing which will change from application to application will be .jmx test script(s). See JMeter Maven Plugin and/or JMeter Ant Task for more details.


问:
How to Apply Regex Validation to a textbox in JQuery to enter only decimal(s),integer(s) numbers(if multiple comma seperated)
My HTML Code is

```<code><input type="text" class="form-control textinput" id="Result" name="Result" value="@p.Result"/>
</code>```

My JQuery Code is :

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

    $(".textinput").keydown(function (e) {
        var test = ^(\d?\d?\d(,\d\d\d)*|\d+)(\.\d\d)?$;
        var value = String.fromCharCode(e.keyCode);
        if (value.match(test)) {
            return false;
        }
    });
});
</code>```

I have reffered to This Question but it isn't working,showing an error so please help

My Sample Inputs will be as follows

1,245.30

24,235

135.60,12.6

235.50

34

Body:
My HTML Code is

<input type="text" class="form-control textinput" id="Result" name="Result" value="@p.Result"/>

My JQuery Code is :

$(function () {

    $(".textinput").keydown(function (e) {
        var test = ^(\d?\d?\d(,\d\d\d)*|\d+)(\.\d\d)?$;
        var value = String.fromCharCode(e.keyCode);
        if (value.match(test)) {
            return false;
        }
    });
});

I have reffered to This Question but it isn't working,showing an error so please help

My Sample Inputs will be as follows

1,245.30

24,235

135.60,12.6

235.50

34

Body: Try this one: ^\d+((?=[\,\.])([\.\,]\d+|$))*$.


问:
BeautifulSoup find a data-reactid
I have a python script using beautifulsoup to scrape a property sales website.
I am trying to get the number of beds from the HTML.

The data-reactid changes for each listing in the search results. The number $11606747 is unique.
I am trying to wild card search for "*$beds.0.0" to return the number of beds =3 in the example.

There is no error message, and the code runs but doesn't return the number.

What am I doing wrong?

The HTML:

```<code><div class="property-features is-regular listing-result__features" data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2"><span class="property-feature__feature" data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds"><span class="property-feature__feature-text-container" data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds.0"><span data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds.0.0">3</span><span data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds.0.1"> </span><span class="property-features__feature-text" data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds.0.2">Beds</span></span>
</code>```

The Python code

```<code>beds = listing.findAll('span',{"data-reactid":re.compile('*$beds.0.0')})
</code>```

答:
You can try like this to get the bed status:

```<code>content='''
<html>
 <body>
  <div class="property-features is-regular listing-result__features" data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2">
   <span class="property-feature__feature" data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds">
    <span class="property-feature__feature-text-container" data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds.0">
     <span data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds.0.0">
      3
     </span>
     <span data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds.0.1">
     </span>
     <span class="property-features__feature-text" data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds.0.2">
      Beds
     </span>
    </span>
   </span>
  </div>
 </body>
</html>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(content,"lxml")
item = soup.select("div span[data-reactid*='$11606747']")[0].text
print(' '.join(item.split()))
</code>```

Result:

```<code>3 Beds
</code>```

Title: BeautifulSoup find a data-reactid

Body:
I have a python script using beautifulsoup to scrape a property sales website.
I am trying to get the number of beds from the HTML.

The data-reactid changes for each listing in the search results. The number $11606747 is unique.
I am trying to wild card search for "*$beds.0.0" to return the number of beds =3 in the example.

There is no error message, and the code runs but doesn't return the number.

What am I doing wrong?

The HTML:

3 Beds

The Python code

beds = listing.findAll('span',{"data-reactid":re.compile('*$beds.0.0')})

Body:
You can try like this to get the bed status:

content='''
<html>
 <body>
  <div class="property-features is-regular listing-result__features" data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2">
   <span class="property-feature__feature" data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds">
    <span class="property-feature__feature-text-container" data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds.0">
     <span data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds.0.0">
      3
     </span>
     <span data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds.0.1">
     </span>
     <span class="property-features__feature-text" data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds.0.2">
      Beds
     </span>
    </span>
   </span>
  </div>
 </body>
</html>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(content,"lxml")
item = soup.select("div span[data-reactid*='$11606747']")[0].text
print(' '.join(item.split()))

Result:

3 Beds


问:
How to extract src from a input tag with BeautifulSoup

I want to extract src from a input tag but when I get the beautifulsoup result, I find the src is ignored.

```<code>for i in soup_image.find_all('input'):
    print(i)
</code>```

I want to get the value of src.

But the value is ignored in the result.
This is the original tag(I inspect it in a browser).

```<code><input src="https://www1.wi.to/2017/08/11/9c01e43e1652635563826de457b06e25.jpg" type="image" onclick="window.open('http://www.viidii.info/?action=image&url=&src='+encodeURIComponent(this.src));return false;">
</code>```

And this is what I get(I look at it in soup),

```<code><input onclick="window.open('http://www.viidii.info/?action=image&url=&src='+encodeURIComponent(this.src));return false;" src="http://cdn1.snapgram.co/imgs/2016/08/01/marker-small.png" type="image"/>
</code>```

I want to get the src from the first input because that src can open in the browser, which is different from the src in the second input. Actually, you can see it disappears in the second input tag.

Dose it get encoded after I crawl it? I have no idea. Please help me.

答:
If you are looking to get the src value from input tag

```<code>soup.find('input')['src']
</code>```

Will help you get it.

Body:
I want to extract src from a input tag but when I get the beautifulsoup result, I find the src is ignored.

for i in soup_image.find_all('input'):
    print(i)

I want to get the value of src.

But the value is ignored in the result.
This is the original tag(I inspect it in a browser).

<input src="https://www1.wi.to/2017/08/11/9c01e43e1652635563826de457b06e25.jpg" type="image" onclick="window.open('http://www.viidii.info/?action=image&url=&src='+encodeURIComponent(this.src));return false;">

And this is what I get(I look at it in soup),

<input onclick="window.open('http://www.viidii.info/?action=image&url=&src='+encodeURIComponent(this.src));return false;" src="http://cdn1.snapgram.co/imgs/2016/08/01/marker-small.png" type="image"/>

I want to get the src from the first input because that src can open in the browser, which is different from the src in the second input. Actually, you can see it disappears in the second input tag.

Dose it get encoded after I crawl it? I have no idea. Please help me.

Body:
If you are looking to get the src value from input tag

soup.find('input')['src']

Will help you get it.


问:
How best to wait until the actor stops in kotlinx.coroutines 0.20?
In kotlinx.coroutines 0.19, actor returns ActorJob which can be joined:

```<code>val myActor = actor<...> { ... }
...
myActor.join()
</code>```

In 0.20, it's changed to return SendChannel. Looking at the implementation, it does still return an instance of a class which extends Job, so I could write

```<code>...
(myActor as Job).join()
</code>```

but this is an obvious code smell. Is there a better alternative?

答: What I ended up doing is creating a Channel and then separately launching a Job iterating over this channel.

Body:
In kotlinx.coroutines 0.19, actor returns ActorJob which can be joined:

val myActor = actor<...> { ... }
...
myActor.join()

In 0.20, it's changed to return SendChannel. Looking at the implementation, it does still return an instance of a class which extends Job, so I could write

...
(myActor as Job).join()

but this is an obvious code smell. Is there a better alternative?


问:
Hibernate makes problems on " nullable = false" in MySQL
I am trying to insert some of the values in MySQL table with hibernate . I am using following table :

```<code>create table test_settings (
  id bigint not null,
  address varchar(64),
  enabled smallint not null,
  max_count integer,
  storage_period integer,
  rocommunity varchar(128) not null,
  skip_unknown smallint not null,
  storage_type integer not null,
  primary key (id)
);
</code>```

and in java file i am trying to add values :

```<code>@Entity
@Table(name = "test_settings ")
public class TestSettings extends Singleton {
@Column(name = "address", nullable = false, length = 64)
    String address;

    @Column(name = "storage_type", nullable = false)
    @Enumerated(EnumType.ORDINAL)
    StorageType storageType = StorageType.MEMORY;

    @Column(name = "max_count")
    Integer maxCountInMemory;

    @Column(name = "storage_period")
    Integer storagePeriod;

    @Column(name = "skip_unknown", nullable = false)
    boolean skipUnknown = true;

    @Column(name = "rocommunity", length = 128, nullable = false)
    String rocommunity = "public";

    @Column(name = "enabled", nullable = false)
    boolean enabled = false;
}
</code>```

I can see my table in MySQL server :

```<code>mysql> describe test_settings;
+---------------------+--------------+------+-----+---------+-------+
| Field               | Type         | Null | Key | Default | Extra |
+---------------------+--------------+------+-----+---------+-------+
| id                  | bigint(20)   | NO   | PRI | NULL    |       |
| address             | varchar(64)  | NO   |     | NULL    |       |
| enabled             | bit(1)       | NO   |     | NULL    |       |
| max_count           | int(11)      | YES  |     | NULL    |       |
| rocommunity         | varchar(128) | NO   |     | NULL    |       |
| skip_unknown        | bit(1)       | NO   |     | NULL    |       |
| storage_period      | int(11)      | YES  |     | NULL    |       |
| storage_type        | int(11)      | NO   |     | NULL    |       |
+---------------------+--------------+------+-----+---------+-------+
8 rows in set (0.00 sec)
</code>```

But i am getting some exception problem while deploying . These are the complete stack trace :

```<code>Caused by: org.springframework.dao.DataIntegrityViolationException: Could not execute JDBC batch update; SQL [insert into mam_db.snmp_settings (address, enabled, max_count_in_memory, rocommunity, skip_unknown, storage_period, storage_type, id) values (?, ?, ?, ?, ?, ?, ?, ?)]; constraint [null];

10:37:41,165 INFO  [stdout] (ServerService Thread Pool -- 116) Caused by: java.sql.BatchUpdateException: Column 'address' cannot be null
10:37:41,165 INFO  [stdout] (ServerService Thread Pool -- 116)  at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1666)
10:37:41,165 INFO  [stdout] (ServerService Thread Pool -- 116)  at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1082)
10:37:41,165 INFO  [stdout] (ServerService Thread Pool -- 116)  at org.jboss.jca.adapters.jdbc.WrappedStatement.executeBatch(WrappedStatement.java:1077)
10:37:41,166 INFO  [stdout] (ServerService Thread Pool -- 116)  at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
10:37:41,166 INFO  [stdout] (ServerService Thread Pool -- 116)  at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
10:37:41,166 INFO  [stdout] (ServerService Thread Pool -- 116)  ... 58 more
</code>```

But i am using  nullable = false in java code . But this is working fine with PostgreSQL and DB2 . Getting exception on MySQL only .

This is the corresponding DB2 table :

```<code>CREATE TABLE TEST_SETTINGS (
  ID BIGINT NOT NULL,
  ADDRESS VARCHAR(64),
  ENABLED SMALLINT NOT NULL,
  MAX_COUNT INTEGER,
  STORAGE_PERIOD INTEGER,
  ROCOMMUNITY VARCHAR(128) NOT NULL,
  SKIP_UNKNOWN SMALLINT NOT NULL,
  STORAGE_TYPE INTEGER NOT NULL,
  PRIMARY KEY (ID)
)#
</code>```

Any suggestion ?

答: @Column(nullable = false) is the JPA way to declare a column to be not-null. If you want that it will be able to insert null address do not use this annotation.

Body:
I am trying to insert some of the values in MySQL table with hibernate . I am using following table :

create table test_settings (
  id bigint not null,
  address varchar(64),
  enabled smallint not null,
  max_count integer,
  storage_period integer,
  rocommunity varchar(128) not null,
  skip_unknown smallint not null,
  storage_type integer not null,
  primary key (id)
);

and in java file i am trying to add values :

@Entity
@Table(name = "test_settings ")
public class TestSettings extends Singleton {
@Column(name = "address", nullable = false, length = 64)
    String address;

    @Column(name = "storage_type", nullable = false)
    @Enumerated(EnumType.ORDINAL)
    StorageType storageType = StorageType.MEMORY;

    @Column(name = "max_count")
    Integer maxCountInMemory;

    @Column(name = "storage_period")
    Integer storagePeriod;

    @Column(name = "skip_unknown", nullable = false)
    boolean skipUnknown = true;

    @Column(name = "rocommunity", length = 128, nullable = false)
    String rocommunity = "public";

    @Column(name = "enabled", nullable = false)
    boolean enabled = false;
}

I can see my table in MySQL server :

mysql> describe test_settings;
+---------------------+--------------+------+-----+---------+-------+
| Field               | Type         | Null | Key | Default | Extra |
+---------------------+--------------+------+-----+---------+-------+
| id                  | bigint(20)   | NO   | PRI | NULL    |       |
| address             | varchar(64)  | NO   |     | NULL    |       |
| enabled             | bit(1)       | NO   |     | NULL    |       |
| max_count           | int(11)      | YES  |     | NULL    |       |
| rocommunity         | varchar(128) | NO   |     | NULL    |       |
| skip_unknown        | bit(1)       | NO   |     | NULL    |       |
| storage_period      | int(11)      | YES  |     | NULL    |       |
| storage_type        | int(11)      | NO   |     | NULL    |       |
+---------------------+--------------+------+-----+---------+-------+
8 rows in set (0.00 sec)

But i am getting some exception problem while deploying . These are the complete stack trace :

Caused by: org.springframework.dao.DataIntegrityViolationException: Could not execute JDBC batch update; SQL [insert into mam_db.snmp_settings (address, enabled, max_count_in_memory, rocommunity, skip_unknown, storage_period, storage_type, id) values (?, ?, ?, ?, ?, ?, ?, ?)]; constraint [null];

10:37:41,165 INFO  [stdout] (ServerService Thread Pool -- 116) Caused by: java.sql.BatchUpdateException: Column 'address' cannot be null
10:37:41,165 INFO  [stdout] (ServerService Thread Pool -- 116)  at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1666)
10:37:41,165 INFO  [stdout] (ServerService Thread Pool -- 116)  at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1082)
10:37:41,165 INFO  [stdout] (ServerService Thread Pool -- 116)  at org.jboss.jca.adapters.jdbc.WrappedStatement.executeBatch(WrappedStatement.java:1077)
10:37:41,166 INFO  [stdout] (ServerService Thread Pool -- 116)  at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
10:37:41,166 INFO  [stdout] (ServerService Thread Pool -- 116)  at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
10:37:41,166 INFO  [stdout] (ServerService Thread Pool -- 116)  ... 58 more

But i am using  nullable = false in java code . But this is working fine with PostgreSQL and DB2 . Getting exception on MySQL only .

This is the corresponding DB2 table :

CREATE TABLE TEST_SETTINGS (
  ID BIGINT NOT NULL,
  ADDRESS VARCHAR(64),
  ENABLED SMALLINT NOT NULL,
  MAX_COUNT INTEGER,
  STORAGE_PERIOD INTEGER,
  ROCOMMUNITY VARCHAR(128) NOT NULL,
  SKIP_UNKNOWN SMALLINT NOT NULL,
  STORAGE_TYPE INTEGER NOT NULL,
  PRIMARY KEY (ID)
)#

Any suggestion ?


问:
Is there any way to disable k8s rescheduler?
I don't want k8s to transfer any pod to another node even the node lost.Because i use hostPath,if the pod rescheduled,the data will lost.

Is there any way to disable rescheduler?

答:
I don't know how to disable rescheduler.

But you can limit this pod to specific node via nodeSelector, or you can use nodeName.

```<code>apiVersion: v1
kind: Pod
metadata:
  name: nginx
  labels:
    env: test
spec:
  containers:
  - name: nginx
    image: nginx
  nodeSelector:
    kubernetes.io/hostname: yourNodeName
</code>```

Note: nodeName will ignore the node which is cordon(kubectl cordon) and has taint.

Body:
I don't know how to disable rescheduler.

But you can limit this pod to specific node via nodeSelector, or you can use nodeName.

apiVersion: v1
kind: Pod
metadata:
  name: nginx
  labels:
    env: test
spec:
  containers:
  - name: nginx
    image: nginx
  nodeSelector:
    kubernetes.io/hostname: yourNodeName

Note: nodeName will ignore the node which is cordon(kubectl cordon) and has taint.


问:
PHP format number to omit trailing zeros
A while ago I wrote a fully working script to magically move the decimal sign, adapted to the number of zeros there are.

https://github.com/jenstornell/magic-number-format/blob/master/magic-number-format.php

I still wonder, is there a PHP function to cover this issue? I feel like my code is just too much:

```<code><?php
function magic_number_format($number) {
    $pos = strpos($number, '.');
    $pos = ( ! $pos ) ? strpos($number, ',') : $pos;

    if( $pos ) {
        $count = strlen($number) - $pos - 1;
        $last = substr($number, -$count);
        $split = str_split($last);
        $split = array_reverse($split);

        $break = false;

        foreach( $split as $char ) {
            if( $char == 0 && $break == false ) {
                $count--;
            }

            if( $char != 0 ) {
                $break = true;
            }
        }

        $first = number_format( substr($number, 0, $pos ), 0, '', '.' );
        $last = substr($number, $pos + 1, $count);
        $result = $first . ',' . $last;

        $result = ( ! is_numeric( substr($result, -1) ) ) ? substr($result, 0, -1) : $result;

        return $result . "\n";
    }
    return number_format( $number, 0, '', '.' ) . "\n";
}

echo magic_number_format('25');
echo magic_number_format('123.32');
echo magic_number_format('12312.3233');
echo magic_number_format('12.0100000');
echo magic_number_format('1231,00');
echo magic_number_format('1231,10');
echo magic_number_format('1,1');
</code>```

The code above will skip the unneeded zeros after the comma or dot sign.

答:
You are reinventing the wheel. Also the code in answer linked as duplicate is not necessary neither the only approach nor the best approach (it also is not necessary fully related to your question). You can successfully stick using plain printf() with ordinary %s formatting for expected results. Test case:

```<code>$vals = [ 1, 1.000, 1.1, 1.230 ];
foreach ($vals as $val) {
    printf("%s\n", $val);
}
</code>```

would produce desired:

```<code>1
1
1.1
1.23
</code>```

Replace printf) with sprintf() if you need to assing formatted value to a variable and you are good to go.

Body:
A while ago I wrote a fully working script to magically move the decimal sign, adapted to the number of zeros there are.

https://github.com/jenstornell/magic-number-format/blob/master/magic-number-format.php

I still wonder, is there a PHP function to cover this issue? I feel like my code is just too much:

<?php
function magic_number_format($number) {
    $pos = strpos($number, '.');
    $pos = ( ! $pos ) ? strpos($number, ',') : $pos;

    if( $pos ) {
        $count = strlen($number) - $pos - 1;
        $last = substr($number, -$count);
        $split = str_split($last);
        $split = array_reverse($split);

        $break = false;

        foreach( $split as $char ) {
            if( $char == 0 && $break == false ) {
                $count--;
            }

            if( $char != 0 ) {
                $break = true;
            }
        }

        $first = number_format( substr($number, 0, $pos ), 0, '', '.' );
        $last = substr($number, $pos + 1, $count);
        $result = $first . ',' . $last;

        $result = ( ! is_numeric( substr($result, -1) ) ) ? substr($result, 0, -1) : $result;

        return $result . "\n";
    }
    return number_format( $number, 0, '', '.' ) . "\n";
}

echo magic_number_format('25');
echo magic_number_format('123.32');
echo magic_number_format('12312.3233');
echo magic_number_format('12.0100000');
echo magic_number_format('1231,00');
echo magic_number_format('1231,10');
echo magic_number_format('1,1');

The code above will skip the unneeded zeros after the comma or dot sign.

Body:
You are reinventing the wheel. Also the code in answer linked as duplicate is not necessary neither the only approach nor the best approach (it also is not necessary fully related to your question). You can successfully stick using plain printf() with ordinary %s formatting for expected results. Test case:

$vals = [ 1, 1.000, 1.1, 1.230 ];
foreach ($vals as $val) {
    printf("%s\n", $val);
}

would produce desired:

1
1
1.1
1.23

Replace printf) with sprintf() if you need to assing formatted value to a variable and you are good to go.


问:
VSTS PowerBI Integration - Cannot see nested Iteration Data
I've retrieved data from an online VSTS instance in Power BI. However, I'm having an issue accessing "2nd level" iteration data. </p>

<p>For example, the VSTS iteration hierarchy is as follows. {Project}/Open/{Current Month}. I can see data up until the "Open" level, but I cannot drill down to the child iteration path. </p>

答: We are deprecating the Power BI.com Visual Studio Team Services (VSTS) Content Pack on November 15, 2017, you could try the Analytics Marketplace extension, or export the work item query to Excel and then import it to PowerBI.</p>

Body:
I've retrieved data from an online VSTS instance in Power BI. However, I'm having an issue accessing "2nd level" iteration data.

For example, the VSTS iteration hierarchy is as follows. {Project}/Open/{Current Month}. I can see data up until the "Open" level, but I cannot drill down to the child iteration path.


问:
How to send multiple base64 images stored in array to Java using ajax call in JavaScript
I allow the user to upload multiple images at once.

I store all image sources in an array and send with ajax.

The ajax call returns an error message that the size is too long.

My code snippet :

```<code>function save_domain_images(base64ImageSrc){
  var datastring = "&token="+domainImgSaveSession+"&imgSrc="+base64ImageSrc+"&action=saveDomainImg";
  $.ajax({
    type : "POST",
    url : base+"/AppUserListServiceProvider",
    data : datastring,
    cache : false,
    success : function(data){
      data                      = JSON.parse(data);
      domainImgSaveSession      = data["randomNew"];
      if(data["error"] == null && data["croppedImg"] != null){
        console.log("data : "+data["croppedImg"]);
      }
    },
    error : function(){}
  });
}
</code>```

答:
```<code>const match = /^\s*data:([\w/]+)(?:;base64)?,/.exec(base64Str);
const type = match[1];
const blob = b64toBlob(url.slice(match[0].length), type);
const formData = new FormData();
formData.append('image', blob, name);

function b64toBlob(base64) {
  const code = window.atob(base64.split(",")[1])
  const aBuffer = new window.ArrayBuffer(code.length)
  const uBuffer = new window.Uint8Array(aBuffer)

  for (let i = 0; i < code.length; i++) {
    uBuffer[i] = code.charCodeAt(i)
  }

  const Builder = window.WebKitBlobBuilder || window.MozBlobBuilder
  if (Builder) {
    const builder = new Builder()
    builder.append(buffer)

    return builder.getBlob(format)
  } else {
    return new window.Blob([buffer], {
      type: format
    })
  }
}
</code>```

then you can post the formData

Body:
I allow the user to upload multiple images at once.

I store all image sources in an array and send with ajax.

The ajax call returns an error message that the size is too long.

My code snippet :

function save_domain_images(base64ImageSrc){
  var datastring = "&token="+domainImgSaveSession+"&imgSrc="+base64ImageSrc+"&action=saveDomainImg";
  $.ajax({
    type : "POST",
    url : base+"/AppUserListServiceProvider",
    data : datastring,
    cache : false,
    success : function(data){
      data                      = JSON.parse(data);
      domainImgSaveSession      = data["randomNew"];
      if(data["error"] == null && data["croppedImg"] != null){
        console.log("data : "+data["croppedImg"]);
      }
    },
    error : function(){}
  });
}

Body:
const match = /^\s*data:([\w/]+)(?:;base64)?,/.exec(base64Str);
const type = match[1];
const blob = b64toBlob(url.slice(match[0].length), type);
const formData = new FormData();
formData.append('image', blob, name);

function b64toBlob(base64) {
  const code = window.atob(base64.split(",")[1])
  const aBuffer = new window.ArrayBuffer(code.length)
  const uBuffer = new window.Uint8Array(aBuffer)

  for (let i = 0; i < code.length; i++) {
    uBuffer[i] = code.charCodeAt(i)
  }

  const Builder = window.WebKitBlobBuilder || window.MozBlobBuilder
  if (Builder) {
    const builder = new Builder()
    builder.append(buffer)

    return builder.getBlob(format)
  } else {
    return new window.Blob([buffer], {
      type: format
    })
  }
}

then you can post the formData


问:
Apache: wrong owner and permission of uploaded file
I have a website running on apache server.

Yesterday, I logged in to my server and restarted passenger, apache server.

I restarted using command:

```<code>touch /tmp/restart.txt
</code>```

After that, I noticed that the new uploaded files are changed ownership to paelz (my username) and permission to -rw-------. The files were uploaded by some other users using the website.

The older files has owner apache and permission: -rw-r--r--.

As a result, the website cannot load the new uploaded files. However, it can load the older ones.

If I run chmod 644 on the new uploaded files, the website can load the files normally. However, I want a permanent solution.

I want the new uploaded file owned by apache and has permission as the old ones.

My question is what caused this issue and how can I fix it.

答:
Finally I found the answer.
It is not related to apache. It is related to passenger instead.

https://stackoverflow.com/a/4232091/1319283

By default, passenger will run your app as the user who owns the
  config/environment.rb or config.ru file, see

The config/environment.rb is owned by my account so passenger will run the app as my account.

Body:
I have a website running on apache server.

Yesterday, I logged in to my server and restarted passenger, apache server.

I restarted using command:

touch /tmp/restart.txt

After that, I noticed that the new uploaded files are changed ownership to paelz (my username) and permission to -rw-------. The files were uploaded by some other users using the website.

The older files has owner apache and permission: -rw-r--r--.

As a result, the website cannot load the new uploaded files. However, it can load the older ones.

If I run chmod 644 on the new uploaded files, the website can load the files normally. However, I want a permanent solution.

I want the new uploaded file owned by apache and has permission as the old ones.

My question is what caused this issue and how can I fix it.


问:
identify lines in a file in php
I have a file, which contains passwords/usernames:

thomas 123

john 321

What would be the best way to identify lines and add to them contact information? Right in password file I dont want store, because the size of the file matters.. I thought to add an identifier string before records, like this:

[1]

thomas 123

[2]

john 321

What do you think? It is a good way to identify lines? If yes, how I can read out line after identifier [number]?

If I can read out, then in a second file I can store contact information.

[1]

email, etc

[2]

email etc

this is a config file of an offline app, sadly I cant change the structure of that file (max. change: add an identifier before lines) or use database.

Thank you so much,

Adrian

答:
You could use a while loop that reads every other line as your id and every other line as your username and password; however, like what @zerkms said, you're better off putting your energy into a tried and tested database.

Learning to use a database will save you time in the future so that on each project you don't have to figure out exactly how to manipulate a flat file.

Reusable solutions enable and empower you to focus on your goal and your product, whatever that may be.

ContentLicense: CC BY-SA 2.5

Title: identify lines in a file in php


问:
Jersey - resource variables null value despite non-null initialization
I have a resource in my Jersey REST api that has a private instance variable:

```<code>@Path("test")
public class TestResource implements ServletContextListener
{
    private String someString;

    @GET
    public void test()
    {
        System.out.println("someString " + someString);
    }

    @Override
    public void contextDestroyed(ServletContextEvent ctxt) {
        System.out.println("Destroying context");
    }

    @Override
    public void contextInitialized(ServletContextEvent ctxt) {
        System.out.println("TestResource initialized!");

        someString = "SET";
        System.out.println("someString has been set. someString: " + someString);
    }
}
</code>```

On server startup/restart the instance variable someString is initialized during contextInitialized() and is correctly printed out. However when I set a GET request to http://localhost:8080/myapp/api/test (i.e. invoke the test() method above) the variable someString is null.

How can I prevent that?

答:
I believe this should be a comment but I don't have enough reputation. So I am writing as an answer.

This question gives an example for @Singleton annotation. It provides a cleaner approach.

Body:
I have a resource in my Jersey REST api that has a private instance variable:

@Path("test")
public class TestResource implements ServletContextListener
{
    private String someString;

    @GET
    public void test()
    {
        System.out.println("someString " + someString);
    }

    @Override
    public void contextDestroyed(ServletContextEvent ctxt) {
        System.out.println("Destroying context");
    }

    @Override
    public void contextInitialized(ServletContextEvent ctxt) {
        System.out.println("TestResource initialized!");

        someString = "SET";
        System.out.println("someString has been set. someString: " + someString);
    }
}

On server startup/restart the instance variable someString is initialized during contextInitialized() and is correctly printed out. However when I set a GET request to http://localhost:8080/myapp/api/test (i.e. invoke the test() method above) the variable someString is null.

How can I prevent that?


问:
How to use single print function to print multiple lines?
I just started learning Python3 and I got to the part where I started using arithmetic operations, I am trying to break the result into multiple lines, I used sep='/n' and /n, but I gives this error (positional argument follows keyword argument) I know it maybe a noob question but I can't figure out how to do it or what to search for in Google.

```<code>x=22
y=18
print('x+y=', x+y, 'x-y=', x-y)
</code>```

The result I get is this:
x+y= 40 x-y= 4.

I want it to be displayed like this:

x+y= 40

x-y= 4

答:
Method 0: Use multiple print statements

```<code>print('x+y=', x+y)
print('x-y=', x-y)
</code>```

Method 1: Add \n when you want to end the line.

```<code>print('\nx+y=', x+y, '\nx-y=', x-y,end='') # end='' just to take total control of when to keep new line
</code>```

Method 2: keep everything you want to print in a line in single argument

```<code>print('x+y=%d'%(x+y),'x-y=%d'(x-y),sep='\n')
</code>```

You can look at the help for print function :help(print)

Body:
I just started learning Python3 and I got to the part where I started using arithmetic operations, I am trying to break the result into multiple lines, I used sep='/n' and /n, but I gives this error (positional argument follows keyword argument) I know it maybe a noob question but I can't figure out how to do it or what to search for in Google.

x=22
y=18
print('x+y=', x+y, 'x-y=', x-y)

The result I get is this:
x+y= 40 x-y= 4.

I want it to be displayed like this:

x+y= 40

x-y= 4

Body:
Method 0: Use multiple print statements

print('x+y=', x+y)
print('x-y=', x-y)

Method 1: Add \n when you want to end the line.

print('\nx+y=', x+y, '\nx-y=', x-y,end='') # end='' just to take total control of when to keep new line

Method 2: keep everything you want to print in a line in single argument

print('x+y=%d'%(x+y),'x-y=%d'(x-y),sep='\n')

You can look at the help for print function :help(print)