text:
Q: How do I calculate conversion rate using Google Analytics? I have created a goal in Google Analytics that is met when the user completes the sign up process. The page that they end up at is
http://my_url.com/?just_signed_up=true

In order to calculate my conversation rate, I need to do this calculation:
goal (sign ups) / new visitors

I know that in order to use new visitor numbers, I can either set up a profile with a new visitor filter or just apply a new user advanced segment on my normal profile.
My problem is that the Google Analytics tracking code is on every page in my site, including my landing page. The sign up process goes like this:
Landing page -> Sign up form -> http://my_url.com/?just_signed_up=true

When the user ends up at the URL above, am I correct in thinking that Google Analytics will no longer consider them a new user, as they would have the cookie from when they landed on the landing page at the start of the sign up process? If so, then there will never be a new visitor that meets the goal. How would I calculate my conversion rate in this scenario?

A: A returning visitor is someone who starts an additional Google Analytics session while using your site. To start a new session they need to close their browser or stop using the site for a period of at least 30 minutes. Browsing around your site clicking links isn't considered stating a new session. This means that, in most cases, signups from new users will be from people (or at least browsers with a set of cookies) who have not visited your site before.


text:
Q: TextField onValueChanged not calling I have a readonly TextField that takes value from DatePicker (not composable).
The problem is that when value of TextField changes the onValueChange callback doesn't calls.
When i try to change value via user input (make readonly = false) i works fine.
So any solutions to call onValueChange without user input?
Some code:
val start = remember { mutableStateOf(state.timeStart) }

OutlinedTextField(
    value = DateTimeConverter.formatLogsTime(start.value),
    onValueChange = {
        start.value = DateTimeConverter.logDateToEpoch(it)!!
        onEvent(Logs.Event.TimeStartChanged(start.value))
    },
    colors = TextFieldDefaults.textFieldColors(
        backgroundColor = Color.White,
        unfocusedIndicatorColor = Color.Transparent,
        focusedIndicatorColor = Color.Transparent
    ),
    textStyle = textStyle,
    modifier = Modifier
        .fillMaxWidth()
        .padding(20.dp)
        .background(
                    LightLightGray,
                    RoundedCornerShape(8.dp)
         ),
         trailingIcon = {
             Icon(
                 Icons.Rounded.DateRange, "DateRange",
                 Modifier.clickable { createDateTimePicker(currentContext, start) })
         },
         readOnly = true
)

private fun createDateTimePicker(
    context: Context,
    dateHolder: MutableState<Long>
) {
    val calendar = Calendar.getInstance()
    val listener = OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
        calendar.set(Calendar.YEAR, year)
        calendar.set(Calendar.MONTH, monthOfYear)
        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
        val rawDate = "$dayOfMonth.$monthOfYear.$year 23:59:59"
        val newDate = DateTimeConverter.logDateToEpoch(rawDate)
        if (newDate != null)
            dateHolder.value = newDate
    }
    val picker = DatePickerDialog(context, listener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH))
    picker.show()
}

A: onValueChange can only be invoked by the TextField. If you change the text in TextField manually, you need to perform the same operations which you do inside the callback yourself.
Try this code:
// Inside Modifier.clickable
createDateTimePicker(currentContext) { date ->
    start.value = date
    onEvent(Logs.Event.TimeStartChanged(start.value))
}

// Now your function will be
private fun createDateTimePicker(
    context: Context,
    onDateChange: (Long) -> Unit
) {
    ...
    if (newDate != null)
        onDateChange(newDate)
    ...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to interpolate grouped time series in a Pandas dataframe I have data in type pd.DataFrame which looks like the following:
type  date  sum
A     Jan-1 1
A     Jan-3 2
B     Feb-1 1
B     Feb-2 3
B     Feb-5 6

The task is to build a continuous time series for each type (the missing date should be filled with 0).
The expected result is:
type  date  sum
A     Jan-1 1
A     Jan-2 0
A     Jan-3 2
B     Feb-1 1
B     Feb-2 3
B     Feb-3 0
B     Feb-4 0
B     Feb-5 6

Is it possible to do that with pandas or other Python tools?
The real dataset has millions of rows.

A: You first must change your date to a datetime and put that column in the index to take advantage of resampling and then you can convert the date back to its original format
# change to datetime
df['date'] =pd.to_datetime(df.date, format="%b-%d")
df = df.set_index('date')

# resample to fill in missing dates
df1 = df.groupby('type').resample('d')['sum'].asfreq().fillna(0)
df1 = df1.reset_index()

# change back to original date format
df1['date'] = df1.date.dt.strftime('%b-%d')

output
  type    date  sum
0    A  Jan-01  1.0
1    A  Jan-02  0.0
2    A  Jan-03  2.0
3    B  Feb-01  1.0
4    B  Feb-02  3.0
5    B  Feb-03  0.0
6    B  Feb-04  0.0
7    B  Feb-05  6.0


text:
Q: Alternative to Point Density I have the coordinates of a bunch of car crashes and I reasoned that the place where they are the densest is where crashes are the most likely to occur. The solution I found when looking into this problem is to use point density, which is simply the number of points within a given radius divided by the area of a circle with that radius. I have two problems with this method:
1) Changing the size of the radius can significantly change your answer. For example, if all points are between 1 and 2 miles of point P, then P will be the most dense if r > 2 and P will be the least dense if r < 1.
2) If you want to find the point with the second highest density, then the result will always be a point immediately next to the point of the highest density.
What is a better method to find density?
P.S. I apologize if this is a duplicate of someone else's question. Whenever I searched for something related to this problem, things about point density always came up.


text:
Q: different versions of Runge's theorem This question is to prove a different version for Runge's theorem.
If $\Omega$ is open set, and $E \subset \mathbb{C}$ be such that $E$ has nonempty intersection with each bounded connected component of $\mathbb{C} - E$ which is relatively compact in $\Omega$. Let $R_E$ be the space of rational functions all whose poles are in $E$. Then $R_E$ is dense in $H(\Omega)$.
I know by Runge's theorem, for each holomorphic function $f$ in $\Omega$ we can find a sequence of rational functions with no poles in $\Omega$ which converges uniformly on compact subsets of $\Omega$, but not sure how to find a sequence of rational functions whose poles are in $E$ and $E$ is subset of $\Omega$.


text:
Q: drawablePadding for RadioButton above API Level 16 I have a RadioButton and I am using a custom Image for button image. now I want to give space between image and the text. I have Used android:drawablePadding attribute to give space but it does not work above api level 16. There is one solution for api level above 16 is   android:paddingLeft. but this works for API level more than 16, for lower api levels it overlap the image and text. So please suggest a solution to provide space between RadioButton Image and text for all API levels.

A: android:drawablePadding works only for the compound drawables (drawableXYZ),
not for the android:button property.
Consider setting android:button="@null" and use
android:drawableLeft="@drawable/your_state_list" or   android:drawableRight="@drawable/your_state_list"
An xml StateList is required to give your custom RadioButton a checked/unchecked state.


text:
Q: Can email ID received from Google OpenID login be considered unique over time? I am using Google OpenID for login to my website. I am using it through Tornado's built-in auth library. I retrieve email ID, first name, last name and name from the openID data. My question is can I use email ID retrieved in this way to remain unique over time - including its case? For e.g. Is it possible that a user may have email ID John.Doe@gmail.com today, but in future it may be john.doe@gmail.com? I cannot find any other field in the returned OpenID data that I can assume unique for a given user.
Update Maybe I should also add that I was hosting my website on Google App Engine before and was using its built-in login. When I migrated to Tornado based implementation, I used email ID from the old logins as the unique identifier of the users. In most of the cases that seems to have work, but recently I ran into a case where the user's email ID returned from OpenID was different from his email ID from GAE version only in case. Therefore I am trying to understand how this can happen.

A: Since it's an email address, you shouldn't consider case, as for normal email case is unimportant. So, you should be able to consider that unique in a case insensitive test.


text:
Q: My list of terms of custom taxonomy displays 7 times I'm building a custom page template to show a list of terms from a custom taxonomy named "autore", and I don't know why it displays the full list more than one time (seven times, to be precise). Can anyone help?
<?php
/**
 * Template Name: Archive Custom Taxonomy
 */

get_header(); the_post(); ?>

<?php
$args=array(
    'public'   => true,
    '_builtin' => false
);
$output = 'names'; // or objects
$operator = 'and';
$taxonomies=get_taxonomies($args,$output,$operator);
if  ($taxonomies) {
    foreach ($taxonomies  as $taxonomy ) {
        $terms = get_terms([
            'taxonomy' => 'autore',
            'hide_empty' => false,
            'orderby' => 'name',
            'order' => 'ASC',
        ]);
        foreach ( $terms as $term) {
            echo '
'.$term->name.'
';
        }
    }
}
?>

<?php get_footer();


text:
Q: DynamicDataRoute with Vs2013 .Net 4.5 I have an old WebForms project in which I successfully add Dynamic feature a few years ago. I also add routing with DynamicDataRoute. All worked fine.
Now, with VS2013 4.5, I create a new web project with both WebForms, MVC and ApiWeb.
I use the same code for rooting dynamic data.
Two things doesn't works :
1/ Urls like "xxx/Pages/Page.aspx" are displayed in Url bar as "xxx/Pages/Page" but works fine.
2/ Routes like "WebSite/XXX/id" doesn't work (404).
What did I make wrong?  Thanks.
Here is my rooting code in global.asax:
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
...
    m_MaBaseModel = new MetaModel();
    m_MaBaseModel.RegisterContext(typeof(xxxx.MaBaseEntities), new ContextConfiguration() { ScaffoldAllTables = true });

    RouteTable.Routes.Add(new DynamicDataRoute("Favoris/{table}/{action}.aspx")
    {
        Constraints = new RouteValueDictionary(new
        {
            action = "List|Details|Edit|Insert|BL01|ListDetails"
        }),
        Model = m_MaBaseModel
    });
    RouteTable.Routes.Add(new DynamicDataRoute("Favoris/{table}/{IDActe}/{action}.aspx")
    {
        Constraints = new RouteValueDictionary(new
        {
            action = "List"
        }),
        Model = m_MaBaseModel
    });


text:
Q: Smarter CSV ignore blank lines in csv I am using Smarter CSV to and have encountered a csv that has blank lines. Is there anyway to ignore these? Smarter CSV is taking the blank line as a header and not processing the file correctly. Is there any way I can bastardize the comment_regexp?
mail.attachments.each do | attachment |
        filename = attachment.filename
        #filedata = attachment.decoded
        puts filename
        begin
          tmp = Tempfile.new(filename)
          tmp.write attachment.decoded
          tmp.close
          puts tmp.path
          f = File.open(tmp.path, "r:bom|utf-8")
          options = {
            :comment_regexp => /^#/
          }
          data = SmarterCSV.process(f, options)
          f.close
          puts data

