text:
Q: Python-Use of list of lists
Construct a class named Matrix that expresses the meaning of the matrix of numbers. The initialization function, __init__, should take as an argument a list of lists of  numbers and should store it in the variable matrix.

Before defining the variable, the matrix dimension must be checked for validity (i.e. if all lists have the same length).

__init__ should also define two lists with names columns, rows. These lists will consist of objects of the Vector class and will be the columns and rows vectors respectively. Also, the dim variable should be defined which will be a pair (set) of numbers where the first will be as many as the number of rows in the table and the second as many as the number of columns.

How do we give as an argument a list of list?
And how do we use this list of lists to check if all lists have the length?
And a third question, how do we use the list of lists to get a tuple of all rows and a tuple of all columns?
My code so far is :
class Matrix:
    def __init__(self, matrix) :
        self.matrix = matrix
        self.columns
        self.rows
        self.dim = (len(self.rows) , len(self.columns))

A: *

*Write a list whose elements are also lists, e.g. [[1, 2], [3, 4]].

*Get the length of the first list in the list of lists. Then use a function like all() to test if the lengths of all the other nested lists have the same length.

*To make the rows variable, use a list comprehension to convert each row of self.matrix into a Vector and collect them into a list. To make the colums variable, use nested loops. The outer loop iterates over the column numbers (from 0 to len(self.matrix[0])), the inner loop iterates over each row, collecting all the values in the column number into a Vector. Then these vectors are collected into a list that's assigned to self.columns.


