text:
Q: Date of max and min value extraction from time series using Google Earth Engine I'm trying to extract the day of maximum and minimum value of time series. The day of minimum value must be after the day of the max value. The day of max can be get by using ".qualityMosaic" in a function. I have troubles in make a working function for the detection of the date if the min.
How can I implement the right function?
/////////THESE FUNCTIONS WORKS FOR A SINGLE YEAR (EXAMPLE)
var max = example.qualityMosaic('precipitation').select('day');
print(max,'max')

var min = example.map(
  function(img) {
  var date = img.date().millis()
  return img.updateMask(max.lt(date))
}).select('precipitation', 'day').reduce(ee.Reducer.min(2)).rename('precipitation','day')
print(min,'min')

///////////HERE IS AS I HAVE IMPLEMENTED FOR A TIME-SERIES WITH > 1 YEAR
// Find the day of max for each year
var max = ee.ImageCollection(
    years.map(function (y) {
      var start = ee.Date.fromYMD(y, startmonth,startday);
      var stop = ee.Date.fromYMD (y,endmonth,endday);
      var x = collection.filterDate(start, stop)
      var w = x.qualityMosaic('precipitation').select('day')
    return w.set({'year': y})
}).flatten());
print(max,'max')
Map.addLayer(max, {min: 1, max: 365}, 'max')

// Find the day of min after day of max for each year
var min = ee.ImageCollection(
    years.map(function (y) {
      var start = ee.Date.fromYMD(y, startmonth,startday);
      var stop = ee.Date.fromYMD (y,endmonth,endday);
      var x = collection.filterDate(start, stop)
      var z = max.filter(ee.Filter.calendarRange(y, y, 'year'))
      var w = x.map(
        function(img) {
        var date = img.date().millis()
        var k = img.updateMask(z.lt(date))
      return k
}).select('precipitation', 'day').reduce(ee.Reducer.min(2)).rename('precipitation','day')
  return w
}).flatten());

print(min,'min')
Map.addLayer(min, {min: 1, max: 365}, 'min')

It looks quite complex because for the detection of the date of min for each of the year i need to use the respective date of max calculated in the previous step.
here is the link to the code
https://code.earthengine.google.com/03e80671a65c95a60535dbd1c50ebe93
Any suggestion?
thanks!!

A: This could work https://code.earthengine.google.com/6a035a4a301f5bebcf7f40d4be9a551c Changed line 119
var z = ee.Image(max
    .filterMetadata('year', 'equals', y).first());


text:
Q: Control SplitView borders in QML I have a SplitView and inside this split view I have two elements (Rectangle (users) and one Item that contains a ColumnLayout (processes) ).
User can choose if he would like to see users or not. If he doesn't want to see users, then, I set rectangle width to 0 and he is able to see only processes, but problem is that in that window, there are two borders.
One is from window, one is from SplitView.
Any idea how can I get rid of these double border?

