text:
Q: Find the nearest time span I have a requirement where I have say 2 parameters a bucketDelta and a start time and I need to calculate the closest time interval in bucketDelta steps that is less than the given time. (sounds convoluted enough ? Here is an example)
say bucketDelta
15minutes and my time is 13 Sep 7:05 PM - returns 13 Sep 7:00 PM
15minutes and my time is 13 Sep 7:17 PM - returns 13 Sep 7:15 PM
15minutes and my time is 13 Sep 7:35 PM - returns 13 Sep 7:30 PM
...
30 minutes and my time is 13 Sep 7:05 PM - returns 13 Sep 7:00 PM
30 minutes and my time is 13 Sep 7:17 PM - returns 13 Sep 7:00 PM
30 minutes and my time is 13 Sep 7:35 PM - returns 13 Sep 7:30 PM
...
60 minutes and my time is 13 Sep 7:05 PM - returns 13 Sep 7:00 PM
60 minutes and my time is 13 Sep 7:35 PM - returns 13 Sep 7:00 PM
60 minutes and my time is 13 Sep 7:55 PM - returns 13 Sep 7:00 PM
24 Hours and my time is 13 Sep 7:05 PM - returns 13 Sep 12:00 AM
24 Hours and my time is 13 Sep 9:05 PM - returns 13 Sep 12:00 AM
..
Here is the logic I have for this but I am not too happy with a million Ifs. Is there a better way to do this ?
            if (bucketDelta == TimeSpan.FromSeconds(900)) {
            if (bucketStop.Minute > 0 && bucketStop.Minute < 15)
            {
                minute = bucketStop.Minute;
            }
            else if (bucketStop.Minute > 15 && bucketStop.Minute < 30)
            {
                minute = bucketStop.Minute - 15;
            }
            else if (bucketStop.Minute > 30 && bucketStop.Minute < 45)
            {
                minute = bucketStop.Minute - 30;
            }
            else if (bucketStop.Minute > 45 && bucketStop.Minute < 60)
            {
                minute = bucketStop.Minute - 45;
            }
        }else if(bucketDelta == TimeSpan.FromSeconds(1800)) {
            if (bucketStop.Minute > 0 && bucketStop.Minute < 30)
            {
                minute = bucketStop.Minute;
            }
            else if (bucketStop.Minute > 30 && bucketStop.Minute < 60)
            {
                minute = bucketStop.Minute - 30;
            }
        } else if(bucketDelta == TimeSpan.FromSeconds(3600))
        {
            if (bucketStop.Minute > 0 && bucketStop.Minute < 60)
            {
                minute = bucketStop.Minute;
            }
        }
        else if (bucketDelta == TimeSpan.FromSeconds(86400))
        {
            if (bucketStop.Hour > 0 && bucketStop.Hour < 24)
            {
                minute = (bucketStop.Hour * 60);
            }
        }
        bucketStop = bucketStop.AddMinutes(-1 * minute);

A: Convert both into integer multiples of a standard unit, divide the absolute time by the length of your bucket, use floor to get an integer, multiply by the length of your bucket, and convert back.  Depending on your language, floor may either be implicit from the type system or explicit.
For example in Java your calculation could look something like the following (untested):
long intervals = originalInstant.toEpochMilli() / bucketInMilliseconds;
Instant answer = Instant.fromEpochMilli( bucketInMilliseconds * intervals );


text:
Q: How to get generic type definition for CRTP type Given the following CRTP type in C#:
public abstract class DataProviderBase<TProvider>
    where TProvider : DataProviderBase<TProvider> { }

How would I get its generic type definition in F#?
let typeDef = typedefof<DataProviderBase<_>>

yields the error:

Type constraint mismatch when applying the default type 'DataProviderBase<'a>' for a type inference variable. The resulting type would be infinite when unifying ''a' and 'DataProviderBase<'a>' Consider adding further type constraints

In C#, it would be:
var typeDef = typeof(DataProviderBase<>);

UPDATE
I found a workaround:
[<AbstractClass>]
type DummyProvider() =
  inherit DataProviderBase<DummyProvider>()

let typeDef = typeof<DummyProvider>.BaseType.GetGenericTypeDefinition()

Is there another way to do it, without the extra type?

A: I think this is actually a very good question. I didn't find a better workaround for this.
You can slightly simplify your workaround by using typedefof like this:
let typeDef = typedefof<DataProviderBase<DummyProvider>>

TECHNICAL DETAILS
The problem is that F#'s typedefof<'T> is just an ordinary function that takes a type argument (unlike typeof in C#, which is an operator). In order to call it, you need to give it an actual type and the function will then call GetGenericTypeDefinition under the cover.
The reason why typedefof<option<_>> works is that F# specifies a default type as an argument (in this case obj). In general, F# chooses the less concrete type that matches the constraints. In your case:
DataProviderBase<_>   will become    DataProviderBase<DataProviderBase<_>> and so on.
Unless you define a new type (as in your workaround), there is no concrete type that could be used as a type argument of typedefof<...>. In this case, the defaulting mechanism simply doesn't work...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Update command on AccessDataSource doesn't update table as expected Update button executes the query, but nothing shows up in my database. Any thoughts as to why?
I've moved it in and out of an UpdatePanel. I've tried with the couple of variations on the variables like @Atty_ID or ?, but I can't seem to get it to work.
When I click the Update button, nothing happens except the page refreshes sometimes.
<asp:UpdatePanel ID="UpdatePanel19" runat="server">
                    <ContentTemplate>
                        <asp:AccessDataSource ID="ChamberLogoDataSource" runat="server"
                          DataFile="~/App_Data/Attorneys.mdb"
                          SelectCommand="SELECT ATTORNEYS.CHAMBER FROM ATTORNEYS WHERE ATTY_ID = ?"
                          UpdateCommand="UPDATE ATTORNEYS SET CHAMBER = ? WHERE ATTY_ID = ?">
                          <SelectParameters>
                            <asp:QueryStringParameter Name="ATT_ID" QueryStringField="ATT_ID" />
                          </SelectParameters>
                          <UpdateParameters>
                            <asp:Parameter Name="CHAMBER" />
                            <asp:Parameter Name="ATTY_ID" />
                          </UpdateParameters>
                        </asp:AccessDataSource>
                        Add a Chambers logo:

                        <asp:TextBox ID="TextBox2" runat="server" TextMode="MultiLine" Rows="5" Columns="50"></asp:TextBox>
                        <asp:Button ID="UpdateChambersLogoButton" runat="server" Text="Update" OnClick="UpdateLogo" />
                    </ContentTemplate>
                </asp:UpdatePanel>

And here is the code behind:
Protected Sub UpdateLogo(ByVal sender As Object, ByVal e As System.EventArgs)
    ChamberLogoDataSource.Update()
End Sub

A: I believe you have your update parameter binding out of order, and that could be causing the update to fail because there are no matches to the WHERE clause.
Reverse the order of the UpdateParameters like below and try it.
<asp:AccessDataSource ID="ChamberLogoDataSource" runat="server"
                  DataFile="~/App_Data/Attorneys.mdb"
                  SelectCommand="SELECT ATTORNEYS.CHAMBER FROM ATTORNEYS WHERE ATTY_ID = ?"
                  UpdateCommand="UPDATE ATTORNEYS SET CHAMBER = ? WHERE (ATTY_ID = ?)">
                  <SelectParameters>
                    <asp:QueryStringParameter Name="ATT_ID" QueryStringField="ATT_ID" />
                  </SelectParameters>
                  <UpdateParameters>
                    <asp:Parameter Name="CHAMBER" />
                    <asp:Parameter Name="ATTY_ID" />
                  </UpdateParameters>
                </asp:AccessDataSource>
              <asp:UpdatePanel ID="UpdatePanel19" runat="server">
                <ContentTemplate>
                    Add a Chambers logo:

                    <asp:TextBox ID="TextBox2" runat="server" TextMode="MultiLine" Rows="5" Columns="50"></asp:TextBox>
                    <asp:Button ID="UpdateChambersLogoButton" runat="server" Text="Update" OnClick="UpdateLogo" />
                </ContentTemplate>
              </asp:UpdatePanel>


text:
Q: Input of 3D array into Sequential model Keras (Python) I have a training input in 3 dimensions (8,50,3).
I am trying to pass it as an input to the Sequential Model in Keras. Looking up the documentation I found that this should work:
model = Sequential()
model.add(Dense(100, activation='relu', input_shape=(50,3)))
model.add(Dense(100,init="uniform", activation='sigmoid'))
model.add(Dense(50,init="uniform", activation='relu'))
model.add(Dense(output_dim=1))
model.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy'])

When I try to train this model:
model.fit(train,labelTrain,epochs=1,batch_size=1,verbose=1)

I get the following error:
Error when checking model target: expected dense_148 to have 3 dimensions, but got array with shape (8, 1)

What can it mean?
Also, my first objective was to pass a 3D array where the middle dimension did not have a fixed size but I gave up after finding it impossible. Could it work?

A: Target means it's the expected result. The problem is in labelTrain, not in the input.
A Dense layer must have a number of neurons. You don't pass it an output shape, you pass the amount of neurons, and the output is automatically (None, neurons)
Your last layer should be:
model.add(Dense(1, activation='I recomend an activation here'))


text:
Q: A simple lp inequality Suppose $f : \mathbf R\rightarrow\mathbf R$ is in $L^p$ for some $p>1$ and also in $L^1$. Show that $\exists c>0$ and $\alpha\in(0,1)$ such that
$$\int_A|f(x)| \, dx\leq c m(A)^\alpha$$
where $m$ is Lebesgue measure.

A: $$\int_A |f|\,dx\leq\|f\|_{L^p(A)} \|1\|_{L^q(A)}=\|f\|_{L^p(A)} m(A)^{1/q}\leq\|f\|_{L^p(\mathbf R)}m(A)^{1/q}\quad\blacksquare$$


text:
Q: Browserify Rails Error - ParseError: 'import' and 'export' may appear only with 'sourceType: module' Recently i want to integrated NPM package in my rails application. I getting this problem :

I search in this forum if someone have same problem like me. Yes, i saw similar question being posted here but they're having different error.
Below is what i have in my application.js :

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require react
//= require react_ujs
//= require components
//= require react-select
//= require react-dom
//= require classnames
//= require_tree .
$(function(){ $(document).foundation(); });

Here's where i try to imported the package