text:
Q: Dynamically add symbol into process symbol table How can I add a symbol to process symbol table dynamically on linux? For example, suppose I parse a script and determine that it has some methods which I then want to add into global address space so that they can be accessed by shared libraries loaded afterwards. What I then want to do is add a function pointer to a stub function that will call the script function and return the result (in C). But I want to say "add 'foo' pointing to &mygenericstub to global symbol table".. so when I then do dlopen() on an .so file with RTLD_GLOBAL flag, it will be able to call 'foo' as though it was a normal C function in the global namespace..
The idea is rather simple: to extend functionality of dynamic linker for that single process to also include names from scripts (but not just having an entry point function that takes a string argument for the script function to be called - but rather making the dynamic linking process transparent to other shared objects that may be loaded later). The idea would be not to modify existing table, but rather to map a new table as an extension to existing one (maybe this can somehow be done using mmap but I don't know what to map and how to extend it). Basically something similar to dlopen with the "global" option that works for dynamic names would be interesting.

A: This looks quite cumbersome. You should probably change your code in order to lookup the symbol directly from your script interpreteur/VM.
but…

suppose I parse a script and determine that it has some methods
  which I then want to add into global address space so that they
  can be accessed by shared libraries loaded afterwards.

AFAIK, there is no API exposed by the dynamic linker to register additional symbols. However, what you can is dlopen a new shared library whith those symbols:

*

*dynamically generate .so file with a symbol for each function you want to expose;

*each of those symbols reference a PLT-like pattern (the code fetch a GOT like entry and jump to it);

*dlopen RTLD_GLOBAL this .so file;

*fill the GOT-like variables;

*you can now dlopen additional .so which will call to the PLT-like fuction and jump through the GOT-like variable to the real function.
Code of the shared object:
    .text
    .globl  main
    .type   main, @function
foo:
    .cfi_startproc
    jmp *foo_got_alike(%rip)
    .cfi_endproc
.bss
    .align 8
    .type   foo_got_alike, @object
    .size   foo_got_alike, 8
foo_got_alike:
    .zero   8

This suppose you have managed to generate a suitable implementation for0 foo using some kind of JIT.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ambiguous prepositional phrase in a legal document In common speech or writing, disambiguation of objects of prepositional phrases can be inferred from context. However, there is no room for error in filling out legal documents! I came across this question:

*

*Have you enrolled or will soon enroll in health insurance but your health coverage has not started yet?
The answer choices are: "Yes, I am enrolled", "I will soon enroll" and "No". I am currently enrolled in health insurance and it has already begun, but I have no idea how to answer this question (or whether I should skip it).
There is an ambiguity in the interpretation of this question. Logically, given propositions A, B, and C, the question " "A or B and C?" can be taken to mean either " A or (B and C) ? " or " ( A or B ) and C ? ", which are not equivalent questions.
Is there a correct interpretation?

A: From a logical perspective, the problem with the question as posted —

Have you enrolled or will soon enroll in health insurance but your health coverage has not started yet?

—is that it invites negative responses from people who fall into two fundamentally different categories.
On the one hand, if you have not enrolled in health insurance and will not soon enroll in health insurance, you can hardly answer "yes" to a question that states as its antecedent condition that you have enrolled or soon will enroll in health insurance; this is quite aside from the question of whether the coverage has started yet—although, obviously, it can't have started if you haven't enrolled.
But on the other hand, if you have enrolled and the coverage has begun, you can hardly answer "yes" to a question framed as "your health coverage has not started yet."
In short, the document asks this question in such a way that the only situation in which it would be logical to answer "yes" is one in which you have enrolled or will soon enroll in health insurance and yet the coverage has not yet begun.
If the author of the document for some reason cares only about people who fall into that particular category of respondents, it doesn't matter that two disparate groups of people get thrown into the same "no" category—and the question as worded has no fatal flaw.
But if the author of the document has any interest in distinguishing—now or in the future—between people who are already enrolled and covered and people who are neither enrolled nor about to enroll nor covered, that author is creating the conditions for a heap of trouble down the road that a more carefully worded question could easily have avoided.

With regard to the grouping issue related to whether the question should be read as

(Have you enrolled or will soon enroll in health insurance) but your health coverage has not started yet?

or as

Have you enrolled or (will soon enroll in health insurance but your health coverage has not started yet)?

I think the issue is illusory in this particular case—although it is certainly very important for people who are drawing up legal documents to be aware of the logical complications posed by sentences that might be interpreted either as "A or (B but C)" or as "(A or B) but C."
It is illusory in this case because the "but C" clause of the sentence is nontrivial only when applied to the "A" clause; the "B" clause necessarily implies the "but C" clause here. That is, it is possible for someone to have enrolled but not yet begun to be covered (assuming that coverage doesn't start at the moment of enrollment), but it is not possible to be planning to enroll "soon" and to be covered already.
Therefore, the combination "[you] have enrolled in health insurance but your health coverage has not started yet" presents a meaningful subcategory within the category "[you] have enrolled in health insurance"; but "[you] will soon enroll in health insurance but your health coverage has not started yet" is trivial because every member of the "[you] will soon enroll in health insurance" category will also fall into the "[you] will soon enroll in health insurance but your health coverage has not started yet" subcategory.
It follows that reading the sentence as incorporating the ordering principle of "(A or B) but C" provides a logical justification for including the "but C" term, whereas reading the sentence as incorporating the ordering principle "A or (B but C)" renders the "but C" term completely superfluous.
I seem to recall from my law school days that courts have a bias toward interpreting contractual terms in a way that treats them as meaningful rather than meaningless; I would have that bias if I were a judge. But regardless of how a court might rule on this question as a matter of law, the logical argument favoring "(A or B) but C" over "A or (B but C)" in this case is extremely strong.

A: The question on the form is worded as "Have you enrolled or will soon enroll in health insurance but your health coverage has not started yet?"
This is worded clumsily, for sure. But I think the intention is: "(Have you enrolled or will soon enroll in health insurance) AND your health coverage has not started yet?"
The reason being that if the government department wanted to know if you had health insurance, and then as a follow up question, if your health insurance had started yet or not, this would (should!) have been two seperate questions. That fact that it is written as a single question suggests the emphasis is on whether it has (not) started.
Since the OP has health insurance and it HAS started, I would be inclined to answer "no".
(This is not legal advice and I appreciate you have already sought independent legal advice. But given the nature of the wording, if you answer this question as truthfully and correctly as you can, if it turns out that they actually meant something else, I think you have a safety net - the blame lays squarely with them).

A: Terrible question, but I would go with "No" because you insurance has already started.
It would be helpful to know more about this document and/or the context to understand what is most relevant or important to the entity that is asking the question - whether you have enrolled in a plan, or whether you currently have coverage.


text:
Q: Connecting phone to external display and launching app Is it possible to create an app which launches on an external display when HDMI is connected to the phone?
Basically. I want to create an app that works like a mini OS, similar to Samsung Dex.
To start off, I'd just like to have the app launch automatically when HDMI is connected and adjust to the screen size, then show the user home screen app icons etc.
Is this possible?
I found some apps on the app store that do this:
Sentio desktop
Leena
How are they doing this?

A: Here's an open source project that can help you. right here


text:
Q: Переустановка виндовс удаляет все вирусы? При переустановке виндовс удаляются все вирусы, которые можно подхватить, лазая в и-нете и скачивая что-то?
И есть ли разница при переустановке винды между форматированием разделов и их удалением. Может ли остаться что-то, если раздел удалить, а не отформатировать?

A: Переустановка Windows удаляет вирусы, которые содержались в файлах Windows. Т.е. если заражена система и вы её переустановите, то файлы системы после этого будут без вирусов, но из каких-либо заражённых файлов, флешек и т.д. это вредоносный код не удалит.

A: Переустановка виндос подразумевает собой полную очистку данных ПК. Естественно вирусы являющиеся файлами так же будут удалены. Не зависимо от того удалите вы или форматируете вирусов точно не будет.


text:
Q: recvfrom read the same frame multiple times im playing around with STP packets and writing a program raw sockets to modify them.
Reading fropm eth0 sending to eth1. System is ubuntu 14.10/ Kernel 3.somewhat.
Packets are generated with additional computers with Karat and Wireshark is running this interfaces too.
Inject a packet and after first run recvfrom didn't stop. Read the same packet from eth0
and send it to eth1. Debugging session ???????
The final edition should read all frame from eth0 , forward all and put all STP in a "unicast tunnel" - Read alle eth1 frame an forward eth0 and "unpack" special "Tunnel"
frames.
i put some code here:
    typedef struct {
            unsigned char mac[6];
            unsigned char ifName[IFNAMSIZ];
            int sockfd;
            struct sockaddr_ll socketaddress;
            struct ifreq ifopts;                    /* set promiscuous mode */

    } interfaces;

    extern int errno;

    nt i;
    int sockopt;
    ssize_t numbytes;

    unsigned char InBuf[BUF_SIZ];   // this is the frame buffer

    interfaces in,out;          // interface struct var's

   unsigned char PeerMac[6]; // Peer mac for simple Tunnel
   unsigned char myMac[6];  // my Peer address
   int c;

    unsigned char IEEE802_1q_STP[6] =  {0x01, 0x80, 0xC2, 0x00, 0x00, 0x0d};

    /* Header structures */
    struct ether_header *InTunnelPtr = (struct ether_header*) InBuf;
    struct ether_header *InPtr = (struct ether_header*) (InBuf+14);
/ First Do it for IN_IF
    memset(&in.socketaddress, 0, sizeof(struct sockaddr_ll));  // clear Var
    in.socketaddress.sll_family = PF_PACKET;
    in.socketaddress.sll_protocol = htons(ETH_P_ALL); // just dummy, don't needed
    in.socketaddress.sll_halen = ETH_ALEN;

/* Open PF_PACKET socket, listening for EtherType ETHER_TYPE */
    if ((in.sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1) {
        perror("listener: socket");
        return -1;
    }

    memset (&in.ifopts, 0, sizeof (struct ifreq));

// Set interface to promiscuous mode - do we need to do this every time?
    strncpy(in.ifopts.ifr_name, in.ifName, IFNAMSIZ-1); // set if name
    ioctl(in.sockfd, SIOCGIFFLAGS, &in.ifopts);   // get current flags
    in.ifopts.ifr_flags |= IFF_PROMISC;         // set promiscuous mode
    ioctl(in.sockfd, SIOCSIFFLAGS, &in.ifopts);  // write flags
    // get my mac addr
    //ioctl(in.sockfd,SIOCGIFHWADDR,&in.ifopts);
    //memcpy(in.mac,in.ifopts.ifr_hwaddr.sa_data,ETH_ALEN);

// find Interface index
    strncpy(in.ifopts.ifr_name, in.ifName, IFNAMSIZ-1);  //
    ioctl(in.sockfd, SIOCGIFINDEX, &in.ifopts);          // get if index

    in.socketaddress.sll_ifindex=in.ifopts.ifr_ifindex;  // set index to sockaddr_ll

// Allow the socket to be reused - incase connection is closed prematurely
    if (setsockopt(in.sockfd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof sockopt) == -1) {
        perror("setsockopt");
        close(in.sockfd);
        exit(EXIT_FAILURE);
    }
// Bind to device
    if (setsockopt(in.sockfd, SOL_SOCKET, SO_BINDTODEVICE, in.ifName, IFNAMSIZ-1) == -1) {
        perror("SO_BINDTODEVICE");
        close(in.sockfd);
        exit(EXIT_FAILURE);
    }
// -----------------------------------
// Now, do the OUT Interface
// -----------------------------------
    memset(&out.socketaddress, 0, sizeof(struct sockaddr_ll));  // clear Var
    out.socketaddress.sll_family = PF_PACKET;
    out.socketaddress.sll_protocol = htons(ETH_P_ALL); // just dummy, don't needed
    out.socketaddress.sll_halen = ETH_ALEN;

// Open PF_PACKET socket, listening for EtherType ETHER_TYPE */
    if ((out.sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1) {
        perror("listener: socket");
        exit(EXIT_FAILURE);
    }

    memset (&out.ifopts, 0, sizeof (struct ifreq));

// Set interface to promiscuous mode - do we need to do this every time? */
    strncpy(out.ifopts.ifr_name, out.ifName, IFNAMSIZ-1);
    ioctl(out.sockfd, SIOCGIFFLAGS, &out.ifopts);
    out.ifopts.ifr_flags |= IFF_PROMISC;
    ioctl(out.sockfd, SIOCSIFFLAGS, &out.ifopts);
    // get my mac addr
    // ioctl(out.sockfd,SIOCGIFHWADDR,&out.ifopts);
    // memcpy(out.mac, out.ifopts.ifr_hwaddr.sa_data, ETH_ALEN);

// find Interface index */
    strncpy(out.ifopts.ifr_name, out.ifName, IFNAMSIZ-1);
    ioctl(out.sockfd, SIOCGIFINDEX, &out.ifopts);

    out.socketaddress.sll_ifindex=out.ifopts.ifr_ifindex;

// Allow the socket to be reused - incase connection is closed prematurely */
    if (setsockopt(out.sockfd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof sockopt) == -1) {
        perror("setsockopt");
        close(out.sockfd);
        exit(EXIT_FAILURE);
    }
// Bind to device */
if (setsockopt(out.sockfd, SOL_SOCKET, SO_BINDTODEVICE, out.ifName, IFNAMSIZ-1) == -1) {
        perror("SO_BINDTODEVICE");
        close(out.sockfd);
        exit(EXIT_FAILURE);
    }

// Working LOOP
// interface in
// buffer structur
//   ------------------------------------------------------------
//   | dest  | source | len |   recv packet                     |
//   ------------------------------------------------------------
//   ^InTunnelPtr           ^ InPtr
repeat:
    numbytes=0;

    numbytes = recvfrom(in.sockfd, &InBuf[14], BUF_SIZ, 0, NULL, NULL) ;

/* let the game begin */
// test multicast addresses here
// and do something:-)

    if (numbytes > 0) {
 /*     if (memcmp(InPtr->ether_dhost,CISCOSHARED_STP, ETH_ALEN) == 0) {
            if (debug == 1) printf("Cisco Shard stp found");
        }
        else if (memcmp(InPtr->ether_dhost,IEEE802_1AD_STP, ETH_ALEN)==0) {
            if ( debug == 1) printf("IEEE802.1AD stp found");
        }
        else */

        if (memcmp(InPtr->ether_dhost,IEEE802_1D_STP, ETH_ALEN)==0)   // this tunnel
        {
            if (debug == 1) printf("IEEE802.1D stp for tunnel eth1\n");

            memcpy(InTunnelPtr->ether_dhost,PeerMac , ETH_ALEN);  // Copy PeerMac to destination  address
            memcpy(InTunnelPtr->ether_shost,myMac , ETH_ALEN);    // Copy my peer mac to source address
            InTunnelPtr->ether_type=numbytes+14;                                            // set tunnel header len

//          if (numbytes = sendto(out.sockfd, &InBuf[0] , (numbytes+14), 0,(struct sockaddr_ll *)&out.socketaddress,sizeof(out.socketaddress)) < 0)
            i = numbytes+14;

            if (numbytes = sendall_eth1(out.sockfd, &InBuf[0] , &i, &out.socketaddress, sizeof(out.socketaddress)) < 0)
            {
                printf("send error %s \n",strerror(errno));
            }

        } else {                            // send untunneled packet out

            if (debug == 1) printf ("send untunneled packet eth1\n");
//          if (numbytes = sendto(out.sockfd, &InBuf[14], numbytes, 0,(struct sockaddr_ll *)&out.socketaddress,sizeof(out.socketaddress)) < 0)
            i = numbytes;

            if (numbytes =
                  sendall_eth1(out.sockfd, &InBuf[14], &i, &out.socketaddress, sizeof(out.socketaddress)) < 0)
            {
                printf("send error %s \n",strerror(errno));
            }
        }
    }

goto repeat


text:
Q: CSS :nth-child - extra spacing at bottom Page in question: http://bit.ly/1xLOmeS
Every third LI has extra spacing at bottom that isn't supposed to be there.
I've tried using nth-child (odd) and (even) as shown below, and have also tried just the li:nth-child(2n+2) condition with the right margin set to 0px to prevent every 2nd box being shifted to the next line. Where is this space coming from??
CSS
ul.comment-card {
    padding: 0;
    margin: 0;
    list-style: none;
}
.comment-card li:nth-child(odd) {
    background: #fff;
    display: inline-block;
    height: 300px;
    list-style: none;
    margin: 0 20px 26px 0;
    padding: 30px;
    width: 327px;
}
.comment-card li:nth-child(even) {
    background: #fff;
    display: inline-block;
    height: 300px;
    list-style: none;
    margin: 0 0 26px 0;
    padding: 30px;
    width: 327px;
}
.comment-card li .meta {
    color: #767da1;
    font-weight: 400;
    line-height: 1.4em;
}
.comment-card .meta img {
    position: relative;
    top: -8px;
}

A: .comment-card li:nth-child(odd) {
background: #fff;
display: inline-block;
height: 300px;
overflow: hidden;
list-style: none;
margin: 0 20px 26px 0;
padding: 30px;
width: 327px;
}
.comment-card li:nth-child(even) {
background: #fff;
display: inline-block;
height: 300px;
overflow: hidden;
list-style: none;
margin: 0 0 26px 0;
padding: 30px;
width: 327px;
}

Example: jsFiddle


text:
Q: Getting a JSON response with ember I am trying to do some experimenting with Ember js. Instead of fixtures I would like to use an API.
This is my code which I am using to get the data:
App.ItemsRoute = Ember.Route.extend({
    model: function() {
        return $.getJSON('http://someurl.json').then(function(data) {
            return data.items_popular.map(function(item) {
                return item;
            });
        });
    }
});

This is what the json file looks like:
{
   "popular":{
      "items_popular":[
         {
            "id":"23",
            "item":"Some title",
            "url":"http://url",
            "user":"girl"
         },
         {
            "id":"56",
            "item":"Title of item 2",
            "url":"http://url",
            "user":"guy"
         }
      ]
   }
}

Currently I keep getting an
Cannot call method 'map' of undefined

Would appreciate any help with refactoring my request

A: You're accessing data.items_popular, but it should be data.popular.items_popular.
Demo: http://jsfiddle.net/rmfRt/


text:
Q: Why my routing does not work properly after changing to lazy-load routing in vue-js? Currently I am working on a website using vue 2.6.12. this is the code of my App.vue file:

App.vue

<template>

    <nvigCompo></nvigCompo>

    <router-view/>
    <footerCompo></footerCompo>

</template>

Also this is the code of my nvigCompo.vue code:

nvigCompo.vue

<template>

          <button @click="menuLogo" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#nav1" aria-controls="nav1" aria-expanded="false" aria-label="Toggle navigation">

          </button>

                <router-link :class="[navBoot, aStyle]" :to="{name: 'Articles'}">مقالات

                </router-link>

                <router-link :class="[navBoot, aStyle]" :to="{name: 'About'}">درباره من

                </router-link>

                <router-link :class="[navBoot, aStyle]" :to="{name: 'Samples'}">نمونه کارها

                </router-link>

                <router-link :class="[navBoot, aStyle]" :to="{name: 'Contact'}">تماس با من

                </router-link>

          <router-link :class="[navBootBrand]" :to="{name: 'Articles'}">

          </router-link>

            {{ this.message.messH1 }}

            {{ this.message.messP1 }}

              {{ this.message.messH2 }}

</template>

That is a bit long but the functionality is clear, it must know the route that currently is active and load some data below the nav links according to that. It worked fine, but today I decided to change the "router/index.js" file to lazy-load my routes. here is the code of my index.js file:

index.js

import Vue from 'vue';
import VueRouter from 'vue-router';
import articles from '../views/Articles';
// import articlesId from '../views/ArticlesId';
// import about from '../views/About';
// import contact from '../views/Contact';
// import samples from '../views/Samples';

Vue.use(VueRouter);
/* main routes of the site  */
const routes = [
  {
    path: '/',
    name: 'Articles',
    component: articles,
    props: true
  },
  {
    path: '/articles/:id',
    name: 'ArticlesId',
    component: () => import(/* webpackChunkName: "articlesId" */'../views/ArticlesId'),
    // component: articlesId,
    props: true
  },
  {
    path: '/about',
    name: 'About',
    component: () => import(/* webpackChunkName: "about" */'../views/About'),
    //component: about,
    props: true
  },
  {
    path: '/samples',
    name: 'Samples',
    component: () => import(/* webpackChunkName: "samples" */'../views/Samples'),
    //component: samples,
    props: true
  },
  {
    path: '/contact',
    name: 'Contact',
    component: () => import(/* webpackChunkName: "contact" */'../views/Contact'),
    //component: contact,
    props: true
  }
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

export default router;

The problem that occurs here is that every page must be loaded at least one time to show the data that is below the nav links correctly. The rest of the page loads correctly, but the part below the links that contains different data for each route does not work correctly. It does not show me any error or warning, and I want to know why this is happening and how to resolve that?

A: I think the issue might come from using this function on created():
created() {
            window.addEventListener('beforeunload', this.rouFunc() );
        },

what you could do is to call this.rouFunc() directly on created(), because the window.addEventListener won't be triggered, as created() is done synchronously after the instance is created (see the lifecycle hooks for Vue2 here).


text:
Q: How do I Parse an AST in Python to Find Just the Variables I'm looking to build an extremely restricted lambda processor submitted by users. I'm using the following code to do so:
import ast, operator
from math import *

#make a list of safe functions
safe_list = ["math", "lambda"]

# use the list to filter the local namespace
safe_dict = dict([(k, locals().get(k, None)) for k in safe_list])

all_args = []
user_submitted_fxn_example = "d>15"
node = ast.parse(user_submitted_fxn_example, mode="eval")
for elem in ast.walk(node):
  if isinstance(elem, ast.Name):
    all_args.append(str(elem.id))

lambda_string = f"lambda {','.join(all_args)}: {fxn}"
a = eval(f"lambda {','.join(all_args)}: {fxn}", {"__builtins__": None}, safe_dict)
print(a(11)) # => Correctly reports 'False'

According to this, the right way to build the list of variables to put in the lambad is with ast.Name but when I do the following, I get both sin and x as a Name.
user_submitted_fxn_example = "sin(d)>0.5"

What am I doing wrong?

A: ast.Call nodes represent function calls. They have 2 key attributes: func and args. The ast.Name node in func represents the method name. args is a list of ast nodes. You might want to do a depth-first search for each node in args, and then look for ast.Name nodes. The reason for doing a DFS is that you could have an input like sin(f(x)), where f(x) would be yet another ast.Call node which contains ast.Name in the args field.
I recommend that you play around with some examples here.


text:
Q: Convert storage macro from frame v1 to frame v2 The title is very descriptive.
I would like to convert this:
decl_storage! {
    trait Store for Module<T: Config> as SimpleTreasury {
        // No storage items of our own, but we still need decl_storage to initialize the pot
    }
    add_extra_genesis {
        build(|_config| {
            // Create the charity's pot of funds, and ensure it has the minimum required deposit
            let _ = T::Currency::make_free_balance_be(
                &<Module<T>>::account_id(),
                T::Currency::minimum_balance(),
            );
        });
    }
}

into frame V2. Below I have my converted version but it seems not working, the minimum balance seems not being set correctly.
#[pallet::genesis_config]
    #[derive(Default)]
    pub struct GenesisConfig {

    }

    #[pallet::genesis_build]
    impl<T: Config> GenesisBuild<T> for GenesisConfig {
        fn build(&self) {
            let _ = T::Currency::make_free_balance_be(
                &<Module<T>>::account_id(),
                T::Currency::minimum_balance(),
            );
        }
    }

Can somebody take a look and tell me what's wrong. I would really appreciate it.
Pallet Github link: https://github.com/herou/recipes/tree/recipes_pallet_v2/pallets/charity
Note: Some tests are failing

A: The pallet macro has a section about upgrading from decl_* macros: https://substrate.dev/rustdocs/latest/frame_support/attr.pallet.html#upgrade-guidelines
I advise to read carefully the section.
To say few points of this doc I can say:

*

*there is a helper inside decl_storage to generate some code for the new pallet macro. By running the macro expansion with the environment variable PRINT_PALLET_UPGRADE: e.g. PRINT_PALLET_UPGRADE=1 cargo check -p $my_pallet$.

*The pallet prefix that the storage use is configured differently: in decl_storage the pallet prefix is given (e.g. SimpleTreasury in your example). Now the pallet prefix is the name configured when constructing the runtime. (e.g. in construct_runtime call, when it is written: MyPalletName: path_to_pallet::{Call, ...},, the name MyPalletName). If the name are different you can use some utility function to create a migration: https://substrate.dev/rustdocs/latest/frame_support/storage/migration/index.html

*The attributes config() and build() that put specific values into the storage should now be put into the GenesisConfig::build implementation.

*Usually the hashers and types to use when declaring the storage should be quite straightforward. But people must be careful about the QueryKind generic. If the storage was written with a value Option<$Something> then the querykind is an OptionQuery, otherwise it is a ValueQuery. (but the helper with PRINT_PALLET_UPGRADE must give you the correct translation.)


text:
Q: Text effect to enhance readability of small fonts In a view I have a smaller font, foreground is white and background is dark grey.
At the moment I use a drop shadow effect like
 <DropShadowEffect BlurRadius="0"
    Opacity="0.99"
    ShadowDepth="1"
    Direction="270"
    Color="Black"

This looks zoomed as this:

It works good on bigger fontsizes, but not very good on small scales as can be seen here:

What would be a good text effect to enhance overall readability?
I found this question which uses an outer stroke around the text,
but it does not work at all on smaller fontsizes.

A: For completeness:
As@sa_ddam213 said use TextFormattingMode.
Furthermore you can experiment with the Anti-Aliasing algorithms via TextRenderingMode.
If you use ClearType, you can additionally experiment with ClearTypeHint.
Alternatives are use larger text or a font specially designed for small sizes like a pixel font.


text:
Q: Many inserts inside a begin-end block I have a sql script containing over 150k lines of statements (most of them are inserts). I only want to execute those inserts if the table is empty:
IF EXISTS (SELECT * FROM [MyTable])
BEGIN
    PRINT 'No need to insert data'
    --Stop executing script
END
ELSE
BEGIN
    --INSERT #1
    --...
    --Insert #150000
END

Problem: it seems like the ELSE block is too large. I tried to use GO, but it doesn't work inside BEGIN-END blocks. How can I solve this problem?

A: To counter the huge else block, you could use any one the the following 3 strategies.
STRATEGY 1
Use Bulk insert from SQL Server. Just dump all your data into a csv file and use the following statement in your else block. Store the csv file on your computer and give it's UNC path after FROM in statement below. This way you will only have a single line in your else block.
BULK INSERT dbo.MyTable
FROM '\\share\somepath\myTableInsertData.csv'
WITH (FORMAT = 'CSV');

STRATEGY 2
Write a stored procedure that inserts only x rows at a time. You could then call this stored procedure in a While loop and your else block would be very small.  You would call this stored procedure repeatedly in a while loop from your original SQL and then the else block would end being just a few lines of t-sql code.
Note that you can control how many rows are inserted by the stored procedure at a time by using an appropriate value for the variable @numberOfRowsAtaTime. I have used 1000 so in a single call of stored procedure 1000 rows get inserted.
Of course, based on your business rules you can script the stored procedure's insert statements. If you have a pattern in your INSERTS then you could script that pattern into the stored procedure logic below.
Stored Procedure
CREATE PROCEDURE dbo.insertXRows
    @startIndex INT,
    @numberOfRows INT
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @counter INT;
    SET @counter = @startIndex;

    WHILE @counter < (@startIndex + @numberOfRows -1)
    BEGIN
    -- Insert statements for rows goes here
    --INSERT FOR @counter -- @counter would be different for each iteration
      SET @counter =  @counter + 1;
    END
END
GO

Your SQL
IF EXISTS (SELECT * FROM [MyTable])
BEGIN
    PRINT 'No need to insert data'
    --Stop executing script
END
ELSE
BEGIN

    declare @insertRowCounter int;
    set @insertRowCounter = 1;
    declare @numberOfRowsAtaTime int;
    set @numberOfRowsAtaTime = 1000;
    WHILE @insertRowCounter <= 150000
      EXEC dbo.insertXRows @insertRowCounter, @numberOfRowsAtaTime -- insert 1000 rows at a time
      SET @insertRowCounter = @insertRowCounter + @numberOfRowsAtaTime;
    END
END

STRATEGY 3
Come up with 10 stored procedures so that each stored procedure has 15000 INSERTS. Then simply call these 10 stored procedures from your else block.
10 stored procedures
CREATE PROCEDURE dbo.insertProc1
  AS
BEGIN

    SET NOCOUNT ON;

    --INSERT1
    --INSERT2

     --INSERT15000

    END
END
GO

CREATE PROCEDURE dbo.insertProc2
  AS
BEGIN

    SET NOCOUNT ON;

    --INSERT15001
    --INSERT15002

     --INSERT3000

    END
END
GO

Your SQL
IF EXISTS (SELECT * FROM [MyTable])
BEGIN
    PRINT 'No need to insert data'
    --Stop executing script
END
ELSE
BEGIN
   EXEC insertProc1
   EXEC insertProc2
   EXEC insertProc3
   EXEC insertProc4
   EXEC insertProc5
   EXEC insertProc6
   EXEC insertProc7
   EXEC insertProc8
   EXEC insertProc9
   EXEC insertProc10
END

A: You could make use of NOEXEC:
create table T (ID int not null)
go
if 1=1
begin
    set noexec on
end
go
insert into T(ID) values (1),(2),(3)
--Repeat more inserts
go
set noexec off
go
select * from T

Which just prints an empty table - hopefully you can see how this would be adapted to your scripts.

A: Can't you simply add this block at the start of your big script, without else begin ... end construct?
IF EXISTS (SELECT * FROM [MyTable])
BEGIN
    PRINT 'No need to insert data'
    --Stop executing script and return
    RETURN
END
--Your old script starts here

A: How about using a GOTO statement to jump out of the insertion statements?
IF EXISTS (SELECT * FROM [MyTable])
BEGIN
    GOTO NODATA
END

--INSERT #1
--...
--Insert #150000

NODATA:
    PRINT 'No need to insert data'


text:
Q: Does there exist an explicit formula for calculating $\sin(x)$? Here's my idea. We have sets $C=\{(x,y):x,y \in \mathbb{R} \land x^2 + y^2 = 1\}$ and $L = \{ (x,y) : x,y,k \in \mathbb{R} \land y = kx \}$. Their intersection can be written as $C \cap L = \{ (x,y) : x^2 + y^2 = 1 \land y = kx \}$. By substituting $kx$ for $y$, we obtain a formula whose solutions for $x$ will be the $x$ coordinates of the points in the intersection.
\begin{align*}
x^2 + (kx)^2 &= 1 \\
x^2 &= \frac{1}{1 + k^2} \\
x &= \pm\sqrt{\frac{1}{1 + k^2}}.
\end{align*}
The motivation for this equation is that if we could somehow express $k$ in terms of radians, we would have a general equation for calculating $\sin(x)$ for any real value. (Here, we are assuming the definition of $\sin$ as the $x$ coordinate of the intersection between a unit circle and a ray, determined by some angle $\theta$.)
I haven't been able to find an equation for $k(\theta)$, but I suspect that it is $\tan(\theta)$ (as some nice values, such as $0$ and $\pi/4$ give the correct results for $k$: $0$ and $1$ respectively), which is problematic, since $\tan$ is usually defined by $\sin$, and if it weren't, we would have to define it independently first in order to obtain an equation for $\sin$. I also suspect that an explicit formula for $\sin(x)$ doesn't exist, as we would have learned it early on in school if it were so easy.
So, what's your thoughts on this? Thanks for all the help. :)

A: It's called the Maclaurin/Taylor series for $\sin(x)$:
$$\sin(x)= \sum_{n=0}^\infty(-1)^n \frac {x^{2n+1}}{(2n+1)!}.$$
You can read more on https://en.m.wikipedia.org/wiki/Taylor_series or watch 3b1b's YouTube video on Taylor series in his Essence of Calculus playlist.


text:
Q: Python: convert string from UTF-8 to Latin-1 I feel stacked here trying to change encodings with Python 2.5
I have XML response, which I encode to UTF-8: response.encode('utf-8'). That is fine, but the program which uses this info doesn't like this encoding and I have to convert it to other code page. Real example is that I use ghostscript python module to embed pdfmark data to a PDF file - end result is with wrong characters in Acrobat.
I've done numerous combinations with .encode() and .decode() between 'utf-8' and 'latin-1' and it drives me crazy as I can't output correct result.
If I output the string to a file with .encode('utf-8') and then convert this file from UTF-8 to CP1252 (aka latin-1) with i.e. iconv.exe and embed the data everything is fine.
Basically can someone help me convert i.e. character á which is UTF-8 encoded as hex: C3 A1 to latin-1 as hex: E1?

A: data="UTF-8 data"
udata=data.decode("utf-8")
data=udata.encode("latin-1","ignore")

Should do it.

A: Can you provide more details about what you are trying to do? In general, if you have a unicode string, you can use encode to convert it into string with appropriate encoding. Eg:
>>> a = u"\u00E1"
>>> type(a)
<type 'unicode'>
>>> a.encode('utf-8')
'\xc3\xa1'
>>> a.encode('latin-1')
'\xe1'

A: Instead of .encode('utf-8'), use .encode('latin-1').

A: If the previous answers do not solve your problem, check the source of the data that won't print/convert properly.
In my case, I was using json.load on data incorrectly read from file by not using the encoding="utf-8". Trying to de-/encode the resulting string to latin-1 just does not help...


text:
Q: undefined method `Ques_id' for # In my application Questionnaires its my controller in that one datatype is t.integer "Ques_id" its not able to acess in my index page.when i run the index page then i will get NoMethodError in Questionnaires#index  error. How to solve this error?
table
class CreateQuestionnaires< ActiveRecord::Migration
  def up
    create_table :questionnaires do |t|
      #t.column "id", :string, :limit => 25
      t.integer "Ques_id"
      t.string "Qname"
      t.string "Header"
      t.string "Description"
      t.string "username"

    end
  end
   def down
     drop_table :questionnaires
   end
end

controller
class QuestionnairesController < ApplicationController
 # layout false
  layout "admin"
    def index
    @questionnaires = Questionnaires.sorted()
    end

  def view
    @questionnaires= Questionnaires.find(params[:id])
  end

  def new
    @questionnaires= Questionnaires.new()
  end

  def create
    # Instantiate a new object using form parameters
    @questionnaires = Questionnaires.new(questionnaires_params)
    # Save the object
    if @questionnaires.save
      # If save succeeds, redirect to the index action
      flash[:notice] = "questions saved successfully."
      redirect_to(:action => 'index')
    else
      # If save fails, redisplay the form so user can fix problems
      render('new')
    end
  end

  def edit
    @questionnaires = Questionnaires.find(params[:id])
  end

  def update
    # Find an existing object using form parameters
    @questionnaires= Questionnaires.find(params[:id])
    # Update the object
    if @Questionnaires.update_attributes(questionnaires_params)
      # If update succeeds, redirect to the index action
      flash[:notice] = "questions updated successfully."
      redirect_to(:action => 'view', :id => @questionnaires.id)
    else
      # If update fails, redisplay the form so user can fix problems
      render('edit')
    end
  end

  def delete
    @Questionnaires= Questionnaires.find(params[:id])
  end

  def destroy
    questionnaires = Questionnaires.find(params[:id]).destroy
    flash[:notice] = "questions '#{Questionnaires.name}' destroyed successfully."
    redirect_to(:action => 'index')
  end

  private

    def questionnaires_params
      # same as using "params[:subject]", except that it:
      # - raises an error if :subject is not present
      # - allows listed attributes to be mass-assigned
      params.require(:questionnaires).permit(:Ques_id,:Qname, :Header, :Description, :visible)
    end

end

index page here i got error
<% @page_title = "Questionnaires" %>

<div class="Questionnaires index"

Questionnaires

  <%= link_to("Add New questions", {:action => 'new'}, :class => 'action new') %>

<%= pluralize(@questionnaires.size, 'questionnaires') %> found

  Questionnaires

      Ques_id
      Qname
      Header
      Description
      Actions

    <% @questionnaires.each do |objQuestionaire| %>
    <tr class="<%= cycle('odd', 'even') %>">

      <%= objQuestionaire.Ques_id %>
      <%= objQuestionaire.Qname %>
      <%= objQuestionaire.Header %>
      <%= objQuestionaire.Description %>

        <%= link_to("view", {:action => 'view', :id => objQuestionaire.id}, :class => 'action view') %>

         <%= link_to("edit", {:action => 'view', :id => objQuestionaire.id}, :class => 'action edit') %>

      <%end %>

##its my error page
 Showing /home/cabox/workspace/app_1/app/views/questionnaires/index.html.erb where line #20 raised:

undefined method `Ques_id' for #<Questionnaires:0x007fcc490c88f8>

Extracted source (around line #20):

17
18
19
20
21
22
23

       <% @questionnaires.each do |objQuestionaire| %>
       <tr class="<%= cycle('odd', 'even') %>">

         <%= objQuestionaire.Ques_id %>
         <%= objQuestionaire.Qname %>
         <%= objQuestionaire.Header %>
         <%= objQuestionaire.Description %>

Rails.root: /home/cabox/workspace/app_1
Application Trace | Framework Trace | Full Trace

app/views/questionnaires/index.html.erb:20:in `block in _app_views_questionnaires_index_html_erb__3549852765576469128_70257686505360'
app/views/questionnaires/index.html.erb:17:in `_app_views_questionnaires_index_html_erb__3549852765576469128_70257686505360'

A: It is looking for a Ques_id column in your table(Questionnaires) which is not been migrated yet. So only it throws
 `NoMethodError`

Please update your database by doing
rake db:migrate

which will migrate all the required fields defined in the migration file to your database so that it will not throw error.


text:
Q: Проблема с импортом react gulp Доброе время суток проблема с импоротом react ошибки покзывает на первый импорт все установил через npm
let React = require('react');
let ReactDOM = require('react-dom');

ReactDOM.render(

Hello, world!
,
  document.getElementById('root')
);

Uncaught ReferenceError: require is not defined

A: попробуйте
import React from 'react';
import ReactDom from 'react-dom';


text:
Q: AVAssetWriterInput does not currently support AVVideoScalingModeFit I'm trying to crop a video using AVAssetWriter. I need more in-depth control over the output than the presets for AVAssetExportSession provide.  I am trying to use the output mode AVVideoScalingModeFit with my AVAssetWriterInput but this causes a crash stating:

AVAssetWriterInput does not currently support AVVideoScalingModeFit

Here are the video settings I am using:
   let videoSettings: [String : Any] = [
        AVVideoCodecKey: AVVideoCodecH264,
        AVVideoWidthKey: 450,
        AVVideoHeightKey: 450,
        AVVideoScalingModeKey: AVVideoScalingModeFit,
        AVVideoCompressionPropertiesKey: [
            AVVideoAverageBitRateKey: 1000000,
            AVVideoProfileLevelKey: AVVideoProfileLevelH264Baseline41,
            AVVideoAllowFrameReorderingKey: false,
            AVVideoExpectedSourceFrameRateKey: 23
        ]
    ]

My questions are two fold: 1) Why does this mode exist if I can't use it? 2) If I can use it, how am I supposed to do so?
Others have asked this question but it remains unanswered. See: here.

A: 1) Just because AVAssetWriter doesn't support AVVideoScalingModeKey, doesn't mean it's not supported somewhere else in AVFoundation.
2) Scale the video frames yourself using Core Image or a VTPixelTransferSession or whatever is appropriate for your pipeline.


text:
Q: calling json-rpc via curl I'am running Bitcoin-qt 0.8.6.1-beta on Qt 4.8.3 on windows 7 64.
below is my .conf content in %appdata%/bitcoin folder
rpcuser=bitcoinrpc
rpcpassword=ahything
rpcallowip=127.0.0.1
rpcallowip=192.168.*.*
rpcport=9332
server=1
daemon=0
addnode=69.164.218.197

using curl 7.26.0 (i686-pc-mingw32), I run the following command:
curl --user 'bitcoinrpc' --data-binary '{"jsonrpc":"1.0","id":"curltext","method":"getinfo","params":[]}' -H 'content-type:text/plain;' http://127.0.0.1:8332

the pc ask for host password.
I have tried the .conf password and the PC password (which is the one I log into my PC)
I always get error 401 (unauthorized) result.
Can anyone advice me where did I went wrong or how do I know which password it refer to?
TIA
Regards,
KK Gian

A: You need to remove the '' around the username
eg:
curl --user bitcoinrpc --data-binary '{"jsonrpc":"1.0","id":"curltext","method":"getinfo","params":[]}' -H 'content-type:text/plain;' http://127.0.0.1:8332


text:
Q: Adding OData Connected Service to the project failed: Value cannot be null. Parameter name: path1 I am using ASP API 2 with OData v3 and Visual Studio 2017 Community  .. I am trying to consume this API by OData Connected Service, and I followed this instructions then it throws error:
Adding OData Connected Service to the project failed: Value cannot be null.
Parameter name: path1
Error
so how to handle that issue ?

A: To clarify CRice's response:
Install the WCF Data Services 5.0 for OData V3
 https://www.microsoft.com/en-us/search/result.aspx?q=WCF+Data+Services
1-Add the Odata Connected Service extension
2-Verify registry contents:
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Microsoft WCF Data Services]

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Microsoft WCF Data Services\5.0]
"Version"="5.0.51212.0"
"InstallLocation"="C:\\Program Files (x86)\\Microsoft WCF Data Services\\5.0\\"

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Microsoft WCF Data Services\VS 2014 Tooling]
"Version"="5.0.51212.0"
"InstallLocation"="C:\\Program Files (x86)\\Microsoft WCF Data Services\\5.0\\"