A: Try to set the visible attribute of your rectangle to false (instead of changing width to 0)
In the example you can change the visible left 'border' of the splitview
(the border is not a border, it's the splitview slider between the first and the second element):
ApplicationWindow {

    title: qsTr("Hello World")
    width: 640
    height: 480
    visible: true

    SplitView {
        anchors.fill: parent

        Rectangle {
            id: rec
            width: 0
            height: parent.height
            visible: false
        }

        Rectangle {
            width: 200
            color:"red"
            height: parent.height
        }

        Button {
            text: "change left border of splitview"
            onClicked: {
                rec.visible = !rec.visible;
            }
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Grails Google map reload markers I have a google map in a page. When page load, I plot some markers etc. When user change drop downlist i submit xhr via jquery. I have a lot of linkage in my domain class so I hope to use render template & pass in a model. But I have no clue in doing. Or can I render javascript/ Can help? This is how I post.
function projectChanged(projectid)
{
      var link = '${createLink(controller:'knowledge', action:'changeSelection')}';
      var type = $("#type1").value;
      var posting = $.post( link , { project: projectid, type:type } );
      posting.done(function( data ) {
       });

}//END project changed

A: in you controller you can do: render(template:"myTemplate", model: [myData: myData])


text:
Q: Windows 10 Upgrade Assistant no longer supports Domain-Joined Machines My primary question is: What is the most efficient and safest way to upgrade to Windows 10 on a Windows 7 domain-joined machine?
After upgrading 10 machines from Windows 7 to Windows 10 with no real issues (the last one was around a month ago), today we hit a snag.  I attempted to run the in-place upgrade and received an error message: "This PC is joined to a domain. Contact your system administrator."Windows 10 Upgrade Assistant Screenshot
This appears to be an issue with the Windows 10 Upgrade Assistant since early June 2016 (see Reddit or search the web for "Windows 10 upgrade problem: User account: This PC is joined to a domain. Contact your administrator.").
Two viable solutions have been proposed
1.  Boot from installation media
2.  Remove the computer from the domain, then rename the computer, then reboot, then upgrade, then rename the computer again and then add it back to the domain.
Both options seem time consuming (previous upgrades have been snappy, seamless, and easy).  The added concern with #2 is potentially losing or corrupting the user profile.
We do use WSUS and Windows 10 upgrade packages are currently declined. Since many others seem to have the same issue without mentioning it, I am inclined to think this isn't the issue.  However, I welcome any comments from others who have used WSUS to push Windows 10 upgrades since early June 2016.

A: I have the same problem!
Yesterday I removed the PC from domain, upgrade to Windows 10 , rejoin the domain and the user profile is not back to normal and I had to move everything by hand copying from the old profile.
Why Microsoft ????

A: We removed one of the machines from the WSUS configuration OU, then ran Windows Update so the Get Windows 10 icon in the system tray appeared.  Using that icon to upgrade to Windows 10 worked.


text:
Q: Is it true that no linear order can have CCC? I am reading about countable chain condition on Wikipedia https://en.wikipedia.org/wiki/Countable_chain_condition
I want to quickly verify that if $(X, \leq)$ is a linear order, then it cannot possibly have the countable chain condition. Is this correct?
Because in a linear order, every elements are comparable. So there does not exist any anti-chain, let alone a countable anti-chain.
Thanks!

A: The countable chain condition means that there does not exist any uncountable antichain.  It doesn't mean that there must exist a countably infinite antichain.  So in fact, every linear order does have the countable chain condition, by your argument.
(Beware, though, that when talking about linear orders, "countable chain condition" usually refers to a different condition.  Namely, it refers to the countable chain condition on the poset of non-empty open intervals in the linear order, ordered by inclusion.  So a linear order is said to be ccc if it has no uncountable collection of disjoint open intervals.)


text:
Q: How send redirect as post request. Spring Security i have my own  AuthenticationSuccessHandler and overriding method onAuthenticationSuccess, where i need to redirect to some page with parameters from request before authenticate (i hope you understand what i mean, sorry for my english)

getRedirectStrategy().sendRedirect(request, response, targetUrl);

How can i do this with POST method (by default it is GET method)

A: You may do it without sendRedirect method using HTTP1.1 307 Temporary Redirect status code.
But AFAIK this is not a common practice and not all web browsers may support this.
Maybe server-side forward will suit your case.
Update:
If you want to send POST-redirect using spring-security API you may implement your own RedirectStrategy.
DefaultRedirectStrategy uses response.sendRedirect that will result in 302 response code sending by servlet container (I'm not sure about every container, at least tomcat sends 302).
Update 2:
You may send 307 back setting response status and "Location" header yourself:
resp.setStatus(SC_TEMPORARY_REDIRECT);
resp.setHeader("Location", absoluteRedirectUrl);

User-agent receiving this response must do next request using the same method that was used in previous request. So if first request was POST redirected request also will be POST.


text:
Q: Shiny: how to create a confirm dialog box I would like to ask if it is possible to have a confirm dialog box, consisting of two buttons, in shiny.
Say, if I click a Delete button, then the dialog box pop up. User pick the choice and return. The app acts according to the user choice.

A: Update using sweetalertR
#install_github("timelyportfolio/sweetalertR")
library(shiny)
library(sweetalertR)
runApp(shinyApp(
  ui = fluidPage(
    actionButton("go", "Go"),
    sweetalert(selector = "#go", text = "hello", title = "world")
  ),

  server = function(input, output, session) {
  }
))

Example 1
You can do something like this, note that the code is taken from Demo on submit button with pop-up (IN PROGRESS)
rm(list = ls())
library(shiny)

ui =basicPage(
  tags$head(
    tags$style(type='text/css',
               "select, textarea, input[type='text'] {margin-bottom: 0px;}"
               , "#submit {
          color: rgb(255, 255, 255);
          text-shadow: 0px -1px 0px rgba(0, 0, 0, 0.25);
          background-color: rgb(189,54,47);
          background-image: -moz-linear-gradient(center top , rgb(238,95,91), rgb(189,54,47));
          background-repeat: repeat-x;
          border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
        }"
    ),
    tags$script(HTML('
          Shiny.addCustomMessageHandler("jsCode",
            function(message) {
              eval(message.value);
            }
          );'
    ))
  )
  ,
  textInput(inputId = "inText", label = "", value = "Something here")
  ,
  actionButton(inputId = "submit", label = "Submit")
  #
  #   alternative approach: button with pop-up
  #    , tags$button("Activate", id = "ButtonID", type = "button", class = "btn action-button", onclick = "return confirm('Are you sure?');" )
  ,
  tags$br()
  ,
  tags$hr()
  ,
  uiOutput("outText")
)
server = (
  function(session, input, output) {

    observe({
      if (is.null(input$submit) || input$submit == 0){return()}
      js_string <- 'alert("Are You Sure?");'
      session$sendCustomMessage(type='jsCode', list(value = js_string))
      text <- isolate(input$inText)
      output$outText <- renderUI({
        h4(text)
      })
    })

  }
)
runApp(list(ui = ui, server = server))

Example 2
Using ShinyBS package
rm(list = ls())
library(shiny)
library(shinyBS)

campaigns_list <- letters[1:10]

ui =fluidPage(
  checkboxGroupInput("campaigns","Choose campaign(s):",campaigns_list),
  actionLink("selectall","Select All"),
  bsModal("modalExample", "Yes/No", "selectall", size = "small",wellPanel(
    actionButton("no_button", "Yes"),
    actionButton("yes_button", "No")
    ))
)
server = function(input, output, session) {

  observe({
    if(input$selectall == 0) return(NULL)
    else if (input$selectall%%2 == 0)
    {
      updateCheckboxGroupInput(session,"campaigns","Choose campaign(s):",choices=campaigns_list)
    }
    else
    {
      updateCheckboxGroupInput(session,"campaigns","Choose campaign(s):",choices=campaigns_list,selected=campaigns_list)
    }
  })

}
runApp(list(ui = ui, server = server))

Edit for Apricot
rm(list = ls())
library(shiny)
library(shinyBS)

campaigns_list <- letters[1:10]

ui =fluidPage(
        checkboxGroupInput("campaigns","Choose campaign(s):",campaigns_list),
        actionLink("selectall","Select All"),
        bsModal("modalExample", "Yes/No", "selectall", size = "small",wellPanel(
                actionButton("yes_button", "Yes"),
                actionButton("no_button", "No")
        ))
)
server = function(input, output, session) {

        observeEvent(input$no_button,{
                updateCheckboxGroupInput(session,"campaigns","Choose campaign(s):",choices=campaigns_list)
        })

        observeEvent(input$yes_button,{
                updateCheckboxGroupInput(session,"campaigns","Choose campaign(s):",choices=campaigns_list,selected=campaigns_list)
        })
}
runApp(list(ui = ui, server = server))

A: Neither ShinyBS nor Javascript is necessary.  The trick is to use a modalDialog and set the footer to be a tagList of several tags, usually, an actionButton for the delete and a modalButton to cancel.  Below is a MWE
app.R
library(shiny)

ui = fluidPage(
   mainPanel(
       actionButton("createfile", "Create"),
       actionButton("deletefile", "Delete")
   )
)

# Define server logic required to draw a histogram
server = function(session, input, output) {

   observeEvent(input$createfile, {
       showModal(modalDialog(
           tagList(
               textInput("newfilename", label = "Filename", placeholder = "my_file.txt")
           ),
           title="Create a file",
           footer = tagList(actionButton("confirmCreate", "Create"),
                            modalButton("Cancel")
           )
       ))
   })

   observeEvent(input$deletefile, {
       showModal(modalDialog(
           tagList(
               selectInput("deletefilename", label = "Delete a file", choices = list.files(pattern="*.txt"))
           ),
           title="Delete a file",
           footer = tagList(actionButton("confirmDelete", "Delete"),
                            modalButton("Cancel")
           )
       ))
   })

   observeEvent(input$confirmCreate, {
       req(input$newfilename)
       file.create(input$newfilename)
       removeModal()
   })

   observeEvent(input$confirmDelete, {
       req(input$deletefilename)
       file.remove(input$deletefilename)
       removeModal()
   })
}

# Run the application
shinyApp(ui = ui, server = server)

Note, if you use shiny modules, you have to use session$ns("inputID") rather than ns("inputID"). See Tobias' answer here.

A: I modified part of your code to call
js_string <- 'confirm("Are You Sure?");'
session$sendCustomMessage(type='jsCode', list(value = js_string))

to call the confirm dialog instead of alert dialog box. Then
tags$script(
            HTML('
                Shiny.addCustomMessageHandler(
                    type = "jsCode"
                    ,function(message) {
                    Shiny.onInputChange("deleteConfirmChoice",eval(message.value));
                })
            ')
)

to send the value returned by the confirm dialog box. Then I just checeked the value of input$deleteConfirmChoice to determine what action is to be done.
Thank you very much! I now understand how to send and receive messages to and from R and Javascript.


text:
Q: How to send many pickled file into a dataframe? I have many files which have been created using "pickle".
I want to send them to a dataframe, calculate the average (from the 2nd row until the end) of each one, multiply it by 1000 and round it to 2 decimals.
So far I have achieved this using 1 pickle file.
import pandas as pd

df = pd.read_pickle(r'C:\Users\file_inference_time')
df = pd.DataFrame(df)
df.rename(columns={0:'MobileNet'},inplace=True)

df_mean=(df.iloc[2::,:].mean()* 1000).round(decimals=2)
df_mean2=pd.DataFrame(df_mean)
df_mean2

Result I get from 1 file.

These are the files ("pickle") that I need to read

EDIT
This is the error that I get when running the 2nd option
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-b72e45d8bcfc> in <module>
     16
     17
---> 18 df_mean_all = pd.concat(df_mean_list).reset_index(drop=True)
     19
     20 print(df_mean_all)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\reshape\concat.py in concat(objs, axis, join, join_axes, ignore_index, keys, levels, names, verify_integrity, sort, copy)
    253         verify_integrity=verify_integrity,
    254         copy=copy,
--> 255         sort=sort,
    256     )
    257

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\reshape\concat.py in __init__(self, objs, axis, join, join_axes, keys, levels, names, ignore_index, verify_integrity, copy, sort)
    302
    303         if len(objs) == 0:
--> 304             raise ValueError("No objects to concatenate")
    305
    306         if keys is None:

ValueError: No objects to concatenate

THIS IS A PLOT WITH THE RESULTS

A: Get a dict of dataframes

*

*Save the calculated mean result for each file, into a dict
from pathlib import Path

dir_path = Path(r'C:\Users\path_to_files')
files = dir_path.glob('**/file_inference_time*')  # get all pkl files in main dir and subdirectories

df_mean_dict = dict()

for i, file in enumerate(files):
    df = pd.DataFrame(pd.read_pickle(file))
    df.rename(columns={0:'MobileNet'}, inplace=True)

    df_mean_dict[i] = pd.DataFrame((df.iloc[2::,:].mean()* 1000).round(decimals=2))

    # if all the file names are unique, the dict key can be the file name (w/o the file extension)
    # df_mean_dict[file.stem] = pd.DataFrame((df.iloc[2::,:].mean()* 1000).round(decimals=2))

Get a single dataframe - This is what I would do

*

*The result df_mean_all will be a single, 2-column dataframe.

*

*column 0 will be MobileNet

*column 1 will be file
dir_path = Path(r'C:\Users\path_to_files')
files = dir_path.glob('**/file_inference_time*')   # get all pkl files in main dir and subdirectories

# to check if the files are found
# if an empty list prints, no files are found
files = list(files)
print(files[:5]

df_mean_list = list()

for file in files:
    df = pd.DataFrame(pd.read_pickle(file))

    df_mean = pd.DataFrame((df.iloc[2::,:].mean()* 1000).round(decimals=2)).reset_index(drop=True).rename(columns={0: 'MobileNet'})
    df_mean['file'] = file  # or file.stem for just the file name

    df_mean_list.append(df_mean)

# df_mean_list is a list of dataframes, pd.concat combines them all into one dataframe
df_mean_all = pd.concat(df_mean_list).reset_index(drop=True)

print(df_mean_all)

   MobileNet                                    file
0       3.24  C:\Users\file_inference_time\file1.pkl
1       2.34  C:\Users\file_inference_time\file2.pkl
2       4.23  C:\Users\file_inference_time\file3.pkl


text:
Q: customly set button background color ios I am trying to change the background color of UIButton to a custom color. All the default greycolor, bluecolor, etc do not suffice.
    UIColor *myColor=[UIColor colorWithRed:1 green:1 blue:0 alpha:1.0f];
    _button.backgroundColor = [UIColor myColor];

It gives error on 2nd line saying

No known class method for selector 'myColor'

A: just change your current code with below code
UIColor *myColor=[UIColor colorWithRed:1 green:1 blue:0 alpha:1.0f];
_button.backgroundColor = myColor;  // because myColor is UIColor

A: your code is fine, the simple mistake is again you creted the [UIColor property] on second line
UIColor *myColor=[UIColor colorWithRed:1 green:1 blue:0 alpha:1.0f];

Not like
  _button.backgroundColor = [UIColor myColor];

Do like
  _button.backgroundColor = myColor;

Update

you can directly use the color property like

   _button.backgroundColor = [UIColor colorWithRed:1 green:1 blue:0 alpha:1.0f];

A: Try this:
 UIColor *myColor=[UIColor colorWithRed:1 green:1 blue:0 alpha:1.0f];
 _button.backgroundColor = myColor;

myColor is not defined in UIColor. It's a variable that you defined.

A: It's much more convenient to use:
 _button.backgroundColor = [UIColor colorWithRed:1.0/255.0 green:1.0/255.0 blue:0.0/255.0 alpha:1.0f];


text:
Q: How do I access this JSON data using D3? I am aware that loading JSON in D3 is done like so and this does not produce any errors:
d3.json("sample_data/unique_items.json", function(json) {
  // do something
});

Inside this block, I then reference the json file using the json variable. Here is the sample structure of the JSON:
{
  "unique_items": [
    {
      "name": "Blah",
      "items": [
        {"id": 1, "note": "blah"},
        {"id": 2, "note": "blah blah"},
        {"id": 3, "note": "blah blah blah"}
      ]
    },
    {
      "name": "Blah2",
      "items": [
        {"id": 1, "note": "blah"},
        {"id": 2, "note": "blah blah"},
        {"id": 3, "note": "blah blah blah"}
      ]
    }
  ]
}

I'm struggling with how to access items in this structure. So for instance I tried this as a test:
for (var item in json["unique_items"]) {
  if (json["unique_items"].hasOwnProperty(item)) {
    console.log(item["name"]);  // 'undefined' error on this line
  }
}

I get an undefined error on the line commented as such above. I would expect to see this in the console:
Blah
Blah2

I tried changing that line to console.log(item.name); but that produced the same error. I then changed the line to simply console.log(item); and the output to the console was 0. I don't understand this.
So my questions are:

*

*How do I access elements within unique_items?

*Is there a better way the json should be structured?

A: try this
for (var key in json["unique_items"]) {
  var item = json["unique_items"][key];
  if (item) {
    console.log(item["name"]);
  }
}


text:
Q: Clicking asp ImageButton returning me back to top of page: Error I am trying to allow users to edit information on a page with a onclick edit button
the page reloads and the page is taken back to the top, each time the button is clicked, it seems to be a huge inconvenience to the user
  <% Page directives ... MaintainScrollPositionOnPostBack="True" .. %>

with my page tag at the top, but its still jumping back to the top any suggestions?
I have tried putting it in the webconfig
   <pages maintainScrollPositionOnPostBack="True" >

i have tried putting an asp:Page tag on the page too
   <asp:Page MaintainScrollPositionOnPostBack="true" .... />

and still puts the position at the top of the page on reload.

A: You should add this to your web.config. It should be your answer
<pages maintainScrollPositionOnPostBack="True">


text:
Q: Programming Android in C Is there any way to program an android device without using java? I have programmed in assembly, basic, c ,c ++, c#,Forth and fortran. I only want to port an application I have written in c,c++,c#. I use it to learn a new language. I cant even get an image to load from an xml file.

A: You might have a look at the Android NDK : http://developer.android.com/sdk/ndk/index.html

A: You must use Java in the main part of the application with your user interface.
[edit]
Android's interface between Java and C is strange and harder to use than the one in iOS.

A: You can do some C coding using the NDK (http://developer.android.com/sdk/ndk/index.html). But I doubt that you can do everything there.

A: I love Eclipse and Java D:
Anyways,
Take a look at the Android NDK


text:
Q: How to Send an Email Template to multiple Recipients in Laravel I am working with Sendinblue API. I am trying to send an email to multiple recipients using sendinblue api. I don't not know how, I can implement it in laravel. I tried it by using multiple inputs but getting error.
I have tried the below code with multiple inputs but getting "Array to string conversion"
If you know the solution please leave your response it will be highly appreciated.
Thank you.
    $ch = curl_init();
    $count = count($request->name);

    curl_setopt($ch, CURLOPT_URL, 'https://api.sendinblue.com/v3/smtp/email');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    for ($i=0; $i < $count; $i++)
    {
        curl_setopt($ch, CURLOPT_POSTFIELDS,

            "\n{\n\"sender\": {\n\"name\": \"$request->name[$i]\",
        \n\"email\": \"$request->email[$i]\"\n},
        \n\"to\":[\n{\n\"email\": \"$request->recieverEmail[$i]\",
        \n\"name\": \"$request->recieverName[$i]\"\n},
        \n\"replyTo\": {\n\"email\": \"$request->replyEmail[$i]\",
        \n\"name\": \"$request->replyName[$i]\"\n},
        \n\"tags\": [\n\"$request->tag[$i]\"\n],
        \n\"templateId\": $request->id[$i]\n}\n"
        );
    }
    curl_setopt($ch, CURLOPT_POST, 1);
    $headers = array();
    $headers[] = 'Accept: application/json';
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Api-Key: API KEY';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close($ch);
    $result = json_decode($result);
    dd($result);


text:
Q: how to ignore XML errors when parsing faulty XML with Sax (on Android) Question on the Sax XML parser on Android, using Java: I need to parse XML files I get from the web, and that I have no control over. Some contain errors and cause the parser to abort with errors like "mismatched tag" or "not well-formed (invalid token)".
Those errors don't matter to me, I want to ignore them and keep going, I can handle the broken XML structure. But I cannot fix the XML files, they are not mine. How can I tell Sax on Android (class org.xml.sax.XMLReader) to not throw an exception and keep going? Attaching an ErrorHandler didn't work, and catching the exception is of no use because I can't resume parsing where it stopped.
My XML is not HTML, but here are some (X)HTML examples where browsers ignore errors and keep going. I want to do this too.

*

*Browsers are fine with "
" instead of "
" even though the tag is never closed.

*" text " works even though the closing tags are in the wrong order.

*"odds & ends" is accepted despite the invalid token, "odds & ends" would be correct.

I'd prefer to not write my own parser, dealing with character set conversions and all that. I don't need to validate XML. Here's my code, reduced to the essentials:
XMLReader r = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
r.setErrorHandler(new MyLenientErrorHandlerThatNeverThrows());
r.setContentHandler(new MyImporterThatExtendsDefaultHandler());
r.parse(new InputSource(new BufferedReader(...)));

Thanks!

A: Ok, it appears it can't be done. Sax supports error detection but not error recovery, which makes it less than ideal for robust code in this example.
Got it to work by replaxing Sax with XmlPullParser, which allows wrapping the next-token call in a try-catch block:
try {
    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
    XmlPullParser xpp = factory.newPullParser();
    xpp.setInput(in);
    int type = xpp.getEventType();
    while (type != XmlPullParser.END_DOCUMENT) {
        switch (type) {
          case XmlPullParser.START_TAG: startTag(xpp);             break;
          case XmlPullParser.END_TAG:   endTag(xpp);               break;
          case XmlPullParser.TEXT:      characters(xpp.getText()); break;
        }
        try {type = xpp.next();}
        catch (XmlPullParserException e) {}
    }
} catch (Exception e) {}


text:
Q: Include Bootstrap glyphs in Laravel Collective link I'm using Laravel Collective's link_to_route() method to create a link. I want to include a Bootstrap glyph with this link.
As it is now, it's printing the actual Html code.
Any tips on how to do this?
My current code:

    {!! link_to_route('companiesindex', " Companies") !!}

As a side question, is it normal to include the glyph in the actual link, or would this normally be before or after?

A: There are few packages you can use,

*

*https://github.com/patricktalmadge/bootstrapper
https://github.com/bradcornford/Bootstrapper
Using these you can easily get rid from thousands of HTML in your views


text:
Q: Index was out of range in grid row command I'd like to reach gridView a cell's value.But it gives the error is 'Index was out of range. Must be non-negative and less than the size of the collection. grid row command'
Can somebody help me?
 <asp:GridView ID="grdList" runat="server" AutoGenerateColumns="False"  GridLines="None"
            PageSize="5" AllowPaging="True" OnPageIndexChanging="Grd_Allergys_PageIndexChanging"
            OnRowCommand="grdList_RowCommand" OnRowDeleting="grdList_RowDeleting" OnRowEditing="grdList_RowEditing">
            <Columns>
                <asp:BoundField DataField="LangId" HeaderText="LangId" />
                <asp:BoundField DataField="LangName" HeaderText="LangName" />
                <asp:TemplateField HeaderText="Edit">
                    <ItemTemplate>
                        <asp:ImageButton ID="imgBtnEdit" runat="server" CommandName="Edit" CommandArgument='<%#Eval("LangId") %>'
                            ImageUrl="~/Image/edit.jpg" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Delete">
                    <ItemTemplate>
                        <asp:ImageButton ID="imgBtnDelete" runat="server" CommandName="Delete" CommandArgument='<%#Eval("LangId")%>'
                            ImageUrl="~/Image/delete_icon.gif" OnClientClick="return confirm('Do you want to continue ?')" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <PagerSettings Mode="Numeric" />
        </asp:GridView>

 protected void grdList_RowCommand(object sender, GridViewCommandEventArgs e)
 {
        DBDataContext dc = new DBDataContext();

        if (e.CommandName == "Edit")
        {
           int rowIndex = int.Parse(e.CommandArgument.ToString());
           string LangName = grdList.DataKeys[rowIndex]["LangName"].ToString();
        }
 }

A: You are assigning LangId and assuming it as row index in command argument. If id is greater then number of rows then you should get out of range index
Change
CommandArgument='<%#Eval("LangId")%>'

To
CommandArgument='<%# ((GridViewRow) Container).RowIndex %>'

A: You also haven't set DataKeys  up.
Add DataKeys="LangName" to your GridView definition.

A: commandargument=<%# Container.DisplayIndex %>

A: I had the same problem before and this is the solution I found.
In the RowCommand the first line must be :
if (e.CommandName == "Page") return;


text:
Q: Displaying Data from Firebase in TableView Cell I have the following code in one of my VC's (as part of my larger project). One of my Firebase DB references is called Sell_Request. It has three children (name, latitude and longitude), but I'm only concerned with name for right now.
I am trying to add it to a String array and am also printing it to the console. I am seeing the names being printed to the console, but I'm not getting the names printed in the individual cells.
Thanks for looking.
import UIKit
import Firebase
import FirebaseDatabase
import MapKit
import CoreLocation

class RequestVC: UITableViewController, CLLocationManagerDelegate {

    var locationManager = CLLocationManager()
    var sellerUserNames = [String]()

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "backToMain" {
            self.navigationController?.navigationBar.isHidden = true
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = manager.location?.coordinate {
            let databaseRef = FIRDatabase.database().reference()
            databaseRef.child("Sell_Request").queryOrderedByKey().observe(.childAdded, with: { (FIRDataSnapshot) in

                if let data = FIRDataSnapshot.value as? NSDictionary {
                    if let name = data[Constants.NAME] as? String {
                                self.sellerUserNames.append(name)
                                print(name)
                                }
                            }
                        })
                    }
                }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return sellerUserNames.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel?.text = sellerUserNames[indexPath.row]

        return cell
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

A: You just need to call tableView.reloadData() after you append the name to the sellerUserNames array, change your function to this...
  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = manager.location?.coordinate {
        let databaseRef = FIRDatabase.database().reference()

        sellerUserNames.removeAll()
        databaseRef.child("Sell_Request").queryOrderedByKey().observe(.childAdded, with: { (FIRDataSnapshot) in

            if let data = FIRDataSnapshot.value as? NSDictionary {
                if let name = data[Constants.NAME] as? String {
                            self.sellerUserNames.append(name)
                            print(name)
                            self.tableView.reloadData()
                            }
                        }
                    })
                }
            }

Edit
where/when you want to call sellerUserNames.removeAll() depends on your code and the life cycle of your table view, but I have edited my code above to add it in where it is most likely appropriate.

A: TableView need to reload after data source has changes i.e sellerUserNames in your code. So after you append the name to sellerUserNames, you need to reload the tableview.
Add this line of code after you append the name.
self.tableView.reloadData()


text:
Q: How to permit strong params for nested attributes? I'm getting a Unpermitted parameters: latitude, longitude, address error in the log when I try to accept nested attributes from a form. The exact params look like:
{
  "widget"=> {
    "owner"=>"100",
    "name"=>"Widget Co",
    "locations_attributes" => {
      "0"=> {
        "latitude"=>"51.4794259",
        "longitude"=>"-0.1026201",
        "address"=>"123 Fake Street"
      }
    }
  },
  "commit"=>"Create Supplier",
  "action"=>"create",
  "controller"=>"widgets"
}

A widget has_many locations, and a location belongs_to a widget. The params are set in the widgets_controller which I thought would permit everything under "0", but doesn't seem to?
def widget_params
  params.require(:widget).permit(:owner, :name, locations_attributes: [{"0" => []}])
end

Is there a working / better way to accept these params?
Thanks

A: Have a try with this
def widget_params
  params.require(:widget).permit(:owner, :name, locations_attributes: [:id, :latitude, :longitude, :address])
end

A: Your widgets_params code should be:
def widget_params
  params.require(:widget).permit(:owner, :name, locations_attributes: [:latitude, :longitude, :address])
end


text:
Q: Is there a way to set an exact match between a connected device via adb and via mtp? Using adb I get the serial number of the connected devices adb devices -l. Using WPD, I get connected devices and view the properties of WPD_DEVICE_SERIAL_NUMBER. On some smartphones, the serial numbers received using adb and wpd do not match.
As a temporary solution, there is an option to download the file via adb and then check its availability via mtp. But I would like to know if there are any other options on how to establish compliance but not by serial numbers?


text:
Q: JBoss não está iniciando Estou com o problema abaixo no JBoss, e gostaria de saber o que devo fazer, pois não está iniciando.

A: Verifique se o persistence.xml foi empacotado no seu war e se no arquivo existe uma persistence-unit com o nome "denuncias-ds".


text:
Q: PowerShell equivalent to "cut -c" in Bash I'm trying to learn PowerShell.
On Bash, I analyze data with the "cut -c" command with multiple positions
For example, if we have this input file:
Get-Process | tail > 1.txt # let's create an example file without headers...

To get the positions of each line from the 4'th to the 7'th characters and from the character range 57-72.
Get-Content .\1.txt | ForEach-Object { $_.substring(4,3)+ ' ' + $_.substring(57,15) }

That's a lot of typing... is there a better way?
An equivalent to the above in Bash is :
 cut -c 4-7,57-72 1.log

A: A shorter way for your specific example in your comments could be something like this;
"abc def ghik"[1..2+10] -join ""


text:
Q: How to log out using KIWI-tcms api I'm using CURL with the intention of making this example as simple as possible. I am not implementing the final version in CURL, but I am able to transform the curl sample in to the final form.
I'm using the jsonrpc version of the api. actual credentials and URL replaced with fake info
I can log in like this:
curl 'http://kiwi.example.com/json-rpc/' \
  -H 'Content-Type: application/json' \
  --data-binary '{"jsonrpc":"2.0","method":"Auth.login", "params":{"username":"me@example.com", "password" : "PASSWORD"}, "id":"jsonrpc"}';

This returns a session id, which, for these purposes is assumed to be "123456789abcdefghijklmnopqrstyvw" which is used below
I can then use that session id to do something like: (just an arbitrary API call)
curl 'http://kiwi.example.com/json-rpc/' \
  -H 'Content-Type: application/json' \
  -H 'Cookie: sessionid=123456789abcdefghijklmnopqrstyvw' \
  --data-binary '{"jsonrpc":"2.0","method":"TestPlan.filter", "params":[{"is_active":true}],"id":"jsonrpc"}';

So why doesn't this work? Or, if you prefer, what should I do differently to log out?
curl 'http://kiwi.example.com/json-rpc/' \
  -H 'Content-Type: application/json' \
  -H 'Cookie: sessionid=123456789abcdefghijklmnopqrstyvw' \
 --data-binary '{"jsonrpc":"2.0","method":"Auth.logout",  "id":"jsonrpc"}';

I expect that after I log out, the session id wouldn't work anymore, but I can still use it to access the data in Kiwi-tcms

A: Auth.logout() calls django.contrib.auth.logout(request) which in turn calls request.session.flush()

I expect that after I log out, the session id wouldn't work anymore, but I can still use it to access the data in Kiwi-tcms

And indeed this is what happens for me:
$ curl 'http://127.0.0.1:8000/json-rpc/' \
     -H 'Content-Type: application/json' \
     -H 'Cookie: sessionid=xyz' \
     --data-binary '{"jsonrpc":"2.0","method":"TestPlan.filter", "params":{"is_active":true}],"id":"jsonrpc"}';

{"id": "jsonrpc", "jsonrpc": "2.0", "error": {"code": -32603, "message": "Internal error: Authentication failed when calling \"TestPlan.filter\""}}

You are probably using an older version of Kiwi TCMS which doesn't check API credentials properly: https://kiwitcms.readthedocs.io/en/latest/changelog.html#kiwi-tcms-8-6-23-aug-2020  <-- this is also a security vulnerability so upgrade immediately.


text:
Q: How to access public attributes in RPyC on nested data? I am trying access public attributes on RPyC call by following this document but don't see it to be working as mentioned in document.
Documentation says if you don't specify protocol_config={'allow_public_attrs': True,} , public attributes , even of builtin data types won't be accessible. However even if we specify this, public attributes of nested data structure is not accessible ?
RPyC Server code.
import pickle
import rpyc

class MyService(rpyc.Service):
    def on_connect(self, conn):
        # code that runs when a connection is created
        # (to init the service, if needed)
        pass

    def on_disconnect(self, conn):
        # code that runs after the connection has already closed
        # (to finalize the service, if needed)
        pass

    def exposed_get_answer(self): # this is an exposed method
        return 42

    exposed_the_real_answer_though = 43     # an exposed attribute

    def get_question(self):  # while this method is not exposed
        return "what is the airspeed velocity of an unladen swallow?"

    def exposed_hello(self, collection):
        print ("Collection is ", collection)
        print ("Collection type is ", type(collection).__name__)
        for item in collection:
            print ("Item type is ", type(item).__name__)
            print(item)

    def exposed_hello2(self, collection):
        for item in collection:
            for key, val in item.items():
                print (key, val)

    def exposed_hello_json(self, collection):
        for item in collection:
            item = json.loads(item)
            for key, val in item.items():
                print (key, val)

if __name__ == "__main__":
    from rpyc.utils.server import ThreadedServer
    t = ThreadedServer(
            MyService(),
            port=3655,
            protocol_config={'allow_public_attrs': True,}
            )
    t.start()

Client Side Calls
>>> import rpyc
>>> rpyc.__version__
(4, 0, 2)
>>> c = rpyc.connect('a.b.c.d', 3655)  ; client=c.root

# Case 1
If data is in nested structure (using builtin data types) , it doesn't work.
>>> data
[{'a': [1, 2], 'b': 'asa'}]
>>> client.hello2(data)
...
AttributeError: cannot access 'items'
========= Remote Traceback (2) =========
Traceback (most recent call last):
  File "/root/lydian.egg/rpyc/core/protocol.py", line 329, in _dispatch_request
    res = self._HANDLERS[handler](self, *args)
  File "/root/lydian.egg/rpyc/core/protocol.py", line 590, in _handle_call
    return obj(*args, **dict(kwargs))
  File "sample.py", line 33, in exposed_hello2
    for key, val in item.items():
  File "/root/lydian.egg/rpyc/core/netref.py", line 159, in __getattr__
    return syncreq(self, consts.HANDLE_GETATTR, name)
  File "/root/lydian.egg/rpyc/core/netref.py", line 75, in syncreq
    return conn.sync_request(handler, proxy, *args)
  File "/root/lydian.egg/rpyc/core/protocol.py", line 471, in sync_request
    return self.async_request(handler, *args, timeout=timeout).value
  File "/root/lydian.egg/rpyc/core/async_.py", line 97, in value
    raise self._obj
_get_exception_class.<locals>.Derived: cannot access 'items'

Case 2 : Workaround, Pass nested data as string using json (poor man's pickle) and decode at server end.
>>> jdata = [json.dumps({'a': [1,2], 'b':"asa"})].
>>> client.hello_json(jdata) # Prints following at remote endpoint.
a [1, 2]
b asa

Case 3 :
Interestingly, at first level builtin items are accessible as in case of
hello method. But calling that on nested data is giving error.
>>> client.hello([1,2,3,4])  # Prints following at remote endpoint.
Collection is  [1, 2, 3, 4]
Collection type is  list
Item type is  int
1
Item type is  int
2
Item type is  int
3
Item type is  int
4

I have workaround / solution to the problem (case 2 above) but looking for explanation on why is this not allowed or if it is a bug. Thanks for inputs.

A: The issue is not related to nested data.
Your problem is that you are not allowing public attributes in the client side.
The solution is simple:
c = rpyc.connect('a.b.c.d', 3655, config={'allow_public_attrs': True})

Keep in mind that rpyc is a symmetric protocol (see https://rpyc.readthedocs.io/en/latest/docs/services.html#decoupled-services).
In your case, the server tries to access the client's object, so allow_public_attrs must be set in the client side.
Actually for your specific example, there is no need to set allow_public_attrs in the server side.
Regarding case 3:
In the line for item in collection:, the server tries to access two fields: collection.__iter__ and collection.__next__.
Both of these fields are considered by default as "safe attributes", and this is why you didn't get error there.
To inspect the default configuration dictionary in rpyc:
>>> import rpyc
>>> rpyc.core.protocol.DEFAULT_CONFIG


text:
Q: Animate UIBarButtonItem like Notes app I just wanted to know how I could copy the trash animation of the Notes.app application. I presume this would include two images and the class of the button is UIBarButtonItem.

A: What you're looking to do is either replace the image with an animated image or if it's already an image stack, play the animation.
Switching:

*

*When the button is released change
the Image of the Button to an
"animated" Image (array) and play the
image stack.

*Once the animation didFinishPlaying
(I think) replace the Button Image
with the original static/single
Image.

(This is much the same way you would easily do it in CSS/HTML.)
Animating:

*

*When the button is release play the
current image stack

*When the animation finishes it's
done.

(Basically when there is only one action: play (on release).)
Now, if you want to do the complete animation cycle of the button and the view it becomes a bit trickier, but not too hard.
The Kitchen Sink:

*

*You need to have the complete image
stack of the trash in it's closed
state, opening animation sequence and
closing animation sequence.

*The releasing on the icon, you start
the first half of the animation
sequences (opening animation).

*At the end of the sequence (or in
parallel) you animate a transition on
the view your "deleting" such as
warping the view so it scales into
the trash.

*When this animation finishes you send
the callback/notification/message to
the button saying I'm done (play
closing animation)

*Then rest at the initial frame of the
image stack (closed state).

I don't have the code written for you but I could write pseudo code if you'd like...
Cheers and good luck! (^_^)

A: In your UINavigationController, this is how you do it:
UIBarButtonItem *clearAll = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(trashMethod)];
self.navigationItem.rightBarButtonItem = clearAll;


text:
Q: Strange behavior with touchDragged I have a problem with a simple thing - I'm trying to impement dragging for actor, but I see strange effect - when I try to drag actor it starts blinking and change positions randomly. Here is a short video: https://youtu.be/KpGujQ7KHc0
Actor is simple:
public class Item extends Actor {
    private String id;
    private TextureRegion texture;

    public Item() {
        this.id = "passport";

        texture = PicturesData.getPicture(getId());
        setSize(texture.getRegionWidth(), texture.getRegionHeight());

        addListener(new DragListener() {
            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                return true;
            }

            @Override
            public void touchDragged(InputEvent event, float x, float y, int pointer) {
                Log.add("Dragged: " + x + ", " + y);
                setPosition(x, y);
            }
        });
    }

    public String getId() {
        return id;
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        batch.draw(texture, getX(), getY());
    }
}

The screen is basic too:
public class GameScreen implements Screen {
    private Stage stage;

    public GameScreen() {
        stage = new Stage(new StretchViewport(800, 600));
        Gdx.input.setInputProcessor(stage);

        Item item = new Item();

        stage.addActor(item);
    }

    @Override
    public void show() {
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

        stage.act(delta);
        stage.draw();
    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {

    }
}

I have no idea why it's happening, could you please help me?

A: Pasha, there's nothing wrong with your DragListener. Use this Item (starting position hardcoded):
public class Item extends Image {
    private String id;

    public Item(String id) {
        super(PicturesData.getPicture(getId());
        this.id = id;
        setPosition(50, 50);
        addListener(new DragListener() {
            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                return true;
            }

            @Override
            public void touchDragged(InputEvent event, float x, float y, int pointer) {
                moveBy(x - getWidth()/2, y - getHeight()/2);
            }
        });
    }

    public String getId() {
        return id;
    }
}

A: I think the reason your DragListener isn't working correctly is because you have overridden the touchDown function which is required for the listener to function correctly. Just change your code to this:
addListener(new DragListener() {
        @Override
        public void drag(InputEvent event, float x, float y, int pointer) {
            Log.add("Dragged: " + x + ", " + y);
            setPosition(x, y);
        }
    });


text:
Q: Discover oracle connection data (Host, SID/Service, Port) from an ODBC connection I'm not an Oracle guy, but I find that I need to touch on some oracle resources to respond to a new report request.  I'm working at an office where the connection to an oracle server uses LDAP and I can't get to the connection info.  I do have an ODBC connection on my machine, so I can get into the database through MS Access.  But I'd like to be able to connect with SQL Developer so I can do more useful profiling on the tables.
Is there any way to use my ODBC connection through Access to tease out Hostname, Port, and SID/Service name so I can connect through SQL Developer?
It seems I do not have permissions to the UTL_INADDR functions.

A: Since you have an ODBC connection defined already, you can open the ODBC Data Source Administrator on your computer (Goto the start menu and type ODBC in to search for it).
In the ODBC Data Source Administrator select the data source for the database in question (it may be on the User, System or File DSN tab) and click the Configure button.
From the Configuration screen you will be able to see the TNS Service Name for the connection.
The TNS Service Name should be all you'll need to supply to SQL Developer when creating the connection. Aside from your account credentials of course.

A: You can query SID and Hostname like this:
select instance_name, host_name from v$instance;

Afaik there is no way to query the port name from the database, see also this article on Ask TOM on this subject:

You cannot get the port -- the port is not necessarily known to the
  database. The listener need not be running on the same machine with
  the database, a single listener might be servicing many databases. A
  database may have many listeners servicing it.


text:
Q: How do I Insert an item at top of QTreeView In my app I'd like to insert an item at the top of a QTreeView.
What I have so far will insert an item just above the currently selected item.  The code (nicked, I think, from the EditableTreeviewDemo):
QModelIndex index = this->selectionModel()->currentIndex();
QAbstractItemModel *model = this->model();

if (!model->insertRow(index.row(), index.parent()))
    return;

I guess what I need is the index to the current first row?  How do I get this?
As a side question, what happens to the current index when a row is inserted?  Does it continue to point to the same item, or the same row?

A: Well first you have to know that insertRow is a function from QAbstractItemModel and it will call insertRows (with an s). This function must be redefined in your model subclass if you want to allow insertion of data in your model.
http://doc.qt.io/qt-5/qabstractitemmodel.html#insertRows
Also consider that any parent of a topmost index is a invalid QModelIndex. Then the call to do would be :
model->insertRow(0, QModelIndex());

And because this is the default value for the second parameter, simply call :
model->insertRow(0);

Then in your redefinition of insertRows simply check the validity of you parent index to ensure you news underlying data is created where you want it to be.
For you question, inserting data in the model won't affect the current and selected items.


text:
Q: How to access an xml with svg content and inject it in the dom I need to inject into the dom an svg that relies in a node_modules's svg file.
the file is under node_modules\react-twemoji-picker\src\twemoji.svg.
It's actually a sort of xml file which looks like the following :
<?xml version="1.0" encoding="utf-8"?>
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><style>svg{display:none}svg:target{display:inline}</style></defs><svg viewBox="0 0 36 36" id="0023-fe0f-20e3" xmlns="http://www.w3.org/2000/svg"><path.....

When trying to import that file :
import localtwemoji from "./twemoji.svg";
console.log("localtwemoji ? :", localtwemoji);  // this logs : "static/media/twemoji.8b3c136fba460302b57fc60ff8b592ca.svg"

i'm getting a string

"static/media/twemoji.8b3c136fba460302b57fc60ff8b592ca.svg"

and when i try to fetch it :
fetch("./twemoji.svg")
      .then((response) => {
        console.log("EmojiComponent ~ response ? :", response);
      })
      .catch(() => {
        console.log("No internet connection found. App is running in offline mode.");
      });

I'm getting such as response which doesn't have any of the real svg content :

The module itself is setting svg links in src of the images it generates which has the following format :
http://localhost:3000/static/media/twemoji.8b3c136fba460302b57fc60ff8b592ca.svg#1fa72

and when i open such as url in the browser , i see the svg with the id specified in that url displayed but I also found all the other svgs which are content of the whole xml too there as shown in this image:

So how to deal with such as xml file and how to access its content and use it in my dom?
Cheers

A: It seems like you are missing the how part of the fetch dance: "how do you want to fetch that resource?"
There are various options but nothing is DOM related as DOM and network are two different worlds.
Your best option is to use:
fetch(resource)
  .then(body => body.text())
  .then(svg => (new DOMParser)
                 .parseFromString(svg, 'image/svg+xml'))
  .then(actualSVG => {
    // append to the body or do your thing
  });

This is one way, another one could be to use a body.blob() and then create a resource with that image/svg+xml mime type and use it as new Image().src = urlResource but this is another story, your issue starts from not accessing the body of the response.


text:
Q: How to create a spike and slab prior plot in R? I was reading a paper and came across a nice plot of a spike and slab prior from page three of EMVS: The EM Approach to Bayesian Variable Selection

It appears that the spike and slab is a bit different than what is traditionally in literature. I was wondering if anyone knew how I can create such a plot in R. Would I need to use grid sampling to create such a plot? It seems due to the niceness of the plot that they used a closed-form. Any advice would be greatly appreciated, Thanks!


text:
Q: How to convert IntoIterator> to Iterator in Rust? I'm running Rust nightly (rustc 1.50.0-nightly (f0f68778f 2020-12-09)).
I learned about a way to accept (as a function parameter) arbitrary objects that can be converted to an iterator. I also learned about a way to do that to allow accepting both String and &str (and maybe other types that can be converted to &str) using AsRef<str>.
So far so good, I have a following test code that demonstrates that:
use std::env;

fn main() {
    let v1: Vec<String> = vec!["a".to_string(), "b".to_string()];
    let v2: Vec<&str> = vec!["a", "b"];
    let args: env::Args = env::args();

    fun1(&v1);
    fun1(&v2);

    fun1(v1);
    fun1(v2);
    fun1(args);
}

fn fun1<I, T>(args: I)
where
    I: IntoIterator<Item = T>,
    T: AsRef<str>,
{
    println!("=================");
    for item in args {
        println!("{}", item.as_ref());
    }
}

It compiles nicely and runs fine. Now, my desire is to convert args from IntoIterator<Item=AsRef<str>> into Iterator<Item=&str> so I don't have to deal with those as_ref() calls throughout the function. In this example it's a simple loop that calls as_ref() in one place but my code that I'm not sharing here is more convoluted – I want to avoid calling as_ref() every time I get a next element out of that iterator.
Unfortunately my naive attempt to do so doesn't work:
use std::env;

fn main() {
    let v1: Vec<String> = vec!["a".to_string(), "b".to_string()];
    let v2: Vec<&str> = vec!["a", "b"];
    let args: env::Args = env::args();

    fun2(&v1);
    fun2(&v2);

    fun2(v1);
    fun2(v2);
    fun2(args);
}

fn fun2<I, T>(args: I)
where
    I: IntoIterator<Item = T>,
    T: AsRef<str>,
{
    println!("=================");
    let iter = args.into_iter();
    let mapped = iter.map(|item| item.as_ref());
    for item in mapped {
        println!("{}", item);
    }
}

% rustc test1.rs
error[E0515]: cannot return value referencing function parameter `item`
  --> test1.rs:23:34
   |
23 |     let mapped = iter.map(|item| item.as_ref());
   |                                  ----^^^^^^^^^
   |                                  |
   |                                  returns a value referencing data owned by the current function
   |                                  `item` is borrowed here

error: aborting due to previous error

For more information about this error, try `rustc --explain E0515`.

and for the life of me I can't get around this (I played with various approaches and all I got was errors like this), I looked through some previous questions and no luck.
Is there even a way to achieve this in Rust?

A: This is not possible without collecting all of the data in the iterator into a Vec or similar. This is because an Iterator<Item = &str> requires that the string data behind the slices is not owned by the iterator, but an Iterator<Item = String> does own the string data by virtue of using an owned type.
This also explains why collecting into a vector works. In that case, the string data would be owned by the vector, and not the iterator, which satisfies the requirement that the Iterator<Item = &str> does not own the string data.
fn fun2<I, T>(args: I)
where
    I: IntoIterator<Item = T>,
    T: AsRef<str>,
{
    println!("=================");

    let vec: Vec<T> = args.into_iter().collect();

    let mapped = vec.iter().map(|item| item.as_ref());
    for item in mapped {
        println!("{}", item);
    }
}

Note that it is not always the case that an T: AsRef<str> type owns the string data. For example, if T = &str, then it doesn't. Unfortunately generic code must handle all cases allowed by the generic parameters, so if the code does not handle the T = String case, it wont compile.
Note that in the case of T = &str, then the vector in the above example does not own the string data. Still, this is ok, because in that case, the string data is owned by some other collection entirely outside of fun2, and that also satisfies the requirement that Iterator<Item = &str> must not own the string data.


text:
Q: NZLOAD is working while External Table in Netezza failing with count of bad input rows reached maxerrors Intermittent issues with Netezza External Table .
External table is failing with the file generated by the system itself(Meant the file generated by external table not from other sources).But we tried to load the same file via nzload utility to another table and that is working without any issues.This issue is not consistent and unable to reproduce most of times.
CREATE EXTERNAL TABLE SP_PORTFOLIO_EXT_DATA_6128_140
(
    CLIENT_ID INTEGER,
    CONFIG_ID INTEGER,
    SCENARIO_ID INTEGER,
    PORTFOLIO_ID INTEGER,
    PORTFOLIO_NAME CHARACTER VARYING(200),
    CUSTOM13 CHARACTER VARYING(600),
    CUSTOM12 CHARACTER VARYING(500),
    CUSTOM11 CHARACTER VARYING(500),
    CUSTOM10 CHARACTER VARYING(500),
    CUSTOM9 CHARACTER VARYING(500),
    CUSTOM8 CHARACTER VARYING(500),
    CUSTOM7 CHARACTER VARYING(500),
    CUSTOM6 CHARACTER VARYING(2000),
    CUSTOM3 CHARACTER VARYING(500),
    CUSTOM2 CHARACTER VARYING(3000),
    CUSTOM1 CHARACTER VARYING(500),
    CREATIVE CHARACTER VARYING(512),
    PLACEMENT CHARACTER VARYING(5000),
    IMPRESSIONS NUMERIC(38,0),
    CLICKS NUMERIC(38,0),
    CONVERSIONS INTEGER,
    TRUE_CONVERSIONS NUMERIC(38,6),
    OPTMETRIC NUMERIC(38,6),
    LASTAD_OPTMETRIC NUMERIC(38,6),
    CURRSPEND NUMERIC(38,6)
)
USING
(
    DATAOBJECT('/san5/Netezza/CAR/CAR_ZEUS/SPBU/test/SP_PORTFOLIO_EXT_DATA_6128_140.csv')
    DELIMITER 254
    ESCAPECHAR '/'
    TIMESTYLE '24HOUR'
    LOGDIR '/tmp'
    Y2BASE 2000
    ENCODING 'internal'
);

The command completed successfully
select COUNT(*) from SP_PORTFOLIO_EXT_DATA_6128_140;
ERROR [HY000] ERROR:  External Table : count of bad input rows reached maxerrors limit

NZLOAD method
CREATE TABLE TEST_LOAD
(
    CLIENT_ID INTEGER,
    CONFIG_ID INTEGER,
    SCENARIO_ID INTEGER,
    PORTFOLIO_ID INTEGER,
    PORTFOLIO_NAME CHARACTER VARYING(200),
    CUSTOM13 CHARACTER VARYING(600),
    CUSTOM12 CHARACTER VARYING(500),
    CUSTOM11 CHARACTER VARYING(500),
    CUSTOM10 CHARACTER VARYING(500),
    CUSTOM9 CHARACTER VARYING(500),
    CUSTOM8 CHARACTER VARYING(500),
    CUSTOM7 CHARACTER VARYING(500),
    CUSTOM6 CHARACTER VARYING(2000),
    CUSTOM3 CHARACTER VARYING(500),
    CUSTOM2 CHARACTER VARYING(3000),
    CUSTOM1 CHARACTER VARYING(500),
    CREATIVE CHARACTER VARYING(512),
    PLACEMENT CHARACTER VARYING(5000),
    IMPRESSIONS NUMERIC(38,0),
    CLICKS NUMERIC(38,0),
    CONVERSIONS INTEGER,
    TRUE_CONVERSIONS NUMERIC(38,6),
    OPTMETRIC NUMERIC(38,6),
    LASTAD_OPTMETRIC NUMERIC(38,6),
    CURRSPEND NUMERIC(38,6)
)
DISTRIBUTE ON RANDOM;

# Loading data  from the same file using Nzload

nzload -host 10.200.29.30 -u xxxxx -pw xxxxx -db SPBU_REPORT_DB_TEST -t test_load -delim 254 -ctrlChars  -df /san5/Netezza/CAR/CAR_ZEUS/SPBU/test/SP_PORTFOLIO_EXT_DATA_6128_140.csv

Load session of table 'TEST_LOAD' completed successfully

[ja.prod@inet11026 ~]$ cat /san5/Netezza/CAR/CAR_ZEUS/SPBU/test/SP_PORTFOLIO_EXT_DATA_6128_140.csv|wc -l
191322

select count(*) from test_load;
191322

Adding the nzlog
File Buffer Size (MB): 8                  Load Replay Region (MB): 0
  Encoding:              INTERNAL           Max errors:            1
  Skip records:          0                  Max rows:              0
  FillRecord:            No                 Truncate String:       No
  Escape Char:           '/'                Accept Control Chars:  No
  Allow CR in string:    No                 Ignore Zero:           No
  Quoted data:           NO                 Require Quotes:        No

  BoolStyle:             1_0                Decimal Delimiter:     '.'

  Disable NFC:           No
  Date Style:            YMD                Date Delim:            '-'
  Y2Base:                2000
  Time Style:            24HOUR             Time Delim:            ':'
  Time extra zeros:      No

Found bad records

bad #: input row #(byte offset to last char examined) [field #, declaration] diagnostic, "text consumed"[last char examined]
----------------------------------------------------------------------------------------------------------------------------
1: 25(184) [21, INT4] expected field delimiter or end of record, "0"[.]

Statistics

  number of records read:      25
  number of bad records:       1
  -------------------------------------------------
  number of records loaded:    0

  Elapsed Time (sec): 0.0

-----------------------------------------------------------------------------
Load completed at: 08-Oct-15 09:59:04 EDT

The .nzbad data containing the bad row (with pipe symbols standing in for the actual delimiter for readbility):
140|1305|6128||NULL|SEO|SEO|test.com/vehicledetail/detail/632888199/overview|SEO|SEO|SEO|SEO Brand|SEO Brand|best Tracking|Google(Seo)|SEO|Impression Tracker|Unknown|0|1|0|0.000000|0.000000|0.000000|0.000000

A: From the nzlog we can tell that the load is failing on the 25th row. Specifically, as it tries to load the 21st column it encounters a value that is not an integer.
The log shows that it encounters a 0 which is then followed by a period. So the data likely has something like 0.0 or 0.1234 which can't be loaded as an integer.
bad #: input row #(byte offset to last char examined) [field #, declaration] diagnostic, "text consumed"[last char examined]
----------------------------------------------------------------------------------------------------------------------------
1: 25(184) [21, INT4] expected field delimiter or end of record, "0"[.]

With the .nzbad data you have provided (here with '|' instead of your actual delimiter for readability purposes):
140|1305|6128||NULL|SEO|SEO|test.com/vehicledetail/detail/632888199/overview|SEO|SEO|SEO|SEO Brand|SEO Brand|best Tracking|Google(Seo)|SEO|Impression Tracker|Unknown|0|1|0|0.000000|0.000000|0.000000|0.000000

One thing I notice here is that you have a varchar field with '/' in it. One of the differences between your external table and your nzload approach is that the external table specifies  escapechar '/' while the nzload doesn't.
You will find that your data 'test.com/vehicledetail/detail/632888199/overview' will be loaded as 'test.comvehicledetaildetail632888199overview' because the '/' characters will be removed as they are not themselves escaped (e.g. '//').
If a '/' directly preceded a column delimiter in the data, it will direct it to consider the column delimeter to be part of the data instead, and will think column 22 in the data is actually for column 21 in the table which would match what we are seeing here.

A: ScottMcG as you said I compared the nzlog files generated by Nzload and External table and found that escape character is the only difference.So I commented out that part and tried again and the things working .
CREATE EXTERNAL TABLE SP_PORTFOLIO_EXT_DATA_6128_140

(
    CLIENT_ID INTEGER,
    CONFIG_ID INTEGER,
    SCENARIO_ID INTEGER,
    PORTFOLIO_ID INTEGER,
    PORTFOLIO_NAME CHARACTER VARYING(200),
    CUSTOM13 CHARACTER VARYING(600),
    CUSTOM12 CHARACTER VARYING(500),
    CUSTOM11 CHARACTER VARYING(500),
    CUSTOM10 CHARACTER VARYING(500),
    CUSTOM9 CHARACTER VARYING(500),
    CUSTOM8 CHARACTER VARYING(500),
    CUSTOM7 CHARACTER VARYING(500),
    CUSTOM6 CHARACTER VARYING(2000),
    CUSTOM3 CHARACTER VARYING(500),
    CUSTOM2 CHARACTER VARYING(3000),
    CUSTOM1 CHARACTER VARYING(500),
    CREATIVE CHARACTER VARYING(512),
    PLACEMENT CHARACTER VARYING(5000),
    IMPRESSIONS NUMERIC(38,0),
    CLICKS NUMERIC(38,0),
    CONVERSIONS INTEGER,
    TRUE_CONVERSIONS NUMERIC(38,6),
    OPTMETRIC NUMERIC(38,6),
    LASTAD_OPTMETRIC NUMERIC(38,6),
    CURRSPEND NUMERIC(38,6)
)
USING
(
    DATAOBJECT('/san5/Netezza/CAR/CAR_ZEUS/SPBU/test/SP_PORTFOLIO_EXT_DATA_6128_140.csv')
    DELIMITER 254
    TIMESTYLE '24HOUR'
    LOGDIR '/tmp'
    Y2BASE 2000
    ENCODING 'internal'
);
select count(*) from SP_PORTFOLIO_EXT_DATA_6128_140;
191322.

A: The data type must be changed as follows: CHARACTER VARYING replace for VARCHAR/ NVARCHAR
CREATE TABLE TEST_LOAD
(
CLIENT_ID INTEGER,
CONFIG_ID INTEGER,
SCENARIO_ID INTEGER,
PORTFOLIO_ID INTEGER,
PORTFOLIO_NAME VARCHAR(200),
CUSTOM13 VARCHAR(600),
CUSTOM12 VARCHAR(500),
CUSTOM11 VARCHAR(500),
CUSTOM10 VARCHAR(500),
CUSTOM9 VARCHAR(500),
CUSTOM8 VARCHAR(500),
CUSTOM7 VARCHAR(500),
CUSTOM6 VARCHAR(2000),
CUSTOM3 VARCHAR(500),
CUSTOM2 VARCHAR(3000),
CUSTOM1 VARCHAR(500),
CREATIVE VARCHAR(512),
PLACEMENT VARCHAR(5000),
IMPRESSIONS NUMERIC(38,0),
CLICKS NUMERIC(38,0),
CONVERSIONS INTEGER,
TRUE_CONVERSIONS NUMERIC(38,6),
OPTMETRIC NUMERIC(38,6),
LASTAD_OPTMETRIC NUMERIC(38,6),
CURRSPEND NUMERIC(38,6)
)
DISTRIBUTE ON RANDOM;


text:
Q: I want to pass the id using ajax call.. i have tried the following code I want to pass the id of the button using ajax call ... and display the result into id called demo2 ...

<button id="111" onclick="loadDoc2()">Button 1</button>
<button id="222" onclick="loadDoc2()">Button 2</button>
<button id="333" onclick="loadDoc2()">Button 3</button>

A: I would had passed it on the function and use it as variable because "this" looks on the window scope.

<button id="111" onclick="loadDoc2(this)">Button 1</button>
<button id="222" onclick="loadDoc2(this)">Button 2</button>
<button id="333" onclick="loadDoc2(this)">Button 3</button>

A: You can do this in two ways
No 1.

<button id="111" onclick="loadDoc2("111")">Button 1</button>
<button id="222" onclick="loadDoc2("222")">Button 2</button>
<button id="333" onclick="loadDoc2("333")">Button 3</button>

No 2.

<button id="111" onclick="loadDoc2()">Button 1</button>
<button id="222" onclick="loadDoc2()">Button 2</button>
<button id="333" onclick="loadDoc2()">Button 3</button>


text:
Q: SonarQube server can not be reached by Jenkins using Docker I have added a SonarQube Scanner analysis step to my Jenkins build, but the step fails:
[Test_gitlab] $ /var/jenkins_home/tools/hudson.plugins.sonar.SonarRunnerInstallation/http_INTERNAL_DOCKER_IP_ADDRESS_9000/bin/sonar-scanner -e -Dsonar.host.url=SERVER_IP_ADDRESS:9000 ******** -Dsonar.projectBaseDir=/var/jenkins_home/workspace/Test_gitlab
INFO: Option -e/--errors is no longer supported and will be ignored
INFO: Scanner configuration file: /var/jenkins_home/tools/hudson.plugins.sonar.SonarRunnerInstallation/http_INTERNAL_DOCKER_IP_ADDRESS_9000/conf/sonar-scanner.properties
INFO: Project root configuration file: NONE
INFO: SonarQube Scanner 2.8
INFO: Java 1.8.0_102 Oracle Corporation (64-bit)
INFO: Linux 3.10.0-327.10.1.el7.x86_64 amd64
INFO: User cache: /var/jenkins_home/.sonar/cache
ERROR: SonarQube server [SERVER_IP_ADDRESS:9000] can not be reached
INFO: ------------------------------------------------------------------------
INFO: EXECUTION FAILURE
INFO: ------------------------------------------------------------------------
INFO: Total time: 0.214s
INFO: Final Memory: 4M/209M
INFO: ------------------------------------------------------------------------
ERROR: Error during SonarQube Scanner execution
org.sonarsource.scanner.api.internal.ScannerException: Unable to execute SonarQube
    at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory$1.run(IsolatedLauncherFactory.java:84)
    at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory$1.run(IsolatedLauncherFactory.java:71)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory.createLauncher(IsolatedLauncherFactory.java:71)
    at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory.createLauncher(IsolatedLauncherFactory.java:67)
    at org.sonarsource.scanner.api.EmbeddedScanner.doStart(EmbeddedScanner.java:218)
    at org.sonarsource.scanner.api.EmbeddedScanner.start(EmbeddedScanner.java:156)
    at org.sonarsource.scanner.cli.Main.execute(Main.java:72)
    at org.sonarsource.scanner.cli.Main.main(Main.java:61)
Caused by: java.lang.IllegalStateException: Fail to download libraries from server
    at org.sonarsource.scanner.api.internal.Jars.downloadFiles(Jars.java:93)
    at org.sonarsource.scanner.api.internal.Jars.download(Jars.java:70)
    at org.sonarsource.scanner.api.internal.JarDownloader.download(JarDownloader.java:39)
    at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory$1.run(IsolatedLauncherFactory.java:75)
    ... 8 more
Caused by: java.lang.IllegalArgumentException: unexpected url: SERVER_IP_ADDRESS:9000/batch_bootstrap/index
    at org.sonarsource.scanner.api.internal.shaded.okhttp.Request$Builder.url(Request.java:141)
    at org.sonarsource.scanner.api.internal.ServerConnection.callUrl(ServerConnection.java:109)
    at org.sonarsource.scanner.api.internal.ServerConnection.downloadString(ServerConnection.java:98)
    at org.sonarsource.scanner.api.internal.Jars.downloadFiles(Jars.java:78)
    ... 11 more
ERROR:
ERROR: Re-run SonarQube Scanner using the -X switch to enable full debug logging.
ERROR: SonarQube scanner exited with non-zero code: 1
Finished: FAILURE

My SonarQube Scanner is declared in Jenkins Global Tool Configuration. The name used is "http://SERVER_IP_ADDRESS:9000". This is the same address as the server base URL that I have set within SonarQube General Settings.
I'm using Docker: Jenkins is in a Docker container, and so does SonarQube.
The "unexpected url" mentioned in the stacktrace SERVER_IP_ADDRESS:9000/batch_bootstrap/index can be opened in a browser,
which displays sonar-scanner-engine-shaded-6.1.jar|SOME_LETTERS_AND_NUMBERS.
So why can't Jenkins reach the server?
I've also tried with Docker internal IP address, that can be found with:
docker inspect SONARQUBE_CONTAINER_ID | grep IP

A: Find place where you define the "unexpected url" mentioned in the stacktrace (parameter sonar.host.url of SonarQube Scanner) and prefix it with http://.
URLs must start with a scheme - see Wikipedia. Browser simply adds http:// by default.


text:
Q: switch between tabs in chrome using arquillian graphene I need to switch tabs using Graphene and continue the test without failing.
I am testing an application that creates a project and then opens that project from a link on a page.
My issue is that it opens the project in a new tab and to continue the test I have to switch to the new tab.
I am using the selenium switch windowHandler but getting an error from the Graphene. I will not know the new URL until the project has been created.
//Switch to tab opened from previous test
    public void switchTab(int tabNumber) throws Exception{
        for (String winHandle : driver.getWindowHandles()) {
            driver.switchTo().window(winHandle);
            Thread.sleep(3000);
        }
    }

Error: The page object 'CreateChangeSubProjStruct' that you are navigating to using either Graphene.goTo() or @InitialPage is not annotated with @Location
I can see the new page opens and is on top but the test is running on the original tab.


text:
Q: $\lim_{n\to\infty} a_n=a$ if and only if $\forall p\in \Bbb N$, $\lim_{n\to\infty} |a_{n+p}-a_n|=0$ I'm doing exercises. In the related book, there is a claim. Is this right? I'm not sure.

For a sequence $\{a_n\}$, there exists a limit $a$ such that $\lim_{n\to\infty} a_n=a$ if and only if for any $p\in \Bbb N$, $\lim_{n\to\infty} |a_{n+p}-a_n|=0$

If not, could you kindly give some counterexamples?
Thanks.

A: The question Is there a divergent sequence such that $(x_{k+1}-x_k)\rightarrow 0$? is very similar.  It asks for a sequence $(a_n)$ that has no limit but such that $\lim\limits_{n\to\infty}(a_{n+1}-a_n)=0$. If $(a_n)$ is any such sequence, then it is also a counterexample for your question, because $$|a_{n+p}-a_n|\leq |a_{n+p}-a_{n+p-1}|+|a_{n+p-1}-a_{n+p-2}|+\cdots+|a_{n+1}-a_n|,$$ and the last expression goes to $0$ because it is a sum of $p$ things that all go to $0$ as $n$ goes to $\infty$.

A: We give an example where the limit, even  in the "extended" ($\infty$) sense does not exist:
$$0, 1, \frac{1}{2}, 0, \frac{1}{3},\frac{2}{3}, 1, \frac{3}{4}, \frac{2}{4},\frac{1}{4},0, \frac{1}{5},\frac{2}{5},\frac{3}{5}, \frac{4}{5}, 1, \frac{5}{6},\frac{4}{6}, \frac{3}{6}, \frac{2}{6},\frac{1}{6},0, \frac{1}{7},\frac{2}{7}\dots.$$
Every real number between $0$ and $1$ is an accumulation point of the above sequence.

A: $a_n = \displaystyle\sum_{k=1}^{n}\frac{1}{k}$ diverges, and $\displaystyle\lim_{n\to \infty} \sum_{k=n+1}^{n+p}\frac{1}{k}=0$.


text:
Q: Alter list of attributes listed by dir function Let's assume you have an instance of the following class:
class Foo(object):
    def __init__(self, data):
        self._data = data

foo = Foo({'bar': 'baz'})

when you do dir(foo) you get:
>>> dir(foo)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_data']

Note _data at the end of the property list
I would like to have a way to customize what dir outputs for instances of my class. In this specific case, I would like to add the key-value pairs in the _data dictionary to be listed as additional items in the previous output, like:
>>> dir(foo)
['__class__', '__delattr__', ..., '_data', 'bar']

Note _data AND bar at the end of the property list
I thought there would be a special function to customize this in a similar way like you can customize an instance with __str__, __repr__, etc. but haven't found anything for this yet.
UPDATE: I'm looking for something that only alters the properties to display, without altering the instance __dict__ with something like:
class Foo(object):
    def __init__(self, data):
        self._data = data
        self.__dict__.update(data)  # I would prefer not to do this

Is there any way to do this? Thanks in advance for your help!

A: Yes, this is the purpose of the __dir__ special method. See the python documentation on dir().
For example:
class Foo(object):

    def __init__(self, data):
        self._data = data

    def __dir__(self):
        return dir(object) + self.__dict__.keys() + [k for k in self._data]

foo = Foo({'bar': 'baz'})

Which gives this:
>>> foo = Foo()
>>> dir(foo)
['__class__',
 '__delattr__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '_data',
 'bar']

Note that it probably only really makes sense to do this if you're defining __getattr__ or __getattribute__ as well so that the user can write something like foo.bar, otherwise dir() would be sort of misleading.


text:
Q: How can I hide the text Using zend form in zend studio //User can see this textfield well i want it to be hidden from user
 $form=new Zend_Form;

    $this->setMethod ( 'post' );

    $purchaseid=$this->createElement('text', 'purchaseid');

    $this->addElement($purchaseid);

A: If you want a hidden field, you can do this:
$purchaseid=$this->createElement('hidden', 'purchaseid');


text:
Q: SSH через OpenVPN Есть пк c Linux на борту нужно наладить ssh!
Провайдер даёт только "серые" ip для обхода этой проблемы решил воспользоваться OpenVPN (vpn брался здесь)
OpenVPN ставился из репозитория и поднимался так.. (sudo openvpn /путь до файла конфигурации .ovpn)
Далее попытка подключится по ssh (ssh TheDog@46.30.45.178:22) но нечего не происходит.
Возможно ли что нужно как то специфично открыть 22 порт для OpenVPN
Конфиг SSH /etc/ssh/sshd_config
# Package generated configuration file
# See the sshd_config(5) manpage for details

# What ports, IPs and protocols we listen for
Port 22
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes

# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 1024

# Logging
SyslogFacility AUTH
LogLevel INFO

# Authentication:
LoginGraceTime 120
PermitRootLogin prohibit-password
StrictModes yes

RSAAuthentication yes
PubkeyAuthentication yes
#AuthorizedKeysFile %h/.ssh/authorized_keys

# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2
HostbasedAuthentication no
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes

# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication yes

# Kerberos options
#KerberosAuthentication no
#KerberosGetAFSToken no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no

#MaxStartups 10:30:60
#Banner /etc/issue.net

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

Subsystem sftp /usr/lib/openssh/sftp-server

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes

A: Правильно я понимаю, что Openvpn сервер находится на машине с "серым" IP?
Если у вас динамический IP выдаваемый провайдером, то лучшим решением будет взять себе бесплатное доменное имя 3го уровня (например через no-ip.com).
Если ваш провайдер выдает вам внутренний локальный адрес, вида 192.168.. или 10...* и у вас есть собственный IPV6, то подключайтесь через IPV6.
Если ваш провайдер выдает вам ТОЛЬКО внутренний локальный адрес, вида 192.168.. или 10...* то единственное что вы можете сделать - попросить провайдера открыть на вас 1 какой-то внешний порт (возможно платно) и пустить VPN трафик через этот порт.


text:
Q: Are websites on subdomains in Azure priced as separate websites in 'Shared' websites? I'm looking to host several websites on Azure.
The 'sales'  website will be on the www.blabla.com domain, but the actual system will be on my.blabla.com, and admin site on admin.blabla.com.
Will I get charged for 3 websites, or just 1 since its on the same domain?
I couldnt find anything on this on the azure website.
Thanks!

A: If you're creating 3 websites in Shared mode, you'll be charged for 3 websites.  Standard mode works differently: you're charged per VM and you can host up to 500 sites in a VM.  Have you looked at the Azure pricing calculator?
http://www.windowsazure.com/en-us/pricing/calculator/


text:
Q: robots.txt file being overridden / injected from external source? We have a couple of Wordpress sites with this same issue.  They appear to have a "robots.txt" file with the following contents:
User-Agent: *
Crawl-Delay: 300
User-Agent: MJ12bot
Disallow: /
User-agent: MegaIndex.ru
Disallow: /
User-agent: megaindex.com
Disallow: /

We have absolutely no idea where this robots.txt file is coming from.
We have looked and there is definitely no "robots.txt" file in the public_html root folder or any sub-folder that we can see.
We have deactivated every single plugin on the site and even changed themes, but the robots.txt file remains exactly the same.  It seems as though it is somehow being injected into the site from an external source somehow!
We have been assured that it couldn't be coming from Google Tag Manager.
Just wondering if anyone happens to recognise the above robots.txt contents and knows how it is existing on our sites???

A: You have a few possibilities.
Some security plugins (WordFence, iTheme etc) actually add files to your site. These files don't generally go away when you just "disable" the plugins. They need to be actually removed/uninstalled and sometimes you have to manually go through and do it.
WordPress will generate a virtual robots.txt.
If Google has cached that. You can go in and tell Google to look at the robots.txt again.
You should also be able to overwrite it by creating your own by just making a robots.txt file and putting it in the root or using another plugin to do it.

A: Turns out it was a generic robots.txt file that our server administrator had set up to be injected into every site on our server to prevent our server being attacked and overloaded by those particular bots (which we had been having trouble with).


text:
Q: How to put an extra row with fixed text between a large list of words in Excel? Who knows a way of simply pasting a list of words in excel in one column, and then Excel instantly creates the same list next to it, but with an extra row with a fixed text between every original row?
example:

input column:

*

*word 1

*word 2

*word 3

... etc.
with the word "beep" as an example of a 'fixed text'.

output column:

*

*word 1

*beep

*word 2

*beep

*word 3

*beep

*... etc.*

Screenshot example:
View example image
The lists are very long (50.000+ words). I can use lists in this format for a Reminder App that only reads lists that are in the above mentioned format. I have to convert a lot of lists in this way
Thanks a lot!

A: Here is a simple VBA routine, based on your screenshot.  You will obviously need to adjust the ranges to match your real data.  Since VBA arrays are used, it should run much more quickly than solutions involving multiple reads/writes from the worksheet.
Option Explicit
Sub NewList()
Dim vInput As Variant, vNewList As Variant
Dim sFixedWord As String
Dim I As Long

vInput = Range("a2", Cells(Rows.Count, "A").End(xlUp))
sFixedWord = Range("b2")

ReDim vNewList(0 To UBound(vInput, 1) * 2, 1 To 1)
vNewList(0, 1) = Range("C1") 'Header
For I = 1 To UBound(vInput, 1)
    vNewList((I - 1) * 2 + 1, 1) = vInput(I, 1)
    vNewList((I - 1) * 2 + 2, 1) = sFixedWord
Next I

With Range("c1").Resize(UBound(vNewList, 1) + 1)
    .EntireColumn.Clear
    .Value = vNewList
    .EntireColumn.AutoFit
End With

End Sub

A: Here is the "simplified" version :
Sub beep()
    Range(Selection.End(xlUp), Selection.End(xlDown)).Select ' optional to select the rest of the words
    values = WorksheetFunction.Transpose(Selection)
    Text = Join(values, vbCrLf & "beep" & vbCrLf) & vbCrLf & "beep"   ' change "beep"
    Set DataObject = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}") ' this is a late bound New MSForms.DataObject
    DataObject.SetText Text
    DataObject.PutInClipboard
    Selection(, 2).PasteSpecial ' optional to paste the values next to the selection
End Sub

Click on any of the words and Alt+F8 to run the macro.
If you want to select the words or paste the result somewere else, you can remove the first and last optional lines in the macro.
Update
The Transpose function is limited to 65535 values and will ignore the rest, so here is the alternative:
Sub beep()
    Range(Selection.End(xlUp), Selection.End(xlDown)).Select ' optional to select the rest of the words
    Selection.Copy
    With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}") ' this is a late bound New MSForms.DataObject
        .GetFromClipboard
        Text = .GetText
        .Clear
        Text = Replace(Text, vbNewLine, vbNewLine & "beep" & vbNewLine) ' change "beep"
        .SetText Text
        .PutInClipboard
    End With
    Selection(1, 2).PasteSpecial ' optional to paste the values next to the selection
End Sub


text:
Q: OpenGL - glDrawElementsInstanced - fragment shader and incorrect colors I have created instancing, that correctly display geometry, but its graphics is incorrect.
My VS look like this
#version 410

#include "engine-variables.inc"
#include "functions.inc"

in vec3 POSITION;
in vec3 NORMAL;
in vec2 TEXCOORD0;
in mat4 INSTANCE_TRANSFORM;

out vec2 vTexCoord;
out vec3 vNormal;

void main()
{
    gl_Position = CalcPositionInWorld_Instance(POSITION, INSTANCE_TRANSFORM);

    vNormal = NORMAL;

    vTexCoord.x = TEXCOORD0.x;
    vTexCoord.y = 1.0 - TEXCOORD0.y;

}

Note: #include is processed by my app - not part of glsl
I have simple fragment shader
#version 410

in vec2 vTexCoord;
in vec3 vNormal;

out vec4 fCol;

uniform sampler2D en_texModel;

void main()
{

  vec4 texVal = texture2D(en_texModel, vTexCoord);

  fCol = vec4(1, 0, 0, 1) + 0.00001 * texVal + vec4(0.00001 * vNormal, 0);

}

Note: 0.00001 values are there because of debugging, when I need to hold texVal and vNormal variables for refractoring within my app.
Result is incorrectly colored. Model is not red, but black and white (randomly distributed over triangles) - only few triangles are red

A: The culprit was the line:
fCol = vec4(1, 0, 0, 1) + 0.00001 * texVal + vec4(0.00001 * vNormal, 0);

Which can still result in a black color if either texVal.x or vNormal.x is large and negative, cancelling out the red color from vec4(1,0,0,1).


text:
Q: Two views displaying live data at the same time I have two view controllers which should work like described below:
First view controller displays a view which has a table in it. The table contains data which is constantly changing. I have a delegate method for reloading the data when a change occurs. So that is taken care of. When the user selects a row in the table I would like to display a second view which would also contain live data in text format (one UITextView which would constantly change).
I would like to allow the user to access view 1 while view 2 would still be monitoring and displaying live data and vice versa. While user is on view 2, view 1 should still be monitoring and displaying any changes in the table content.
I guess its like having two view controllers present at the same time and switching between them.
What is the easiest or the most standard way to accomplish this? I dont mind if its all done programatically.

A: what you have is a problem where you need a custom parentviewcontroller
look into splitviews as one example  :: SplitView like Facebook app on iPhone
cool intros of how to do custom container view controllers :: Container View Controller Examples

A: It's a little hard to tell what you're asking here. First, views shouldn't be processing data at all -- they should only be displaying it. It sounds like what you're describing is having a background process that updates to your second view. That process could certainly be running while your table is on screen, and when you switch to the second view, you can update it using this running process. Exactly how you would do this depends on the details of what you're trying to do. So, I think we could help you better if you provide more context on what kind of process you want going on that updates your second view, and how choosing a row in your table affects that process.
After Edit:
You can certainly do what you want to do. I think the main thing is that you need to have a property (typed strong) in your first view controller that points to your second view controller, so that when you go back to the second controller a second time, it goes back to the same instance. Based on the selection from the table, you can start whatever process you need to populate your text view, and that process can keep running even after you go back to the table view, since that controller won't get deallocated when it's view goes off screen (due to the strong reference you have). You would just have to have some sort of if clause in your second view controller to know whether the user has selected the same row again, and if so, just show the updated text view, rather than starting a new process.
That's about as specific as I can be without more detail from you.


text:
Q: Use number in where condition in Laravel Query The below query works well in mysql but how to represent the same thing using Laravel.
select * from user_subscription where vendor_id = 'user_100'
and 0 = (select count(*) from user_restricted_dates where vendor_id = 'user_100')

I tried with code but gives error as unknown column '0' in where clause
$list = UserSubscription::where('vendor_id', '=', $vendor_obj->vendor_id)
    ->where(0, '=', "(select count(*) from user_restricted_dates where vendor_id = 'user_100'")
    ->get();

Well the error indicates what it is but how to represent it

A: The where method of the Query Builder maps the first value you pass to a field in the model. You'd have to use the whereRaw method instead.
$list = UserSubscription::where('vendor_id', '=', $vendor_obj->vendor_id)
    ->whereRaw("0 = (select count(*) from user_restricted_dates where vendor_id = 'user_100')")
    ->get();


text:
Q: GRAV CMS TNTSearch title page override I'm trying to customize the "TNTSearch Search" string from the search.md page of the Plugin.
---
title: TNTSearch Search
---

Tried to put an override in my template folder and other stuff without success.
How can this be customized?

A: Create file /user/pages/search/search.md and add your new title. E.g.:
---
title: My New Title
---

Update after chat:
When default search_route: '/search' has been changed in config of plugin, above folder must match the name of the route.
Eg. if route is defined as search_route: '/mysearch' the overriding file should be /user/pages/mysearch/search.md


text:
Q: ReactJS - What are the pros and cons of managing context outside of the component tree? In a React (Native) application, consider a util file such as:
let apples = 0;

export function addApple() {
    apples++;
}

export function getApples() {
    return apples;
}

Is it okay to store the state of apples this way such that components can modify it like:
import { addApple } from "./myUtil";

export function AddAppleButton {
    return <button onClick={addApples} />
}

And non-React code can use it like:
import { addApple } from "./myUtil";

export function addMultipleApples(numberOfApples) {
    for (let i = 0; i < numberOfApples; i++) {
        addApple();
    }
}

What are the pros and cons of managing context this way?

A: Essentially, it won't work. Since apples is not managed by react state, when it changes, React will not trigger a re-render so the value will not update on screens that read from it. It may accidentally look like it's working if a re-render happens for some other reason, React will pick up the new value -- but this would be extremely fragile and inevitably lead to indeterminate states and race conditions you don't want to exist.
For what you need to do, it would make more sense to build a store container (like a class) and put this in the React state, then add methods to that store such that its values can be read and written from the outside. The store would need to inform components listening to it the value changed, via a subscription mechanism or similar. This is a fairly complex thing to set up, so it'd probably be better to adopt a library that supports reading/writing stores from outside of React. Like Zustand.


text:
Q: how to get the long & lat value of four corners in the mapview in android? i working on map view. i want to put overlay item  on the map view.  that overlay items are all depends on currently showing map view and zoom level. how to get current map view's longitude and latitude of that four corner and how to analyze how many overlay item inside it. also we have to check thee zoom level.Any Idea? how to do it?

A: If you're using the google-play-services library and the SupportMapFragment in particular.
this.getMap() will give you the instance of GoogleMap (which wraps MapView)
Then just:
map.getProjection().getVisibleRegion();

A: Are you looking for something like this?
Projection proj = mapView.getProjection();
GeoPoint topLeft = proj.fromPixels(0, 0);

GeoPoint bottomRight = proj.fromPixels(mapView.getWidth()-1, mapView.getHeight()-1);

double topLat = topLeft.getLatitudeE6()/1E6;
double topLon = topLeft.getLongitudeE6()/1E6;
double bottomLat = bottomRight.getLatitudeE6()/1E6;
double bottomLon = bottomRight.getLongitudeE6()/1E6;

Hope it helps!

A: I think you have to use
mapview.getProjection().frompixel(intx, int y)

For the 4 corners of your screen (you can get their coordinates by getwidth and getheight on your mapView, and starting with (0,0), (getwidth(),0), (0,getheight()) and (getwidth(), getheight())
This will give you 4 geopoints from which you can extract latitude and longitude


text:
Q: fetch EKEvent from custom calendar return null Recently I met this problem.
1, create a custom calendar (iCloud source)
2, add new event and save successfully, shown on device calendar.
3, save eventIdentifier in NSUserDefaults
But,
When I use this method
EKEvent *event = [store eventWithIdentifier: identifier];

Always said: "Error getting event with identifier..."
This problem won't happen if I save event to default calendar.
Thanks for kindly help in advance.
Updated:
I make a demo with 4 buttons
1, create calendar,
2, search calendar using NSPredicate,
comparing the identifier, it is same.
3, create event,
4, search event using NSPredicate
also same.
What is wrong with calendarWithIdentifier & eventWithIdentifier?
if using these 2 methods, always return null.