var React = require('react');
var ReactDOM = require('react-dom');
var FileBase64 = require('react-file-base64');
var MembersNew = React.createClass(
{
 render()
 {
  return(

ACCOUNT DETAILS

Fill in your member account details below

   Membership ID :

     Username*
                 <input ref="name" type="text"/>

              First Name*
                 <input ref="name" type="text"/>

              Last Name*
                 <input ref="name" type="text"/>

              Email Address*
                 <input ref="name" type="text"/>

I have mess up my gemfile for like below. Maybe this is why the problem occur :

source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

gem 'rails-assets-react-select','~> 1.0.0.rc.3', source: 'https://rails-assets.org'
gem 'rails-assets-react-dom', source: 'https://rails-assets.org'
gem 'rails-assets-classnames', source: 'https://rails-assets.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.2'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

gem 'react-rails'
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
gem 'responders'
gem 'foundation-rails'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
gem 'browserify-rails'

someone can help me to solve this error ?

A: I think the issue you might be having is that the npm module that you are trying to install and use is an ES6 JS module. From your error log, I guess you are using Browserify to load your JS modules. IIRC Browserify out of the box only supports Common JS modules, which means you'll have to run your JS through a tool like Babel or Babelify (babel's browserify transform) to transform that ES6 module into an ES5 module with module.exports syntax.


text:
Q: How to display selected value's information in Vue I have an API to fetch data and it is coming like this:
"data": {
    "type": "products",
    "id": "2021-01-04.1.1",
    "attributes": {
      "name": "product 1",
      "descriptions": "some description",
      "image": null,
      "date": "2021-01-04",
      "valid_from": null,
      "valig_untill": null,
      "xparc_paid_product_id": 1,
      "xparc_unpaid_product_id": 1,
      "xparc_access_id": 1,
      "stock": null,
      "variations": [
        {
          "id": 1,
          "product_template_id": "1",
          "name": "child ticket",
          "description": "Only for children!",
          "price_excl_vat": 1,
          "created_at": "2021-09-15T13:16:00.000000Z",
          "updated_at": "2021-09-15T13:16:00.000000Z"
        },
        {
          "id": 2,
          "product_template_id": "1",
          "name": "Adults",
          "description": "Not for children!",
          "price_excl_vat": 2,
          "created_at": "2021-09-15T13:16:10.000000Z",
          "updated_at": "2021-09-15T13:16:10.000000Z"
        },
        {
          "id": 3,
          "product_template_id": "1",
          "name": "Test",
          "description": "Test",
          "price_excl_vat": 10,
          "created_at": "2021-09-30T11:29:44.000000Z",
          "updated_at": "2021-09-30T11:29:44.000000Z"
        }
      ]
    },

What I am trying to do is I put these variations of the data into the dropdown as you see in the picture:

So here is my dropdown component:
<template>

            {{ selected }}

                {{ option }}

</template>

And this is how I displayed the names of the variants into the dropdown:
<Dropdown
   :options="getVariations"
   :default="'Choose an option'"
   class="select"
/>
computed: {
  getVariations() {
    return this.product.attributes.variations.map(p => p.name);
  },
},

So what I am trying to do is according to the selected value I want to display more information of the selected variations inside of the div. For example here:
 {{variations.description}} But I dont know how to do. Can you help me?

A: To show it in Dropdown component send data from computed like:
computed: {
  variations() {
    return this.data.attributes.variations
  }
}

then i template show data like:
{{ selected.name }}

To show description on parent component emit event $emit('input', option), so try to listen to @input="getSelected" and filter data in method
getSelected(opt) {
  this.sel = opt.description
}

Vue.component('Dropdown', {
  template: `

            {{ selected.name }}

Description child :{{ selected.description }}

                {{ option.name }}

  `,
   props: {
        options: {
            type: Array,
            required: true,
        },
        default: {
            type: String,
            required: false,
            default: null,
        },
        tabindex: {
            type: Number,
            required: false,
            default: 0,
        },
    },
    data() {
        return {
            selected: this.default
                ? this.default
                : this.options.length > 0
                    ? this.options[0]
                    : null,
            open: false,
        };
    },
    mounted() {
        this.$emit("input", this.selected);
    },
})

new Vue({
  el: '#demo',
  data(){
    return {
      "data":
          {
            "type": "products",
            "id": "2021-01-04.1.1",
            "attributes": {
              "name": "product 1",
              "descriptions": "some description",
              "image": null,
              "date": "2021-01-04",
              "valid_from": null,
              "valig_untill": null,
              "xparc_paid_product_id": 1,
              "xparc_unpaid_product_id": 1,
              "xparc_access_id": 1,
              "stock": null,
              "variations": [
                {
                  "id": 1,
                  "product_template_id": "1",
                  "name": "child ticket",
                  "description": "Only for children!",
                  "price_excl_vat": 1,
                  "created_at": "2021-09-15T13:16:00.000000Z",
                  "updated_at": "2021-09-15T13:16:00.000000Z"
                },
                {
                  "id": 2,
                  "product_template_id": "1",
                  "name": "Adults",
                  "description": "Not for children!",
                  "price_excl_vat": 2,
                  "created_at": "2021-09-15T13:16:10.000000Z",
                  "updated_at": "2021-09-15T13:16:10.000000Z"
                },
                {
                  "id": 3,
                  "product_template_id": "1",
                  "name": "Test",
                  "description": "Test",
                  "price_excl_vat": 10,
                  "created_at": "2021-09-30T11:29:44.000000Z",
                  "updated_at": "2021-09-30T11:29:44.000000Z"
                }
              ]
            },
          },
          sel: ''

    }
  },
  computed: {
    variations() {
      return this.data.attributes.variations
    }
  },
  methods: {
    getSelected(opt) {
      this.sel = opt.description
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false

Description parent :{{ sel }}

  <Dropdown
    :options="variations"
    :default="'Choose an option'"
    class="select"
    @input="getSelected"
  />

A: Instead of <"return this.product.attributes.variations.map(p => p.name)">, you could <"return this.product.attributes.variations">.
In that way, the options prop inside the Dropdown component will be an array of variations objects.
Then, you could access more info like this: option.name, option.description, etc....


text:
Q: DHCP option to control interface metric For some reason Windows is using only one interface for local network broadcasting (the one with lowest metrics). When client connects to VPN network, i want it to make new network preferred for broadcasting by changing metric value for 255.255.255.255 route on the  interface. Microsoft has a DHCP option that helps tweaking interface metric: Default Router Metric Base (http://msdn.microsoft.com/en-us/library/cc227277.aspx). However, i can't make it working.
Client is running Windows 8, but similar problem exists on Windows 7 (can't say for earlier versions, although it must be present, as Windows identifies itself as "MSFT 5.0" since Windows 2000). Server is ISC DHCP Server 4.2 (isc-dhcp42-server-4.2.4_2). Client connects to the  server through  OpenVPN tunnel and receives DHCP information. According to Wireshark capture vendor specific options are sent as well. But it does not make any difference, table is identical to the one without that vendor option being sent.
Here is DHCP config:
default-lease-time 600;
max-lease-time 7200;

authoritative;

log-facility local7;

option space ms-specific;
option ms-specific.metric-fix code 3 = unsigned integer 32;

subnet 172.16.130.0 netmask 255.255.255.0
{
  range 172.16.130.80 172.16.130.130;
  option routers 172.16.130.8;
  option broadcast-address 172.16.130.255;
  default-lease-time 600;
  max-lease-time 7200;
  vendor-option-space ms-specific;
  option ms-specific.metric-fix 1;
}

Here is client's routing table after connecting
         Address          Mask            Gateway        Interface    Metric
          0.0.0.0          0.0.0.0      172.16.13.8     172.16.13.80     20
          0.0.0.0          0.0.0.0     172.16.130.8    172.16.130.80     30
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    306
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    306
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    306
      172.16.13.0    255.255.255.0         On-link      172.16.13.80    276
     172.16.13.80  255.255.255.255         On-link      172.16.13.80    276
    172.16.13.255  255.255.255.255         On-link      172.16.13.80    276
     172.16.130.0    255.255.255.0         On-link     172.16.130.80    286
    172.16.130.80  255.255.255.255         On-link     172.16.130.80    286
   172.16.130.255  255.255.255.255         On-link     172.16.130.80    286
        224.0.0.0        240.0.0.0         On-link         127.0.0.1    306
        224.0.0.0        240.0.0.0         On-link      172.16.13.80    276
        224.0.0.0        240.0.0.0         On-link     172.16.130.80    286
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    306
  255.255.255.255  255.255.255.255         On-link      172.16.13.80    276
  255.255.255.255  255.255.255.255         On-link     172.16.130.80    286

172.16.13.0/24 is physical local network. 172.16.130.0/24 is VPN. As you can see, routes from physical local network have lower metric. I believe it should be possible to prioritize VPN because Hamachi, for example, also creates virtual interface with 'Automatic metric' turned on, but after connecting it always has lower metric than both physical network and OpenVPN tunnel. I tried changing adapter order in 'Advanced settings' in 'ncpa.cpl', but it also had no effect.
So, is there any way to make my OpenVPN tunnel preferred for 255.255.255.255 broadcasting? It would be excellent if i can do it on server side, so clients do not have to  adjust anything.


text:
Q: Read Text after custom word My goal is to find a way how to read the text after a word in a File. An example of this is:
Word("Text")
The output would be Text.
Is this achievable?

A: Cut your problem into small pieces:

*

*Read a text file

*Divide the text into a sequence of words

*Skip all words in the sequence until the word that you are looking for

*Use the rest of the sequence of words

Read the characters in a text file as a sequence of characters
public IEnumerable<char> ReadTextFile(string fileName)
{
    using (TextReader textReader = new StreamReader(fileName))
    {
        // read the characters one by one until there are no more character (= -1)
        int readResult = textReader.Read();
        while (readResult != -1);
        {
            yield return (char)readResult;
        }
    }
}

I decided to return a sequence of char instead of a string. This is a small optimization. If you decide not to read all characters, then not the complete file is read.
Divide a sequence of characters into a sequence of words.
The problem is: what is a word? Probably something like: all characters between two white spaces. Something special with the beginning and the end of the sequence.
But how about this: "Hello..World" Are these only the words "Hello" and "World", or is there also an empty word between the two dots? And what if the sequence of characters starts with a dot: ".Hello"?
I'll write this part as an extension method, so you can use it in a LINQ. If you are not familiar with extension methods, consider to read Extension methods demystified.
public static IEnumerable<string> ToWords(this IEnumerable<char> source)
{
    string word = String.Empty;
    foreach (char c in source)
    {
        if (Char.IsWhiteSpace(c))
        {
            // white space. only a word if already read something
            if (word.Length != 0)
            {
                yield return word
                word = String.Empty;
            }
            // else: the sequence starts with a white space: not a word
        }
        else
        {
            // not a white space: add the character to the word
            word = word + c;
        }
    }

    // if word not empty, then there were characters after the last whitespace
    // like: "Hello World". "Hello" already returned. "World" not yet
    if (word.Length != 0)
        yield return word;
}

Consider to optimize the word = word + c; part.
Use LINQ to concatenate what you want
string fileName = ...
string wordToFind = "Hello";

// in this example ignore case:
IEqualityComparer stringComparer = StringComparison.CurrentCultureIgnoreCase;
IEnumerable<string> wordsAfterHello = ReadTextFile(fileName)
    .ToWords()
    .SkipWhile(word => stringComparer.Equals(word, wordToFind);

Of course if you plan to use this often, you could write extension methods for this.


text:
Q: Prove that this set of points is finite or countable Let $X \subset \mathbb{R} $ be such that $|x-y| > 3 \ \  \forall x, y \in X, x \ne y$. Prove that $X$ is a finite or countable set.
Here, normally I would try to find a formula or any other reasonable way to build a bijection between the set and $\mathbb{N}$.
In this case, however, the approach when I tried to fix $y$ and then consider $x > y_0+3$ and $x < y_0 - 3$ and thus show that we can enumerate each set in the union with natural numbers resulted in a counter-intuitive conclusion.
How do I build the bijection in this case?

A: Consider all intervals $[n,n+1]$ ($n\in\Bbb Z$). If $X$ was uncountable, at least one of those intervals would have more than one element of $X$. Can you take it from here?

A: For each $n\in \Bbb Z$ there is at most one $x\in X\cap [n,n+3).$ So for $x\in X$ let $f(x)=n$ if $n\in\Bbb Z$ and $x\in [n,n+3).$ Then $f:X\to \Bbb Z$  is injective.


text:
Q: Bar chart in details band renders with final record data for each record I'm making a basic SQL-based report with Jasper Reports.  I've created a bar chart in the detail band using data from the main dataset query.  When I preview it with multiple rows of data returned, I get one graph per record, as expected, but the bars on the chart all reflect the final record of data - even though other text fields with field expressions show the correct values, even within the chart title itself!
I've been looking through the jaspersoft PDF docs a fair bit and tried playing with different values for the chart's evalationTime and its dataset's incrementType and resetType, but none of it seems to help, and I'm pretty sure the defaults are correct ("Now", "None" and "Report" respectively).
It seems like a workaround might be to make a subreport, which I haven't figured out yet, but it doesn't seem like this should be necessary - any ideas on what I'm doing wrong?

*

*report jrxml


text:
Q: Why does my Iframe load its page twice? When I land on the main page for the first time fiddler shows the iframe site loading once.  When I F5 or click back to the page it seems to load the site twice.
Fiddler shows that the first time has a symbol signifying it was aborted.

Explaining the points on the image

*

*The first time the page loaded the iframe page loaded fine (in this case its an ASP page, but it occurs for non ASP pages).

*On F5 page refresh this is my issue; the page loads but it looks like it was aborted.  I'm trying to figure out why.  Is it even an issue?  Will it cause extra resources to be used on the client/server?

*The page then loads fine.

My IFrame looks like this:

I've a watcher on ActiveLink and it only changes from undefined to defined once.
However I've added logging to the function trustSrc and it appears to be called 3 times.  I've no idea why yet.
The Iframe is added as a template URL within the app.js as such:
.state('Retrieved', {
      url: '/Retrieved',
      templateUrl: 'Scripts/AngularJs/Views/_GenericIframeContainer.html'
  })

I think that because the iframe is using ng-src the variable goes through the digest cycle and becomes evaluated.  Could it be that this evaluation is causing the iframe to reload?

A: The fix was to alter the angular JS (version 1.4.9) file that we use. Around line 20365 we replaced the following
attr.$set(name, value);

with (which adds a 10ms delay)
setTimeout(function () {
   attr.$set(name, value);
}, 10);

We also changed
if (msie && propName) element.prop(propName, attr[name]);

with
if (msie && propName && element[0].tagName !== 'IFRAME') element.prop(propName, attr[name]);

So it is probably a IE only issue.  The same code is in AngularJS 1.6.4
It seems like the issue is addressed here: https://github.com/angular/angular.js/issues/9843 but the fix wasn't in place IMO.


text:
Q: Importing images in SQL Server 2005 Dear All, I have another issue. I have in the SQL table Employees. This table has lot of details but I was missing images or photos.
So i managed to take all pictures for all employees but I have the pictures in the folder. Each picture is named like an Employee_id which matches the record in the table. How do I import images into SQL Employee table to match the name of the picture to Employee_id.
Any ideas?

A: A cursor and a bit of dynamic SQL should do the trick.
declare EmployeeCursor cursor fast_forward for
    select Employee_id
        from Employee

declare @sql nvarchar(4000)
declare @Employee_id int

open EmployeeCursor

while (1=1) begin
    fetch next from EmployeeCursor into @Employee_id

    if @@FETCH_STATUS<>0 break

    set @sql = N'UPDATE Employee
                     SET ImageColumn =
                         (SELECT * FROM
                              OPENROWSET(BULK N''c:\images\' + cast(@Employee_id as nvarchar(10)) + N'.jpg'', SINGLE_BLOB) AS img)
                              WHERE Employee_id = ' + cast(@Employee_id as nvarchar(10))

    exec(@sql)
end /* while */

close EmployeeCursor
deallocate EmployeeCursor

A: You can use OPENROWSET BULK to open an external file as a value for an INSERT or UPDATE.
Here's an example:
UPDATE Employees SET Picture=(SELECT * FROM OPENROWSET(BULK 'c:\temp\1234.jpg', SINGLE_BLOB) as Picture) WHERE Employee_id=1234


text:
Q: Handling time variables in R for ANOVA im relatively new to R. I´m doing an experiment where i measure the exact time where a couple of insects mate in 14 days in different luminic conditions (12:12H Light/Dark, Continious light, Continious dark).The idea is to analyze this data with ANOVA, but i'm having problems with the data. So I have a .csv file with 3 columns: Light condition, Date and Time. Date is not required for the analysis so i dont need it. But i have trouble converting the time data for a proper data R can work with. I've already tried read.csv(file="",stringsAsFactors = FALSE) but it doesnt work at all, I've also tried with lubridate , as.POSIX function and strptime() but nothing seems to work (or maybe im not converting the data at all for a proper analysis)
Thank you in advance.

A: It looks like you have date and time in two different columns and for time you have only hour and minutes. You can combine them using paste and convert to date time using appropriate format.
df$DateTime <- as.POSIXct(paste(df$Dia, df$Hora),
                         format = "%Y-%m-%d %H:%M",tz = "UTC")
#Can also use strptime
df$DateTime <- strptime(paste(df$Dia, df$Hora),
                       format = "%Y-%m-%d %H:%M", tz = "UTC")

Or with lubridate
df$DateTime <- lubridate::ymd_hm(paste(df$Dia, df$Hora))


text:
Q: Karate API framework - Validate randomly displayed items in response I am using Karate API framework for the API automation and came across with one scenario, the scenario is when I am hitting a post call it gives me some json response and few of the items are having tags whereas few of them are showing tags as blank to get all the tags below is the feature file scenario line
* def getTags = get response.items[*].resource.tags

It is giving me response as
[
[
],
[
],
[
  {
   "tags" : "Entertainment"
  }
],
[
],
[
  {
   "tags" : "Family"
  }
],

As you can see out of 5 or 6 tags only 2 tags are having the value, so I want to capture if any tags value is showing or not. What would be the logic for the assertion considering these tags can all come as empty and sometimes with come with a string value. In above case "Family" & "Entertainment"
Thanks in advance !

A: * match each response.items[*].resource.tags == "##string"

This will validate that tags either doesn't exist or is a string.

A: I think you can use a second variable to strip out the empties, or maybe your original JsonPath should use .., you can experiment:
* def allowed = ['Music', 'Entertainment', 'Documentaries', 'Family']
* def response =
"""
[
   [

   ],
   [

   ],
   [
      {
         "tags":"Entertainment"
      }
   ],
   [

   ],
   [
      {
         "tags":"Family"
      }
   ]
]
"""
* def temp = get response..tags
* print temp
* match each temp == "#? allowed.contains(_)"


text:
Q: Average number of skipped steps We have a probability space $(\Omega, \mathbb{P})$ and a sequence of random variables $(s(\cdot \ ; i,k))_{i\ge 1, 0\le k\le i}$ such that, for each $i,k$, $s(\cdot \ ; i,k):\Omega \rightarrow \{j\in\mathbb{N}\mid j\ge i\}$, i.e. each random variable $s(\cdot \ ; i,k)$ takes values in the set of integers greater or equal to $i$. We can assume that $i = \mathbb{E}[s(\cdot \ ; i,0)] < \mathbb{E}[s(\cdot \ ; i,1)]<\dots < \mathbb{E}[s(\cdot \ ; i,i)] < +\infty$ for all $i$ and that all these random variables are independent from each other.
Lets take $X: \Omega \rightarrow \mathbb{N}_{>0}$ defined as follows:
$$X(\omega) = \begin{cases}
n &\text{if } \exists J \text{ with } 1<J<+\infty, \ \exists (r_j)_{j=0}^J \\ &\text{ s.t. } r_0 = 0, r_1 = 1\\ &\text{ and } r_{j} = s(\omega; r_{j-1},r_{j-1}-r_{j-2}) > r_{j-1} \text{ for all } 1<j < J\\ &\text{ and } r_{J} = s(\omega; r_{J-1},r_{J-1}-r_{J-2}) = r_{J-1}=n\\[1em]
+\infty &\text{otherwise}
\end{cases}$$

An intuitive interpretation of this random variables (that is not meant to be taken too seriously) is that we are dropping a ball down an infinite descending (not uniform) ladder, whose steps are indexed by integers (starting from stair 0), and the random variable $s(\omega; i,k)$ express the index of the successive step the ball bounces to once it has hit the $i$-th step coming from the $(i-k)$-th step. Then the variable $X(\omega)$ express the index of the stair over which the ball stops.
My question are:

*

*Does this random variable $X$ remind you anything known?

*Do we have $\mathbb{E}[X] < +\infty$? Under which conditions?

*Can we express $\mathbb{E}[X]$ in a nice form (e.g. dependent from the averages of the $s(\omega; k,i)$s)?

Thanks!


text:
Q: how to fetch json data and store it in an array in iphone app and access it I am using this code to access the json data.  It shows the two objects in array but then stops
SBJsonParser *parser = [[SBJsonParser alloc] init];

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://celeritas-solutions.com/emrapp/AppointmentListings.php"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *object = [parser objectWithString:json_string error:nil];
//appDelegate.books = [[NSMutableArray alloc] initWithCapacity:0];

appDelegate.books = [[NSMutableArray alloc] init];

NSArray *results = [parser objectWithString:json_string error:nil];
NSLog(@"%@", results);

for (int i=0; i<[results count]; i++) {
    AppointmentListing *aBook = [[AppointmentListing alloc] initWithDictionary:[results objectAtIndex:i]];
    [appDelegate.books addObject:aBook];
    [aBook release];
}

Below is my json data
[{"ProviderNPI":"7610922880","PatientID":"556712","AppointmentDate":"2012-03-20","AppointmentTime":"09:00:00","AppointmentListingsID":"1","UpdateDateTime":"2012-03-20 00:30:35"},{"ProviderNPI":"7610922880","PatientID":"712211","AppointmentDate":"2012-03-20","AppointmentTime":"10:00:00","AppointmentListingsID":"2","UpdateDateTime":"2012-03-20 00:31:25"}]

A: Just copy & paste  & replace to your code will solve your problem :
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://celeritas-solutions.com/emrapp/AppointmentListings.php"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSArray *books=[json_string JSONValue];

for (int i=0; i<[books count]; i++) {
    /*AppointmentListing  *aBook = [[AppointmentListing alloc] initWithDictionary:[books objectAtIndex:i]];
    [books addObject:aBook];
    [aBook release];*/

    NSDictionary *dict=[books objectAtIndex:i];

    book.appointmentdate=[dict valueForKey:@"AppointmentDate"];
    book.AppointmentListingsID=[dict valueForKey:@"AppointmentListingsID"];
    book.AppointmentTime=[dict valueForKey:@"AppointmentTime"];
    book.PatientID=[dict valueForKey:@"PatientID"];
    book.ProviderNPI=[dict valueForKey:@"ProviderNPI"];
    book.UpdateDateTime=[dict valueForKey:@"UpdateDateTime"];

    NSLog([dict description],nil);
}

NSLog(@"%@", json_string);

//May this will help you out.
//You just need to import "Json.h" to your class header

//Log I got from this piece of code :
2012-03-21 14:34:34.841 ProgressiveDownload[1045:f803] {
    AppointmentDate = "2012-03-20";
    AppointmentListingsID = 1;
    AppointmentTime = "09:00:00";
    PatientID = 556712;
    ProviderNPI = 7610922880;
    UpdateDateTime = "2012-03-20 00:30:35";
}

2012-03-21 14:34:37.356 ProgressiveDownload[1045:f803] {
    AppointmentDate = "2012-03-20";
    AppointmentListingsID = 2;
    AppointmentTime = "10:00:00";
    PatientID = 712211;
    ProviderNPI = 7610922880;
   UpdateDateTime = "2012-03-20 00:31:25";
}

A: From your code I presume that you are using that JSON folder for json parsing, containing many Json Parser related file...
Do one thing, First import JSON.h file:
#import "JSON.h"

Then parse your response string like this,
first create an object like this:
SBJSON *json = [[SBJSON new] autorelease];
NSDictionary *response_dict = [json objectWithString:json_string];

And you're done!!!

A: NSMutableData *responseData1= [NSMutableData data] ;
responseData1 = [NSMutableData dataWithContentsOfURL:[NSURL URLWithString:@"http://celeritas-solutions.com/emrapp/AppointmentListings.php"]];
// NSLog(@"%@",responseData1);
NSString *responseString1 = [[NSString alloc] initWithData:responseData1 encoding:NSUTF8StringEncoding];
//NSLog(@"REs:-->%@",responseString1);
//[responseData1 release];
responseData1 = nil;
NSMutableArray *responseArray = [[NSMutableArray alloc]init];
responseArray = (NSMutableArray *)[responseString1 JSONValue];
// NSLog(@"ghfchfvghv%@",responseArray);
//[responseString1 release];
//return responseArray;
NSLog(@"%@",[responseArray description]);

A: //This is for the Dictionary You can use in the same way for Array.
NSString *url = @"http://weather.yahooapis.com/forecastjson?w=22117";
NSString *myJson=[[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:url]];

if([myJson length]==0)
{
    [myJson release];
    return;
}
SBJsonParser *praser=[[SBJsonParser alloc]init];
    NSDictionary *dicParser=[[praser objectWithString:myJson error:nil] copy];


text:
Q: What is the difference between maven publish with artifact() and components? When you want to publish your library, there are two ways to do it.

*

*Using artifact()

publishing {
    publications {
        aar(MavenPublication) {
            groupId packageName
            version = libraryVersion
            artifactId project.getName()

            // Tell maven to prepare the generated "*.aar" file for publishing
            artifact("$buildDir/outputs/aar/${project.getName()}-release.aar")

            pom.withXml {
                def dependencies = asNode().appendNode('dependencies')
                configurations.getByName("_releaseCompile").getResolvedConfiguration().getFirstLevelModuleDependencies().each {
                    def dependency = dependencies.appendNode('dependency')
                    dependency.appendNode('groupId', it.moduleGroup)
                    dependency.appendNode('artifactId', it.moduleName)
                    dependency.appendNode('version', it.moduleVersion)
                }
            }
        }
    }
}

*Using components:

afterEvaluate {
    publishing {
        publications {
            release(MavenPublication) {
                groupId = "com.app.core"
                artifactId = project.name
                version = "1.0.1"

                from components.release
            }
        }
        artifactoryPublish {
            publications(publishing.publications.release)
        }
    }
}

I read some blog posts and they mention that pom.withXml needs to be included in order to include the transitive dependencies. i.e if your library uses a third party dependency, then it will not included if you don't use the pom.withXml section and app will crash on runtime.
When you use components definition, it automatically includes the transitive dependencies. I couldn't find any documentation on usage of these APIs. What is actually the components definition is doing? What is the difference between using components and artifact definitions?


text:
Q: Regex python extracting between two fields Hello I have a text file like such
"text": "Tart\u0131\u015fmal\u0131 kararlara Deniz \u00c7oban yorumu Tart\u0131\u015fmal\u0131 kararlara Deniz \u00c7oban yorumu 19 Ocak 2021 21:14 beIN SPORTS yorumcusu Deniz \u00c7oban, S\u00fcper Lig 'de g\u00fcn\u00fcn kar\u015f\u0131la\u015fmalar\u0131nda ya\u015fanan tart\u0131\u015fmal\u0131 hakem pozisyonlar\u0131n\u0131 yorumlad\u0131. \u0130lgili Haberler", "country": "TR",

and I want to grab
"Tart\u0131\u015fmal\u0131 kararlara Deniz \u00c7oban yorumu Tart\u0131\u015fmal\u0131 kararlara Deniz \u00c7oban yorumu 19 Ocak 2021 21:14 beIN SPORTS yorumcusu Deniz \u00c7oban, S\u00fcper Lig 'de g\u00fcn\u00fcn kar\u015f\u0131la\u015fmalar\u0131nda ya\u015fanan tart\u0131\u015fmal\u0131 hakem pozisyonlar\u0131n\u0131 yorumlad\u0131. \u0130lgili Haberler"

I have
(?<="text": ")[^"]*

This pattern produces
Tart\u0131\u015fmal\u0131 kararlara Deniz \u00c7oban yorumu Tart\u0131\u015fmal\u0131 kararlara Deniz \u00c7oban yorumu 19 Ocak 2021 21:14 beIN SPORTS yorumcusu Deniz \u00c7oban, S\u00fcper Lig 'de g\u00fcn\u00fcn kar\u015f\u0131la\u015fmalar\u0131nda ya\u015fanan tart\u0131\u015fmal\u0131 hakem pozisyonlar\u0131n\u0131 yorumlad\u0131. \u0130lgili Haberler

How should I change my regex pattern so that it includes the chat marks "..."?

A: Use
re.findall(r'"text":\s*("[^"]*")', s)

See regex proof.
EXPLANATION
--------------------------------------------------------------------------------
  "text":                  '"text":'
--------------------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    "                        '"'
--------------------------------------------------------------------------------
    [^"]*                    any character except: '"' (0 or more
                             times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
    "                        '"'
--------------------------------------------------------------------------------
  )                        end of \1

See Python proof:
import re

regex = r'"text":\s*("[^"]*")'

s = " \"text\": \"Tart\\u0131\\u015fmal\\u0131 kararlara Deniz \\u00c7oban yorumu Tart\\u0131\\u015fmal\\u0131 kararlara Deniz \\u00c7oban yorumu 19 Ocak 2021 21:14 beIN SPORTS yorumcusu Deniz \\u00c7oban, S\\u00fcper Lig 'de g\\u00fcn\\u00fcn kar\\u015f\\u0131la\\u015fmalar\\u0131nda ya\\u015fanan tart\\u0131\\u015fmal\\u0131 hakem pozisyonlar\\u0131n\\u0131 yorumlad\\u0131. \\u0130lgili Haberler\", \"country\": \"TR\", \"lan\": \"turkish\", \"url\": \"https://tr.beinsports.com/haber/tartismali-kararlara-deniz-coban-yorumu-23\", \"img_src\": \"https://media04.ligtv.com.tr/img/news/2021/1/20/tartismali-kararlara-deniz-coban-yorumu-23/748_416/tart.jpg\"}, {\"uuid\": \"d6af15db0375a93056c5ab330f13d59f92570415\", \"author\": \"\", \"published\": \"2021-01-19T23:05:00.000+02:00\", \"text\": \"Mart\\u0102\\u00adn P\\u0102\\u0160rez Padr\\u0102\\u0142n, entrenador del equipo femenil de Santos - Mexsport Fallece Mart\\u0102\\u00adn P\\u0102\\u0160rez t\\u0102\\u0160cnico de Santos por Covid-19 El ex entrenador del Club Santos Laguna Femenil ten\\u0102\\u00ada 57 a\\u0102\\u0105os y ten\\u0102\\u00ada experiencia en los banquillos de Cruz Azul Hidalgo y en Fuerzas B\\u0102\\u0104sicas Por Publisport Martes 19 de enero de 2021, a las 14:54 Mart\\u0102\\u00adn P\\u0102\\u0160rez Padr\\u0102\\u0142n, entrenador del equipo femenil de Santos - Mexsport Multicontactos contra supresor de picos:\\u00c2 lo que necesitas saber para mantenerte protegido\\nEl Santos dio a conocer este martes el fallecimiento de Mart\\u0102\\u00adn P\\u0102\\u0160rez Padr\\u0102\\u0142n, entrenador del equipo femenil de la instituci\\u0102\\u0142n. El equipo lagunero lament\\u0102\\u0142 la muerte de Mart\\u0102\\u00adn P\\u0102\\u0160rez y envi\\u0102\\u0142 su p\\u0102\\u0160same a la familia del director t\\u0102\\u0160cnico.\\n\\u00e2\\u0080\\u009cMart\\u0102\\u00adn P\\u0102\\u0160rez, quien fue un gran ser humano y excelente compa\\u0102\\u0105ero, sigui\\u0102\\u0142 todos los protocolos y tratamientos correspondientes; sin embargo, al final fue una v\\u0102\\u00adctima m\\u0102\\u0104s de esta pandemia que aqueja no solamente al pa\\u0102\\u00ads, sino a todo el mundo\\u00e2\\u0080\\u009d, indic\\u0102\\u0142 Santos en un comunicados. Lamentamos el sensible fallecimiento de nuestro Director T\\u0102\\u0160cnico, @Perezpadron64 .\\nNos unimos en oraci\\u0102\\u0142n por su eterno descanso.\\nDescansa en paz, Mart\\u0102\\u00adn. \\u00c2\\u0104Siempre ser\\u0102\\u0104s un #Guerrero ! \\u0111\\u009f\\u0099\\u008f pic.twitter.com/ZrcgTYheAC \\u00c2\\u017cQu\\u0102\\u0160 diferencia hay entre IQOS y los vapeadores? \\u00c2 Ent\\u0102\\u0160rate aqu\\u0102\\u00ad\\nTambi\\u0102\\u0160n hicieron un llamado a la poblaci\\u0102\\u0142n para redoblar esfuerzos y cumplir con todas las medidas de prevenci\\u0102\\u0142n.\\nMart\\u0102\\u00adn P\\u0102\\u0160rez Padr\\u0102\\u0142n, dirigi\\u0102\\u0142 25 encuentro con las Guerreras en dos torneos, en donde sum\\u0102\\u0142 cinco victorias, siete empates y 13 derrotas.\\nEntre sus equipos que dirigi\\u0102\\u0142 se encuentra Cruz Azul Hidalgo, \\u0102\\u0081guilas Reales de Zacatecas, Orizaba y las fuerzas b\\u0102\\u0104sicas de Santos Laguna.\\nP\\u0102\\u0160rez Padr\\u0102\\u0142n fue uno de los casos anunciados en el inicio del Guardianes 2021 por la instituci\\u0102\\u0142n lagunera. Un profundo dolor para toda la familia @Orlegi_Sports y del f\\u0102\\u015ftbol mexicano\\u2026\\nDescansa en paz, Mart\\u0102\\u00adn P\\u0102\\u0160rez Padr\\u0102\\u0142n. \\u0111\\u009f\\u0099\\u008f pic.twitter.com/V6eP8LxPaO\\n\\u2014 Atlas FC Femenil (@AtlasFCFemenil) January 19, 2021 La Familia de la LIGA MX Femenil Lamenta Profundamente el Fallecimiento de Mart\\u0102\\u00adn P\\u0102\\u0160rez Padr\\u0102\\u0142n, Estratega del @ClubSantosFem pic.twitter.com/WXcil9Ld7m Nos unimos a la pena que embarga a la familia del f\\u0102\\u015ftbol por el fallecimiento de Mart\\u0102\\u00adn P\\u0102\\u0160rez Padr\\u0102\\u0142n, Director T\\u0102\\u0160cnico del Club Santos Laguna Femenil.\\nPronta resignaci\\u0102\\u0142n a familiares y amigos. QEPD. #FMFporNuestroF\\u0102\\u015ftbol pic.twitter.com/5KB55Ecfz9\\n\\u2014 Federaci\\u0102\\u0142n Mexicana de F\\u0102\\u015ftbol (@FMF) January 19, 2021 Publimetro te recomienda\","

print(re.findall(regex, s))


text:
Q: Getting Classcast exception on calling Session.openActiveSession of facebook sdk for android I am working on a application in which i want to show the friend list of the user and select one of them and show it on my screen. But when i call Session.openActiveSession to get the active session because user is not logged in yet it gives me a Exception "Key protocol version expected String but value was Integer". But when i further investigate it on multiple devices it comes on only those devices that doesn't have facebook application installed. So my question is what to do to show a friend list in this case.
Thanks.

A: The Key protocol version expected String but value was Integer it is not an error from your part. It is an error from the Facebook SDK itself. I had thought it was an error that wasn't allowing me to log in, but it turns out it is not. Check this link and look at the answer by hakanostrom.


text:
Q: Display zip codes based on selected states I would like to know whats the best way to display zip codes based on selected state.
I have a database in MySQL with all cities and zip codes from the USA.  I would like to make a query to mysql which I already have, but to display the data, for example if I select from a drop-down box - state Florida, I want to display all cities, then I select city and then display all zip codes..

*

*select a state (cities appear)

*select city (zip codes appear)

*zip codes (only a few that are allowed)

A: Just have a column for every entry in the table for state as well? Then do something like
select city from your_table where state=thestateselected

This will display all cities.
Then do something similar for the zip codes to get all zip codes in the city
select zipcode from your_table where city=thecityselected


text:
Q: datetimepicker not taking runtime minDate & maxDate I am trying to pass startDate and endDate as per my active academic value (i.e. 2016-04-01 to 2017-03-31). I have successfully passed these values in request parameter and getting that on the jsp page as shown below:
<input type="hidden" id="startDate" value="<%=request.getParameter("startDate")%>">
<input type="hidden" id="endDate" value="<%=request.getParameter("endDate")%>">

Now, I am trying to use this value on the datetimepicker so restrict the calendar view. If I pass this value as shown below, the calendar is not getting opened.
<script>
$('#datetimepicker').datetimepicker({
dayOfWeekStart : 1,
lang:'en',
timepicker:false,
format:'Y/m/d',
closeOnDateSelect:true,
minDate:$('#startDate').val(),
maxDate:$('#endDate').val(),
});
</script>

I tried to show these values on alert as shown below and I am able to get the correct values:
alert($('#startDate').val() + " : " + $('#endDate').val());

I also tried by passing hard-coded values on calendar script as shown below and it is working fine:
<script>
$('#datetimepicker').datetimepicker({
dayOfWeekStart : 1,
lang:'en',
timepicker:false,
format:'Y/m/d',
closeOnDateSelect:true,
minDate:'2016/04/01',
maxDate:'2017/03/31',
});
</script>

The Problem in Short: The calendar is not functioning if I try to use minDate and maxDate from the values that I stored on hidden variable.
Kindly help.


text:
Q: How to Use df.to_sql and Export Data With Two Indexes to a Table in SQL Server? I have a data frame with two indexes, and I am trying to export it to a SQL Server table.  Here is the code that I am using.
grouped_and_summed.to_sql(x, engine, if_exists='append', index=True, index_label=None)

The 'x' variable is the name of the table and the 'engine' variable comes form here.
engine = "mssql+pyodbc://MyServerName/MyTableName?driver=SQL Server Native Client 11.0?trusted_connection=yes"

When I have just one index, and export the results to a SQL Server table, everything works fine.  When I have two indexes and export the results to a CSV, everything works just fine.  I have problems exporting a DF with two indexes to a SQL Server table.  I read through the documentation here.
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html
The documentation says 'A sequence should be given if the DataFrame uses MultiIndex'.  I'm not sure what that means.  I'm not sure how to to handle that in Python code.  Any thoughts, anyone?

A: try to set index_label=['MultiIndex1 name', 'MultiIndex2 name']


text:
Q: Converting JSON files to Parquet format through avro format I have a huge number of JSON files, all the JSON files contain a subset of ~200 attributes, most of which are complex attributes (the attribute has multiple nested attributes). Not all the attributes are necessarily present in all the JSON files.
I want to convert these JSONs to Parquet formatted file, searching for a way to do this, I found out that I need to convert the JSONs to avro format, then convert the avro formatted data to Parquet format.
My problem is that I can't find a way to extract the avro schema, trying to use JsonUtil.inferSchema will not work since not all the attributes are present in every json file. I have the attributes present in POJO java class in a library, but using avro reflection to get the schema does not work because the pojo has generics in it, which is still not supported in avro. My last resort will be to write the schema manually but it is going to be very time consuming.
Is there any other way to get the avro schema? This is a problem that I have been trying to find a solution to for the past two days and is frustrating me.


text:
Q: Is it possible to change the constraint in the optimization problem in following way? I want to solve an optimization problem. One of the constraint is given as follows $$\max(0,g(x))\geq c_1$$ where $c_1\geq 0$ and $g(x)$ is a concave function which can also have negative values. For any $c_1>0$ can I change the above constraint to the following constraint? $$g(x)\geq c_1$$ I will be very thankful for your help in this regard.

A: For a particular $x$, if $g(x)<0$, then $\max(0, g(x)) = 0$ and hence $0\ge c_1$ doesn't hold. Hence if $g(x)<0$,  then $x$ is not feasible.
Hence for $x$ to be feasible, we need $g(x) \geq 0$, that is $\max(0, g(x)) = g(x).$
Hence, yes, you can change the constraint to $g(x) \ge c_1$.


text:
Q: How to access the elements by index number from a list of intervals? I encountered this while solving a data structures problem, which says
given a list of intervals: a = [(1,4),(3,5),(4,8)]
Here (1,4) means an interval of numbers from 1 to 4.
How do I access the elements using their index numbers from this list?
a[i][j] doesn't work for me.
Edit: found the solution (python), in case anyone else is looking for the same:
a = [(1,4),(2,6),(9,11)]

for i in range(len(a)):
    #to print first number from the interval
    print(a[i][0])
    #to print second number from the interval
    print(a[i][1])

A: a = [(1,4),(3,5),(4,8)]
for interval in a:
    for each in interval:
        print(each)


text:
Q: Transposing JSONB Array Elements - Postgres 11.5? I have a table the structure is defined as below
CREATE TABLE logs (
    logid uuid NOT NULL,
    logjson jsonb NOT NULL,
    createdtime timestamp NOT NULL
);

The sample JSONB string is shown below
{
    "RouteId": "353f89f5-b414-40cd-bd19-20378d51e723",
    "RouteName": "GetPickCompleteMessages",
    "CustomLinks": {
    },
    "MachineName": "12ws3",
    "DataBaseTimings": [
        {
            "ApiMethod": null,
            "ExecuteType": "OpenAsync",
            "CommandString": "Connection OpenAsync()",
            "DurationMilliseconds": 1138.5,
        },
        {
            "ApiMethod": null,
            "ExecuteType": "Reader",
            "CommandString": "GetPckg",
            "DurationMilliseconds": 124.5,
        },
            {
            "ApiMethod": null,
            "ExecuteType": "Close",
            "CommandString": "Connection Close()",
            "DurationMilliseconds": 27.9,
        }

    ],
    "DurationMilliseconds": 1546.2
}

I am looking for an output in this manner
| RouteName                 | OpenAsyncTime | ReaderTime | CloseTime | TotalDuration |
--------------------------------------------------------------------------------------
| GetPickCompleteMessages   |    1138.5     | 124.5      | 27.9      |  1546.2       |
--------------------------------------------------------------------------------------

Any pointers on this is greatly appreciated.
Also how do I extend the solution if there were multiple arrays. By multiple arrays this is what I mean
{
    "RouteId": "353f89f5-b414-40cd-bd19-20378d51e723",
    "RouteName": "GetPickCompleteMessages",
    "CustomLinks": {
    },
    "MachineName": "12ws3",
    "ChildProfiles": [
        {
            "ApiMethod": "PublishShipViaRequestToQueue",
            "DurationMilliseconds": 0.1,
        }
    ],
    "DataBaseTimings": [
        {
            "ApiMethod": null,
            "ExecuteType": "OpenAsync",
            "CommandString": "Connection OpenAsync()",
            "DurationMilliseconds": 1138.5,
        },
        {
            "ApiMethod": null,
            "ExecuteType": "Reader",
            "CommandString": "GetPckg",
            "DurationMilliseconds": 124.5,
        },
            {
            "ApiMethod": null,
            "ExecuteType": "Close",
            "CommandString": "Connection Close()",
            "DurationMilliseconds": 27.9,
        }

    ],
    "DurationMilliseconds": 1546.3
}

The output needs to be in this fashion
| RouteName                          | PublishShipViaRequestToQueueTime | OpenAsyncTime | ReaderTime | CloseTime | TotalDuration |
-----------------------------------------------------------------------------------------------------------------------------------
| GenerateRequestAndPublishToQueue   |    0.1                           | 1138.5        | 124.5       | 27.9      |  1546.3       |
------------------------------------------------------------------------------------------------------------------------------------

Thanking you in advance

A: I think a few json accesses should do it:
SELECT
   logjson -> 'RouteName' AS "RouteName",
   logjson -> 'DataBaseTimings' -> 0 -> 'DurationMilliseconds' AS "OpenAsyncTime",
   logjson -> 'DataBaseTimings' -> 1 -> 'DurationMilliseconds' AS "ReaderTime",
   logjson -> 'DataBaseTimings' -> 2 -> 'DurationMilliseconds' AS "CloseTime",
   logjson -> 'DurationMilliseconds' AS "TotalDuration"
FROM
   logs

If that doesn't cut it because the indices are not known, you'd have to do subqueries on the json array:
SELECT
   logjson -> 'RouteName' AS "RouteName",
   (SELECT el -> 'DurationMilliseconds'
       FROM jsonb_array_elements(logjson -> 'DataBaseTimings') el
       WHERE el ->> 'ExecuteType' = 'OpenAsync'
   ) AS "OpenAsyncTime",
   (SELECT el -> 'DurationMilliseconds'
       FROM jsonb_array_elements(logjson -> 'DataBaseTimings') el
       WHERE el ->> 'ExecuteType' = 'Reader'
   ) AS "ReaderTime",
   (SELECT el -> 'DurationMilliseconds'
       FROM jsonb_array_elements(logjson -> 'DataBaseTimings') el
       WHERE el ->> 'ExecuteType' = 'Close'
   ) AS "CloseTime",
   logjson -> 'DurationMilliseconds' AS "TotalDuration"
FROM
   logs

Or do it the fancy way and use
SELECT
   logjson -> 'RouteName' AS "RouteName",
   typed_values -> 'OpenAsync' AS "OpenAsyncTime",
   typed_values -> 'Reader' AS "ReaderTime",
   typed_values -> 'Close' AS "CloseTime",
   logjson -> 'DurationMilliseconds' AS "TotalDuration"
FROM
   logs,
   LATERAL (
       SELECT jsonb_object_agg(el ->> 'ExecuteType', el -> 'DurationMilliseconds') AS typed_values
       FROM jsonb_array_elements(logjson -> 'DataBaseTimings') el
   ) AS t


text:
Q: When should I NOT use App Engine's Full Text Search API? So far, I've used App Engine's Full Text Search to help search through existing entities in my datastore. This involves creating at least one Document per entity, and linking the two together somehow. And every time I change the entity, I must change the corresponding Documents.
My question is, why not just store all my data in Documents and forget about Datastore entities? The search API supports a much richer query language that can handle multiple inequality filters and boolean operators, unlike the datastore.
Am I missing something about the design of the search API that would preclude using it to replace the Datastore entirely?

A: According to the Java docs

However, an index search can find no more than 10,000 matching
  documents. The App Engine Datastore may be more appropriate for
  applications that need to retrieve very large result sets.

Though I don't see that as a common use case.
More realistically, getting entities by key will be a lot cheaper with the Datastore (presumably faster as well). With the search API, you can either use Index.get() to find a document by ID, or duplicate the ID by storing it in a field and searching on that field.
Here's a cost breakdown:
- Index.get():     $0.10 /  10,000 or 0.00001 per get
- Index.search():  $0.13 /  10,000 or 0.000013 per get
- Datastore get(): $0.06 / 100,000 or 0.0000006 per get

As you can see, a Datastore get is much cheaper than the Search API options (16x cheaper than Index.get()).
If your data is structured in a way that makes use of a lot of direct gets and few complex searches, the Datastore will be a clear winner in terms of cost.
Note: I did not include the extra cost for storing duplicate data with the Index.search() method, since that depends on how many entities you store.

A: Just put the data in both - the storage is cheap and depending how much writes your app does it could be cheap to do updates as well. For easy queries and getting single entities by key - use memcache and datastore. For complex queries use search api. You'll have to make the tradeoff once pricing is announced.

A: right now indexing an entity in the searchdoc every time i put it and i also index a serialized version of the entity.
its actually much much faster searching for documents over the search api and extracting the serialized field than getting the same amount of entities from the datastore.

A: Wouldn't you:

*

*lose any benefits of memcache

*face lower quotas.  "we expect that our free quota will cover about 1,000 searches per day once the feature has graduated from experimental"  I can't see the number of reads you get but I believe it's higher for datastore.  I looked at https://developers.google.com/appengine/docs/quotas#Resources
Also, for an entity update, we are charged differently by update or new put.  It seems the indexes are not updated but rather added as a new document (that's what I'm doing anyway).  Not having the details of index pricing, it's difficult to know exactly but perhaps updating one or two indexed values on an entity would be cheaper that putting a new whole index.  It would depend on your data I guess.
Finally, the Total Index Size for indexes is now at 250M while data is capped at 1 GB.  The datastore is larger then and no word yet on additional pricing costs for the index.

*need to come up with a backup plan.  I don't know anyway now to backup or restore the index if it got corrupted.  Having the data in entities means the search index could be recreated.  You can backup with the admin console for the datastore now.

A: In addition to performance costs for querying large sets of data, the datastore also has the advantage of allowing strongly consistent data. Take a look at this link for more information on strongly consistent vs. eventual consistent data.
It should be assumed that documents stored in the Search API indexes are eventually consistent.


text:
Q: Duplicate entries for derived navigation properties in EF Core 6 I have an .NET 6 API server (currently) using a local instance of SQL Server.  All non-Image entities derive from the 'EntityBase' class, which is not defined as a physical table.  The Images table uses both a Foreign Key column of EntityBaseId and discriminator columns which also contain the Id of the parent entity, as shown in the Images table below.
The three classes in question are as follows:
public abstract class EntityBase
{
    public int Id { get; set; } = default;

    public Guid EntityCode { get; set; } = Guid.NewGuid();
    public bool IsActive { get; set; } = false;
    public DateTimeOffset CreateDate { get; set; } = DateTimeOffset.Now;
    public DateTimeOffset UpdateDate { get; set; } = DateTimeOffset.Now;

    public List<Image> Images { get; set; } = new List<Image>();
}

public class Person: EntityBase
{
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
    public string? Title { get; set; }
    public string? EmailAddress { get; set; }
    public string? MobileNumber { get; set; }
    public int CurrentAddressId { get; set; }
}

public class Image
{
    public int Id { get; set; }

    public EntityBaseType ParentType { get; set; }
    public string? CloudUri { get; set; }
    public string? CloudThumbnailUri { get; set; }
    public bool IsThumbnail { get; set; }
    public DateTimeOffset CreateDate { get; set; }
    public string? Description { get; set; }
    public int Order { get; set; }
    public int Height { get; set; }
    public int Width { get; set; }
    public string? Breakpoints { get; set; }

    public int EntityBaseId { get; set; }
    [JsonIgnore]
    public EntityBase? EntityBase { get; set; }
}

From my dbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Ignore<EntityBase>();
    modelBuilder.Entity<Image>().ToTable("Images");
    modelBuilder.Entity<Job>().ToTable("Jobs");
    modelBuilder.Entity<JobChangeItem>().ToTable("JobChangeItems");
    modelBuilder.Entity<JobNote>().ToTable("JobNotes");
    modelBuilder.Entity<Location>().ToTable("Locations");
    modelBuilder.Entity<Person>().ToTable("People");
    base.OnModelCreating(modelBuilder);
}

public DbSet<Image> Images => Set<Image>();
public DbSet<Job> Jobs => Set<Job>();
public DbSet<JobChangeItem> JobChangeItems => Set<JobChangeItem>();
public DbSet<JobNote> JobNotes => Set<JobNote>();
public DbSet<Location> Locations => Set<Location>();
public DbSet<Person> People => Set<Person>();

And my controller action:
    [HttpPut("{id}")]
    public async Task<IActionResult> PutPerson(int id, Person Person)
    {
        if (id != Person.Id)
        {
            return BadRequest();
        }

        var existingPerson = _context.People
            .Include(i => i.Images)
            .FirstOrDefault(f => f.Id == id);

        existingPerson!.CurrentAddressId = Person!.CurrentAddressId;
        existingPerson!.EmailAddress = Person!.EmailAddress;
        existingPerson!.IsActive = Person!.IsActive;
        existingPerson!.CreateDate = Person!.CreateDate;
        existingPerson!.EntityCode = Person!.EntityCode;
        existingPerson!.FirstName = Person!.FirstName;
        existingPerson!.Id = Person!.Id;
        existingPerson!.LastName = Person!.LastName;
        existingPerson!.MobileNumber = Person!.MobileNumber;
        existingPerson!.Title = Person!.Title;
        existingPerson!.UpdateDate = Person!.UpdateDate;

        foreach (Image image in Person!.Images)
        {
            //image!.EntityBaseId = Person!.Id;
            //_context.Images.Attach(image);
            existingPerson!.Images.Add(image);

        }

        //_context.People.Update(Person);

        //existingPerson.Images = Person!.Images;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException ex)
        {
            if (!PersonExists(id))
            {
                return NotFound();
            }
            else
            {
                throw ex;
            }
        }

        return NoContent();
    }

SQL People table:
TABLE_NAME  COLUMN_NAME DATA_TYPE
People  Id  int
People  FirstName   nvarchar
People  LastName    nvarchar
People  Title   nvarchar
People  EmailAddress    nvarchar
People  MobileNumber    nvarchar
People  CurrentAddressId    int
People  EntityCode  uniqueidentifier
People  IsActive    bit
People  CreateDate  datetimeoffset
People  UpdateDate  datetimeoffset

SQL Images table:
TABLE_NAME  COLUMN_NAME DATA_TYPE
Images  Id  int
Images  ParentType  int
Images  CloudUri    nvarchar
Images  IsThumbnail bit
Images  CreateDate  datetimeoffset
Images  Description nvarchar
Images  Order   int
Images  Bytes   bigint
Images  Format  nvarchar
Images  Path    nvarchar
Images  PublicId    nvarchar
Images  ResourceType    nvarchar
Images  Signature   nvarchar
Images  Type    nvarchar
Images  Version int
Images  VersionId   nvarchar
Images  Height  int
Images  Width   int
Images  Breakpoints nvarchar
Images  EntityBaseId    int
Images  LocationId  int
Images  PersonId    int
Images  CloudThumbnailUri   nvarchar

I've verified the incoming Person entity contains only one Image.  I've also verified the attached existingPerson entity contains no Images before adding the Image and only one Image after the foreach() loop has completed.
Thus far, I've tried many variations of Attach, changing State, Add, Update, etc. to no avail while updating the Person entity and one Image navigation property.  Each attempt either produces no Image or duplicate Images in the database.

*

*Duplication is of the entire row with the exception of the Image
primary key, of course.  Both the EntityBaseId and the PersonId are
correctly inserted for each row.

*Adding the image separately via _context.Images.Add(image) produces a record in the database with the EntityBaseId populated, but the discriminator column of PersonId
is null, so EF is unable to associate the navigation property with
its parent entity.

I've read many, many other stackoverflow posts, other guides and tutorials, but I can't seem to find anything that quite matches the issue I'm having.  This is the reason why I'm thinking my issue revolves around inheritance.  This speaks to my lack of knowledge regarding TPC (not TPH) inheritance: Since there are technically two foreign keys of EntityBaseId and PersonId in the Images database table, is EF trying to perform an insert twice, once for each key?
It's preferable if I can both understand as well as fix this issue rather than ripping out the inheritance and moving from a monolithic to a more discrete approach.  My original thinking was, "Well, if I want all entities to contain a List<Image>, why not have all non-Image entities inherit from an abstract base class?"
Please let me know what required information I am missing from this post; any help is greatly appreciated.
Regards
Zac


text:
Q: Build error for gnutls-3.7.8 on Ubuntu 20.04.5 - weirdness with streebog512_ctx I am trying to install gnutls 3.7.8 on an Ubuntu 20.04.5 server. Had to install nettle first.
Command I am running for configure:
PKG_CONFIG_PATH="/usr/lib/pkgconfig/:$PKG_CONFIG_PATH" ./configure  --prefix=/usr --with-included-unistring --with-included-libtasn1
Running "make --debug=j", this is where things start to go sideways; everything is running smoothly until then:
Making all in nettle
make\[4\]: Entering directory '/home/meowmeow/Installed_Programs/gnutls-3.7.8/lib/nettle'
Putting child 0x56123e85f740 (mac.lo) PID 1065461 on the chain.
Live child 0x56123e85f740 (mac.lo) PID 1065461
CC       mac.lo
In file included from gost/hmac-gost.h:42,
from mac.c:39:
gost/streebog.h:48: warning: "streebog256_init" redefined
48 | #define streebog256_init \_gnutls_streebog256_init
|
In file included from /usr/include/nettle/hmac.h:44,
from mac.c:33:
/usr/include/nettle/streebog.h:44: note: this is the location of the previous definition
44 | #define streebog256_init nettle_streebog256_init
|
In file included from gost/hmac-gost.h:42,
from mac.c:39:
gost/streebog.h:49: warning: "streebog256_digest" redefined
49 | #define streebog256_digest \_gnutls_streebog256_digest
|
In file included from /usr/include/nettle/hmac.h:44,
from mac.c:33:
/usr/include/nettle/streebog.h:45: note: this is the location of the previous definition
45 | #define streebog256_digest nettle_streebog256_digest
|
In file included from gost/hmac-gost.h:42,
from mac.c:39:
gost/streebog.h:50: warning: "streebog512_init" redefined
50 | #define streebog512_init \_gnutls_streebog512_init
|
In file included from /usr/include/nettle/hmac.h:44,
from mac.c:33:
/usr/include/nettle/streebog.h:46: note: this is the location of the previous definition
46 | #define streebog512_init nettle_streebog512_init
|
In file included from gost/hmac-gost.h:42,
from mac.c:39:
gost/streebog.h:51: warning: "streebog512_update" redefined
51 | #define streebog512_update \_gnutls_streebog512_update
|
In file included from /usr/include/nettle/hmac.h:44,
from mac.c:33:
/usr/include/nettle/streebog.h:47: note: this is the location of the previous definition
47 | #define streebog512_update nettle_streebog512_update
|
In file included from gost/hmac-gost.h:42,
from mac.c:39:
gost/streebog.h:52: warning: "streebog512_digest" redefined
52 | #define streebog512_digest \_gnutls_streebog512_digest
|
In file included from /usr/include/nettle/hmac.h:44,
from mac.c:33:
/usr/include/nettle/streebog.h:48: note: this is the location of the previous definition
48 | #define streebog512_digest nettle_streebog512_digest
|
In file included from gost/hmac-gost.h:42,
from mac.c:39:
gost/streebog.h:62:8: error: redefinition of 'struct streebog512_ctx'
62 | struct streebog512_ctx
|        ^\~\~\~\~\~\~\~\~\~\~\~\~\~\~
In file included from /usr/include/nettle/hmac.h:44,
from mac.c:33:
/usr/include/nettle/streebog.h:58:8: note: originally defined here
58 | struct streebog512_ctx
|        ^\~\~\~\~\~\~\~\~\~\~\~\~\~\~
In file included from gost/hmac-gost.h:42,
from mac.c:39:
gost/streebog.h:92: warning: "streebog256_update" redefined
92 | #define streebog256_update \_gnutls_streebog512_update
|
In file included from /usr/include/nettle/hmac.h:44,
from mac.c:33:
/usr/include/nettle/streebog.h:88: note: this is the location of the previous definition
88 | #define streebog256_update nettle_streebog512_update
|
In file included from mac.c:39:
gost/hmac-gost.h:51: warning: "hmac_streebog256_set_key" redefined
51 | #define hmac_streebog256_set_key \_gnutls_hmac_streebog256_set_key
|
In file included from mac.c:33:
/usr/include/nettle/hmac.h:80: note: this is the location of the previous definition
80 | #define hmac_streebog256_set_key nettle_hmac_streebog256_set_key
|
In file included from mac.c:39:
gost/hmac-gost.h:52: warning: "hmac_streebog256_digest" redefined
52 | #define hmac_streebog256_digest \_gnutls_hmac_streebog256_digest
|
In file included from mac.c:33:
/usr/include/nettle/hmac.h:81: note: this is the location of the previous definition
81 | #define hmac_streebog256_digest nettle_hmac_streebog256_digest
|
In file included from mac.c:39:
gost/hmac-gost.h:53: warning: "hmac_streebog512_set_key" redefined
53 | #define hmac_streebog512_set_key \_gnutls_hmac_streebog512_set_key
|
In file included from mac.c:33:
/usr/include/nettle/hmac.h:82: note: this is the location of the previous definition
82 | #define hmac_streebog512_set_key nettle_hmac_streebog512_set_key
|
In file included from mac.c:39:
gost/hmac-gost.h:54: warning: "hmac_streebog512_update" redefined
54 | #define hmac_streebog512_update \_gnutls_hmac_streebog512_update
|
In file included from mac.c:33:
/usr/include/nettle/hmac.h:83: note: this is the location of the previous definition
83 | #define hmac_streebog512_update nettle_hmac_streebog512_update
|
In file included from mac.c:39:
gost/hmac-gost.h:55: warning: "hmac_streebog512_digest" redefined
55 | #define hmac_streebog512_digest \_gnutls_hmac_streebog512_digest
|
In file included from mac.c:33:
/usr/include/nettle/hmac.h:84: note: this is the location of the previous definition
84 | #define hmac_streebog512_digest nettle_hmac_streebog512_digest
|
In file included from mac.c:39:
gost/hmac-gost.h:60:8: error: redefinition of 'struct hmac_streebog512_ctx'
60 | struct hmac_streebog512_ctx HMAC_CTX(struct streebog512_ctx);
|        ^\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~
In file included from mac.c:33:
/usr/include/nettle/hmac.h:254:8: note: originally defined here
254 | struct hmac_streebog512_ctx HMAC_CTX(struct streebog512_ctx);
|        ^\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~
Reaping losing child 0x56123e85f740 PID 1065461
make\[4\]: \*\*\* \[Makefile:2346: mac.lo\] Error 1
Removing child 0x56123e85f740 PID 1065461 from chain.
make\[4\]: Leaving directory '/home/meowmeow/Installed_Programs/gnutls-3.7.8/lib/nettle'
Reaping losing child 0x562065819fa0 PID 1065420
make\[3\]: \*\*\* \[Makefile:2901: all-recursive\] Error 1
Removing child 0x562065819fa0 PID 1065420 from chain.
make\[3\]: Leaving directory '/home/meowmeow/Installed_Programs/gnutls-3.7.8/lib'
Reaping losing child 0x557239209220 PID 1065419
make\[2\]: \*\*\* \[Makefile:2505: all\] Error 2
Removing child 0x557239209220 PID 1065419 from chain.
make\[2\]: Leaving directory '/home/meowmeow/Installed_Programs/gnutls-3.7.8/lib'
Reaping losing child 0x563a8ddd7ab0 PID 1065402
make\[1\]: \*\*\* \[Makefile:2257: all-recursive\] Error 1
Removing child 0x563a8ddd7ab0 PID 1065402 from chain.
make\[1\]: Leaving directory '/home/meowmeow/Installed_Programs/gnutls-3.7.8'
Reaping losing child 0x55f76896c820 PID 1065391
make: \*\*\* \[Makefile:2182: all\] Error 2
Removing child 0x55f76896c820 PID 1065391 from chain.

I am a biologist, I just want to be able to run remote blast on my server and am basically a monkey typing commands when it comes to compiling things - so at this point, I'm pretty much out of knowledge.
I have tried to reinstall nettle many times using different options; have tried searching through the Makefile trying to find what is happening here; have tried multiple configurations of ./configure for gnutls, googled this every which way. I was expecting...to install gnutls.


text:
Q: How to give a number of columns with CSS grid where I have grid-auto-flow set to column I have a list of time slots, the grid-auto-flow is set to column. On a small screen I want 1 column, on a big screen (max) 4 columns. As you can see in the code below I use
grid-template-rows: repeat(8, 1fr);
How can I just give the numbers of columns instead of using grid-template-rows: repeat(8, 1fr);?

.container {
    display: grid;
    grid-gap:20px;
}

.container > .slot {
    background:tomato;
    font-size:30px;
    padding:10px;
}

@media (min-width: 600px) {
  .container  {
    grid-auto-flow: column;
    grid-template-rows: repeat(7, 1fr);
  }
}

12.00

12.15

12.30

12.45

13.00

13.15

13.30

13.45

14.00

14.15

14.30

14.45

15.00

15.15

15.30

15.45

16.00

16.15

16.30

16.45

17.00

17.15

17.30

17.45

18.00

A: This is a job for Columns and not CSS grid:

.container>.slot {
  background: tomato;
  font-size: 30px;
  padding: 10px;
  margin-bottom: 20px;
  /* we use inline-block because block is buggy with column*/
  display: inline-block;
  width: 100%;
  /**/
  box-sizing: border-box;
}

@media (min-width: 600px) {
  .container {
    column-count: 4;
    column-gap: 20px;
  }
}

12.00

12.15

12.30

12.45

13.00

13.15

13.30

13.45

14.00

14.15

14.30

14.45

15.00

15.15

15.30

15.45

16.00

16.15

16.30

16.45

17.00

17.15

17.30

17.45

18.00

A: You can use grid-template-columns: 1fr; and grid-template-columns: 1fr 1fr 1fr 1fr;.

Note: Also, you can use grid-auto-rows: 100px; to set the height of the rows.

.container {
    display: grid;
    grid-template-columns: 1fr;
    grid-gap:20px;
}

.container > .slot {
    background:tomato;
    font-size:30px;
    padding:10px;
}

@media (min-width: 600px) {
  .container  {
    grid-template-columns: 1fr 1fr 1fr 1fr;
  }
}

12.00

12.15

12.30

12.45

13.00

13.15

13.30

13.45

14.00

14.15

14.30

14.45

15.00

15.15

15.30

15.45

16.00

16.15

16.30

16.45

17.00

17.15

17.30

17.45

18.00


text:
Q: Express adds first part of URL to injections if you use 2 level URLs? I am using Node.js + Express.
When you have 1-level URL like:
/estonia

All of the scripts and styles are loaded correctly but if you have a 2-level URL like:
/estonia/tallinn

Scripts and styles injections are failing because it adds /estonia to the path:
Before: http://localhost:5050/js/config.js
After: http://localhost:5050/estonia/js/config.js
Here is my routes.js file:
app.get('*', function(req, res) {
    var url = req.url.slice(1);
    var urlParamsArray = url.split("/");
    if ( countries[urlParamsArray[0]] && (urlParamsArray.length===1 || cities[urlParamsArray[1]]) ) {
        res.sendFile(config.ROOT_PATH +'/'+ config.PUBLIC_PATH+'/index.html');
    } else {
        res.status(404).sendFile(config.ROOT_PATH + '/'+ config.PUBLIC_PATH+'/404.html');
    }
});

Here is my express.js file:
app.set('view engine', 'ejs');
app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
});

app.use(bodyParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(session({secret:config.EXPRESS_SESSION_SECRET}));
app.use(favicon(config.ROOT_PATH+'/public/favicon.ico'));
app.use(express.static(config.ROOT_PATH+"/"+config.PUBLIC_PATH));

How can I fix that?

A: Add <base href="/"> to <head> section of your templates.


text:
Q: If $f$ is continuous and $g$ is integrable on $[a,b]$, with $g(x) \ge 0$ for all $x \in [a,b]$ ...
Suppose $f : [a,b] \to \mathbb{R}$ is continuous and $g \in \mathcal{R}[a,b]$ with $g(x) \ge 0$ for all $x \in [a,b]$. Show that there exists a $c \in [a,b]$ such that $$\int_a^b f(x)g(x) \, dx = f(c) \int_a^b g(x) \, dx.$$

My attempt:
My class proved a theorem which states that $f$ attains its minimum and maximum ($m$ and $M$, respectively), since $f$ is continuous on a closed interval like $[a,b]$. So we would have $m \le f(x) \le M$. Multiplying both sides by $g$ and integrating, we get $$m \int_a^b g(x) \, dx \le \int_a^b f(x) g(x) \, dx \le M \int_a^b g(x) \, dx.$$
I am stuck after this. Where can I go from here?

A: We know that $\forall$ $x \in [a,b]$, $m \le  f(x)$ $\le$ M, where $m =\inf(f)$ and $M = \sup(f)$. Then $mg(x)$ $\le$ $f(x)g(x)$ $\le$ $Mg(x)$, $\forall$ $x$ $\in$ $[a,b]$. It follows that $$m\int_a^b g(x)dx \le \int_a^b f(x)g(x)dx \le M\int_a^b g(x)dx$$
Therefore, $\exists$ $d$ $\in$ $[m,M]$ such that $d\int_a^b g(x)dx = \int_a^b f(x)g(x)dx$. Since $f$ is continuous, $\exists c \in [a,b]$ such that $d=f(c)$ .

A: If $\int_a^b g(x)dx=0$, then you are done - you can take any $c$. If not, divide both sides of your inequality by $\int_a^b g(x)dx$ and apply intermediate value theorem.


text:
Q: Pytorch find the matching 2x2 tensor in a batch of 2x2 tensors I have a 2x2 reference tensor and a batch of candidate 2x2 tensors. I would like to find the closest candidate tensor to the reference tensor by summed euclidean distance over the identically indexed (except for the batch index) elements.
For example:
ref = torch.as_tensor([[1, 2], [3, 4]])
candidates = torch.rand(100, 2, 2)

I would like to find the 2x2 tensor index in candidates that minimizes:
(ref[0][0] - candidates[index][0][0])**2 +
(ref[0][1] - candidates[index][0][1])**2 +
(ref[1][0] - candidates[index][1][0])**2 +
(ref[1][1] - candidates[index][1][1])**2

Ideally, this solution would work for arbitrary dimension reference tensor of size (b, c, d, ...., z) and an arbitrary batch_size of candidate tensors with equal dimensions to the reference tensor (batch_size, b, c, d,..., z)

A: Elaborating on @ndrwnaguib's answer, it should be rather:
dist = torch.cdist( ref.float().flatten().unsqueeze(0), candidates.flatten(start_dim=1))
print(torch.square( dist ))
torch.argmin( dist )

tensor([[23.3516, 21.8078, 25.5247, 26.3465, 21.3161, 17.7537, 24.1075, 22.4388,
         22.7513, 16.8489]])

tensor(9)

other options, worth noting:
torch.square(ref.float()- candidates).sum( dim=(1,2) )

tensor([[23.3516, 21.8078, 25.5247, 26.3465, 21.3161, 17.7537, 24.1075, 22.4388,
         22.7513, 16.8489]])

diff = ref.float()- candidates
torch.einsum( "abc,abc->a" ,diff, diff)

tensor([[23.3516, 21.8078, 25.5247, 26.3465, 21.3161, 17.7537, 24.1075, 22.4388,
         22.7513, 16.8489]])

A: The following line returns the index of the tensor in candidates that minimizes the summation of the element-wise Euclidean distance to ref
In [1]: import torch
In [2]: ref = torch.as_tensor([[1, 2], [3, 4]])
   ...: candidates = torch.rand(100, 2, 2)
In [3]: %timeit torch.argmin(((ref - candidates) ** 2).sum((1, 2)))
16.9 µs ± 350 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)


text:
Q: Externalize jdbc properties Spring I want to put jdbc property file into the directory where pom file is. I put the path on pom as a system variable myApp./jdbc.properties
then on ${myApp}
but when running jetty:run it says ${myApp} cannot be opened. How can I fix this issue.
Please reply me.


text:
Q: Pearson correlation coefficient after transformation For two random variables $X$ and $Y$, if I know the Pearson correlation coefficient $r=\mbox{Corr}(X,Y)$, is there a general way to obtain the correlation between $F(X)$ and $G(Y)$?
Any assumption, for example, c.d.f. of $X$ and $Y$ and the properties about $F(\cdot)$ and $G(\cdot)$, can be added if necessary.
Or if someone provides me some related literatures, I will appreciate it.


text:
Q: DataGroup and BasicLayout: how to position the ItemRenderers? I'm quite new to flex and ActionScript and I'd like to create a custom component acting as a calendar (using a Sprite), in which the calendar events are represented as rectangles the user can interact with (click to get information about the event, drag and drop for setting start and end dates...). It seems that using a subclass of DataGroup is a good way to do it, but some things are obscure to me...
For example, how should I use the Sprite? as a child of the DataGroup? Also, the calendar events will be drawn using a custom ItemRenderer, and I will have to use a BasicLayout in my DataGroup, but where should I tell that an ItemRenderer should draw its rectangle in the Sprite at the corresponding (x,y) coordinates?

A: Just bind the itemRenderer's x and y to something in the data that tells it where the x and y is.  If this is not part of the data, consider using a TileLayout instead.


text:
Q: Как обновить данные в списке ListView? Данные в ListView передаются из массива
String[] items = new String[] {"First", "Second"};

setListAdapter(new ArrayAdapter<String>(this, R.layout.items, items));

Периодически items меняется, например:
items = new String[] {"First", "Second", "Third"};

При этом не происходит обновления списка на экране. Как обновить данные в ListView, так чтобы обновление отобразилось на экране?
A: adapter.notifyDataSetChanged()

пробовал?
A: Получилось сделать вот так
items = new ArrayList<String>(Arrays.asList("", ""));
adapter = new ArrayAdapter<String>(this, R.layout.items, items);

и
items.clear();
items.addAll(found);

adapter.notifyDataSetChanged();


text:
Q: Get rid of second page that opens when executing an imacros script How can I get rid of this second page that opens when using this href to execute an imacros script

the first tab is a simple html page that contains this tag:

    <button>Run macro</button>

when clicking this link a second tab opens containing what in the image and that the one I want to get rid of. the third page contains what I want to execute.
note: I want to keep the first page open.

A: Can't test this but I would try:

      <button>Run macro</button>

A: Try this. If it works, it is better practice than using javascript hrefs and wrapping buttons in links
You can use a button instead of a link

window.addEventListener("load",function() {
  document.querySelector("#imacro").addEventListener("click",function(e) {
    e.preventDefault();
    window.open(this.dataset.href)
  })
})
.button {
    display: block;
    width: 100px;
    height: 20px;
    padding: 10px;
    text-align: center;
    border-radius: 5px;
    border:1px solid black;
    font-weight: bold;
    text-decoration: none;
}

   Run macro


text:
Q: Combining strings when aggregating in R without creating a list of lists I have a set of data in the form of strings.  They are text responses given to a question, and some people gave multiple responses to the question.  I want to combine each individual's text responses, i.e. aggregate by individual.
However, when I aggregate(), even using paste, paste0, or str_c (from stringr package), I get essentially a list of lists.
I cannot turn this into a dataframe to write to csv, I cannot seem to flatten these by unlisting without going by each individual cell which is prohibitive as I have over 300 responses.
Is there a way I can aggregate that will combine each person's response into a single string?  Or an easy way to flatten them out so that I can do so?
Response <- c("A","B","A","A","B","C","A","B")
df<-cbind(Person,Response)
df<-aggregate(Response~Person,data=df,paste0)```

I have:

Person      Response
1             "A"
1             "B"
2             "A"
3             "A"
3             "B"
3             "C"
4             "A"
4             "B"

I want to get to:

Person        Response
1               "AB"
2               "A"
3               "ABC"
4               "AB"

What I'm getting instead is:

Person     Response
1           c("A","B")
2           "A"
3           c("A","B","C")
4           c("A","B")

Thanks.

A: We can change the paste0 to paste with collapse = ""
aggregate(Response ~ Person, data = df, FUN = paste, collapse="")
#  Person Response
#1      1       AB
#2      2        A
#3      3      ABC
#4      4       AB

Here, paste0 is not doing anything, and resulting in a list column instead of a concatenated string, e..g
paste0(c("A", "B", "C")) # returns the same vector
#[1] "A" "B" "C"

paste(c("A", "B", "C"), collapse="")
#[1] "ABC"

whereas paste0 works, when two vectors are concatenated
paste0("A", "B")
#[1] "AB"

data
df <- structure(list(Person = c(1L, 1L, 2L, 3L, 3L, 3L, 4L, 4L), Response = c("A",
 "B", "A", "A", "B", "C", "A", "B")), class = "data.frame",
 row.names = c(NA, -8L))


text:
Q: Built-in function for flatten a 3d array into pandas df? I have a numpy array like below:
import pandas as pd
import numpy as np
np.random.seed(10)
data = np.random.randint(0, 10, size=(1000, 4, 3))

I want to be able to flatten this data into a df with 12 columns and 1000 rows.
What I've done is:
df = pd.DataFrame( index=range(data.shape[0]))

for i in range(data.shape[1]):
    for j in range(data.shape[2]):
        df[str(i)+'_'+str(j)] = pd.DataFrame((data[:,i,j]))

By doing so, I'll be able to flatten this 3d data into 2d pandas df.
- Does anyone know any neat built-in function that I can use, in addition to what I've done?

A: Just reshape the array to (-1, 12) and create the dataframe
 pd.DataFrame(data.reshape(-1, 12))


text:
Q: about syncing username, icon image on cloudkit. (swift) I'd like to reduce API call that's why I added username and icon image filed to all tables on cloudkit.
there is a userinfo table and it have a username and icon image field.
and I add those into all tables like posting and comment when creating new data.
my question is this. how can I sync all username and icon image if user change userinfo data?
thanks in advance


text:
Q: Changing foreach iteration variable and implementation differences between C# and C++/CLI Consider the following C# code.
string[] stringArray = new string[10];
foreach (string s in stringArray)
    s = "a new string";  // Compiler error - Can't assign to foreach iteration variable

Now consider the following valid C++/CLI code.
array<String^>^ stringArray = gcnew array<String^>(10);
for each(String^% s in stringArray)
    s = "a new string";

When foreach is used with array type, compiler translates it into normal for loop. This implementation is same for C# and C++/CLI. So I wonder if C++/CLI can allow this, why not for C# compiler?
This error makes sense when the type is not an array as foreach will be compiled into GetEnumerator call and use the enumerator for iteration. But I think it can be allowed for array types.
Any thoughts?
As a side note, the following is a valid C++/CLI code too but will not produce the expected result.
List<String^>^ stringList = gcnew List<String^>(10);
for each(String^% s in stringList)
    s = "a new string"; // I think this should be prevented by compiler as it makes no sense.

A: There seem to be three different questions here:

*

*Why does C++ allow you to assign to a for each iteration variable?

*Why doesn't C#?

*Why do the C++ and C# compilers behave differently?

The answers are fairly straightforward:

*

*Because the C++ team didn't decide to explicitly disallow it, and technically the iteration variable is just a local variable - it doesn't get special treatment.

*Because the C# team did decide to disallow it, because (most likely) they believe it would lead to bugs or incorrect code.  Assigning to any loop variable is commonly considered a code smell.

*Because the C++ team and the C# team are different teams.  C++ has always been a language that allows you to shoot yourself in the foot, if you so choose, and goes so far as to hand you the loaded gun.  C# will often try to enforce "correct code" rules.
There might actually be another question here, which is:

*

*Why would C# compile a foreach into a for if it doesn't allow assignment?  Or, the converse - why doesn't allow this if that's how it gets compiled anyway?

There are actually two answers to this one:

*

*Because it's faster.  foreach operates on IEnumerable, which requires a new IEnumerator class to be instantiated.  Array types are special types recognized by the compiler, so if the compiler already knows that the IEnumerable is actually an Array, then it compiles down to indexed access instead, which is much cheaper.
This little performance tweak is simply an implementation detail, however; it is not part of the specification, and if you were able to write code that depends on the specific implementation, the C# team would be unable to change that implementation later without breaking existing code.  They would certainly want to avoid such a situation.

*Because it doesn't actually matter the way one might think it does.  If you could do the assignment in C#, you would not actually be modifying the array, only the contents of the local variable that initially held something from the array.  This, again, falls under the category of "make it difficult to write incorrect code" - if the construct did allow you to assign to the variable, some programmers might think that this would actually change the collection, which would be false.
I think that should explain it pretty well.

A: This is because C# is using smoke and mirrors (ie magic).  The variable you get back in the foreach is not the actual item in the array, it is a copy made by the iteration object... or something else.  We don't really know (well we do, but we have to break the abstraction layer and look at the implementation of the iterator object.)
If you want to change the values IN the array, you have to deal directly with the array's interface to access those items.  In c++ this happens, but mostly by mistake (a lot of c++ is like this, the original implementations were actually macros and pre-processing).   In C# it is explicitly defined not to work -- thus a compiler message.  (See section 5.3.3.16 in the spec.)

A: I think you've answered your own question when you state that for the C++ case:

When foreach is used with array type, compiler translates it into normal for loop.

If you code the C# as a for loop you can do this.
The comments on this MSDN page explain more, but it boils down to the fact that by modifying the string you are changing the indexing of the collection - which is why the loop breaks.

A: Re Hogan:
Yes, a copy gets made by it. In fact, when I was running into it (today) I was banking on it being a modifieable copy:
foreach (string Token in tokenize(Command))
{
foreach (KeyValuePair<string, string> Replacement in TokensToReplace)
    {
    if (Token==Replacement.Key)
        {
        Token = Replacement.Value;
        }
    }
TokenList.Add(Token);
}

I think it's unfortunate that this doesn't work.

A: Aaronaught, the loop doesn't have to reverse the function it just has to create a string variable "Token" and initialize it with the value from tokenize. After that it doesn't have anything to do with any internals of tokenize.
What I was trying to get at is that the loop variable shouldn't be some magic pointer into a collection but an Object that gets created by "string Token=" just as if it was created in a for or while loop.
I am NOT trying to modify some internal collection value but overwrite a local variable. It's not supposed to have consequences for the data in the collection since the pointer to the old string gets lost after the assignment.
In C++ it works.


text:
Q: Anchor links in hidden divs Because I am working with a very limited and old CMS, I don't have many options. I hope this is possible:
I have a page with 4 divs. The first one is always visible and the other ones are hidden through the class faded-in and faded-out. With a mouse over function, visitors can make the others visible with hover. The current active div fades into the new one. So far so good. (This is done with plain javascript as the jQuery on the site is very old, and I cannot update it).
What I need now is the ability to link to the other divs from other pages. I have tried the following:
Making a toggle function in javascript to hide/show the relevant div. I tried to call this function from the other page, but it seems impossible. Is there another way for this? Let me know if you need more details.
I used the search function and found some "anchor links in hidden elements" topics, but because they are in a different situation, the solution does not apply to me sadly!
HTML code with the divs:

Div 1

Div 2

Div 3

This is div 1

This is div 2

This is div 3

The fade JS:

Sorry for messing up the alignment, the cms is horrible (uses basic html text blocks).

A: You can add fragment to the URL identifying which div should be visible. Something like this:
www.mysite.com/pagewithfourdivs.html#div3

And then, on page load, you can read the fragment value (e.g. #div3 ) from window.location.hash and hide/show the divs accordingly.