3-Use the Add Connected Service Reference context menu from VS 2017

A: There has been success for some people with adding registry keys that tell the connected service plugin where the WCF Data Services files are installed.
See https://github.com/OData/lab/issues/64
You can try make a .reg file with the following after you check the paths and run it.
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Microsoft WCF Data Services]
[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Microsoft WCF Data Services\VS 2014 Tooling]
"Version"="5.6.61587.0"
"InstallLocation"="C:\Program Files (x86)\Microsoft WCF Data Services\5.6\"

I think if this will work may depend on what version of visual studio you are running, it has not fixed the issue for me yet.  I will update this answer when I find out how to get it going in VS2017.

A: I had another error

Adding OData Connected Service to the project failed: Cannot write to
a closed TextWriter.

But when I search for it I land here, that's why I want to leave an answer for that problem.
In my case metadata xml file with edmx contained the following line
<Annotation Term="Core.SchemaVersion" String="1.0.0" xmlns="http://docs.oasis-open.org/odata/ns/edm"/>

The problem was solved by removing this line.


text:
Q: Moving the perspective vanishing point in Processing My application has a split screen mode where just half of the screen is used to display the 3d scene. So I want the vanishing point to be placed in the middle of the left half.
I already tried various combinations of camera() and translate() but the vanishing point doesn't move one pixel from the center of the sketch window..
void setup(){
  size(800,400, P3D);
  fill(255,120);
}