Sample File:
[
output

A: Let's first construct your file.
str = <<~_
#
# Report
#---------------
Date              header1           header2  header3      header4
        20200 jdk;df           4543 $8333              4387

        20200 jdk              5004 $945876              67

_

fin_name = 'in'
File.write(fin_name, str)
  #=> 223

Two problems must be addressed to read this file using the method  SmarterCSV::process. The first is that comments--lines beginning with an octothorpe ('#')--and blank lines must be skipped. The second is that the field separator is not a fixed-length string.
The first of these problems can be dealt with by setting the value of process' :comment_regexp option key to a regular expression:
:comment_regexp => /\A#|\A\s*\z/

which reads, "match an octothorpe at the beginning of the string (\A being the beginning-of-string anchor) or (|) match a string containing zero or more whitespace characters (\s being a whitespace character and \z being the end-of-string anchor)".
Unfortunately, SmarterCSV is not capable of dealing with variable-length field separators. It does have an option :col_sep, but it's value must be a string, not a regular expression.
We must therefore pre-process the file before using SmarterCSV, though that is not difficult. While are are at, we may as well remove the dollar signs and use commas for field separators.1
fout_name = 'out.csv'

fout = File.new(fout_name, 'w')
File.foreach(fin_name) do |line|
  fout.puts(line.strip.gsub(/\s+\$?/, ',')) unless
    line.match?(/\A#|\A\s*\z/)
end
fout.close

Let's look at the file produced.
puts File.read(fout_name)

displays
Date,header1,header2,header3,header4
20200,jdk;df,4543,8333,4387
20200,jdk,5004,945876,67

Now that's what a CSV file should look like! We may now use SmarterCSV on this file with no options specified:
SmarterCSV.process(fout_name)
  #=> [{:date=>20200, :header1=>"jdk;df", :header2=>4543,
  #     :header3=>8333, :header4=>4387},
  #    {:date=>20200, :header1=>"jdk", :header2=>5004,
  #     :header3=>945876, :header4=>67}]

1. I used IO::foreach to read the file line-by-line and then write each manipulated line that is neither a comment nor a blank line to the output file. If the file is not huge we could instead gulp it into a string, modify the string and then write the resulting string to the output file: File.write(fout_name, File.read(fin_name).gsub(/^#.*?\n|^[ \t]*\n|^[ \t]+|[ \t]+$|\$/, '').gsub(/[ \t]+/, ',')). The first regular expression reads, "match lines beginning with an octothorpe or lines containing only spaces and tabs or spaces and tabs at the beginning of a line or spaces and tabs at the end of a line or a dollar sign". The second gsub merely converts multiple tabs and spaces to a comma.
File.new(fout_name, 'w')
File.foreach(fin_name) do |line|
  fout.puts(line.strip.gsub(/\s+\$?/, ',')) unless
    line.match?(/\A#|\A\s*\z/)
end
fout.close


text:
Q: How can I build criteria around a percentage? Conditions suedo code would be:
IF Total Adjustment Percentage IS  Greater Than 5%
I've tried the following to no avail.
Total_Adjustment_Percentage__c  >  -5  (the true value in database show as negative value)
Total_Adjustment_Percentage__c  >  5
Total_Adjustment_Percentage__c  >  .05 (doesn't allow the period)

thanks.

A: Try Total_Adjustment_Percentage__c  > -0.05


text:
Q: Website DOMContentLoaded fast but Favicon Always Load after 21 Seconds? Why? My website, https://homegift.vn, has a performance problem: DOMContentLoaded only 2s, but the favicon.ico always loads after 20s.
NOTE that:

*

*This was not happening before and I have not updated the code.

*Website Assets all optimized and can load fast.

*This happens for all
pages (DOM maybe faster or slower, but all loads always finished
after 21s with favicon).

I have tried to remove all slowing resources and third party content like Facebook.

A: Maybe this causion by some Script with DOM loaded event, i have try remove that and all look good now!
Many thank @All


text:
Q: Vuetify - Sync pagination with URL params Vuetify has a Data table component which supports external pagination + sorting (via API).
What's the best way to sync these with URL params (2-way binding)?

Example URL:
http://localhost:3000/users?page=22
When I go to this link, I want to see 22 as the current page in the pagination.
When I click the Next button in the pagination component, I want to see the URL updated to http://localhost:3000/users?page=23

A: You can do this:

*

*Assocciate @pagination event to some method and 'page' prop whith data item.

*In you method, set the url with window.history.pushState

*In created() lifecycle hook, get query param from url and set it into data.

An example:
<template>
<div>
  <v-data-table
    :headers="headers"
    :items="desserts"
    :items-per-page="5"
    class="elevation-1"
    @pagination="setQueryPage"
    :page="paramPage"
  ></v-data-table>
</div>
</template>
<script>
  export default {
    data () {
        return {
            headers: [
            {
                text: 'Dessert (100g serving)',
                align: 'start',
                sortable: false,
                value: 'name',
            },
            { text: 'Calories', value: 'calories' },
            { text: 'Fat (g)', value: 'fat' },
            { text: 'Carbs (g)', value: 'carbs' },
            { text: 'Protein (g)', value: 'protein' },
            { text: 'Iron (%)', value: 'iron' },
            ],
            desserts: [
            {
                name: 'Frozen Yogurt',
                calories: 159,
                fat: 6.0,
                carbs: 24,
                protein: 4.0,
                iron: '1%',
            },
            {
                name: 'Ice cream sandwich',
                calories: 237,
                fat: 9.0,
                carbs: 37,
                protein: 4.3,
                iron: '1%',
            },
            {
                name: 'Eclair',
                calories: 262,
                fat: 16.0,
                carbs: 23,
                protein: 6.0,
                iron: '7%',
            },
            {
                name: 'Cupcake',
                calories: 305,
                fat: 3.7,
                carbs: 67,
                protein: 4.3,
                iron: '8%',
            },
            {
                name: 'Gingerbread',
                calories: 356,
                fat: 16.0,
                carbs: 49,
                protein: 3.9,
                iron: '16%',
            },
            {
                name: 'Jelly bean',
                calories: 375,
                fat: 0.0,
                carbs: 94,
                protein: 0.0,
                iron: '0%',
            },
            {
                name: 'Lollipop',
                calories: 392,
                fat: 0.2,
                carbs: 98,
                protein: 0,
                iron: '2%',
            },
            {
                name: 'Honeycomb',
                calories: 408,
                fat: 3.2,
                carbs: 87,
                protein: 6.5,
                iron: '45%',
            },
            {
                name: 'Donut',
                calories: 452,
                fat: 25.0,
                carbs: 51,
                protein: 4.9,
                iron: '22%',
            },
            {
                name: 'KitKat',
                calories: 518,
                fat: 26.0,
                carbs: 65,
                protein: 7,
                iron: '6%',
            },
            ],
            paramPage : 1,
        }

    },
    methods: {
       setQueryPage(paginationObject){
           let url = 'users?page='+ paginationObject.page
           window.history.pushState("", "", url);
        }
    },
    created(){
        console.log(this.$route.query.page)
        this.paramPage = parseInt(this.$route.query.page)
    }

  }
</script>

A: I define a computed page variable operating directly on query param:
computed: {
  page: {
    get () {
      return parseInt(this.$route.query.page) || 1
    },
    set (page) {
      if (this.page !== page) {
        this.$router.replace({ query: { ...this.$route.query, page } })
      }
    }
  }
}

And using it as page prop with sync modifier as follows:
<v-data-table :headers="headers" :items="filteredUsers" :page.sync="page" />

This will work if table data is fetched before the table is displayed. If your data is loaded asynchronously, you'd need to reset the page (due to a bug?).

A: Here is a librairie we made at my work: https://github.com/socotecio/vue-datatable-url-sync
It has an option and example to work directly with vuetify.
Working with vue 2 and 3. And has some useful parameters.


text:
Q: IEEE floating points implementation, precision and accumulation of approximations If I understand IEEE floating points correctly, they are unable to accurately represent some values. They are accurate in very limited cases and pretty much every floating point operation increases the accumulated approximations. Also, another downside - the "minimum step" grows with the exponent.
Wouldn't it be better to offer some more concrete representation?
For example, use 20 bits for the "decimal" part, but not all all 2^20 values, instead only 1000000, giving a full 1/millionth smallest possible representation/resolution, and use the other 44 bits for the integer part, giving quite the range. This way "floating point" numbers can be calculated using integer arithmetic, which may even end up faster. And in the case of multiplication, addition and subtraction there is no accumulation of approximations, the only possible loss is during division.
This concept rests on the fact that 2^n values are not optimal for representing decimal numbers, e.g. 1 does not divide that well into 1024 parts, but it divides pretty well into 1000. Technically, this is omitting to make use of the full precision, but I can think of plenty of cases where LESS can be MORE.
Naturally, this approach will lose both range and precision in a way, but in all the cases where extremities are not required, such a representation sounds like a good idea.

A: What you describe as a proposition is a fixed point arithmetic. Now, it's not necesserily about better or worse; each representation has advantages and disadvantages that often make one more suitable than the other for some specific purpose. For example:

*

*Fixed point arithmetic does not introduce rouding errors for operations like addition and subtraction, what makes it suitable for financial calculations. You certainly don't want to store money as a floating point values.

*Speculation: arguably, fixed point arithmetic is simpler in terms of implementation, which probably leads to smaller, more efficient circuits.

*Floating-point representation covers extremely large range: it can be used to store really big numbers (~1040 for 32-bit float, 10308 for 64-bit one) and really small positive ones (~10-320) at the expense of precision, while the fixed-point representation is linearly limited by its size.

*Floating-point precision is not distributed uniformly accross the representable range. Instead, most of the values (in terms of number of representable numbers) lies in the unit ball around 0. That makes it very accurate in the range we operate in most often.
You said it yourself:

Technically, this is omitting to make use of the full precision, but I
  can think of plenty of cases where LESS can be MORE

Exactly, that's the whole point. Now, depending on the problem at hand, a choice must be made. There is no one-size-fits-all representation, it's always a tradeoff.


text:
Q: 4k @60hz stoped working on Ubuntu 20.04 overnight I bought a new monitor and connected it to my  work laptop. It worked at 4k@60hz with no issue. I turned the laptop off and connected the monitor to my personal computer.
The other day, when I turned my work laptop on, it did not display the 60hz anymore.
What could possible have made it happen? How to fix it?


text:
Q: Pointer addresses of Python Lists and Matrix when reversing I am trying to understand how Python matrices are implemented as compared to Java/C style 2D arrays.
Specifically the problem I am facing is this:
Given a matrix (list of lists), I am asked to reverse the individual lists in the matrix in-place. I came up with the following code:
CODE 1
------

def flip(matrix):
    for list in matrix:
        list=list[::-1]

matrix=[[1,0,0],[0,0,1]]
flip(matrix)
print(matrix) # Outputs "[[1,0,0],[0,0,1]]" i.e. does not reverse

If I modify the code a bit,
CODE 2
------

def flip(matrix):
    for list in matrix:
        list.reverse()

matrix=[[1,0,0],[0,0,1]]
flip(matrix)
print(matrix) # Outputs "[[0,0,1],[1,0,0]]" i.e. works correctly this time

I know that list.reverse() does in-place operation and list[::-1] creates a shallow copy. However in CODE 1, I am assigning the address of the shallow copy to the same variable (list) only. So the variable matrix should effectively get changed. Because the variable matrix[i] is the variable list. So if list gets modified, so should matrix.
To illustrate my previous point, the following code is provided:
CODE 3
------

def test(matrix):
    for i, list in enumerate(matrix):
        print(matrix[i] is list)

matrix=[[1,0,0],[0,0,1]]
test(matrix) # Outputs "True True"

If matrix[i] is list, then changing list means changing matrix[i] and changing matrix[i] means changing matrix.
If I modify CODE 1 so that instead of list being assigned the address of the newly created reversed list, matrix[i] be assigned that address, then surprisingly it works!
CODE 4
------

def flip(matrix):
    for i, list in enumerate(matrix):
        # Instead of  list=list[::-1]
        matrix[i]=list[::-1]

matrix=[[1,0,0],[0,0,1]]
flip(matrix)
print(matrix) # Correctly Outputs [[0,0,1], [1,0,0]]

I would like an explanation why CODE 1 does not work and why CODE 4 works.

A: The first time through the loop, list is just a name for matrix[0].
Mutating the object that list names, as in CODE 2, obviously mutates the object that matrix[0] names, because they're naming the same object.
But just rebinding list to some different object, as in CODE 1, doesn't change matrix[0] in any way. If you think about it, that makes sense. After all, the next time through the loop, list is going to get rebound to matrix[1], and you certainly wouldn't want that to change what's in matrix[0], right?
In C terms (and this is literally true, if you're using the normal CPython implementation), being names for the same object means being pointers to the same object. If list is a List *, assigning to list doesn't do anything to whatever was in *list.
So, why does CODE 4 work? Well, in code 4, you're still not mutating the list—but you're rebinding matrix[0], instead of list, and of course that rebinds matrix[0].
I'm guessing that, despite talking about "Java/C", you're really thinking in C++ terms. In C++, = is an operator, which can be overloaded. Plus, you don't just have pointers, but references, which sort of magically work without needing to explicitly dereference them. So, if list is a reference to a list object, rather than a pointer, list = isn't changing it into a reference to another list object, it's calling a special method, ListType::operator=. That's actually pretty weird. There's nothing like that in Java. or C. any more than there is in Python.

For more detail on what happens under the covers:
If you want to think of it in C terms, the actual C API used by the main (CPython) implementation may make things clear here.

*

*Your function's locals are just an array of pointers to Python objects. That matrix is locals[0], list is locals[1], etc.

*What's in *locals[0] is a PyListObject struct, which contains, among other things, a pointer to an array of Python objects. Each of which is pointing to another PyListObject struct. But inside those inner lists' arrays are pointers to PyLongObject structs, which just hold numbers.

*The for loop is a bit more complicated than this, but pretend it's just doing locals[1] = (*locals[0]).elements[0], then locals[1] = (*locals[0]).elements[1], etc.

*So, assigning to list is just changing locals[1], not *locals[1], and therefore it's not changing *locals[0].elements[0].

*But assigning to *locals[0].elements[0] is a different story.

*And so is calling the reverse method. When you do that, self just ends up as yet another pointer to the same object, but its implementation mutates things on *self.


text:
Q: How to pass parameters with php in my case I am getting an "Uncaught SyntaxError: Unexpected token ILLEGAL" error when try to load a page with a php variable.
$(document).ready(function() {
       $.get("index.html", {token:<?php echo $token; ?>}, function(data) {
                 //codes..
               });
 });

I can't seem to echo $token in my javascript and I am sure $token is valid.
Can someone help me solve this issue? Thanks a lot!

A: You're echoing text from PHP into a Javascript context, which means you have to generate valid Javascript code. Simplest solution: json_encode()
{token : <?php echo json_encode($token) ?>}

json_encode() will take care of any quoting/escaping which needs to be done.
e.g. if $token = 'foo', then you'd be producing
{token: foo}

and be producing an undefined variable error.

A: you need to put quotes around the php output otherwise it will be treated as a javascript variable rather than a string
{token:'<?php echo $token; ?>'}


text:
Q: Nuxt: How to log errors on production I got an error on my nuxt production environment.
Server error
An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.

Where can I find detailed error logs?
I start the server with this command:
npm run start -- --port 3333

In my console I get only this output:
ERROR  Request failed with status code 403                                                        16:40:07

  at createError (node_modules/axios/lib/core/createError.js:16:15)
  at settle (node_modules/axios/lib/core/settle.js:17:12)
  at IncomingMessage.handleStreamEnd (node_modules/axios/lib/adapters/http.js:236:11)
  at IncomingMessage.emit (events.js:323:22)
  at IncomingMessage.EventEmitter.emit (domain.js:505:15)
  at endReadableNT (_stream_readable.js:1204:12)
  at processTicksAndRejections (internal/process/task_queues.js:84:21)

But this does not help. I would like to see what has been sended to the server and what came back as a response. (I guess there is somewhere an authentication problem)
EDIT:
It seems that this it the only output from nuxt. There is no additional log. But you can add to your project a tool like sentry to get more informations. Unfortunately the error log in sentry is also not enough in my case. Is there another way to get more insides?


text:
Q: Vectorize a Newton method in Python/Numpy I am trying to figure out if Python/Numpy is a viable alternative to develop my numerical software which is already available in C++. In order to get performance in Python/Numpy, one need to "vectorize" the code. But it turns out that as soon as I move away from very simple examples, I struggle to vectorize the code (I am not talking about SIMD instructions but "efficient Numpy code" without loops). Here is an algorithm that I want to get efficiently in Python/Numpy.

*

*Create an numpy array containing: 1.0, 1.0 + 1/n, 1.0 + 2/n, ..., 2.0

*For every u in the array, compute the root of x^2 - u, using a Newton method, stopping when |dx| <= 1.0e-7. Store the result in an array result.

*Sum all the elements of the result array

Here is the algorithm in Python I want to speed up
import numpy as np

n = 1000000
data = np.arange(1.0, 2.0, 1.0 / n)

def newton(u):
  x = 2.0
  while True:
    f = x**2 - u
    df_dx = 2 * x
    dx = f / df_dx
    if (abs(dx) <= 1.0e-7):
      break
    x -= dx
  return x

  result = map(newton, data)

  print result[n - 1]

Here is a version of the algorithm in C++11
#include <iostream>
#include <vector>
#include <cmath>

int main (int argc, char const *argv[]) {
  auto n = std::size_t{100000000};

  auto v = std::vector<double>(n + 1);
  for(size_t k = 0; k < v.size(); ++k) {
    v[k] = 1.0 + static_cast<double>(k) / n;
  }

  auto result = std::vector<double>(n + 1);
  for(size_t k = 0; k < v.size(); ++k) {
    auto x = double{2.0};
    while(true) {
      auto f = double{x * x - v[k]};
      auto df_dx = double{2 * x};
      auto dx = double{f / df_dx};
      if (std::abs(dx) <= 1.0e-7) {
        break;
      }
      x -= dx;
    }
    result[k] = x;
  }

  auto somme = double{0.0};
  for(size_t k = 0; k < result.size(); ++k) {
    somme += result[k];
  }

  std::cout << somme << std::endl;
  return 0;
}

It takes 2.9 seconds to run on my machine. Is there a way to make a fast Python/Numpy algorithm that does the same thing (I am willing to get something that is less than 5 times slower).
Thanks.

A: You can do step 1. with numpy efficiently:
1.0 + np.arange(n + 1) / n

however I think you would need the np.vectorize() method to feed back x into your calculated values and it's not an efficient function (basically a wrapper for a python loop). If you can use scipy then there are built in methods that might do what you want http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.optimize.newton.html
EDIT: Having thought a bit more about this I followed up on @ev-br's point and tried some alternatives. The masking uses too much processing but the abs().max() is pretty fast so a compromise might be to "divide the problem into blocks" both in the 1st dimension of the array and in iteration direction. The following doesn't do too badly (< 20s) on my pretty low power laptop - certainly much faster than np.vectorize() or any of the scipy solving systems I could find. (If I set m too big it runs out of something (memory?) and grinds to a complete halt!)
n = 100000000
m = 5000000

block = 3
u = 1.0 + np.arange(n + 1) / n
x = np.full(u.shape, 2.0)
dx = np.ones(u.shape)

for i in range(0, n, m):
  while np.abs(dx[i:i+m]).max() > 1.0e-7:
    for j in range(block):
      dx[i:i+m] = (x[i:i+m] ** 2 - u[i:i+m]) / (2 * x[i:i+m])
      x[i:i+m] -= dx[i:i+m]

A: Here's a toy example. Notice that often vectorization means writing your code as if you're manipulating numbers, and letting numpy do its magic:
>>> import numpy as np
>>> a = np.array([1., 2., 3.])
>>> def f(x):
...    return x**2 - a, 2.*x    # function and derivative
>>>
>>> def newt(f, x0):
...    x = np.asarray(x0)
...    for _ in range(5):    # hardcode the number of iterations (I know)
...        v, dv = f(x)
...        x -=  v / dv
...    return x
>>>
>>> newt(f, [1., 1., 1.])
array([ 1.        ,  1.41421356,  1.73205081])

If this is a performance bottleneck, this is unlikely to be competetive with hand-written C++ code: First of all, you're manipulating python objects with all the overhead; then numpy is likely doing a bunch of array allocations under the hood.
An often viable strategy is to start by writing things in python/numpy, and then move bottlenecks into a compiled code --- eg Cython or C++ wrapped by Cython. In this particular case since you already have the C++ code, just wrapping it with Cython is likely easiest but YMMV.

A: I'm not looking to wave small snippets of code as a solution, but here's something to get you started. I have a strong suspicion that you're having troubles just declaring such an array in python without spending too much time on it, so I'll mostly help you out there.
As far as the square roots come in, please add your example python code and I'll see what I can help optimize from that point on. In my example roots and sums are found with the default numpy functions/methods.
def summing():
    n = 1000000
    ar = np.arange(0, n)
    ar = ar/float(n)
    ar = ar + np.ones(n)
    sqrt = np.sqrt(ar)
    return np.sum(ar)

In short, to get the starting array it's best to use a "workaround".

*

*initialize an array ar with values `[1,2,3,....n]

*divide ar with n. This gets us the  1/n, 2/n ... members

*add to that an array of same dimensions that contain just the number 1.0
This gets us the full array [ 1., 1.000001, 1.000002, ..., 1.999998, 1.999999]) we're after. If I understood you right.

*find square roots, sum it

Average of 10 sequential execution times is 0.018786 seconds.

A: Obviously I'm 6 years late to this party, but this question is a common stumbling block for people in effectively using numpy for real scientific work.  The basic idea is covered in @ev-br's answer.  The OP points out that the solution offered there (even modified to stop iterating when a convergence criterion is met rather than after a fixed number of iterations) takes the same number of passes for each element of u.  I want to show how you can avoid that objection using pure numpy code, making explicit the mask suggestion in @ev-br's comment.
However, I also want to point out that in many real world situations, the number of passes for Newton-like iteration to converge varies so little that this general technique I illustrate here will actually slow numpy code down significantly.  If the average number of iterations will be within a factor of two or three of the maximum number of iterations, you should stick with something closer to @ev-br's answer (including his first comment).
The numpy performance numbers you need to understand are these: Loops over array indices will run 200 to 500 times slower in pure numpy code than in compiled code.  On the other hand, if you manage to use numpy's array syntax to avoid all index loops, you can get within about a factor of 5 of compiled speed.  (The factor of 5 is partly because of memory management as @ev-br mentions, but also because optimized compiled code overlaps many different arithmetical operations inside each index loop, while numpy just performs a single arithmetic operation, storing everything back to memory after each operation.)  The point is that factor of 100 difference means that it often pays to do substantial amounts of "extra" work in numpy code: Even if you do 10 times the number of floating point operations in vectorized numpy code, it will still run 10 times faster than the index-loop code that avoids the "extra" work.  (Incidentally, the python map function is implemented as an interpreted index loop - it has nothing to do with numpy array operations.)
from numpy import asfarray, broadcast_arrays, arange

# Begin by defining the function to be inverted by Newton's method.
def f_dfdx(x):
    x = asfarray(x)  # always avoid repeated type conversions
    return x**2, 2.*x

# First, the simplest algorithm to find x such that f(x)=y.
# We must supply a starting guess x0 for x.
def f_inverse0(f_dfdx, y, x0, tol=1.e-7):
    y, x = broadcast_arrays(asfarray(y), asfarray(x0))
    x = x.copy()  # without this may clobber input x0
    for npass in range(20):
        f, dfdx = f_dfdx(x)
        dx = (f - y) / dfdx
        if (abs(dx) <= tol).all():
            break  # iterate all x until all have converged
        x -= dx
    else:
        raise RuntimeError("failed to converge")
    return x

# A frequently slower algorithm that avoids extra iterations.
def f_inverse1(f_dfdx, y, x0, tol=1.e-7):
    y, x = broadcast_arrays(asfarray(y), asfarray(x0))
    shape = x.shape
    y, x = y.ravel(), x.flatten()  # avoid clobbering x0
    unconverged = arange(y.size)
    for npass in range(20):
        f, dfdx = f_dfdx(x[unconverged])
        dx = (f - y[unconverged]) / dfdx
        unc = abs(dx) > tol
        unconverged = unconverged[unc]
        if not unconverged.size:
            break  # iterate all x until all have converged
        x[unconverged] -= dx[unc]
    else:
        raise RuntimeError("failed to converge")
    return x.reshape(shape)

On my machine, the OP's C++ program runs in 2.03 s (1.64+0.38 user+sys).  For n=100 million as for the C++ program, f_inverse0 runs in 20.4 s (4.7+15.6 user+sys).  As expected, f_inverse1 is slower, 51.3 s (11.5+39.8 user+sys).  Again, don't automatically try to minimize total operation count when you are writing numpy code.  The high system overhead is probably due to heavy memory management - every vector temporary is 0.8 GB and the memory manager is struggling.
Cutting the array size to n = 1 million elements (8 MB), then multiplying the runtime by 100 brings the system time down by a large factor, f_inverse0 now takes 16.1 s (12.5+3.6), while f_inverse1 takes 22.3 s (16.2+5.1).  This factor of 8 to 10 slower than compiled code is not unreasonable to expect for numpy performance.


text:
Q: req.body returns undefinded after setting bodyParser urlencoded to extended as false I am a newbee to nodejs . I have tried to create simple chat App. The req.body in my app.post seems to return undefinded  even after setting my body-parser urlencoded ({extented:false}).can anybody walk me through this?!..thanks in advance
here is my code server.js for server side:
var express = require('express')
 var bodyParser = require('body-parser')
 var app = express()

app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
app.use(express.static(__dirname))

var messages = [
{name:'Brue',message:'Hello Diana'},
{name:'Diana', message:'Hey Bruce.'} ]

app.get('/messages', (req,res) => {
res.send(messages) })

app.post('/messages', (req,res) => {
messages.push(req.body)
res.sendStatus(200)})

var server = app.listen(8080, (err,data) => {
console.log('The server runs on the port:', server.address().port) })

here is my client side code:
<!DOCTYPE html>   <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Message App</title>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

 Send Message

    <input class="form-control" type="text" placeholder="Name">

    <textarea placeholder = "Message" class="form-control" id="mesage" cols="30" rows="10"></textarea>

    <button id = "send" class="btn btn-success"> Send</button>


text:
Q: Pass JS foreach to JS post without form totalforms[i] is reading all inputs from page (dynamically generated) (eg: <input name="test" type="text">)
I want to send all inputs (get from foreach in JS array) to https://example.com/client_area?add_to_cart<?php echo $product_id; ?>.
Function to post data (JS):
function post(path, params, method='post') {

              const form = document.createElement('form');
              form.method = method;
              form.action = path;

              for (const key in params) {
                if (params.hasOwnProperty(key)) {
                  const hiddenField = document.createElement('input');
                  hiddenField.type = 'hidden';
                  hiddenField.name = key;
                  hiddenField.value = params[key];

                  form.appendChild(hiddenField);
                }
              }

              document.body.appendChild(form);
              form.submit();
            }

Function to run getting of all inputs in page:
function runToCart() {
      var forms = document.getElementsByTagName("input");
      document.getElementById("addToCart").innerHTML = `Add To Cart   <i class="fas fa-spinner fa-spin"></i>`;
      var totalforms = new Array();
      var totalforms_values = new Array();
      var i;
      for (i = 0; i < forms.length; i++) {
        totalforms.push(forms[i].name);
        totalforms_values.push(forms[i].value);
      }
      post('/client_area?add_to_cart=<?php echo $product; ?>', {names: totalforms, values: totalforms_values});
    }

so?
I tried to search, but nothing like that specific found.
P.S: i want to make an array for array like totalforms[number_if_input_name]['value_of_name_of_input']
SOLVED BY ADDING form= attribute in my inputs, no need js anymore here.

A: Just fill an object with data
let totalforms = {};
for (i = 0; i < forms.length; i++) {
  totalforms[i] = totalforms[i] || {};
  totalforms[i][forms[i].name] = forms[i].value;
}


text:
Q: How to access elements in a nested list I have a list of elements.  Each element is a list.  Eg
a=[[1,2,3,[1,2,3,4]], [4,5,6,[2,5]], [7,8,9,[3,3,4]]...]]

How do I go about getting say the second element from each element in the outer list i.e. [2,5,...]?
a[:,2] would be nice (what other possible interpretation could it have) but it would seem that the only way for me to do this is with a for loop of some description.  If it is the latter it would seem to me that I would be better rewriting my code with a named array for each element.  I would then ask - when would a list actually be useful?
I could equally ask the same question if I used rounded brackets and replaced the term list with tuple which then leads me to ask why bother with the difference?  what does a tuple give me that I cant achieve with a list?

A: If you want to avoid loops you can use itemgetter and map to extract the list:
import operator

a = [[1,2,3,[1,2,3,4]], [4,5,6,[2,5]], [7,8,9,[3,3,4]]]
print map(operator.itemgetter(1), a) # [2, 5, 8]

Depending what data your list holds you might be better off creating a class and using objects instead. Using lists gives you an ability to use list operations and allows sublists to be used as sequences and iterables which might be beneficial depending on what you want to do with the data. Same kind of functionality can be achieved with custom class and magic methods but it would require more work.
Using tuples would allow you to use them in sets and dict keys because they are immutable. There are other questions with detailed answers regarding the differences.

A: Have your tried this?
>>> a=[[1, 2, 3, [1, 2, 3, 4]], [4, 5, 6, [2, 5]], [7, 8, 9, [3, 3, 4]]]
>>> [ i[1] for i in a]
[2, 5, 8]


text:
Q: IBM Mobilefirst migration to v8.0 - user migration We have a mobile apps running on v7.1. And now we want to migrate to v8.0. I have read the migration cookbook, however it does not seem to explain the following:
How to migrate the existing user? The user has already subscribe to push-notification. I believe the information are stored in mobile first database, and I read from this  it does not have a script to migrate the database.
How do we keep the existing user information? So, the migration process will require 2 versions running in parallel and slowly move the user to the new version? It seems that we cannot "upgrade" the old server to the new version, is that correct?

A: You cannot migrate the user information from MFP 7.x to 8.0 as the security architecture is completely different between these versions.


text:
Q: Preview of the ringtone This is my first question, & i am new to iOS Development. I wanted to ask how can i play preview of the ringtone when tapped on a cell in table view on iphone.
Basically i am trying to write an app which allows downloading of ringtone from my server on iphone, in that i want to add a preview feature, through which person will be able to listen the tone if he likes he will download. then he will be able to set it as ringtone.
I have managed to get the links of tones, on my server in a table view. now i want to play preview. how can i do that??
Request: please describe as i am newbie. not an advance programmer.
please ignore my mistakes.
Regards,
Malhaar
edit: i am using this code..
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                               pathForResource:[[ringArray objectAtIndex:indexPath.row]getName]
                                               ofType:@"m4r"]];
    AVAudioPlayer *click = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
    [click play];
    [click release];

}

A: There are not too many details given, but at a high level, you would want to do the following:
1) Implement the "tableView:didSelectRowAtIndexPath:" delegate method of UITableView in order to respond to touches on the table cells.
2) Obtain the data for the ringtone. You could do this using NSURLConnection.
3) Play the ringtone using AVFoundation, specifically AVAudioPlayer.


text:
Q: Apache 2.4 .htaccess - Point All Requests to index.html With One Exception I currently have the following .htaccess:
<IfModule mod_rewrite.c>
    Options Indexes FollowSymLinks
    RewriteEngine On
    RewriteBase /production/
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>

The web server's document root is currently the /production folder referenced in the above (the .htaccess file is in the parent folder since /production is deleted and rebuilt with every code commit).  The above will direct all traffic to my site to index.html.
I would like to make an exception to this.  If the request is www.mydomain.com/specialrequest, I would like a PHP script called script.php in the parent folder to run.
To review, this is my /var/www/html directory:
-html
    -production
    -anotherfolder
    -.htaccess
    -script.php

Apache is pointing to /var/www/html/production and I would like all requests to go to the index.html file in that directory unless the request is /specialrequest - in which case, I would like script.php to run.

A:
Apache is pointing to /var/www/html/production

So, /var/www/html/production really is defined as the DocumentRoot. And so your .htaccess file is located above the document root. And the file you want to rewrite to (upon receiving this special request) is also above the document root.
Unfortunately, you can't rewrite to a file that is above the document root using .htaccess (regardless of where that .htaccess file is located). This is because the RewriteRule substitution in per-directory .htaccess files takes a URL-path, so trying to rewrite to a URL above the document root is simply invalid. If, however, you had access to the server config (or virtual host) then you could rewrite to a filesystem path (including above the document root) - instead of a URL-path - using this method.
So, script.php would need to be within the document root in order to be able to do this using .htaccess. In which case, you could do something like:
RewriteEngine On

# Exception
RewriteRule ^specialrequest$ /script.php [L]

# Front controller
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

But in this case, script.php is would need to be located at /html/production/script.php (in the document root), not at /html/script.php (above the document root) - as in your current filesystem structure.
Incidentally, the RewriteBase /production/ directive in your .htaccess file is entirely superfluous. You're not using a relative path substitution anyway, but since /production is the document root then /index.html (a document root relative URL-path) will rewrite to /production/index.html anyway.

If, however, you could write this directly in your server config (or virtual host), then you could do what you require. For example:
RewriteEngine On

# Rewrite to filesystem path (in the server config)
RewriteRule ^/specialrequest$ /var/www/html/script.php [L]

# Front controller
RewriteRule ^/index\.html$ - [L]
RewriteCond %{LA-U:REQUEST_FILENAME} !-f
RewriteCond %{LA-U:REQUEST_FILENAME} !-d
RewriteRule ^/. /index.html [L]


text:
Q: Why strict refs error in this Perl function? Minimum code
#!/usr/local/bin/perl
use strict;
use warnings;
use Math::Geometry::Planar qw(SegmentLineIntersection);

sub x_intercepts {
    my $xa = @{ $_[0] };
    my @xcross = ();
    my @x_axis = ( [0, 2000], [1, 2000] );

    foreach my $i (0 .. 1) {
        my $xc = SegmentLineIntersection([ @$xa[$i, $i + 1], @x_axis ]);
        push @xcross, $xc;
    }
    return \@xcross;
}

my @xs = qw/22.595451 20.089094 17.380813 15.091260 12.477935 10.054821 7.270003 4.804673 4.728526 4.619254 4.526920 4.418416 4.321419 4.219890 4.123336 4.009777 3.912648 3.804183 3.705847 3.597756 3.512301 3.393413 3.301963 3.196725 3.098560 3.007482 2.899825 2.801002 2.688680 2.598862 2.496139 2.393526 2.282183 2.190449 2.084530 1.987778 1.877562 1.788788 1.678473 1.578123 1.467071 1.373372 1.283629 1.176670 1.071805 0.975422 0.877622 0.767820 0.667409 0.562480 0.469068 0.354589 0.264291 0.152522 0.063765 -0.045323 -0.136783 -0.248559 -0.343694 -0.459178 -0.551917 -0.640803 -0.755502 -0.845535 -0.955227 -1.045879 -1.155600 -1.254556 -1.365163 -1.461669 -1.571370 -1.658043 -1.772672 -1.865942 -1.981037 -2.073702 -2.176205 -2.276184 -2.367371 -2.476278 -2.567385 -2.686326 -2.777433 -2.884357 -2.980067 -3.087754 -3.183607 -3.291003 -3.386942 -3.495822 -3.586759 -3.702955 -3.793550 -3.900680 -3.999672 -4.093094 -4.200047 -4.301026 -4.399742 -4.493190 -4.602013 -4.705124 -4.812383 -4.907510 -5.022904 -5.109829 -5.214304 -5.317662 -7.703172 -10.350131 -12.921361 -15.431203 -18.188013 -20.544248 -22.822808 -25.679854 -22.999092 -20.540434 -17.964916 -15.398857 -12.990375 -10.402209 -7.888263 -5.504909 -5.217892 -5.109841 -5.014187 -4.908558 -4.811807 -4.704282 -4.605555 -4.504613 -4.406546 -4.292540 -4.204043 -4.088770 -3.995524 -3.905669 -3.796544 -3.707958 -3.596449 -3.490966 -3.382869 -3.293054 -3.185821 -3.088417 -2.971214 -2.880314 -2.772518 -2.677986 -2.569794 -2.473668 -2.365096 -2.276422 -2.179232 -2.068195 -1.973110 -1.859565 -1.771873 -1.669422 -1.569953 -1.462626 -1.364911 -1.258100 -1.159318 -1.050486 -0.959979 -0.849149 -0.749421 -0.640950 -0.547122 -0.451754 -0.344463 -0.252269 -0.134625 -0.051640 0.052970 0.154112 0.266505 0.353926 0.468739 0.561666 0.673810 0.759169 0.881697 0.973207 1.082409 1.170424 1.282163 1.378096 1.472728 1.586454 1.678473 1.785688 1.873862 1.984090 2.086021 2.196799 2.292400 2.386097 2.493190 2.601726 2.694346 2.803450 2.901878 3.011959 3.103050 3.196979 3.294507 3.397563 3.504076 3.600163 3.712539 3.809573 3.919799 4.012314 4.120694 4.216406 4.322895 4.416466 4.522871 4.623917 4.735925 4.826929 7.361253 9.647208 12.337984 14.870260 17.439730 19.921717 22.524080 25.125903/;

foreach my $i ( x_intercepts(@xs) ) {
    print "$i \n";
}

which gives

Can't use string ("22.595451") as an ARRAY ref while "strict refs" in
  use at test5.pl line 8.

Something basic here wrong in declaring the variables.
Declaring my main::$xa = main::$xa; in initialization is not the way to go.
Why is this error coming?

A: You're reading the first argument you pass to the function (22.595451), which is a string, and are trying to treat it as an array (which it isn't).
Presumably you intended to pass an array reference as a single argument instead of passing each member of the array as a separate argument.
x_intercepts(\@xs)

Having converted the arrayref to a regular array, you then seem to try to treat it as a scalar:
my $xa = @{ $_[0] };

That doesn't make sense.
Based on what you do later, it looks like you want $ax to be an arrayref, so don't dereference it:
my $xa = $_[0];

A: Your example boils down to:
#!/usr/bin/env perl

use strict;
use warnings;

run();

sub run {
    print_x('x');
}

sub print_x {
    my @x = @{ $_[0] };
    print "@x\n";
}

You pass to print_x a list of strings (in this case, a list with just one element), but in print_x, you are treating the first argument as a reference to an array.
Note that if that were the case, you would be creating a second (shallow) copy of the array by copying all of its elements to the lexically scoped @x. In most cases, this is not necessary or desired.
Reduce the problems you encounter to the shortest complete and runnable script that still exhibits the problem. That will help you learn.


text:
Q: #1064 - You have an error in your SQL syntax for coding a new database
1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near ')' at line 5

The code is:
CREATE TABLE click_count (
     id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
     page_url VARCHAR(255) NOT NULL,
     page_count INT UNSIGNED NOT NULL,
);

A: Remove the trailing comma before the closing parenthesis:
CREATE TABLE click_count (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    page_url VARCHAR(255) NOT NULL,
    page_count INT UNSIGNED NOT NULL
);


text:
Q: Not all references released, 1 still live I'm learning about retain and release methods for counting references in Objective-C, but Instruments says that is still living 1 reference of MyClass, the code:
#import <Foundation/Foundation.h>
#import "MyClass"

int main(int argc, const char * argv[])
{

@autoreleasepool {

    MyClass *obj;

    for (int i=0; i < 200000; i++){

        obj = [[MyClass alloc] init];
        [obj setSomeValue:100];

        NSLog(@"itineration %i", i);

        [obj release];
    }
}//@autoreleapool
}//main

MyClass.h
@interface MyClass : NSObject

@property int someValue;

@end

Why Instruments shows "16LiveBytes" "1#Living" "199999#Transient" "200000#Overall" in MyClass? Should be 0 right?


text:
Q: Does the integral from $1$ to infinity of $\frac{\ln(x)}{x}$ converge or diverge? $$
\int_1^\infty \frac{\ln x} x \, dx
$$
The integral is from $1$ to infinity. Solve by taking the limit as $t$ approaches infinity. Not sure how to set up from here.

A: When $x>e$ then $\ln x>1,$ so we have:
$$
\int_e^t \frac{\ln x} x\, dx > \int_e^t \frac 1 x \, dx \to\infty\text{ as } t\to\infty.
$$
The part from $1$ to $e$ does not alter this bottom line.

A: We can explicitly calculate the integral using $u$-substitution.
$$\int_1^\infty \frac{\ln(x)} x \,dx = \lim_{t \to \infty} \int \limits_1^t \frac{\ln(x)} x \,dx.$$
Now, for each $t$, if we let $u = \ln(x)$, then $du = \frac{1}{x} \,dx$ and when $x = 1$, $u = 0$ while when $x = t$, $u = \ln(t)$, giving:
$$ \int_1^t \underbrace{\ln(x)}_u \underbrace{\frac{1}{x} \,dx}_{du} = \int_0^{\ln(t)} u \,du = \left.\frac{u^2}{2} \right|_0^{\ln(t)} = \frac{(\ln(t))^2} 2$$
Now we take $t$ to $\infty$.  Since $\lim \limits_{t \to \infty} \ln(t) = \infty$, then $\lim \limits_{t \to \infty} \frac{(\ln(t))^2} 2 = \infty$, implying $\int\limits_1^\infty \frac{\ln(x)} x \,dx = \infty$, as desired.

A: At first, $x \mapsto \frac{\ln(x)}{x}$ is continuous and locally integrable at $[1,+\infty)$.
Let $X>1$
if you put $u=\ln x$ then
$$F(X)=\int_1^X\frac{\ln(x)}{x}~\mathrm dx=\int_0^{\ln(X)}u~\mathrm du=\frac{1}{2}(\ln(X))^2$$
$$\implies \lim_{X\to+\infty}F(X)=+\infty$$
thus the integral is divergent.

A: $\int \frac{\log(x)}{x} dx= \frac{\log(x)^2}{2}$.
$\int\limits_{1}^x \frac{\log(t)}{t}dt=\frac{\log(x)^2-1}{2}$ which diverges to infinity when $x$ goes to infinity.


text:
Q: Cache mysql queries in variable and available for every request I just started to maintain a browser-game and optimize its code. I can see some functions run more than hundred times. I thought about how to optimize the code.
1- Modify whole platform of programming of the game. (it doesn't make sense because it needs at least 9 months to modify it. Also maybe cause of unexpected bugs and I don't want to get in the way).
2- Working on caching for more efficiency.
I am going to use second way. For more clarifying I put a function of the game here.
function modifyResource($vid, $wood, $clay, $iron, $crop, $mode) {

    if($wood<0)$wood=0;
    if($clay<0)$clay=0;
    if($iron<0)$iron=0;
    //if($crop<0)$crop=0;

    $q = "SELECT * from " . TB_PREFIX . "vdata where wref = $vid";
    $result = $this->query($q,__FILE__,__LINE__);
    $res=$this->mysql_fetch_all($result);

    if($wood+$res[0]['wood']>$res[0]['maxstore'] && $mode)$wood=$res[0]['maxstore']-$res[0]['wood'];
    if($clay+$res[0]['clay']>$res[0]['maxstore'] && $mode)$clay=$res[0]['maxstore']-$res[0]['clay'];
    if($iron+$res[0]['iron']>$res[0]['maxstore'] && $mode)$iron=$res[0]['maxstore']-$res[0]['iron'];
    if($crop+$res[0]['crop']>$res[0]['maxcrop'] && $mode)$crop=$res[0]['maxcrop']-$res[0]['crop'];

    if($res[0]['wood']<$wood && !$mode)$wood=$res[0]['wood'];
    if($res[0]['clay']<$clay && !$mode)$clay=$res[0]['clay'];
    if($res[0]['iron']<$iron && !$mode)$iron=$res[0]['iron'];
    if($res[0]['crop']<$crop && !$mode)$crop=$res[0]['crop'];

    if(!$mode) {
        $wood = -$wood;
        $clay = -$clay;
        $iron = -$iron;
        $crop = -$crop;
    }
    $q = "UPDATE " . TB_PREFIX . "vdata set wood = wood + $wood, clay = clay + $clay, iron = iron + $iron, crop = crop + $crop where wref = $vid";
    $r = $this->query($q,__FILE__,__LINE__);
    if($r){
        // $this->logging->addResourceLog($vid, $wood, $clay, $iron, $crop, $log);
    }
    return true;
}

As you can see the function select vdata table to get necessary information then modify it and finally update the table. two queries run in this function. vdata is a real big table for example in the case is more than 500MB for 80,000 rows. The function runs 88 times for every request from user. This means 88 times a big table Selected and Updated. it costs very much hardware resources and also raise loading time.
An Idea is crossed my mind, Store select query in a variable then update it If function run for the first time. And for other times only update the variable until the class of database destroyed then apply all changes. this will cause save 2x87 queries.
Note:
this caching in variable only persistent until user request accomplished. then destroy all stored(cached) data.
This is just an idea, I have no idea how it can be functioning, Or would be useful if I coded it. Or is there any alternative way or any suggested plugins or class that have same functioning?
Therefore my question has three parts:
1- Would be this idea useful?
2- if yes! Is there any class or plugin that I use it or get more idea?
3- if no! What will be your suggestion to optimze the game?


text:
Q: Output the least appearing item using SQL There is a table called song which has these attributes-
song(songID: integer, songName: string, genre: string, year: integer)
I am supposed to list the genres for which there are lowest number of songs. The output should be genre and cannot contain duplicates.
I have to find this output using min and without out using Min. Currently stuck on finding it through the use of min.
Any starter help?
I am starting off with this
select MIN(genre)
from song;
Where song.id<=ALL
 (select songID
  from song);

But all this gives me is the first alphabetical genre it gets.
Additional info, SongID is primary key but I doubt that matters.

A: You can get a count for each genre like so:
SELECT genre, count(*) FROM song GROUP BY genre;

From there, you'll probably want to read up on commands such as MIN(), LIMIT, ORDER BY, and the like. Google around for examples and tutorials.


text:
Q: how retrieve check box data from data base in the front end asp.net c# coding I have some value stored in the database from the check box and again when I open the page I need the check box value to be checked as it already has some data.
Can any body help

A: In the Form Loaded event you should read your checkbox's stored value from the database then assign it to the checkbox's Checked property.
private void Form1_Load(object sender, EventArgs e)
    {
      myCheckBox.Checked = database.isChecked;
    }

Then in the checkbox's changed events you can save the state back to the database:
private void myCheckBox_CheckedChanged(Object sender, EventArgs e)
{
      database.isChecked = myCheckBox.Checked;
}

you can read a little more about events from here:
http://www.dotnetperls.com/form


text:
Q: Create "Many to Many" relationship between multiple tables with Sequelize I have an already existing schema in MSSQL (image below),
I have a searches table, each search is made up of some metadata and 3 types of filters (can be multiple of each for each search), and I have a "Many to Many" table to connect all types of filters to the search.
I'd like to use Sequelize to query my searches and get the filters for each, but I couldn't find any way to connect the multiple filters to my search table to model using the connecting table (filters)

Searches: contains metadata of the search and the search id.
Filters: contains search id and matches it to filter using filter id and filter type (enum: "range","datetime","exact").
Range filter, datetime filters, exact filters: the filter itself and it's info.
In case it's not possible to query them all together, I thought it might be a possible (but less efficient maybe) to create a view over these tables and create a model for it in Sequelize, but I'm not sure I could do that as well.
Is it possible to model the way I want? And if it is, how can i create this connections?
Thanks!

A: In Sequelize when you have other attributes other than foreign keys in the middle table, you'll have to define its model too.
According to above schema, you'll have to have model of all the tables including the middle one (filters).
Assign associations in this way:
//associations from search model
SearchesModel.belongsToMany(RangesFiltersModel, {through: FiltersModel, foriegnKey: 'filter_search_id', otherKey: 'filter_id'});
SearchesModel.belongsToMany(ExactFiltersModel, {through: FiltersModel, foriegnKey: 'filter_search_id', otherKey: 'filter_id'});
SearchesModel.belongsToMany(DatetimeFiltersModel, {through: FiltersModel, foriegnKey: 'filter_search_id', otherKey: 'filter_id'});

//associations from filters
RangesFilterModel.belongsToMany(SearchesModel, {through: FiltersModel, foreignKey: 'filter_id', otherKey: 'filter_search_id'});
ExactFilterModel.belongsToMany(SearchesModel, {through: FiltersModel, foreignKey: 'filter_id', otherKey: 'filter_search_id'});
DatetimeFilterModel.belongsToMany(SearchesModel, {through: FiltersModel, foreignKey: 'filter_id', otherKey: 'filter_search_id'});

Now, suppose I have a search object:
search.getRangesFilterModels({through: {filterType: 'range'}});
search.getDatetimeFilterModels({through: {filterType: 'datetime'}});
search.getExactFilterModels({through: {filterType: 'exact'}});

When you want to retrieve all search objects where each object contains all associated filters, you can query this way:
SearchesModel.findAll({
    include: [{
        ExactFilterModel,
        through: {filterType: 'exact'}
    }, {
        DatetimeFilterModel,
        through: {filterType: 'datetime'}
    }, {
        RangesFilterModel,
        through: {filterType: 'range'}
    }]
});

P.S. The exact code might not work, but the concept is same. Hope this would help you. For more information, follow the link in the reference
Reference: Sequelize Associations

A:
May be you could use above design with two table one is searches and other is filter which refer searches, with adding cases in your filters based on filter type.
Example:-
case when type is exact then pick only key_exactvalue column.
case when type is range(int/date) then pick respective cast/convert(min_range & Max_range) with range_datatype
Solution 2:-
create view VW_Filters as

select filter_id,'Range' as filter_type,....[other columns]
from ranges_filters

union

select filter_id,'Exact' as filter_type,....[other columns]
from ranges_filters

union

select filter_id,'Datetime' as filter_type,....[other columns]
from ranges_filters

Then you need to create a view on top of filter tables and then join with your main filter table on filter_id and filter_type to fetch required filters for search criteria.


text:
Q: Closed-form solution for a matrix equation involving pseudo-inverses and Frobenius norms Let $A\in \mathbb{C}^{m \times n}$ be a wide unknown complex matrix ($m<n$), and $\Sigma\in \mathbb{R}^{p \times n}$ a known rectangular diagonal matrix. $A$ has full row-rank. Is it possible to obtain a closed form solution for $A$ in terms of $\Sigma$ from the following equation:
$\frac{\left\Vert \Sigma A^H (AA^H)^{-1}\right\Vert_F^2}{\left\Vert A \right\Vert_F^2} AA^H =  (AA^H)^{-1} A \Sigma^H \Sigma A^H (AA^H)^{-1}$,
where $\Vert\cdot\Vert_F$ is the Frobenius norm, $(\cdot)^H$ denotes conjugate traspose, and $(\cdot)^{-1}$ denotes matrix inverse?


text:
Q: is it right way to load library in static block? I am using opencv library in my application through maven dependency. I am loading opencv in static block when application starts. Still,I am working in development environment and it is working fine.But i want to ask,is it a right way to load opencv in static block ?
Loading opencv
@SpringBootApplication
@EnableScheduling
public class SamepinchApplication extends SpringBootServletInitializer{

static {
        try{
            nu.pattern.OpenCV.loadShared();
            System.loadLibrary(org.opencv.core.Core.NATIVE_LIBRARY_NAME);
        }catch(Exception exception){
            System.out.println("Open CV Library could not load due to " + exception.getCause());
        }
    }

 public static void main(String[] args) {
        SpringApplication.run(SamepinchApplication.class, args);
    }

}

Maven dependency
<dependency>
            <groupId>nu.pattern</groupId>
            <artifactId>opencv</artifactId>
            <version>2.4.9-7</version>
        </dependency>

Please help me,what is a good practice to load opencv or other native library ?

A: Loading a native library in static block is good practice. However there are a few  things to keep in mind.
A class could be loaded once only (leaving the occasional respective Classloader garbage collection, which may unload it providing the opportunity for reload) , so if something goes wrong with the library loading, you'll probably have to restart your JVM or reload this class somehow manually.
For example if you're loading library in static block of a REST service or Servlet, and library was not loaded for some reason, you have to redeploy the application or restart the Application server to reload the class to run the static block again for the next try.
However if the library was loaded somewhere other than static block, it can be loaded in the next call of the service or servlet HTTP method.
Multiple calls to System.loadLibrary() don't do anything, if the library is loaded already, so there's no side effect.
All that said, in my opinion loading a native library in a static block is the way to go.


text:
Q: c# Linq expression builder Expression.Equal showing parms around the wrong way I am trying to build some dynamic Linq using expressions for an advance search facility.
I call my define expression builder like so:
IQueryable<DocPod> retval = Enumerable.Empty<Doc>().AsQueryable();
retval = DefineSearchExpression(x => x.Id,
                                     searchCriteria.searchData.Comparison,
                                     searchCriteria.searchData.NumberFrom,
                                     searchCriteria.searchData.NumberTo);

To explain the above, I have multiple properties on a page where each property  has a drop down providing various search types, so in the case above I have an int called Id, then a comparison which can be things like equals, not equals, greater than, etc... Then depending on the selected comparison, NumberFrom is the main search parameter and should always be populated, but in the case of between comparison, the NumberTo parameter is also populated.
The function DefineSearchExpression, is shown below:
    private IQueryable<Docs> DefineSearchExpression(Expression<Func<Docs, object>> searchColumnName, int compare, object minValue, object maxValue)
    {
        IQueryable<Docs> retval = Entities.Docs.AsQueryable();

        // We must have a minValue to process
        if (minValue == null)
        {
            return retval;
        }

        // LINQ Expression that represents the column passed in searchColumn
        var columnExpression = GetMemberExpression(searchColumnName);

        // LINQ Expression to represent the parameter of the lambda you pass in
        ParameterExpression parameterExpression = (ParameterExpression)columnExpression.Expression;
        // Expressions to represent min and max values
        Expression minValueExpression = null;
        Expression maxValueExpression = null;
        Expression minComparisonExpression = null;
        Expression maxComparisonExpression = null;

         // Represents the completed filter
        Expression<Func<Docs, bool>> filterLambdaExpression = null;
        // setup vars
        if (minValue.IsNumeric())
        {
            var intfromValue = int.Parse(minValue.ToString());
            minValueExpression = Expression.Constant(intfromValue);
            if (maxValue != null)
            {
                var inttoValue = int.Parse(maxValue.ToString());
                maxValueExpression = Expression.Constant(inttoValue);
            }
        }
        else if (minValue.IsDate())
        {
            var dtfromValue = DateTime.Parse(minValue.ToString());
            minValueExpression = Expression.Constant(dtfromValue);
            if (maxValue != null)
            {

                var dttoValue = DateTime.Parse(maxValue.ToString());
                maxValueExpression = Expression.Constant(dttoValue);
            }
        }

        // Expression represented by selection in dropdown List
        switch (compare)
        {
            //
            // THIS IS WHERE THE FIRST ISSUES IS LOCATED
            //
            //
            case 0: // This should be equivalent to: field = value
                minComparisonExpression = Expression.Equal(minValueExpression, columnExpression);
                filterLambdaExpression = Expression.Lambda<Func<Docs, bool>>(minComparisonExpression, parameterExpression);
                break;
        }

        retval = retval.AsQueryable().Where(filterLambdaExpression);
        return retval.AsQueryable();
    }

As you can see, I am trying to take into account numeric, datetime and finally string data for searching.
When the above code is executed, when the code within the switch Case 0 provides the following anomaly.
minComparisonExpression has the debug value of 1977836648 == $x.Id
I have tried to swap these values around, but with little success, if anyone knows how to fix this, I would be very grateful.
Secondly, when DefineSearchExpression returns, the new expression is lost, this is most probably me, but I just cannot see it.
Oops. Thank you for spotting the error, but that does not help as the offending code is in the Switch Case 0 statements, the date code is not run at all at the moment.
Code updated!


text:
Q: How to make text underline and remove text at the same time I have a text in which there is indicator tag that indicate from where i will make text underline, I want to make text underline from that indicator also want to remove indicator so that it wont appear in string, here is what I'm trying:
  String consent = "By clicking this, you confirm you understand the services provided by your Health at Hand doctor and give <clickable>consent</clickable> to proceed.";
    int i1 = consent.indexOf(">");
    int i2 = consent.indexOf("</");
    consentCheck.setMovementMethod(LinkMovementMethod.getInstance());

    consentCheck.setText(consent, CheckBox.BufferType.SPANNABLE);

    consent = consent.replace("</clickable>", "");
    consent = consent.replace("<clickable>", "");

    Spannable mySpannable = (Spannable)consentCheck.getText();
    mySpannable.setSpan(clickableSpan, i1+1, i2 , Spannable.SPAN_INCLUSIVE_INCLUSIVE);

A: If you want to display the text in TextView you could replace "clickable" tags with "u" tags and then use Html.fromHtml() in setText:
String consent = "By clicking this, you confirm you understand the services provided by your Health at Hand doctor and give <clickable>consent</clickable> to proceed.";
consent = consent.replace("<clickable>", "<u>").replace("</clickable>", "</u>");
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
    tvConsent.setText(Html.fromHtml(consent, Html.FROM_HTML_MODE_LEGACY));
} else {
    tvConsent.setText(Html.fromHtml(consent));
}

EDIT:
If u want to edit "consent" part freely you could split the text into three parts and then edit each part independently
String consent = "By clicking this, you confirm you understand the services provided by your Health at Hand doctor and give <clickable>consent</clickable> to proceed.";
String start = "<clickable>";
String end = "</clickable>";
String part1 = consent.substring(0, consent.indexOf(start));
String part2 = consent.substring(consent.indexOf(start)+start.length(),consent.indexOf(end));
String part3 = consent.substring(consent.indexOf(end), consent.length()).replace(end, "");


text:
Q: Как сделать генерацию чисел от 0 до 1 Как сделать генерацию чисел от 0 до 1. Если выпадет 0 то человек победил и в консоле выводит это. Если 1 то он проиграл и так же пишет в консоле java.

A: Random rand = new Random();
int i = rand.nextInt(2);

A: Классика
int i = (int) (Math.random() * 2);
System.out.println(i);

Тест
public class Test {
    public static void main(String[] args) {
        for (int n = 0; n < 100_000_000; n++) {
            int i = (int) (Math.random() * 2);

            if (i != 1 && i !=0) {
                System.out.println(i);
                break;
            }
        }
    }
}


text:
Q: How do I parse a .eml file using C/C++? How do I parse .eml files using C/C++ (or preferably Objective-C)?
I looked around but couldn't find any details about the structure of the file.

A: EML files are plain ASCII (7-bit) files.  The file format is specified in RFC 2822.  The mail header will be separated from the body by an empty line.
If you will be dealing with emails that contain attachments, or characters whose value is greater than 127, you will need a base64 decoder.  maybe this link will help.


text:
Q: Jersey returns 500 when trying to return an XML response I'm trying to create my own RESTful WS application using Jersey 2.12 based from this article. I want to return an XML representation of a class depending on the id been passed from the url, however, I'm getting a 500 response code when trying from either Advanced Rest Client Application (google chrome app) or browser. Below are the details:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
    app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>WS_RESTful_Practice</display-name>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <!-- Register resources and providers under com.vogella.jersey.first package. -->
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>test.services</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
 </servlet-mapping>
</web-app>

TestRestModel.java
package test.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class TestRestModel{

    /**
     *
     */
    private static final long serialVersionUID = -8391589100962515747L;
    private String name;
    private String content;

    public TestRestModel(String name, String content){
        this.name = name;
        this.content = content;
    }

    public String getName() {
        return name;
    }

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

TestResource.java
package test.services;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import test.dao.TestModelDao;
import test.model.TestRestModel;

@Path("/test")
public class TestResource {

    @GET
    @Path("{id}")
    public Response getModel(@PathParam("id") String id){
        return Response.ok().entity(TestModelDao.instance.getModel().get(id)).build();
    }
}

TestModelDao.java
package test.dao;

import java.util.HashMap;
import java.util.Map;
import test.model.TestRestModel;

public enum TestModelDao {
    instance;

    private Map<String, TestRestModel> container = new HashMap<String, TestRestModel>();

    private TestModelDao(){

        TestRestModel model = new TestRestModel("a", "this is first");
        container.put("1", model);
        model = new TestRestModel("b", "this is second");
        container.put("2", model);
        model = new TestRestModel("c", "this is third");
        container.put("3", model);
    }

    public Map<String, TestRestModel> getModel(){
        return container;
    }
}

I'm totally new to Jersey and REST. And I don't know how to log error from Jersey yet.

A: This happens when you don't provide a default no arg constructor to your JAXB bean. So in your case you should amend the class by adding one:
  public TestRestModel(){

    }

This is due to a requirement in the JSR-222:

existing types, authored by users, are required to provide a no arg
  constructor. The no arg constructor is used by an unmarshaller during
  unmarshalling to create an instance of the type.

A: Stuff below is not the answer, but will probably help Johne to find out, whats up.
Out of the comments I've extract, that the main problem is, that you don't have any noticeable debug output in your console. So you are not able to find the issue by yourself, rather than give us some logs which would help to find out, what the exact problem could be.
Therefore pls implement an ExceptionMapper first, which will force console output of the stacktrace:
Example:
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class HelpMeExceptionMapper implements ExceptionMapper<Exception> {

    @Override
    public Response toResponse(Exception e) {
        e.printStackTrace();
        return Response
                    .status(Status.INTERNAL_SERVER_ERROR)
                    .type(MediaType.APPLICATION_JSON)
                    .entity(e.getCause())
                    .build();
    }

}

The ExceptionMapper has to be in a subpackage of your resource-config/providers path test.services:
<init-param>
    <param-name>jersey.config.server.provider.packages</param-name>
    <param-value>test.services</param-value>
</init-param>

As i didn't implement your/vogellas code i would like to recommend you, to debug this step by step to find out whats up.
I reckon, that you miss to import something. But who knows ...
Have a nice day ...

A: To the ones with the same problem, I had something like it but in my case it was a List that i wanted in my response. The source of the problem was that the object had a lazy load relationship and when I used GenericEntity> to return my list the same problem as occurred to me.
Just change to null the relationship or bring the lazy load relation to the object before create GenericEntity> and it will be fine.

A: We need to understand this problem first
Jersey returns 500 when trying to return an XML response. This issue is coming because of missing dependency in pom.xml and that is:
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.2.11</version>
</dependency>

But this is not enough. This will resolve the 500 Error but one more error will come, while using endpoint.
javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: com/sun/xml/bind/v2/model/annotation/AnnotationReader

To resolve this you need to add following dependencies too into pom.xml
<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-core -->
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>2.3.0.1</version>
</dependency>

        <!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl -->
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.3.1</version>
</dependency>

So this is the complete solution, to make your Jersey webApp work


text:
Q: FROM is not valid at this position. UPDATE statement I have this code from an online SQL Server tutorial. I need to convert it for MySql. I have already changed ISNULL to ifnull, but I still have the error from the question title:
UPDATE a
SET PropertyAddress = ifnull(a.PropertyAddress, b.PropertyAddress)
FROM Nashvillehousing as a
JOIN Nashvillehousing as b
    ON a.ParcelID = b.ParcelID
    AND a.UniqueID <> b.UniqueID
WHERE a.PropertyAddress IS NULL;

How can I fix this to run on MySql?

A: You don't need a join for this.
UPDATE nashvillehousing
SET propertyaddress =
(
  SELECT ANY_VALUE(src.propertyaddress)
  FROM (select * from nashvillehousing) src
  WHERE src.parcelid = nashvillehousing.parcelid
  AND src.uniqueid <> nashvillehousing.uniqueid
)
WHERE propertyaddress IS NULL;

I had to write FROM (select * from nashvillehousing) src instead of a mere FROM nashvillehousing src. That is due to a limitation in MySQL where you cannot directly select from the same table that you are updating.
The original statement assumes that you find at most two rows for a parcelid. This is usually not guaranteed to be the case, so I put in ANY_VALUE to get this safe. (You can of course just as well use MIN or MAX here, if you like this better.)

A: The MySql syntax for using a JOIN in an UPDATE is different from SQL Server. I don't write this for MySql very often, but I think you want this:
UPDATE Nashvillehouse as a
INNER JOIN Nashvillehouse as b
    ON a.ParcelID = b.ParcelID
    AND a.UniqueID <> b.UniqueID
SET a.PropertyAddress = ifnull(a.PropertyAddress, b.PropertyAddress)
WHERE a.PropertyAddress IS NULL;


text:
Q: Any suggestions for a good login manager? I tried using RoboForm but it's like Oracle - incredibly complex. We could never get it to share the corporate passwords but keep individual ones for each user.
Anyone know of a good login mananger?
We want one that has a shared company repository and individual repositories for each user for their person passwords. Preferably simple enough that there's only 5 - 10 options and only 1 password per user.

A: Have you looked at LastPass?  It allows sharing individual passwords, but not a complete repository of passwords (at least as far as I know) so it may not fit your needs.


text:
Q: Recovering ring information from localizations I'm curious if such a statement is true:

Let $R$ be a commutative ring with unity. Then if $x \in R$ and $x = 0$ in $R_p$ for all primes $p$, where $R_p$ is the localization of $R$ at prime $p$, then $x = 0$ in $R$.

A: Yes this is true. You can even restrict to maximal ideals. To say that $r\in\ker(R\rightarrow R_\mathfrak{m})$ for a maximal ideal $\mathfrak{m}$ means that there is some $s\in R\setminus\mathfrak{m}$ with $sr=0$. It follows that $s\in\mathrm{Ann}_R(r)$. If this is true for every maximal ideal $\mathfrak{m}$ of $R$, then the ideal $\mathrm{Ann}_R(r)$ cannot be contained in any maximal ideal, and therefore must be equal to $R$. So $1\in\mathrm{Ann}_R(r)$, i.e. $0=1\cdot r=r$.


text:
Q: 2d mixed with activity, is that easy in android? My whole application is very common except an area that display 2d graphics(text marqueezing and some visual effect). The app is like a media player --- it has buttons, and lots of dialogs(for configuration uses).
I wonder how could I do this?
First I use activity and build-in animations but obviously the animations are too limited.
So should I use game engine to achieve good graphics? But how about those dialogs in this case? Are they hard to implement in game engine? Or I can mix activity dialog with 2d game engine?

A: You should not have difficulty to use a 2D engine with dialogs and classic UI.
I advice you to look at AndEngine. It's a very well known game engine, really easy for 2D.


text:
Q: Definitive list of object properties available through column formatting I have been referring to:
Use column formatting to customize SharePoint
And also reading multiple blog posts around the subject.
I have not yet found a definitive list of object properties available through column formatting.
I looked around the SharePoint REST API v1 docs, but there doesn't seem to be any complete reference there (and I'm not sure if what is available via the API is also available through column formatting).
Does a resource like this exist?
I am specifically trying to find what properties are accessible in a Person object.
I want to show the username in a column, based of an existing Person column.
I have had success implementing this basic formatting:
{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
  "elmType": "div",
  "txtContent": "[$Person.title]"
}

And this has also worked for:  [$Person.email], [$Person.id].
But I cannot see how to access username and workemail, etc.

A: Using column formatting on Person or Group type field you can only access below properties as of now (with example values):
{
   "id": "122",
   "title": "Kalya Tucker",
   "email": "kaylat@contoso.com",
   "sip": "kaylat@contoso.com",
   "picture": "https://contoso.sharepoint.com/kaylat_contoso_com_MThumb.jpg?t=63576928822",
   "department":"Human Resources",
   "jobTitle":"HR Manager"
}

Official documentation:
Column Formatting in SharePoint - Special string values - Check People fields section


text:
Q: issue in putting toolbar and picker as subview of UIPopoverController i want to put tool bar and picker view as sub view of popovercontroller and for that i do following  and so far my picker view is displaying perfectly but just above that i also want to display my tool bar in which there is button named Done for that i do following please guide me if you see something wrong that i am doing
- (IBAction)setAlarm:(id)sender {

    UIViewController* popoverContent = [[UIViewController alloc] init];
    UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 344)];
    popoverView.backgroundColor = [UIColor whiteColor];

    [popoverView addSubview:toolbar];
    [popoverView addSubview:timePicker];

    timePicker.hidden = NO;
    toolbar.hidden = NO;

    popoverContent.view = popoverView;

    //resize the popover view shown
    //in the current view to the view's size
    popoverContent.contentSizeForViewInPopover = CGSizeMake(320, 216);

    //create a popover controller
    popoverController = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
    timePicker.frame = popoverView.bounds;
    toolbar.frame    = popoverView.bounds;

    CGRect popoverRect ;
    popoverRect.origin.x =591;
    popoverRect.origin.y = 139;
    popoverRect.size.height = 95;
    popoverRect.size.width = 44;

    [popoverController presentPopoverFromRect:popoverRect
                                       inView:self.view
                     permittedArrowDirections:UIPopoverArrowDirectionUp
                                     animated:YES];

    //release the popover content
    [popoverView release];
    [popoverContent release];

    timePicker.hidden = NO;
    toolbar.hidden = NO;

}

A: The problem is that you set the frame of booth subviews to the same value:
timePicker.frame = popoverView.bounds;
toolbar.frame    = popoverView.bounds;

So, which ever one was added first will be hidden behind the other. You need to set the frames so that the toolbar is correctly positioned above the picker (and size the popover to allow space for both of them).

Something like:
CGRect toolbarFrame = toolbar.frame;
toolbarFrame.size.width = 320;
toolbar.frame = toolbarFrame;

CGRect pickerFrame = timePicker.frame;
pickerFrame.origin.y = toolbarFrame.size.height;
pickerFrame.size.width = 320;
timePicker.frame = pickerFrame;

popoverView.frame = CGRectMake(0, 0, 320, pickerFrame.origin.y + pickerFrame.size.height);

popoverContent.contentSizeForViewInPopover = popoverView.frame.size;


text:
Q: Global variables defined inside a class I found a solution to Leetcode NO. 543 Diameter of Binary Tree which is solved with the use of global variables. I have the solution shown in the text below. The author used a scalar variable, 'self.res', to store the final answer which is updated when the program traverses through the given binary tree.
I am wondering why the author needs to use self.res rather than a generic integer variable---for example, res only---to store the answer; when I replace self.res with res, the answer is wrong. Can anyone point out the difference?
class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        self.res = 0
        def depth(root):
            if not root:
                return 0
            left = depth(root.left)
            right = depth(root.right)
            self.res = max(self.res, left + right)
            return max(left, right) + 1
        depth(root)
        return self.res

A: Strictly speaking, it doesn't have to be an attribute. It could be a non-local variable.
class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        res = 0
        def depth(root):
            nonlocal res
            if not root:
                return 0
            left = depth(root.left)
            right = depth(root.right)
            res = max(res, left + right) # the key to memorize the result
            return max(left, right) + 1
        depth(root)
        return res
Without the nonlocal statement, res would be a local variable that isn't set the first time depth tries to use it in the call to max.
Python 2 did not have a nonlocal statement, so an instance attribute would have been the best alternative to a global variable for persisting state between calls to depth. (The type hints indicate this probably wasn't written for Python 2, but old habits can die hard.) In Python 3, using nonlocal, the above no longer even uses self, so diameterOfBinaryTree can trivially be written as a regular function rather than an instance method of an unnecessary class.


text:
Q: Braces and alignment
\begin{align}
\begin{cases}
2x + y &= 5 \\
2x - 3y &= 1
\end{cases} \\
\hline
0x + 4y &= 4
\end{align}

Is there any way to keep all equal signs aligned both inside and outside the cases?

A: You can get something like this with blkarray.
\documentclass[fleqn]{article}
\usepackage{blkarray}
\begin{document}
\[\begin{blockarray}{r@{\,}l}
\begin{block}{\{r@{\,}l}
2x+y &=5\\
2x-3y &=1\\
\BAhline
\end{block}
0x+4y&=4
\end{blockarray}\]
\end{document}

Without additional packages it becomes less straightforward/elegant.
\documentclass[fleqn]{article}
\usepackage{amsmath}
\begin{document}
\begin{align*}
\left\{
\begin{array}{@{}r@{\,}l}
2x + y \,&= 5 \\
2x - 3y \,&= 1\\
\end{array} \right.&\\
\hline
0x + 4y = 4~~&
\end{align*}
\end{document}


text:
Q: JPA Design Model For OneToMany Relation I have a database design like this: tb_address( id, address ) and tb_store( id, name, address_id ) and tb_user( id, name, address_id ) where both address_id are a reference key of tb_address.
I want to design java model using spring-data-jpa. I had already create model one by using tool in Intellij to generate database script, but I am not getting what I want. What I got is like this tb_address( id, address, store_id, user_id ) and I don't want that. So Please help me.

A: Seems like you don't get what you want because of the design of your Models or Entities. I think this is what you're looking for:
@Entity
@Table(name = "td_address")
public class Address {

    @Id
    private Long id;
    private String address;

    //getters and setters

}

@Entity
@Table(name = "tb_store")
public class Store {

    @Id
    private Long id;
    private String name;
    @ManyToOne
    @JoinColumn(name = "address_id")
    private Address address;

    //getters and setters

}

@Entity
@Table(name = "tb_user")
public class User {

    @Id
    private Long id;
    private String name;
    @ManyToOne
    @JoinColumn(name = "address_id")
    private Address address;

    //getters and setters
}


text:
Q: C loop not formatting correctly with array So, I tried to modify this code from Samfoundry of a FCFS Scheduler. I removed the things pertaining to the turnaround time as I don't really need it and modified it so it can process elements already inside of an array instead of a user input. I think the logic is correct, but the formatting is not, and I don't really know why even when it's almost identical with the source code.
int main()
{
    int pid[5] = {1, 2, 3, 4, 5};
    int bt[5] = {5, 3, 1, 2, 3};
    int n = 5;

    int i, wt[n];
    wt[0]=0;

    //for calculating waiting time of each process
    for(i=1; i<n; i++)
    {
        wt[i]= bt[i-1]+ wt[i-1];
    }

    printf("Process ID      Burst Time     Waiting Time\n");
    float twt=0.0;
    for(i=0; i<n; i++)
    {
        printf("%d\t\t", pid[i]);
        printf("%d\t\t", bt[i]);
        printf("%d\t\t", wt[i]);

        //for calculating total waiting time
        twt += wt[i];

    }
    float awt;

    //for calculating average waiting time
    awt = twt/n;

    printf("\nAvg. waiting time= %f\n",awt);
}

Expected output:
ProcessID       BurstTime     WaitingTime
1               5             0
2               3             5
3               1             8
4               2             9
5               1             11

Actual output:
ProcessID       BurstTime     WaitingTime
1               5               0               2               3               5               3               1               8               4               2               9           5
3               11

A: Everything works fine in code you just need to add some extra tab spaces and new line character inside the for loop  change
printf("%d\t\t\t\t", pid[i]); //add two more tab spaces

printf("%d\t\t\t\t", bt[i]); //same as here add two tab spaces

printf("%d\t\t\n", wt[i]);  // add a \n i.e new line


text:
Q: adb screen streaming to python + opencv I know add can record screen and take screen shots. Is is possible to capture a live stream of the screen with any of these commands?
Would it be possible, for instance, to make a 10fps streaming with adb shell screencap directly, without any other app?
I've tried this, but it returns "pipe:: Invalid data found when processing input"
adb shell screenrecord --output-format=h264 - | ffplay -