void draw(){

  background(111);

  float camEyeX = 0;
  float camEyeY = 400;
  float camEyeZ = (height/2) / tan(PI/6);
  float camCenterX = 0;
  float camCenterY = -200;
  float camCenterZ = 0;
  float camUpX = 0;
  float camUpY = 1;
  float camUpZ = 0;

  pushMatrix();
  camera( camEyeX, camEyeY, camEyeZ, camCenterX, camCenterY, camCenterZ, camUpX, camUpY, camUpZ );
  translate( -200, 0, 0);
  rectMode(CENTER);
  rect(0,0, 800,400);
  rect(0,0, 100,100);
  popMatrix();
  hint(DISABLE_DEPTH_TEST);
  rectMode(CORNER);
  rect(400,0, 400,400);
  hint(ENABLE_DEPTH_TEST);
}

On this topic I just found this unanswered question asked a decade ago...
Does anyone know if this is possible to achieve at all?

A: You could just use the createGraphics() function to create a buffer for your left viewport, then draw to the buffer, then draw the buffer to the screen.
PGraphics leftSide;

void setup(){
  size(800,400, P3D);
  leftSide = createGraphics(width/2, height, P3D);
}

void draw(){

  leftSide.beginDraw();
  leftSide.background(111);

  float camEyeX = 0;
  float camEyeY = 400;
  float camEyeZ = (height/2) / tan(PI/6);
  float camCenterX = 0;
  float camCenterY = -200;
  float camCenterZ = 0;
  float camUpX = 0;
  float camUpY = 1;
  float camUpZ = 0;

  leftSide.pushMatrix();
  leftSide.camera( camEyeX, camEyeY, camEyeZ, camCenterX, camCenterY, camCenterZ, camUpX, camUpY, camUpZ );
  leftSide.translate( -200, 0, 0);
  leftSide.rectMode(CENTER);
  leftSide.rect(0,0, 800,400);
  leftSide.rect(0,0, 100,100);
  leftSide.popMatrix();
  leftSide.hint(DISABLE_DEPTH_TEST);
  leftSide.rectMode(CORNER);
  leftSide.rect(400,0, 400,400);
  leftSide.hint(ENABLE_DEPTH_TEST);

  leftSide.endDraw();

  image(leftSide, 0, 0);
}

More info can be found in the reference.


text:
Q: Apache virtual hosts on subdirectories I am trying to setup Apache to serve multiple apps on one IP-Address over subdirectories. Lets say, I would like to access App1 over http://aaa.bbb.ccc.ddd/app1 and App2 over http://aaa.bbb.ccc.ddd/app2. Both, App1 and App2, are independent django projects. I ensured, that both apps are working fine by serving only one of them over Apache.
I added the following lines to the httpd.conf file of Apache:
# App1
<VirtualHost *:80>
    DocumentRoot "D:/Projects/App1/App1"
    ServerName App1

    <Directory "D:/Projects/App1/App1">
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    WSGIScriptAlias /app1 "D:/Projects/App1/App1/wsgi.py"
</VirtualHost>

# App2
<VirtualHost *:80>
    DocumentRoot "D:/Projects/App2/App2"
    ServerName App2

    <Directory "D:/Projects/App2/App2">
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    WSGIScriptAlias /app2 "D:/Projects/App2/App2/wsgi.py"
</VirtualHost>

Working like this results into an error saying "Forbidden, You don't have permission to access this resource." when I call http://aaa.bbb.ccc.ddd/app2 from another machine. Similar to this, if I put the App2 virtual host in front of the App1 virtual host, I can not access http://aaa.bbb.ccc.ddd/app1 anymore. So it is either App1 or App2 that is accessible, but never both of them.
First question: Is my idea of serving to webpages over sub-URL's even possible? If not, what would be the alternative? Using different ports for different applications? If it is a "valid" approach, why do I have access to just one but not both apps at with this configuration.

A: The purpose of the VirtualHost directive is to provide different applications based on the requested hosts.
To resolve an application based on the directory, you may use the  Alias directive instead of VirtualHost.


text:
Q: ReactJs - Issue in routering the component I'm using the HashRouter dependency that is mandatory for the project I'm doing and the <BillingCycle /> component is not appearing on the screen. When I click on the link, the url: http://localhost:8080/#/billingCycles appears in the browser but does not change the page, the Dashboard page continues to appear. No error message appears. Did I forget something?
import React from 'react'
import { HashRouter, BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom';

import Dashboard from '../dashboard/Dashboard'
import BillingCycle from '../billingCycle/BillingCycle'

export default props => (
  <HashRouter>
    <Switch>
      <Route exact path='/billingCycles' component={BillingCycle} />
      <Route exact path='/' component={Dashboard} />
      <Redirect from='*' to='/' />
    </Switch>
  </HashRouter>
)

Below, I have the parent component that imports the <Route /> component
import '../common/template/dependencies'
import React from 'react'

import Header from '../common/template/Header'
import SideBar from '../common/template/SideBar'
import Footer from '../common/template/Footer'
import Routes from './Routes'

export default (props) => (

    <SideBar />

     <Routes />

)

Down here I have the link component that is clicked to direct to the  component.
import React from 'react'
import MenuItem from './MenuItem'
import MenuTree from './MenuTree'

export default props => (

    <MenuItem path='#' label='Dashboard' icon='dashboard' />
    <MenuTree label='Cadastro' icon='edit'>
      <MenuItem path='#/billingCycles' label='Ciclos de Pagamentos'icon='usd'/>
    </MenuTree>

)

A: In order to re-route using React-Router you need to make use of the Link component which is unique to the library.
First bring in the Link component from the library. Then wrap the MenuItem component inside a Link like so.
import { Link } from "react-router-dom"

   <Link to='/billingCycles'>
      <MenuItem label='Ciclos de Pagamentos'icon='usd'/>
   </Link>


text:
Q: how to change button text after succes in ajax I want to change button text on success.. I want to change this to accepted after success
    <button type="button" onclick="saveData<?php echo $row1->id; ?>()">Accept</button>
      <script>
      function saveData<?php echo $rrr->id; ?>(){

      $.ajax({
        type: "POST",
        url: "<?php echo base_url().'home/accept_seller/'. $rrr->id; ?>",
        data:{},
        success:function( data )
        {

        }
       });
  }

My function is properly working because i have used alert after success but i dontknow how to chage its text after success. pls help

A: You can associate a class with the button:
<button type="button" onclick=".." class="submit-btn">Accept</button>

Now, in your AJAX success code, mention the following:
 $.ajax({
    type: "POST",
    url: "<?php echo base_url().'home/accept_seller/'. $rrr->id; ?>",
    data:{},
    success:function( data ) {
       $(".submit-btn").html("Accepted");   // Add this line
    }
});

A: $.ajax({
  type: "POST",
  url: "<?php echo base_url().'home/accept_seller/'. $rrr->id; ?>",
  data: {},
  success: function(data) {
   $("#btn").text('your new text here'); // add id to your button
  }
});

<button id="btn" type="button" onclick="saveData<?php echo $row1->id; ?>()">Accept</button>

A: 1) pass this in function
2) Use .text() function to change text of button.
<button type="button" onclick="saveData<?php echo $row1->id; ?>(this)">Accept</button>
<script>
          function saveData<?php echo $rrr->id; ?>(obj){
              $.ajax({
                 type: "POST",
                 url: "<?php echo base_url().'home/accept_seller/'. $rrr->id; ?>",
                 data:{},
                 success:function( data )
                 {
                      $(obj).text("New Text");
                 }
              });
          }
</script>

A: HTML : add id in button
<button type="button" id="accept" onclick="saveData<?php echo $row1->id; ?>()">Accept</button>

script:
 success:function( data ) {
       $("#accept").html("accepted");
    }

A: id; ?>()">Accept

      function saveDataid; ?>(){
  $.ajax({
    type: "POST",
    url: "<?php echo base_url().'home/accept_seller/'. $rrr->id; ?>",
    data:{},
    success:function( data )
    {
       $("#buttonid").html('Changetext');
    }
   });


text:
Q: How to validate & instantiate Java Locale from strings? My app is being fed string from an external process, where each string is either 2- or 5-characters in length, and represents a java.util.Locales. For example:

en-us
ko

The first example is a 5-char string where "en" is the ISO language code, and "us" is the ISO country code. This should correspond to the "en_US" Locale. The second example is only a 2-char string, where "ko" is the ISO language code, and should correspond to the "ko_KR" (Korean) Locale.
I need a way to take these strings (either the 2- or 5-char variety), validate it (as a supported Java 6 Locale), and then create a Locale instance with it.
I would have hoped that Locale came with such validation out of the box, but unfortunately this code runs without exceptions being thrown:
Locale loc = new Locale("waawaaweewah", "greatsuccess");

// Prints: "waawaaweewah"
System.out.println(loc.getDisplayLanguage());

So I ask, given me the 2 forms that these string will be given to me in, how can I:

*

*Validate the string (both forms) and throw an exception for strings corresponding to non-existent or unsupported Java 6 Locales; and

*Instantiate a new Locale from the string? This question really applies to the 2-char form, where I might only have "ko" and need it to map to the "ko_KR" Locale, etc.

Thanks in advance!

A: Locale.getISOCountries() and Locale.getISOLanguages()
return a list of all 2-letter country and language codes defined in ISO 3166 and ISO 639 respectively and can be used to create Locales.
You can use this to validate your inputs.

A: You have two options,

*

*Use a library for doing this commons-lang has the LocaleUtils class that has a method that can parse a String to a Locale.

*While your own method, the validation here is non trivial as there are a number of different sets of country codes that a valid for a Locale - see the javadoc
A starting point would be to split the String and switch on the number of elements:
public static Locale parseLocale(final String locale) {
    final String[] localeArr = locale.split("_");
    switch (localeArr.length) {
        case 1:
            return new Locale(localeArr[0]);
        case 2:
            return new Locale(localeArr[0], localeArr[1]);
        case 3:
            return new Locale(localeArr[0], localeArr[1], localeArr[2]);
        default:
            throw new IllegalArgumentException("Invalid locale format;");
    }
}

Presumably you would need to get lists of all valid country codes and languages and compare the elements in the String[] to the valid values before calling the constructor.


text:
Q: the identifier __VA_ARGS__ can only appear in the replacement lists of variadic macros I am attempting to create a macro to perform api calls. My current issue is the passing of parameters for the call. I get the following error message:

the identifier __VA_ARGS__ can only appear in the replacement lists of variadic macros

#define DO_CALL(api_name)(...) wow64hg::do_call(FNV(#api_name), __VA_ARGS__)

const auto status = DO_CALL(TerminateProcess)(process_handle, 0);

It technically may be possible to fix this by using operator loading, but I am confident there should be a way to keep it simple like this and get it to work.

A: Variadic macro syntax doesn't work like that; the ... has to represent additional arguments of the macro.  A macro can't take multiple sets of arguments in separate sets of parentheses like an iterated function call.
I think you have to do the following:
#define DO_CALL(api_name, ...) wow64hg::do_call(FNV(#api_name), __VA_ARGS__)

const auto status = DO_CALL(TerminateProcess, process_handle, 0);


text:
Q: How to change the font of percent signs? In my document below, I would like to change the font of all percent signs to the font of the attached image. How can I do it?
BTW, I'm using XeLaTeX on TL2012.

\documentclass{article}
\begin{document}
\texttt{\%}
\[
\%
\]
\begin{tabular}{c}
$\%$
\end{tabular}
\end{document}

A: pcrr8a is just an 8 letter name of an 8bit encoding for old systems, you just want Courier which you can load as a system font in xetex and use in maths just by using
\texttt{\char`\%}

after having set up \texttt to use Courier rather than computer modern


text:
Q: How do I get value function/critic values from Rllib's PPO algorithm for a range of observations? Goal: I want to train a PPO agent on a problem and determine its optimal value function for a range of observations. Later I plan to work with this value function (economic inequality research). The problem is sufficiently complex so that dynamic programming techniques no longer work.
Approach: In order to check, whether I get correct outputs for the value function, I have trained PPO on a simple problem, whose analytical solution is known. However, the results for the value function are rubbish, which is why I suspect that I have done sth wrong.
The code:
from keras import backend as k_util
...

parser = argparse.ArgumentParser()

# Define framework to use
parser.add_argument(
    "--framework",
    choices=["tf", "tf2", "tfe", "torch"],
    default="tf",
    help="The DL framework specifier.",
)
...

def get_rllib_config(seeds, debug=False, framework="tf") -> Dict:
...

def get_value_function(agent, min_state, max_state):
    policy = agent.get_policy()
    value_function = []
    for i in np.arange(min_state, max_state, 1):
        model_out, _ = policy.model({"obs": np.array([[i]], dtype=np.float32)})
        value = k_util.eval(policy.model.value_function())[0]
        value_function.append(value)
        print(i, value)
    return value_function

def train_schedule(config, reporter):
    rllib_config = config["config"]
    iterations = rllib_config.pop("training_iteration", 10)

    agent = PPOTrainer(env=rllib_config["env"], config=rllib_config)
    for _ in range(iterations):
        result = agent.train()
        reporter(**result)
    values = get_value_function(agent, 0, 100)
    print(values)
    agent.stop()

...

resources = PPO.default_resource_request(exp_config)
tune_analysis = tune.Tuner(tune.with_resources(train_schedule, resources=resources), param_space=exp_config).fit()
ray.shutdown()

So first I get the policy (policy = agent.get_policy()) and run a forward pass with each of the 100 values (model_out, _ = policy.model({"obs": np.array([[i]], dtype=np.float32)})). Then, after each forward pass I use the value_function() method to get the output of the critic network and evaluate the tensor via keras backend.
The results:
True VF (analytical solution)
VF output of Rllib
Unfortunately you can see that the results are not that promising. Maybe I have missed a pre- or postprocessing step? Does the value_function() method even return the last layer of the critic network?
I am very grateful for any help!

A: It's not part of your script, but I assume that you have trained the policy before you attempt to get useful values out of it.
You are correct in assuming that the value_function() returns the output of the last layer of the critic network in RLlib's implementations.
Have a look at the value function metrics to see if it's actually learning anything (RLlib logs .../learner_stats/vf_loss and .../learner_stats/vf_explained_var)!
After training the model, I'd also try to query the model directly. If that looks better, something is likely off with the code you posted here.


text:
Q: Proving that a functional is as minimiser I am attempting to prove that $x^*(t)$ (satisfying the boundary conditions of $x(t_0)=x_0$ and $x(t_1)=x_1$) is a minimiser for the functional $$J[x]=\int_{t_0}^{t_1}[c(t)\dot{x}^2(t)+a(t)x(t)^2]dt$$ where $c(t)\geq 1$ and $a(t)\geq0$ for all $t\in[t_0,t_1]$, and they are both twice differentiable, as is $x^*(t)$.
I am trying to show that $\Delta J=J[y]-J[x^*]\geq0$ by letting $y$ be a weak variation such that $y(t)=x^*(t)+ \gamma(t)$ where $\gamma(t)=0$ at both end points and is also twice differentiable. My proof is looking like this, but I keep getting stuck (and I'm not sure if some of my steps are valid).
$$J[y]-J[x]=\int_{t_0}^{t_1}\Big[c(t)\big[\dot{x}^*(t)+ \dot{\gamma}(t)\big]^2+a(t)\big[x^*(t)+\gamma(t)\big]^2\Big]dt-\int_{t_0}^{t_1}[c(t)\dot{x}^{*2}(t)+a(t)x^{*2}(t)]dt$$
$$=\int_{t_0}^{t_1}\Big[c(t)\big[2\dot{x}^*(t)\dot{\gamma}(t)+ \dot{\gamma}^2(t)\big]+a(t)\big[2x^*(t)\gamma(t)+\gamma^2(t)\big]\Big]dt$$
From here I argue that as $c(t),a(t), \gamma^2(t), \dot{\gamma}^2(t)$ and the constant 2 are all positive, we can reduce this to.
$$\int_{t_0}^{t_1}\Big[\dot{x}^*(t)\dot{\gamma}(t)+x^*(t)\gamma(t)\Big]dt$$
From here I would like to use integration by parts but I just seem to be going around and around in circles, not being able to conclude anything. Could you please point out where I am going wrong? Any help is greatly appreciated. Thank you a lot.

A: If $x^*$ satisfies
$$\int_{t_0}^{t_1} c(t) \dot x^*(t) \dot \gamma(t) + a(t)x^*(t)\gamma(t)\, dt=0
$$
(that is essentially the weak form of the Euler-Lagrange equation) then your calculation shows
$$J[y]-J[x^*]=\int_{t_0}^{t_1} c(t)\dot \gamma(t)^2+a(t)\gamma(t)^2 \, dt \ge 0,
$$
and actually $J[y]>J[x^*]=0$ unless $\gamma=0$ (i.e. $y=x^*$). So any solution of the Euler-Lagrange equations is a minimiser.
However, you need the existence of $x^*$ to use this argument, which also can be adapted for other convex variational problems.


text:
Q: What is the best practice to have a variable which lives for application lifetime in Node.js? I am developing a web service 'A' using Node.js, which communicate with an another service 'B'. A needs to get an access token from B at the beginning, and it needs to refresh it when the token expires.
I am not very familiar with Node.js, I need to store access token and refresh token comes from B and refresh them time to time, but I am not sure if there are global variables to do this. For example, in Flask I would have kept my tokens in app['tokens'] and could be update it.
Basically what I want to do is to have a B class and a global object of B, B will have accessToken and refreshToken fields, obj.sendRequest({requestInfo}) will send a request to B service by checking expiration time of tokens and refresh them if necessary.
What is the best practice to overcome such a problem in Node.js?

A: From your question I don't see if you are using TypeScript or not. I highly recommend it, but it is not required. I will give you my answer with a TypeScript example because it is easier to read and understand (I think). Adapting it to pure JS should be easy.
class ApiService {
  private accessToken?: string
  private accessTokenExpires?: Date
  private async getAccessToken(): Promise<void> {
    const apiResult = await GET_TOKEN_FROM_API
    this.accessToken = apiResult.access_token
    this.accessTokenExpires = apiResult.access_token_expires
  }

  public async GetItem(id: string): Promise<Item> {
    if (!this.accessToken || this.accessTokenExpires < new Date()) {
      await this.getAccessToken()
    }

    return GET_ITEM_FROM_API
  }
}

export let itemService = new ItemService()
export function mockitemService(mock: any) {
  itemService = mock
}

at the place where you want to use the class you can
import { itemService } from './services/item'
const item = itemService.getItem('123')

Using ServiceClasses like this makes easier to maintain the code later or to write tests with mocked data sources.


text:
Q: How to add allowDiskUse to mongooperation.find method in spring boot The below query i want to add allowDiskUse true. I am able to add allowDiskUsage to aggregation query but not able to find a solution for find method
Query query = new Query().with(pageable).addCriteria(criteria).collation(collation);
mongoOperations.find(query, RuntimeApplication.class, RUNTIME_APP);

I want to know is that possible to add allowDiskUsage to find method or i need to change query to aggregation.
i just found in below query from internet. but i am not getting how to convert it into spring boot
db.collection.find(<match>).sort(<sort>).allowDiskUse()

A: What kind of spring-data version are you using? You should be able to add allowDiskUse to the Query object just like this:
val query = Query()
    .with(Pageable.ofSize(1))
    .addCriteria(Criteria())
    .allowDiskUse(true)

And then afterwards use the query with find for instance with mongoTemplate.
Here is the documentation: https://javadoc.io/doc/org.springframework.data/spring-data-mongodb/latest/org/springframework/data/mongodb/core/query/Query.html


text:
Q: How to reassemble packets with Java NIO Sockets If I have two connections to a server which require multiple reads on a channel to complete a packet, how will I know which read goes with which packet?
For example two packets which are received as four interleaved buffers:

*

*PacketA buffer part1

*PacketB buffer part1

*PacketA buffer part2

*PacketB buffer part2

The first part MAY have a header but the second part could arrive as being split anywhere along the packet.
When receiving a partial packet, how do I know which buffer goes where?
I'm thinking about building a map to associate each channel object with its respective output buffer which will hold the reassembled packet. Is this the way it's supposed to be done?

A: Indeed, typical practice is to have separate buffers for each channel. You don't necessarily need a map. You could attach extra information to each SelectionKey. Every key can hold an object of your choice that your code can retrieve later. This is a convenient place to store a buffer, or a set of buffers.


text:
Q: Conservation and potential with non-cartesian forces I understand how to determine if a force is conservative from
\begin{equation}
\nabla\times \mathbf{F}=0 \implies \mathbf{F}\text{ is conservative}
\end{equation}
When $F$ is in cartesian coordinates.
What happens if you're given a force such as
\begin{equation}
\mathbf{F}=r\sin\theta e^{i\phi}\hat{r}
\end{equation}
How do you compute the curl and potential?

A: The curl of any vector $\vec{F}$ in spherical polar coordinates is:
$$
\nabla \times \vec{F}  =  \frac{1}{r\sin \theta}\left(\frac{\partial (F_\phi
  \sin \theta) }{\partial \theta} -
                   \frac{\partial F_\theta}{\partial \phi}\right)\,\hat{\boldsymbol r} +
                   \frac{1}{r}\left(\frac{1}{\sin \theta}
                   \frac{\partial F_r}{\partial \phi} - \frac{\partial
                     (r F_\phi)}{\partial r}\right)\,
                   \hat{\boldsymbol \theta} + \frac{1}{r}\left(\frac{\partial (
r
                     F_\theta)}{\partial r} -
                   \frac{\partial F_r}{\partial \theta}\right)\,
                   \hat{\boldsymbol \phi} \ .
$$
To "compute the potential" you would have to solve the equation
$$ \nabla V = -\vec{F}\ , $$
which, in spherical polar coordinates for a force which only has a $\hat{r}$ component, gives three equations:
\begin{eqnarray}
\frac{\partial V}{\partial r} & = & -F_r \\
\frac{1}{r}\frac{\partial V}{\partial \theta} & = & 0 \\
\frac{1}{r\sin \theta}\frac{\partial V}{\partial \phi} & = & 0
\end{eqnarray}
The potential is not uniquely determined because you can add any scalar field with a zero gradient to $V$.


text:
Q: Remove empty string elements from string array in Java I am trying to get the contents of a text file, remove everything other than alphabets and then convert it into an array of Strings for individual processing of words.
I do this for getting the text file :
String temp1= IOUtils.toString(FIS,"UTF-8");
String temp2=temp1.replaceAll("[,.!;:\\r\\n]"," ");

And then to tokenize the string, I do this:
String[] tempStringArray = temp2.split(" ");

The problem is that when the array is created, there are empty String at various indices.These empty String are at the position of linebreak, more than one whitespace, replaced punctuation marks, etc in the text file.
I want these empty Strings to be removed from my String array or in a way which they are unable to enter the String array.
How can this be done?

A: Split by all whitespaces like: String[] tempStringArray = temp2.split("\\s+")

A: In your example, if you have more than one character from your character set [,.!;:\r\n] in a row, it will replace it with more than one empty space. When you call the split() method, it then places empty occurrences in the array that refer to the multiple blank spaces in a row.
You can use a regex in the split() method, which will work a lot better for your example.
Try repacing temp2.split(" ") with temp2.split("\\s+"). This will look for multiple spaces in a row, and just tokenise the text around the large gaps of empty space.

A: While the answers of Daniel Arthur and Young Millie are correct, one can replace the two steps by directly splitting at the Characters you want to avoid:
String[] tempStringArray = temp1.split("[,.!;:\\s]+");


text:
Q: Length of continued fractions Consider, for any pair of relatively prime positive integers $0 <j <n$, the expansion as a continued fraction of the quotient $\frac{n}{j}$
$$
\frac{n}{j}=b_1-\frac{1}{b_2-\dfrac{1}{\cdots-\dfrac{1}{b_l}}}.
$$
Set $l_j^n:=l$ for the length of this expansion and consider the rational number
$$
m(j,n)=\frac{l_j^n+l_{n-j}^n}{n}.
$$
What do we know about the set $M:={m(j,n)}$?
By a Result of Riemenschneider (Lemma 4 in this paper) I know that $l_j^n+l_{n-j}^n=1+ \sum_{i=1}^{l_j^n}(b_i-1)$.
In particular if $j=1$, then $b_1=n$, $l_1^n=1$,  and so $m(1,n)=1$.
It seems to me that $1$ is the maximum possible value, in other words that, for every $j, n, m (j, n) \leq 1$ holds. But I cannot prove it.
In general, I would appreciate any result on $M$. I'm interested in particular to the set $L$ of all possible limits of $m(j_k,n_k)$ for sequences $(j_k,n_k)$ where $n_k\to \infty$.
The sequence $(1,n)$ shows that $1 \in L$.
If my computations are correct, the sequence $(n,2n-1)$ (here $l_n^{2n-1}=2, b_1=2, b_2=n$) shows $\frac{1}{2} \in L$.
Is it possible to determine explicitly the set $L$? Or at least a "big" subset of it?

A: This answer proves the following claims :
Claim 1 : $m(j,n)\le 1$
Claim 2 : For any pair of positive integers $(j,t)$ satisfying $t\lt j$ and $\gcd(j,t)=1$, $\displaystyle\lim_{k\to\infty}m(j,jk+t)=\dfrac 1j$
Claim 3 : For any integer $t\ge 2$, $\displaystyle\lim_{k\to\infty}m(k,tk-1)=\dfrac 1t$
Claim 4 : For any integer $t\ge 1$, $\displaystyle\lim_{k\to\infty}m(k,tk+1)=\dfrac 1t$
Claim 5 : $\displaystyle\lim_{k\to\infty}m(k,k^2-k+1)=0$

Let
$$[b_1,b_2,\cdots, b_l]:=b_1-\frac{1}{b_2-\dfrac{1}{\cdots-\dfrac{1}{b_l}}}$$

Claim 1 : $m(j,n)\le 1$
Proof : Let us prove $$m(j,n)\le 1\tag1$$ by induction on $j$.
If $j=1$, then we have $m(1,n)=1$, so $(1)$ holds.
Suppose that $(1)$ holds for $1,2,\cdots, j-1$ where $j\ge 2$.
We have
$$\frac nj=\left\lceil\dfrac nj\right\rceil-\frac{1}{\dfrac{j}{j\left\lceil\dfrac nj\right\rceil-n}}$$
There are integers $l,b_1,b_2,\cdots, b_l$ such that
$$\dfrac{j}{j\left\lceil\dfrac nj\right\rceil-n}=[b_1,b_2,\cdots, b_l]$$
Using this, we can write
$$\frac nj=\bigg[\left\lceil\frac nj\right\rceil,b_1,b_2,\cdots, b_l\bigg]$$
Since $0\lt j\left\lceil\frac nj\right\rceil-n\lt j$, we have, by the supposition of induction,
$$m\bigg(j\left\lceil\frac nj\right\rceil-n,j\bigg)\le 1$$
which is equivalent to
$$b_1+b_2+\cdots +b_l\le j+l-1\tag2$$
There are positive integers $s,t$ such that $n=sj+t$ with $t\lt j$.
So, we have
$$n-\left\lceil\frac nj\right\rceil-j+1=sj+t-(s+1)-j+1=(s-1)(j-1)+t-1\ge 0$$
from which we have
$$j+l-1\le n+(l+1)-1-\left\lceil\frac nj\right\rceil\tag3$$
It follows from $(2)$ and $(3)$ that
$$\left\lceil\frac nj\right\rceil+b_1+b_2+\cdots +b_l\le n+(l+1)-1$$
which is equivalent to $m(j,n)\le 1$.$\quad\blacksquare$

Claim 2 : For any pair of positive integers $(j,t)$ satisfying $t\lt j$ and $\gcd(j,t)=1$, $\displaystyle\lim_{k\to\infty}m(j,jk+t)=\dfrac 1j$
Proof : We have $\frac{jk+t}j=k+1-\frac{1}{\frac{j}{j-t}}$. There are integers $l,b_1,b_2,\cdots, b_l$ such that $\frac{j}{j-t}=[b_1,b_2,\cdots, b_l]$, so we get $m(j-t,j)=\frac{1-l+b_1+b_2+\cdots +b_l}{j}$ from which we have $b_1+b_2+\cdots +b_l=jm(j-t,j)+l-1$. Using this, we get $m(j,jk+t)=\frac{1+k-l+(jm(j-t,j)+l-1)}{jk+t}=\frac{1+\frac{jm(j-t,j)}{k}}{j+\frac tk}\to\frac 1j$ as $k\to\infty$.$\quad\blacksquare$

Claim 3 : For any integer $t\ge 2$, $\displaystyle\lim_{k\to\infty}m(k,tk-1)=\dfrac 1t$
Proof : Since $\frac{tk-1}{k}=t-\frac 1k$, we get $m(k,tk-1)=\frac{1+t-1+k-1}{tk-1}=\frac{1+\frac{t-1}{k}}{t-\frac 1k}\to \frac 1t$ as $k\to\infty$.$\quad\blacksquare$

Claim 4 : For any integer $t\ge 1$, $\displaystyle\lim_{k\to\infty}m(k,tk+1)=\dfrac 1t$
Proof : Using the fact that $\frac{N+1}{N}=[\underbrace{2,2,\cdots, 2}_{N}]$ which can be proven by induction, we have $\frac{tk+1}k=t+1-\frac{1}{\frac{k}{k-1}}=[t+1,\underbrace{2,2,\cdots, 2}_{k-1}]$, so we get $m(k,tk+1)=\frac{1+(t+1-1)+(k-1)(2-1)}{tk+1}=\frac{1+\frac tk}{t+\frac 1k}\to \frac 1t$ as $k\to\infty$.$\quad\blacksquare$

Claim 5 : $\displaystyle\lim_{k\to\infty}m(k,k^2-k+1)=0$
Proof : Since $\frac{k^2-k+1}{k}=k-\frac{1}{\frac{k}{k-1}}=[k,\underbrace{2, 2, \cdots, 2}_{k-1}]$, we get $m(k,k^2-k+1)=\frac{2k-1}{k^2-k+1}\to 0$ as $k\to\infty$.$\quad\blacksquare$

A: the first question about the lengths of the HJ-Continued fraction can be found in the following paper (preprint) https://arxiv.org/pdf/1912.07378.pdf Lemma 3.3.


text:
Q: Setting per request Time.zone based on a model instance and keeping DRY I have the following code:
around_filter :event_time_zone

def event_time_zone(&block)
  @event.present? ? Time.use_zone(@event.venue.time_zone_name, &block) : yield
end

I placed it in my ApplicationController.
The problem is that the instance variable @event is never set when this around_filter is called. It is however available before the action in every resource controller ( by use of CanCan), however I do not want to sprinkle a bunch of around_filter calls in all those controllers.
Is there a simple way that I can use this above code but not repeat myself everywhere?
I could do a user based time_zone, but what if a user is managing events in different time zones? The only relevant date to display would only ever be in the events time zone.

A: I think your issue has to do with the ordering that the filters are firing, i.e. the around_filter is running before your filter that sets the @event variable
I personally would do this per controller as needed, your application will eventually have many controller/actions that have nothing to do with events.

*

*Setup user based timezone setting/handling which is handled in the application controller

*Set the timezone based on @event as needed to override user setting

You may be interested in this blog post I did on rails timezones (see also the example code on github) - http://jessehouse.com/blog/2013/11/15/working-with-timezones-and-ruby-on-rails/


text:
Q: NSUserDefaults clears its value after specific time I save my dictionary using NSUserDefaults as follow:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dictionary];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"key"];
[[NSUserDefaults standardUserDefaults] synchronize];

// unarchive
NSData *newData = [[NSUserDefaults standardUserDefaults] objectForKey:@"key"];
NSDictionary *newDict = [NSKeyedUnarchiver unarchiveObjectWithData:data];

Problem: The dicitionary contains a name value with some other values, but after specific time period (mostly after 24 Hours), the name values gives me " "(blank) value.
I see this kind of issue first time, help me to solve this.
Thank you.

A: The problem is not in this pice of code.
1) Try to check if your application contains [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"key"] in another classes/methods.
2) Check if NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dictionary]; is not empty when you are writing it (Maybe it get's corrupted, and wipes the already written data).
To check the issue you can make a small versioning and debug the issue, here is the code.
    NSMutableArray *datas = [[[NSUserDefaults standardUserDefaults] objectForKey:@"datas"] mutableCopy];
    if (!datas) {
        datas = [NSMutableArray new];
    }
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dictionary];
    [datas addObject:data];
    [[NSUserDefaults standardUserDefaults] setObject:datas forKey:@"datas"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    // Debug code to see the result
    NSLog(@"======= Logging saved datas");
    for (NSData *data in datas) {
        NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        NSLog(@"%@", dict);
    }

This code will allow you to see all the versions of dictionaries saved in NSUserDefaults, and probably you will get the moment when Empty data is saved.

A: I think you place your code where it is called again after you save for first time and load next time but then your nsdata object is empty.
Scenario :
1st time run app it will save the prefrences
Close the application completely.and then again open your application it again save prefrences while your nsdata object is empty
Edit
Why you not save dictionary directly in NSUserDefaults?


text:
Q: onMouseover custom dictionary that automatically parses contents applies tooltips? I have a website that uses terms which are not "common" and sometimes require clarification.  I have considered creating a JavsScript solution that will read terms from a dictionary file, parse each page and then apply highlighting and an onMouseover tooltip for users to easily read term definitions.
Is there a library that already exists to accomplish this?  I've seen a few things that are half baked options, but nothing is very clean and comprehensive in this regard to what I'm looking for.
To give an example scenario, I'd like for the solution to function similarly:  I would provide a data / definition file something like:
"some term 1", "the definition will be explained over here in verbose terms"
"some term 2", "the definition will be explained over here in verbose terms"
"some term 3", "the definition will be explained over here in verbose terms"

Then the JavaScript, on page load, would parse this definition file.  It would then parse the contents of the dom and isolate each term (some term 1,some term 2, etc.), populating the term's tooltip with the appropriate definition text.  Obviously the elegance of this is that it only ever requires updating the definition file and all of the site content will have a handy dictionary in place for the reader.

A: I would use jQuery UI for this...
http://jqueryui.com/tooltip/
As far as the dictionary part, I would create a script that loads on each page and looks for the existence of specific words and checks them against a JSON file.
Do you want code? Or is concept good enough?

A: You can use Tipsy and add the clarification to the element title.
It's a tooltip which is displayed on hover.


text:
Q: Limit upload size to S3 with presigned URL Using the below code I can sign an upload URL to Amazon S3.  What I would like to add to this is the ability to limit the upload size.
AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider(configFileName, profileName));
GeneratePresignedUrlRequest generateUploadPresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKETNAME, key);
generateUploadPresignedUrlRequest.setMethod(HttpMethod.PUT);
generateUploadPresignedUrlRequest.setExpiration(getFutureDate( 2*DAYS ));
URL uploadURL = s3client.generatePresignedUrl(generateUploadPresignedUrlRequest);

I am aware that what I need is to add a policy that sets the "content-length-range".  Example: ["content-length-range", 0, 10485760]
But all my attempts to encode this in Java have failed with 403 Forbidden.
EDIT: I ommitted non-working code and adding this before the generatePresignedUrl which was my "fix".
Date futureDate = getFutureDate( 2*DAYS );
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String date = df.format(futureDate);
String policy = "{ \"expiration\": \""+date+"\","+
                            "\"conditions\": [" +
                                "{\"bucket\": \""+BUCKETNAME+"\" }," +
                                "['content-length-range', 0, 25000]," +
                            "]" +
                    "}";
generateUploadPresignedUrlRequest.addRequestParameter("Policy", policy);

A: LOL - 5 min after posting I found my error...
ANSWER - note the "Policy" instead of "policy" (capital P)
generateUploadPresignedUrlRequest.addRequestParameter("Policy", policyStr);

A: I tried this code, aws s3 fails and returns:
<?xml version="1.0" encoding="UTF-8"?> <Error>MalformedPolicy<Message>Policies must be valid JSON and the first byte must be '{'</Message><RequestId>D6617E1A36C438A4</RequestId><HostId>nsBW8QdBaRWXVWRv+FYQc9mWPab2ZQ4N85I5CWh7He2IxaX+OkZL+u01ZA2Cgihb0Oaa1o1/7A0=</HostId></Error>

I've tried encode policy to Base64(as it says here), it gives same result.
It seems, that policy field does not work with presigned urls.


text:
Q: Unable to start mysqld_safe Situation
I am working on an aws ubuntu server. It has a mysql 5.5.*, with some databases. Now I need to install 5.6.25 without the affecting the older version.
I followed this link to install the database.
Problem
Now I am unable to start the mysql server. When I run, mysqld_safe I am getting the following error
$ sudo bin/mysqld_safe --user=mysql --defaults-file=/usr/local/mysql-5.6.25/my2.cnf
150626 13:29:03 mysqld_safe Logging to '/var/log/mysql/error.log'.
150626 13:29:03 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
150626 13:29:05 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended

The relevant content in my2.cnf,
[client]
port        = 8889
socket      = /tmp/mysqld.sock

# Here is entries for some specific programs
# The following values assume you have at least 32M ram

# This was formally known as [safe_mysqld]. Both versions are currently parsed.
[mysqld_safe]
socket      = /tmp/mysqld.sock
nice        = 0

[mysqld]
#
# * Basic Settings
#
user        = mysql
pid-file    = /tmp/mysqld.pid
socket      = /tmp/mysqld.sock
port        = 8889
basedir     = /usr/local/mysql-5.6.25
datadir     = /usr/local/mysql-5.6.25/data
tmpdir      = /tmp
lc-messages-dir = /usr/local/mysql/share/mysql/english/
skip-external-locking

The log file has following entries
150626 13:29:03 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
2015-06-26 13:29:03 0 [Warning] Using unique option prefix key_buffer instead of key_buffer_size is deprecated and will be removed in a future release. Please use the full name instead.
2015-06-26 13:29:03 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2015-06-26 13:29:03 0 [Note] /usr/local/mysql-5.6.25/bin/mysqld (mysqld 5.6.25) starting as process 22267 ...
2015-06-26 13:29:03 22267 [ERROR] Can't find messagefile '/usr/share/mysql/errmsg.sys'
2015-06-26 13:29:03 22267 [Warning] Using unique option prefix myisam-recover instead of myisam-recover-options is deprecated and will be removed in a future release. Please use the full name instead.
2015-06-26 13:29:03 22267 [Note] Plugin 'FEDERATED' is disabled.
/usr/local/mysql-5.6.25/bin/mysqld: Unknown error 1146
2015-06-26 13:29:03 22267 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
2015-06-26 13:29:03 22267 [Note] InnoDB: Using atomics to ref count buffer pool pages
2015-06-26 13:29:03 22267 [Note] InnoDB: The InnoDB memory heap is disabled
2015-06-26 13:29:03 22267 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2015-06-26 13:29:03 22267 [Note] InnoDB: Memory barrier is not used
2015-06-26 13:29:03 22267 [Note] InnoDB: Compressed tables use zlib 1.2.3
2015-06-26 13:29:03 22267 [Note] InnoDB: Using CPU crc32 instructions
2015-06-26 13:29:03 22267 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2015-06-26 13:29:03 22267 [Note] InnoDB: Completed initialization of buffer pool
2015-06-26 13:29:03 22267 [Note] InnoDB: Highest supported file format is Barracuda.
2015-06-26 13:29:03 22267 [Note] InnoDB: 128 rollback segment(s) are active.
2015-06-26 13:29:03 22267 [Note] InnoDB: Waiting for purge to start
2015-06-26 13:29:04 22267 [Note] InnoDB: 5.6.25 started; log sequence number 1600797
2015-06-26 13:29:04 22267 [ERROR] /usr/local/mysql-5.6.25/bin/mysqld: unknown variable 'defaults-file=/usr/local/mysql-5.6.25/my2.cnf'
2015-06-26 13:29:04 22267 [ERROR] Aborting

2015-06-26 13:29:04 22267 [Note] Binlog end
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'partition'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'BLACKHOLE'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_FT_DELETED'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_METRICS'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_CMPMEM'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_CMP_RESET'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_CMP'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_LOCKS'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'INNODB_TRX'
2015-06-26 13:29:04 22267 [Note] Shutting down plugin 'InnoDB'
2015-06-26 13:29:04 22267 [Note] InnoDB: FTS optimize thread exiting.
2015-06-26 13:29:04 22267 [Note] InnoDB: Starting shutdown...
2015-06-26 13:29:05 22267 [Note] InnoDB: Shutdown completed; log sequence number 1600807
2015-06-26 13:29:05 22267 [Note] Shutting down plugin 'ARCHIVE'
2015-06-26 13:29:05 22267 [Note] Shutting down plugin 'MRG_MYISAM'
2015-06-26 13:29:05 22267 [Note] Shutting down plugin 'CSV'
2015-06-26 13:29:05 22267 [Note] Shutting down plugin 'MEMORY'
2015-06-26 13:29:05 22267 [Note] Shutting down plugin 'MyISAM'
2015-06-26 13:29:05 22267 [Note] Shutting down plugin 'sha256_password'
2015-06-26 13:29:05 22267 [Note] Shutting down plugin 'mysql_old_password'
2015-06-26 13:29:05 22267 [Note] Shutting down plugin 'mysql_native_password'
2015-06-26 13:29:05 22267 [Note] Shutting down plugin 'binlog'
2015-06-26 13:29:05 22267 [Note]
150626 13:29:05 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended

Questions

*

*why is mysqld_safe giving errors for pid file.

A: It sounds like you're trying to run both 5.5 and 5.6 at the same time.  It also looks like you have some possible shared paths - check the 5.5 config to see if any of the common values (pidfile, socket, port, etc) are pointing to the same locations.


text:
Q: "a client and a doctor" vs. "a client and doctor" I'm conducting a survey related to health care. You can describe yourself using 3 categories: a client, a doctor or "a client and (a) doctor." I'm wondering if I should repeat the second "a" before the noun "doctor" or omit it because I've already used it before the noun "client."

A: When you have a list of single nouns, you can use a only for the first noun and omit it for all subsequent nouns.
There are an apple, pear, plum and peach on the table.
So, you can say a client and doctor. But you can still use a client and a doctor - it may even sound better if it's not in a sentence. On the other hand, in surveys, it may be good if all is made as short as possible.
Or you can say a patient and doctor, if you think this is appropriate to say in your survey.


text:
Q: Two Samba servers but only one is available I have two linux systems one running Centos7 and the other Fedora30.
The SMB.CONF files of both are as close to identical as I can make them.
My Windows 10 system can only find the Centos System.  I have disabled IPV6 & selinux on both but it has not helped.
Any suggestions appreciated


text:
Q: Infinite scrolling random numbers on screen after running fsck manually Yesterday I had a lot of Java applications open that were eating into my RAM. I'm a Java developer so what I usually do in such situations is just reboot. I closed all the apps and did a shutdown. On booting, I was dropped into an initramfs prompt. Screenshot: https://imgur.com/YoUWcRL
initramfs is something I had no clue about, so I just did an exit: https://imgur.com/lsqgNRd
The suggestion was to run fsck on the mentioned filesystem, which I did: https://imgur.com/11Ed7zg The last line here appears to be the one that causes the mess that follows. Typing y for yes and my entire screen becomes a top-to-bottom infinite scrolling random numbers: https://imgur.com/3b22QaC
How do I get back control of my computer?
UPDATE: Screenshots of the SMART Data -- https://imgur.com/MWwU4YJ and https://imgur.com/PH7l8RY

A: re: "I was dropped into an initramfs prompt on boot with the message dev/mapper/ubuntu--vg-root contains a file system with errors, check forced... do a manual fsck."
At the initramfs prompt, type:
fsck -f /dev/mapper/ubuntu--vg-root # check the file system
Update #1:
Note: fsck failed to resolve problems

*

*boot to a Ubuntu Live DVD/USB

*select the "Try Ubuntu" option

*once to the desktop, start the Disks app

*select the target disk in the left pane

*click on the "hamburger" icon and select SMART Data & Tests

*take screenshots of the SMART Data and edit them into your question so I can review them

*run the SMART tests

Note: SMART Data looks fine. HDD is not suspect at this time
Update #2:

*

*whilst booted to the Ubuntu Live DVD/USB, backup whatever data you might still be able to find, to an external source

*start terminal and type: sudo dmidecode -s bios-version and then visit the manufacturer's web site and check for a newer BIOS

*start gparted and lay down a fresh GPT partition table (this will wipe the disk)

*reinstall Ubuntu (no real need for LVM)

*run fsck

*restore data

*set up Deja Dup (Backups) to backup to an external source (not /home)

Update #3:
Do regular fscks for a while...

*

*boot to a Ubuntu Live DVD/USB

*open a terminal window

*type sudo fdisk -l

*identify the /dev/XXXX device name for your "Linux Filesystem"

*type sudo fsck -f /dev/XXXX # replacing XXXX with the number you found earlier

*repeat the fsck command if there were errors

*type reboot

A: The following steps worked for me:

*

*Create a  bootable pen drive and go to Try Ubuntu.

*Open the terminal and run the following command:
$ sudo fsck -f <your_drive_name>

*Type a when asked and let it run for 4-5 minutes.

*Once exited normally after the successful run of previous steps, reboot the system.

A: Having a partition with Windows, Grub displays at start-up. When I had the numbers scrolling issue I just pressed power off, then on again and opted for "Advanced options for Ubuntu" the on "recovery mode" and it sorted the issue for me after checking/repairing the damaged partition.


text:
Q: Какая разница между двумя запусками окна? Первый способ:
MyWindow *wnd = new MyWindow(this);
wnd->show();

Второй способ:

MyWindow wnd(this);
wnd.show();
wnd.exec();

Зачем во втором способе нужен exec() ?
A: Разница между show() и exec() состоит в том, что при show() основной поток продолжает выполняться, а при exec() выполнение основной программы приостанавливается до закрытия child-окна. Применяется, например, в модальных диалогах.
Видимо, в коде, из которого вы взяли второй пример, дочернее окно делает что-то, что необходимо основному. Поэтому основной поток ждет закрытия дочернего окна.


text:
Q: An example of an operation in ordinary arithmetic that is idempotent I came across this question in the book Axiomatic set theory by Suppes:

Can you give an example of an operation of ordinary arithmetic which is idempotent?

So, here I have some things that I cannot completly understand and I need your help:

*

*What is the meaning of ordinary arithmetic? I would understand that it means $+$ and $\times$ on $\mathbb R$, but I'm not sure.

*Does the meaning of an operation which is idempotent mean for all the elements of the universe? I mean I can think of $1$ in $\times$ or $0$ in $+$ because $1\times 1=1$ and $0+0=0$, does this count?

A: Here is a binary idempotent operation: $a*b=(a+b)/2$.

A: $y=|x| \quad \Longrightarrow \quad |y|=y$.

A: Since you refer to a book called Axiomatic set theory, I would guess that ordinary arithmetic is Presburger arithmetic, the first-order theory of the natural numbers with addition, but it might also be Peano arithmetic.
An operation $*$ on a set $S$ is idempotent if, for all $s \in S$, $s * s = s$.
Two examples of idempotent operations are $\max(x,y)$ and $\min(x, y)$ on the natural numbers (or on the real numbers, if you prefer).

A: Let $X$ be a non empty set and $P(X)$ the power set of $X$. Union $\cup$ and intersection $\cap$ are famously idempotent operations over $P(X)$:
$$Y\cup Y =Y,\ \forall\ Y\in P(X),$$
$$Y\cap Y =Y,\ \forall\ Y\in P(X).$$

$\max$ and $\min$ are also well known examples of idempotent binary operations over (numeric) set $\Bbb R$.