text:
Q: When should I write a Linux kernel module? Some people want to move code from user space to kernel space in Linux for some reason. A lot of times the reason seems to be that the code should have particularly high priority or simply "kernel space is faster".
This seems strange to me. When should I consider writing a kernel module? Are there a set of criterias?
How can I motivate keeping code in user space that (I believe) belong there?

A: I'm not sure the question is the right way around. There should be a good reason to move things to kernel space. If there aren't any reasons, don't do it.
For one thing, debugging is made harder, and the effect of bugs is far worse (crash/panic instead of simple coredump).

A: Basically, I agree with rpj. Code has to be in user-space, unless it's REALLY necessary.
But, to emphasize your question, which condition?
Some people claims that driver has to be in the kernel, which is not true. Some drivers are not timing sensitive, in fact lots of drivers are like that.
For example, the framer, RTC timer, i2c devices, etc. Those drivers can be easily moved to user space. There are even some file-systems that are written in user-space.
You should move to kernel space where the overhead, eg. user-kernel swap, becomes unacceptable for your code to work properly.
But there are lots of way to deal with this. For example, the /dev/mem provides a good way to access your physical memory, just like you do it from the kernel space.
When people talk about going to RTOS, I'm usually skeptical.
These days, the processor is so powerful, that most of the time, the real-time aspect becomes negligible.
But even, let's say, you're dealing with SONET, and you need to do a protection switching within 50ms (actually even less, since the 50ms constrains applies to the whole ring), you still can do the switching very fast, IF your hardware supports it.
Lots of framer these days can give you a hardware support that reduces the amount of writes that you need to do. Your job is basically responds to the interrupt as quickly as possible. And Linux is not bad at all. The interrupt latency I got was less 1ms, even if I have tons of other interrupts running (eg. IDE, ethernet, etc.).
And if that's still not enough, then maybe your hardware design is wrong. Some things are better left on the hardware. And when I said hardware, I mean ASIC, FPGA, Network Processor, or other advanced logic.

A: Code running in the kernel accesses memory, peripherals, system functions in ways that are different from userspace code and thus has the ability to be more efficient. Not to mention the reduced security restrictions for kernel code. However, all this usually comes  at a cost, such as increasing the possibility of opening the kernel up to security threats, locking up the OS, complicating the debugging, and so forth.

A: Rule of thumb: try your absolute best to keep your code in user-space. If you don't think you can, spend as much time researching alternatives to kernel code as you would writing the code (ie: a long time), and then try again to implement it in user-space. If you still can't, research more to ensure you're making the right choice, then very cautiously move into the kernel. As others have said, there are very few circumstances that dictate writing kernel modules and debugging kernel code can be quite hellish, so steer clear at all costs.
As far as concrete conditions you should check for when considering writing kernel-mode code, here are a few: Does it need access to extremely low-level resources, such as interrupts? Is your code defining a new interface/driver for hardware that cannot be built on top of currently exported functionality? Does your code require access to data structures or primitives that are not exported out of kernel space? Are you writing something that will be primarily used by other kernel subsystems, such as a scheduler or VM system (even here it isn't entirely necessary that the subsystem be kernel-mode: Mach has strong support for user-mode virtual memory pagers, so it can definitely be done)?

A: There are very limited reasons to put stuff into the kernel. If you're writing device drivers it's ok. Any standard application: never.
The drawbacks are huge. Debugging gets harder, errors become more frequent and hard to find. You might compromise security and stability. You might have to adapt to kernel changes more frequently. It becomes impossible to port to other UNIX OSs.
The closest I've ever come to the kernel was a custom filesystem (with mysql in the background) and even for that we used FUSE (where the U stands for userspace).

A: If your people want really high priority, determinism, low latency etc, the right way to go is to use some real-time version of Linux (or other OS).
Also look at the preemptible kernel options etc. Exactly what you should do depends on the requirements, but to put the code in kernel modules is not likely the right solution, unless you are interfacing some hardware directly.

A: Another reason to not move code into kernel space is that when you use it in production or commercial situations, you will have to publish that code due to the GPL agreement. A situation that many software companies don't want to come into. :)

A: As general rule. Think on what you want to know and if that is something you would see in an operating system development book or class then it has a good chance to belong into the kernel. If not, keep it out of the kernel. If you  have a very good reason to break that rule, be sure, you will have enough knowledge to know it by yourself or you will be working with someone that has that knowledge.
Yes, might sound harsh, but this exactly what I meant, if you don't know, then be almost sure the answer is no, don't do it in the kernel. Moving your development to kernel space opens a giant can of worms that you must be sure to be able to handle.

A: If you're asking such a question, then you shouldn't go to the kernel layer. Basically just wondering means you don't need to. The time of the context switch is so negligible that it doesn't matter anyway these days.

A: If you just need lower latency, higher throughput, etc., it is probably cheaper to buy a faster computer than to develop kernel code.
Kernel modules may be faster (due to less context switches, less system call overhead, and less interruptions), and certainly do run at very high priority. If you want to export a small amount of fairly simple code into kernel space, this might be OK. That is, if a small piece of code is found to be crucial to performance, and is the sort of code that would benefit from being placed in kernel mode, then it may be justified to place it there.
But moving large parts of your program into kernel space should be avoided unless all other options are completely exhausted. Aside from the difficulty of doing so, the performance benefit is not likely to be very large.


text:
Q: Traverse list of related tables I have a peculiar situation. In my MySQL database, I have around 90 odd tables and most of the tables have been indexed (We are using INNODB). Some of the tables are having a link like this:
A -> B -> C->D->E
Is there a way where-in I can find the list of all the sub-child tables when i have only table A and E to work with?  I have do a dynamic query builder mechanism, and for that purpose I list the users with the list of tables, and in a given situation like above, need to get the required information from just table "A" and "E" alone, without the tables "B","C" and "D" being selected by the search user.
The tables are linked in normal manner..each table is linked to another via a proper foreign key constraint.
Eg.
Table A (Transaction)
Id, Trxn-Date, Amount
Table B (Transaction Header)
Id, Agent_Id (FK to Agent_Profile), Upd_Time, Trnx_Hdr_ID (FK to Table A)
Table C (Agent_Profile)
Id, Prof_ID (FK to Profile)
Table D (Profile)
ID, Pers_Info_Id (FK to Personal_Info)
Table E (Personal_Info)
Id, Firstname, Lastname
User selects Trxn_Date, FirstName, LastName.
How can I retrieve the sub-linked table information, when the selected tables(in this case), happens to be only Transaction and Personal_Info.

A: Seems like you could consolidate a few of those tables into 2-3 tables without losing anything useful. Tables C D and E just contain columns to point to other tables.
If changed, a query with trxn_date and first/last name would be a ton easier.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MQTT.js how to hook connected status with vuex Am still learning vuex, i have a 3 export method connect to mqtt broker with call backs to console out.
The thing after page refresh the client disconnect and client.on("end/disconnect") is not fired.
was thinking if there was a way from software design perspective of view, on how to implement it with vuex to track client connection status and act accordingly.
EDIT:
here is my current code.

export let client = null

export var status = 'initial'

export var startSub = ({username, password}) => {
    client = mqtt.connect("ws://192.168.1.30:9001/mqtt",{
        clientId: `mqttjs_ + ${Math.random().toString(16).substr(2, 8)}`,
        username: username,
        password: password
    })
    client.on("connect", () => {
        status =  client.connected
        client.subscribe('hello/#')
        console.log("startSub,Subsecribed")
    }).on('error', err => {
        status =  client.connected
        console.log("error", err)
        client.end()
    }).on("message", (topic, message) => {
        status =  client.connected
        console.log(`topic, ${topic}, msg:: ${JSON.parse(message)}`);
    })

    //on disconnect call bacl
    client.on("disconnect", (packet)=>{
        status =  client.connected
        console.log('client of discconect call back', packet)
    })

    //on disconnect call bacl
    client.on("end", function () {
        console.log('client of end call back')
    })
}

now when the page refresh the client automatically disconnect.
on my vuex store, if i import status, as state, its useless to track because after refresh its always initial. to be more clear my aim is to after refresh to keep the connection active without it being disconnected.


text:
Q: selectedSegmentIndex doesn't change I have a UITableView with one row, inside this row I have a UISwitch with 3 segments. In my case, I need to get the selected index, with a code that select by tag:
- (void)viewDidLoad {
[super viewDidLoad];

    UITableViewCell *cellAttachment = [_tableView dequeueReusableCellWithIdentifier:@"MyCell0"];

    UISegmentedControl *btnAttachment = nil;
    btnAttachment = (UISegmentedControl*)[cellAttachment viewWithTag:100];
    NSLog(@"Segment -> %ld",(long)btnAttachment.selectedSegmentIndex);
}

With this code, I can get the segment selected, but when I try to change the segment with:
btnAttachment.selectedSegmentIndex = [self.arrayFields[19] intValue];//Inside this array has a number 1!

Nothing is done, whats the problem? (I'm doing without a IBOutlet, is possible?)

A: You can do this without IBOutlet. You just have to add action handler from code (in viewDidLoad):
[btnAttachment addTarget:self action:@selector(segmentedControlDidChange:) forControlEvents:UIControlEventValueChanged];

then add action method:
-(void)segmentedControlDidChange:(UISegmentedControl *)sender {
NSLog(@"Segment -> %ld",(long) sender.selectedSegmentIndex);
}


text:
Q: Frame displaying twice I'm facing a browser issue with my ASP.Net application. When I ran my application, some of the browsers are displaying my home page twice in the same page vertically.
This is the code im uisng in my aspx page, in my home.aspx page.
<frameset rows="121,*" cols="*" frameborder="no" border="5" framespacing="0" bordercolor="#999999"runat="server">
  <frame src="TopHeader.aspx" name="topFrame" scrolling="no"  noresize="noresize" id="topFrame" title="topFrame" />
  <frameset rows="*" cols="253,*" framespacing="5" frameborder="yes" border="1"  bordercolor="#e5e5e5" >
    <frame src="LeftNav.aspx" name="leftFrame" scrolling="yes" frameborder="no"  id="leftFrame" title="leftFrame" runat="server" />
    <frame src="Default.aspx" name="mainFrame" id="mainFrame" title="mainFrame" frameborder="no" runat="server" />
  </frameset>
</frameset>

A: I gone through your code, there you wrote frameborder="no" and border="5" those two may cause the effect. if border="5" then use frameborder="yes" and frameborder="0" will work instead of "no"
Use cols="30%,70%" instead of cols="" because the cols="" will occupy all the available space.
I have run your code in my system and did not get page multiple times.


text:
Q: Python - Read files and add the data to a list The issue here is that I want to read a lot of files from a folder and add the data into a 2D list.
Let's that I have the following two txt files in my folder
The first file is fruits.txt with the following content:
apple
orange
banana

The second file is colors.txt with the following content:
yellow
blue

Now I want to add the data from fruits.txt and colors.txt into a 2D list like below:
myList[fruits][apple]
myList[fruits][orange]
myList[fruits][banana]
myList[colors][yellow]
myList[colors][blue]

As you can see in the first dimension is the name of the file and in second dimension is a line from the file.
Not sure how can be implemented this and if its better to add the data in a dictionary

A: So this is what you want?
with open("fruits.txt",'r') as f:
    fruits = f.read().split("\n")

with open("colors.txt","r") as f:
    colors = f.read().split("\n")

Result = {'fruits':fruits,'colors':colors}
# {'fruits': ['apple', 'orange', 'banana'], 'colors': ['yellow', 'blue']}

Or if you want to read all the file in current directory.
Your folder construction:
- Yourfolder
   - fruits.txt
   - colors.txt
.....

You can use glob module to read all the *.txt files:
import glob

Result = {}
for name in glob.glob("*.txt"):
    with open(name,'r') as f:
        Result[name.split(".")[0]] = f.read().strip().split("\n")

print(Result)


text:
Q: Duvida com LocalStorage - Tenho esse código que está contando a quantidade de Clicks, só que queria que quando fechar o Browser o contador não zere.

  var p = document.createElement("p");
  document.body.appendChild(p);

  $(document).ready(function(){
      var cout = 0;
      $("#btnCount").click(function(){
          cout = cout+1;
          $('p').html(cout);
      });
  });
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
    </head>
    <body>
        <button type="button" id="btnCount">Click me</button>
    </body>
    </html>

A: Para salvar antes de fechar a página
window.onbeforeunload = function(count) {
    localStorage.setItem('count', count);
}

Como recuperar do localstorage
var count = localStorage.getItem('count');

A: Não é necessário armazenar o localStorage quando sair da página ou do navegador. Basta criar/atualizar ele dentro do evento onde são contados os cliques, e a variável cout deve ter um operador || para ter um de dois valores: 0 ou o do localStorage caso ele exista.
Outra coisa, você pode criar o <p> com jQuery mesmo, conforme sugiro abaixo:
$("body").append("</p>");
$(document).ready(function(){
   var cout = localStorage.getItem("cout") || 0;

   $("#btnCount").click(function(){
       cout = parseInt(cout)+1;
       $('p').html(cout);
       localStorage.setItem("cout", cout);
   });
});

Outra coisa é que é preciso converter o valor de cout para int com
  parseInt() porque o localStorage é em formato de string.

A: Você pode utilizar a função setItem do localStorage para guardar sua variável contador, ela possui a seguinte sintaxe
localStorage.setItem(keyName, keyValue);

Você pode acrescentar no seu código o seguinte para salvar em localStorage quando o browser for fechado.
Exemplo
window.onbeforeunload = function(count) {
   localStorage.setItem('count', count);
}

Recuperar o dado
Para recuperar o dado igualmente possuímos a funca getItem
var count = JSON.parse(localStorage.getItem('count'));


text:
Q: Verification: Prove $\theta$ is a congruence on unary algebra $ \underline{A} $ with subuniverse $B$ Let $\underline{A}$ be a unary algebra with $B$ as a subuniverse and define $\theta$ as $a\theta b$ iff $a = b$ or $\{a,b\} \subseteq B$
Equivalence Relation:
Reflexive :
let $a \in B$ $a=a$ so $a \theta a$
Symmetry:
let $a,b \in B$ and assume $a\theta b$
then $a=b $ or ${a,b} \subseteq B$ so we have $b=a$ or $\{b,a\} \subseteq B$ thus $b\theta a$
Transitive:
let $a,b,c \in B$ and $a\theta b$ and $b \theta c$ then $a = b = c \implies a=c$ or $\{a,b\},\{b,c\}\subseteq B \implies \{a,c\} \subseteq \{a,b,c\} \subseteq B \implies \{a,c\} \subseteq B $ thus $a\theta c$
We get that $\theta $ is an equivalence relation.
Now, $B$ is assumed to be a subuniverse of $\underline{A}$ hence for all operations in $\underline{A}$ we know $B$ is closed under them.
Consider, $a,b \in B$ such that $a \theta b$ and let $f$ be a unary function in $\underline{A}$:
Case 1: $a=b$ then $f(a) = f(b)$ thus $f(a) \theta f(b)$
Case 2: $\{a,b\} \subseteq B$ as $B$ is closed under all fundamental operations in the algebra thus we know $f(a), f(b) \in B$ thus $\{f(a),f(b)\} \subseteq B$
Therefore, $\theta$ is a congruence on $\underline{A}$
This seems pretty straightforward but I want to make sure I am doing this correctly.


text:
Q: How can I tell if a certain Active Directory login has been used today? How can I tell if a somebody used the login 'Accounts' today to log into a pc in my Active Directory domain?  It seems to be causing errors if 2 people are logged in using the same username and I don't know if this is the case or not.

A: To see the last time a particular account has logged in to your domain, you can run the net user command via a command prompt. Syntax is as follows (without the brackets):
net user [username] [/domain]
That will return several pieces of information, including Last logon time.

A: With Active Directory a user can be logged into different workstations without causing problems.  What are the issues you are seeing?  If you have the proper auditing on your DCs you could search through the event logs for login events for that user.
A more accurate answer could be given if you provide more information on what OS you are running on your DCs and what Domain & Forest Function level you are running.
You could also use the Lockout Tool to search the username if your problem is related to the account getting locked out.  It will search the event logs for bad logon attempts on the DCs and show you the most recent attempt.


text:
Q: How to access pod by it's hostname from within other pod of the same namespace? Is there a way to access a pod by its hostname?
I have a pod with hostname: my-pod-1 that need to connect to another pod with hostname:
my-pod-2.
What is the best way to achieve this without services?

A: Through your description, Headless-Service is you want to find. You can access pod by accessing podName.svc with headless service.
OR access pod by pod ip address.

A: In order to connect from one pod to another by name (and not by IP),
replace the other pod's IP with the service name that points on it.
for example,
If my-pod-1 (172.17.0.2) is running rabbitmq,
And my-pod-2 (172.17.0.4) is running a rabbitmq consumer (let's say in python).
In my-pod-2 instead of running:
spec:
  containers:
  - name: consumer-container
    image:  shlomimn/rabbitmq_consumer:latest
    args: ["/app/consumer.py","-p","5672","-s","172.17.0.2"]

Use:
spec:
  containers:
  - name: consumer-container
    image:  shlomimn/rabbitmq_consumer:latest
    args: ["/app/consumer.py","-p","5672","-s","rabbitmq-svc"]

Where rabbitmq_service.yaml is,
apiVersion: v1
kind: Service
metadata:
  name: rabbitmq-svc
  namespace: rabbitmq-ns
spec:
  selector:
    app:  rabbitmq
  ports:
  - name: rabbit-main
    protocol: TCP
    port: 5672
    targetPort: 5672

Shlomi


text:
Q: How to get a Total of Last Five Values In Sqlite? In my Database,
There is Data like this,
 ID  average_time
 1    5
 2    10
 3    15
 4    20
 5    25
 6    30

I create a query;
 select total(average_time) from tbl_Timer order by id desc limit 5

It"s give the total of all values.
I want Total of LastFive Data,
How can i Do that?

A: Try this:
select  sum(avtime) from
  (SELECT average_time AS avTime
   FROM tbl_Timer
   ORDER BY id DESC LIMIT 5)

A: If ID is sequential how about something like this
select sum(average_time) from data where id >= (select max(id)-4 from data);


text:
Q: Sort the main query in subcategories/terms? I've got a 'downloads' custom post, with his custom taxonomy. The taxonomy has 2 main terms. One of the 2, has 4 sub-terms. I'm currently using the wp templating system to get a standard wpquery of the parent term into a taxonomy-taxonomyname-termname.php page. Till here, all fine.
Now what I'd like to do is to show all the posts under the parent term, without pagination (this is not a problem). But I would like show them splitted/grouped by sub-terms (with the sub-term name above each of the 4 sub-terms groups).
Normally, I would perform a custom query. But since this time I'm trying to take  advantage of the default wp query system, I'd like to use just the loop. Is there a way to have the posts grouped by sub-term?

A: Always great if someone wants to use better, more correct and more efficient ways to get things done. To achieve what you need is not difficult.
WORKSFLOW:

*

*Use the usort() to create your custom sort order

*Use the the_posts filter to sort and return the sorted array of posts just before the loop is executed

*Inside the loop, all you need to do is to compare the previous post and current post terms and act on that
THE CODE:
Lets look at the code:
First, get the sorting done using usort() and the_posts filter: (Requires at least PHP 5.4+. If you don't have at least PHP 5.4, then you are sure to run into security issues. Also note, all the code is untested and might be buggy)
add_filter( 'the_posts', function ( $posts, $q )
{
    if ( $q->is_main_query() // Target the main query only
         && $q->is_tax() // Change to target only specific term or taxonomy
    ) {
        /**
         * We will now sort the $posts array before the loop executes. We will use usort()
         *
         * There is a bug in usort causing the following error:
         * usort(): Array was modified by the user comparison function
         * @see https://bugs.php.net/bug.php?id=50688
         * This bug has yet to be fixed, when, no one knows. The only workaround is to suppress the error reporting
         * by using the @ sign before usort
         */
        @usort( $posts, function ( $a, $b )
        {
            /**
             * Get the respective terms from the posts
             * We will use the first term's name
             */
            $array_a = get_the_terms( $a->ID, 'TAXONOMY_NAME_HERE' )[0]->name;
            $array_b = get_the_terms( $b->ID, 'TAXONOMY_NAME_HERE' )[0]->name;

            // Sort by term name, if they are the same, sort by post date
            if (  $array_a != $array_b ) {
                return strcasecmp( $array_a, $array_b ); // Sort terms alphabetically, ascending
                // return strcasecmp( $array_b, $array_a ); // Sort terms alphabetically, descending
            } else {
                return $a < $b; // Sort by date if terms are the same. Change < to > if the post date order is incorrect
            }
        }
    }
}, 10, 2 );

This should take care of the sorting. As I have stated, just make sure the date sorting is correct within the terms. If not, just change < to >
Now we can display the term names inside the loop. Adjust and modify as needed
if ( have_posts() ) {
    // Define variable to hold previous post term name
    $term_string = '';
    while ( have_posts() ) {
    the_post();
        global $post;
        // Get the post terms. Use the first term's name
        $term_name = get_the_terms( $post->ID, 'TAXONOMY_NAME_HERE' )[0]->name;
        // Display the taxonomy name if previous and current post term name don't match
        if ( $term_string != $term_name )
            echo '
' . $term_name . '
'; // Add styling and tags to suite your needs

        // Update the $term_string variable
        $term_string = $term_name;

        // REST OF YOUR LOOP

    }
}

A: If I understand the question correctly, you want to produce something like this:
Sub-Item 1
Post 1
Post 2
[...]
Sub Item 2
Post 1
Post 2
[...]
There may be a more efficient way than what I am about to tell you, but I would try something like this:
First create an array to hold your sorted posts.
$sortedPosts = array();

Next, create an array for each of your sub-terms.
foreach ($subTerms as $subTerm) {
    $sortedPosts[$subTerm] = array();
}

Loop through the posts in your query, and sort them based on the assigned term.
if (have_posts()) {
    while (have_posts()) {
        the_post();
        $postTerms = get_terms('taxonomyName', array('fields' => 'name'));

        if (is_array($postTerms)) {
            foreach ($subTerms as $subTerm) {
                if (in_array($subTerm, $postTerms)) {
                    global $post;

                    $sortedPosts[$subTerm][] = $post;
                    /* This grabs the array stored at $sortedPosts[$subTerm]
                       and then inserts the current post at the end of it. */
                }
            }
        }
    }
}

Once all the posts have been sorted, loop through your sorted array to print the display.
foreach ($subTerms as $subTerm) {
    $myPosts = $sortedPosts[$subTerm];

    echo '
' . $subTerm . '
';

    foreach ($myPosts as $currentPost) {
        global $post;
        $post = $currentPost;

        // Enter post display stuff here
    }

    echo '
'
}

A: Ok, thank you all for your good answers. Anyway, I need more flexibility, so I ended up not using the wp template auto-sugars...
This answer is therefore not strictly related to my own original question, but I think it can help people too.
I built a custom function that retrieves a set of custom posts form a specific custom taxonomy and an optional parent term. If parent is passed, returned posts will belong to direct parent term children. This is the code:
// $post_type: string
    // $taxonomy: string
    // $parent_term: string (slug) || int (term_id)
    // retrieves posts of a specific post_type and taxonomy, sorted by term
    function get_taxonomy_posts($post_type, $taxonomy, $parent_term = ''){

        if(!$post_type || !$taxonomy) return false;

        global $wpdb;

        //if $parent_term is defined and is not an integer then should be a slug, so let's get its id
        if(!empty($parent_term) && !is_int($parent_term)){
            $parent_data = get_term_by('slug',$parent_term,$taxonomy);
            $parent_term = $parent_data->term_id;
        }

        $term_ids = get_terms($taxonomy, array( 'parent' => $parent_term, 'fields' => 'ids' ));
        if(is_wp_error($term_ids)) return false;

        $term_ids_str = implode(',',$term_ids);

      // NOTE: terms.term_order gets added to tables by this plugin:
      // http://wordpress.org/plugins/taxonomy-terms-order/
      $query = $wpdb->prepare(
        "select p.ID, p.post_title, p.post_content, p.post_excerpt, t.term_id, t.term_order, t.name as term_name, t.slug as term_slug, tt.count
        from " . $wpdb->prefix . "posts p
        inner join " . $wpdb->prefix . "term_relationships rel on p.ID = rel.object_id
        inner join " . $wpdb->prefix . "term_taxonomy tt on tt.term_taxonomy_id = rel.term_taxonomy_id
        inner join " . $wpdb->prefix . "terms t on tt.term_id = t.term_id
        where p.post_type = %s and p.post_status = %s and t.term_id in (" . $term_ids_str . ")
        order by t.term_order, p.menu_order"
        ,$post_type
        ,"publish"
      );

      $records = $wpdb->get_results($query);
      $posts_array = array();

      foreach($records as $record){
        $term_name = $record->term_name;
        if(!key_exists($term_name, $posts_array)) $posts_array[$term_name] = array();
        $posts_array[$term_name][] = $record;
      }

      return $posts_array;

    }//end get taxonomy_posts

It will give you an array where keys are term names and values are arrays of posts (or more precisely, post data of posts) belonging to that term. It can be easily modified to have for example keys as term_id instead of term_name. The single post data returned is like this:
    object(stdClass)#2308 (9) {
      ["ID"]=>
      string(3) "269"
      ["post_title"]=>
      string(26) "title"
      ["post_content"]=>
      string(0) "content"
      ["post_excerpt"]=>
      string(0) "excerpt"
      ["term_id"]=>
      string(3) "803"
      ["term_order"]=>
      string(1) "2"
      ["term_name"]=>
      string(27) "term name"
      ["term_slug"]=>
      string(26) "term-slug"
      ["count"]=>
      string(1) "3"
    }

SIDE NOTE 1: currently, I'm using the taxonomy-terms-order plugins and so in the query I'm ordering terms by the custom term_order field. Again, if you don't use the plugin, just change the fields retrieved and order by clause as you prefer.
SIDE NOTE 2: Instead of a taxonomy-taxonomyname-termname.php, now I basically use a dummy page and apply a custom template (I mean /* Template Name: [name] */): this is not mandatory, but I do it to have the wp's main query just do a simple 1 post query instead a sort of duplicated term query.
Hope it helps!


text:
Q: Como mover registros desde Routed Zone publica a privada Acudo a todos para ver si me pueden dar una mano con un proyecto en el que me encuentro atrasado, y necesito resolverlo lo antes posible.
El mismo consiste en mover los registros del dominio publico a privado.
Por ejemplo yo cuento con los siguiente registros dentro del dominio publico.

A su vez cuento con un dominio privado.
Esto necesitando encontrar un metodo con un script que me permirta mover los registros publicos a privados. Estaba pensando en un script en Python, pero escucho sugerencias.
Alguien me podra dejar algún ejemplo en Python o algún otro leguanje que me permita realizar esto?


text:
Q: Adding dielectric to a capacitor When we introduce a dielectric of dielectric constant $K$ in the space between the conducting plates(slowly) of a capacitor connected to a battery with a voltage $V$ across it, we find that an extra $(K-1)\frac{CV^2}{2}$ amount of work is done by the external agent inserting the dielectric material. My question is, where does this work go? Is it used as energy to overcome the force experienced by dielectric by the conducting plates while it is being inserted, or is it used to change the arrangement of the dipoles in the dielectric to produce net bound charge, or is it (or a portion of it) lost in the form of heat?
I think it is a combination of all of these.

A: So alright, this question is a fun one. In the overall scheme, the system indeed gain a energy of $(K-1)\frac{CV^2}{2}$. But I guess you're asking why and how this happens.
Why:
Because for any configuration of an electrostatic (or magnetostatic, the calculations can be made analogous) system, we can define electric potential energy. There are two equivalent ways of doing so,
$$U_{total}=\frac{1}{2}\sum_{i\in\text{All particles}}\sum_{j\in\text{All other particles}} \frac{q_iq_j}{4\pi\epsilon_0|\mathbf r_i-\mathbf r_j|}$$
$$U_{total}=\int_\text{entire space} \frac{\epsilon(\mathbf r)\,\mathbf E(\mathbf r)\cdot\mathbf E(\mathbf r)}{2}\,dV=\int_\text{entire space} \frac{\mathbf D(\mathbf r)\cdot\mathbf E(\mathbf r)}{2}\,dV$$
The problem with the first (and more conventional) method is that you need to account for all charges everywhere, free or bound. In the second one, knowing the field configuration is enough, and thus it is easier to compute in this system.
In our system, the electric field exists only in the interior of the capacitor and it has a constant (independent of the dielectric constant in that vertical section) amplitude since $V=\Delta V=-\int_{y=0}^{h} \mathbf E(x,y)\cdot\mathrm d\vec y$, i.e. the potential of the capacitor is constant across different $x$ and movement across $y$ is homogeneous: $\mathbf E(x,y) = -(V/h)\,\hat y$.
So we can simply integrate this in the volume of the capacitor:
$$U_{total}=\int_\text{entire space} \frac{\epsilon(\mathbf r)\,\mathbf E(\mathbf r)\cdot\mathbf E(\mathbf r)}{2}\,dV=\int_{x=0}^d \int_{y=0}^h \int_{z=0}^d \frac{K\epsilon_0 V^2}{2h^2}\,dz\,dy\,dx$$
$$=\frac{K\epsilon_0 V^2dhL}{2h^2}=K\frac{\epsilon_0dL}{2h}V^2=K\frac{C}{2}V^2$$
Since in the initial state $K=1$, difference is $(K-1)\frac{CV^2}{2}$.
Notice that I just calculated $\Delta E_{total}$ only in terms of the change of electrostatic potential energy: I assume there is no kinetic energy, and that there is no other contributions to the potential term. However there is no explanation as to how we add energy to the system. To see a more complete picture, we need to investigate
How:
How do we introduce energy into this system? There are two plausible ways: 1) Mechanical work done on the dielectric (pushing/pulling), and 2) The battery. First way is a simple $W=Fx$, but the second one is the more important but occasionally ignored $W=\int_{t=0}^{T}IV\,dt=V\,\Delta Q$.
The battery always keep the capacitor voltage at $V$. Now ask yourself: If you increase the capacitance of a capacitor, does its charge change? The answer is yes, and this change is $\Delta Q = C_f\,V - C_i\,V$ with $C_f=K\,C_i$, so $\Delta Q = (K-1)CV$. Notice that this is positive, and thus the battery needs to do work in order to establish the new equilibrium, $W_{battery} = V\,\Delta Q = (K-1)\,CV^2$.
So we found that the battery adds twice the energy needed to increase the potential energy. The rest is either converted to kinetic energy, or we hold the system back from going in with an acceleration and thus take back (negative) work, $W_{mechanical}=-(K-1)\frac{CV^2}{2}$.
The answer to your question is, the energy is used to hold the new charges in equilibrium. However we do not push the dielectric in, on the contrary we need to hold it back from going in by itself. The part that does the work is the battery that maintains the voltage of the capacitor.


text:
Q: while loop conditions with more than 1 condition/condition type C# Trying to get my while loop to have more than 1 condition , basically User inputs a height in numbers and the code continues etc. the height data will be pass down the code for later calculations.
Currently I have set it to when user doesn't enter a number (such as the Letter 'H') it enters a while loop for an error message. HOWEVER i want there to also be the condition that the height entered cannot be more than 3 and if say user enters 5, it also enters the loop for the error message. Currently when entering the loop user can retry and enter a number ( can enter letters will keep going back).
in my while condition i have tried to add && (heightM >3) -
(while (double.TryParse(userInput, out double heightM)&& (heightM <3) == false) - but doesnt seem to do what i want. in this case it ignores the tryparse, if user inputs 4 it loops correctly but if a letter , application crashes.
Im very new - still learning , sorry if this is a simple question : /
double height;
string userInput = Console.ReadLine().ToLower();
while (double.TryParse(userInput, out double heightM) && (heightM<3) == false)
{
    Console.Clear();
    Console.WriteLine("Incorrect value or input");
    Console.WriteLine("");
    Console.WriteLine("Enter Height in Meters only up to Maxmium of 3 meters");
    userInput = Console.ReadLine().ToLower();
}

height = double.Parse(userInput);

A: Using a while(true) loop, we can check the conditions and break out of the loop, or the loop will continue forever until a correct value is inputted.
double height;
double maxHeight = 3;
while (true)
{
    var userInput = Console.ReadLine();
    if (double.TryParse(userInput, out var heightM) && heightM <= maxHeight)
    {
        height = heightM;
        break;
    }

    Console.Clear();
    Console.WriteLine($"Please enter Height in Meters only up to maximum of {maxHeight} meters");
}
Console.WriteLine(height);

A: Parsing a string that is not a number will result in the out variable set to 0, so your logic is flawed. Instead you should change it to
double heightM;
string userInput = Console.ReadLine().ToLower();
while (!double.TryParse(userInput, out heightM) || (heightM > 3))
{
    ....
}

The first change is used to have a single hejghtM variable, then the second change is how do we test the result of TryParse, if the parsing fails we could immediately enter the retry code. So the third change is using the || instead of && and this leads to the fourth change where we test for value bigger than three to enter the retry loop.


text:
Q: How do I communicate with an application/program via USB I have a program running on a small computer. For simplicity, let's say the program displays a string that says "adjusting" when adjusting and "ready" when ready. The manual for this program is sparse but says I can query this string by using the command "STATUS? " via serial interface. I have no idea what this means, so if someone could please give me a starting point that would be great. Essentially I would like to know how I could even send this query command to the software. I'm only marginally familiar with MATLAB, so if someone with experience with this type of communication could say what tools are necessary to write a loop that constantly queries the status and returns a logical when the program is "ready" that would be great.
Below is all I could find in the manual:
Serial interface
command instructions


text:
Q: Messagebox error shown during compilation, from an OCX When compiling a VB6 project I am getting an error shown in a messagebox:

(Note again, this is not a runtime error, but a compile-time error. When building an EXE).
VBCCR16 is the name of an OCX library, and so it seems apparently some code in the OCX is being run during compilation of the project which references it. I never knew OCX / DLL code was run at compile time.
I have never seen this before and am trying to debug it, but with no success yet. I have tried looking at VB6.exe and its compiler processes in Process Monitor & Process Explorer, but that showed nothing obvious to go on. Nor did Event Viewer (no entries).
Since error zero typically means "no error" in VB6, that doesn't seem to be a useful clue in itself.
What code gets called in an OCX / DLL during compilation? What could possibly cause this?
Any suggestions on how to debug this problem?

Note 1 - this error occurs on our build machine (a Win7 virtual machine) but does not occur on my own PC during compilation. It also does not occur if I just run the code in the IDE.
The build setup has been used for years without ever seeing this before. I don't think it is a memory or disk space issue.

Note 2 - I have also posted a question to the OCX library's author, but I'm not sure if this is really a problem with the library or something else, hence the question here.

Note 3 - I have just seen this other question which describes what code is run during compilation. So that apparently explains the general context of this issue, but not the actual root cause.

A: The issue may be related to the designer.
Suggest comparing the designer part with the previous source which compiled in the last time and finds strange changes like font which set to CTX and not to a specific font.
For Example:
font            =   "MyControl.ctx":0848
instead of
BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851}
        Name         =   "MS Sans Serif"
        Size            =   9.75
        Charset         =   0
        Weight          =   400
        Underline       =   0   'False
        Italic          =   0   'False
        Strikethrough   =   0   'False
EndProperty


text:
Q: Reading Category attribute inside test method using Reflection I'm trying to add test methods using the category property of the TestMethod custom attribute by reading a .dll using reflection, something like this:
if the test method is:
[TestMethod, Category("xyz"), Category("abc")]
public void VerifySomething()
{
   //some code
}

I'm reading the .dll using reflection like this:
 Assembly _assembly = Assembly.LoadFile(AssembleyPath);
            Type[] types = _assembly.GetExportedTypes();
            foreach (Type type in types)
            {
                Attribute _classAttribute = type.GetCustomAttribute(typeof(TestClassAttribute));
                if (_classAttribute != null)
                {
                    TreeNode _n = new TreeNode();
                    _n.Text = type.Name;
                    if (type.Name.ToLower().Contains("testbase"))
                        // For exculding test base class from tree node list
                        continue;
                    MemberInfo[] members =
                        type.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod);
                    foreach (MemberInfo member in members)
                    {

                            Attribute _att = member.GetCustomAttribute(typeof(TestMethodAttribute));
                            if (_att != null)
                            {
                                TestMethod _t = new TestMethod(member.Name);

                            }

                    }
                 }
            }

Using this i'm unable to add test methods filtered by particular category inside treeview node.
Basically all i want is to read TestCategoryAttribute from dll which has value something like "xyz" or "abc" as per the example i've mentioned above and then based on the filter (TestCategoryAttribute) value i would want to load methods from the dll and add them to the treeview node. Can anybody please guide me how can i achieve that.

A: This is how to get a TestMethod as a MethodInfo from Reflection.
var _t= typeof(testClass).GetMethod(methodName); // testClass should be the type in your foreach

Given a TestMethod _t (assuming everything is right till there), you can get the categories with the following
var testCategories = IEnumerable<TestCategoryAttribute>)_t.GetCustomAttributes(typeof(TestCategoryAttribute), true));

How to filter them based on some conditions?
Does a Linq Any do the trick?
    if testCategories.Any(c => c == "xyz" || c == "abc") )
    {
        // then add to the treeview node, etc...


text:
Q: How to detect other user is disconnected on sinch video call Now I am making the video call app using sinch, but I have one problem.
If receiver click end call button, I can process it on caller side.
But assume if the receiver's network is disconnected suddenly, how to detect it on caller side.
If anyone have previous experience about it, please guide me.
Thanks

A: There is no way for that, if the users come back it will reconnect automatically.
Its a feature that may come, but not for now

A: https://github.com/TheCaffeineDev/Video-Call-implementation-Using-Sinch-SDK
This is the reference source code, when the receiver disconnected suddenly, the caller is still in the calling status instead of ending call and go back to the previous screen.
I want to go back previous screen when the receiver is disconnected.

A: My way is working fine and you can refer:
When call is established, one side created a call history record on server side contains 2 fields lastTimeCallerUpdate and lastTimeCalleeUpdate. Every minute, each side will update its current time, and check the difference of 2 fields, if variance is greater than MAX duration it will automatically call endCal();


text:
Q: Is Bias necessarily need at Colvolution Layer? I'm building CNN + Ensemble model for classify images with Tensorflow at Python. I crawled dog and cat images at google images. Then changed them to 126 * 126 pixel size and gray scale, add label 0 to dog, 1 to cat. CNN has 5 conv layer and 2 fc layer. HE, PReLU, max-pooling, drop-out, Adam are used in model. When Parameter Tuning finished, I added Early-Stopping, the model learned 65~70 epoch, finished with 92.5~92.7% accuracy.
After learning finished, I want change my CNN model to VGG network, I checked my CNN parameter, shockingly, I found I didn't add Bias at conv layer. 2 fc layer had Bias but 5 conv layer didn't have Bias. So I added Bias at 5 conv layer, BUT my model could not learn. Cost increased to infinite.
Bias is not necessarily at Deep Convolution Layer?

A: How did you add your bias to the convolutional layer? There are two ways to do this: Tied biases which share one bias per kernel and untied biases which use one bias per kernel and output. Also read this.
Regarding your question whether or not they are necessary, the answer is no. Biases in convolutional layers increase the capacity of your model, making it theoretically able to represent more complex data. If your model however already has the capacity to do this, they are not necessary.
An example is this implementation of the 152 layer ResNet architecture where the convolution layers have no bias.
Instead the bias is added in the subsequent batch normalization layers.


text:
Q: Using object members before object is constructed I have following simple code:
#include <iostream>
#include <vector>

template <class Derived>
struct Base
{
    Base()
    {
        static_cast<Derived*>(this)->foo();
    }

    std::vector<int> m_ints;
};

struct Derived : Base<Derived>
{
    Derived() : Base()
    {
        std::cout << a;
    }

    void foo()
    {
        m_ints.push_back(37);
        a = 4;
    }

    int a;
};

int main()
{
    Derived d;
    return 0;
}

I know about order of calling constructors when object is created. Constructor are called from the "most base -> down". So At the Base constructor Derived object is not fully constructed.
1) Is it safe, to call Derived::foo in Base constructor, when Derived::foo do no touch Derived object? I mean, when there is no such line as a = 4, just touching Base object.
2) If I run posted code, it really works, although I'm touching a which should not exist at that time. Is it guarantee to work? (I tested it on VS2013, VS2010, and GCC 4.8.1 on Ideone)

A: It will work in this specific case, but I would advise not to do this.
Subtle changes in the code might suddenly break the logic (e.g. someone making the method foo virtual, someone initializing data member a in the constructor or Derived, ...).
If the base class needs information from a derived class, then the derived class must pass that information to the constructor of the base class.  In this class, the value 37 should be passed from the constructor of Derived to the constructor of Base.
And when data member a must be initialized, initialize it in the constructor of Derived, not somewhere else.
EDIT: In C++11, if the Derived class wants to inject code in the constructor of Base, it can pass a lambda to Base.  Base then simply executes the lambda in its constructor.


text:
Q: Ideal way to read data in bucket stored batches of data for Keras ML training in Google Cloud Platform? This is my first attempt at training a model in the cloud and I am struggling with all the little intracacies.
I have training data stored in a bucket within the google cloud platform,
along the lines of  gs://test/train
The dataset is about 100k.
Currently the data is distributed in separate folders in accordance with its labels.
I don't know the ideal way to get access to the data.
Usually in Keras I use,ImageDataGenerator with flow_from_directory and it automatically creates a generator which I can feed into my model.
Is there such as function for Python for the Google Cloud Platform?
If not what is the ideal way to access the data via generator so I can feed it to
Keras model.fit_generator
Thank you.

A: ImageDataGenerator.flow_from_directory() currently does not allow you to stream data directly from a GCS bucket. I think you have a couple of options:
1/ Copy your data from GCS to a disk local to the VM your are using to run your script. I suppose you are doing this either via ML Engine or on a Compute Engine instance. Either way, you can copy the data at the beginning of your training script using gsutil or the python cloud storage API. There is a downside here: this will cost you some time at the beginning of your script, especially when the dataset is large.
2/ When using tf.keras, you can train your model on a tf.data Dataset. The nice thing here is that TensorFlow's io utilities allow you to read directly from GCS buckets. If you would convert your data to TFRecords, you could instantiate a Dataset object without downloading the data to local disk first:
# Construct a TFRecordDataset
ds_train tf.data.TFRecordDataset('gs://') # path to TFRecords on GCS
ds_train = ds_train.shuffle(1000).batch(32)

# Fit a tf.keras model
model.fit(ds_train)

See this question for more information on the TFRecord option. This works also fine with a Dataset object that is instantiated directly from images on GCS with Dataset.from_tensor_slices, so that you don't have to store your data in the TFRecords format first:
def load_and_preprocess_image(path):
"""Read an image GCS path and process it into an image tensor

Args:
    path (tensor): string tensor, pointer to GCS or local image path

Returns:
    tensor: processed image tensor
"""

    image = tf.read_file(path)
    image = tf.image.decode_jpeg(image, channels=3)
    return image

image_paths = ['gs://my-bucket/img1.png',
               'gs://my-bucket/img2/png'...]
path_ds = tf.data.Dataset.from_tensor_slices(image_paths)
image_ds = path_ds.map(load_and_preprocess_image)
label_ds = tf.data.Dataset.from_tensor_slices(labels) # can be a list of labels
model.fit(tf.data.Dataset.zip((images_ds, labels_ds)))

See the tutorials on the TF website for more examples.
3/ Finally, it should also be possible to write your own python generator or to adapt the source code of the ImageDataGenerator such that the images are read in with a TensorFlow io function. Again, these work fine with gs:// paths:
import tensorflow as tf
tf.enable_eager_execution()
path = 'gs://path/to/my/image.png'
tf.image.decode_png(tf.io.read_file(path)) # this works

See also this related question. This will probably work slower than the options listed above.


text:
Q: Add Unmapped Data to NHibernate I have an object I'm trying to persist to a legacy database with NHibernate.  I have all of the relevant columns from a table mapped in my domain object, but have a few fields in the table that must be populated for the structure of the legacy db.
Following a few recommendations, I created and registered an NHibernate interceptor to do this for me.
 public class CustomLineItemInterceptor : EmptyInterceptor
 {

  public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, IType[] types)
  {
    var lineItem = entity as SomeCustomLineItem;

    if (lineItem == null)
    return false;

    List<string> propertyNameList = propertyNames.ToList();
    List<IType> typeList = types.ToList();
    List<object> stateList = state.ToList();

    propertyNameList.Add("Source");   // the unmapped column in the database
    typeList.Add(NHibernateUtil.String);
    stateList.Add("My Application's Name");  // the value I need to persist

    state = stateList.ToArray();
    propertyNames = propertyNameList.ToArray();
    types = typeList.ToArray();

    return true;
    }
}

I've looked at this NHibernate add unmapped column in interceptor and Unmapped Columns in NHibernate? without finding the answer.
What I'm seeing is that I the OnSave method does fire, but I get nothing stored in the database (or the SQL query generated by NHibernate).
What am I doing wrong?

A: there is also this approach using virtual Properties and IPropertyAccessor. I used it in one of my projects in the domain model and for me its easier to declare it once in the mapping than everywhere where i open a session, which happens in several different projects (Application, imports, ETLs, integration of other programs)

A: I don't know a lot about how NHibernate Interceptors work, but I wouldn't expect that changing the passed in array variables would actually change anything external to the method.  In order for the new arrays to end up back outside of the method, they would need to be passed by reference (ref) parameters.
Looking at your first linked question (add unmapped column in interceptor), the first difference that jumps out is that at the end of his method, he calls the base method passing in the updated parameters (return base.OnSave(entity, id, state, propertyNames, types);).  Perhaps that would help?


text:
Q: Selecting columns in R depending on user input I have a dataframe col_metadata in R that goes as:
sample | b | c | ...
____________________
S1     | 1 | 1 | ...
S2     | 1 | 2 | ...
S3     | 2 | 2 | ...
S4     | 3 | 3 | ...

I want to make a function that gives me samples that have given values in front of them. For eg.,
fun(b,c(1,2))

should return
S1 S2 S3

while
fun(c,c(2,3))

should return
S2 S3 S4

and so on. If the column would have been fixed (say, b), I could simply do:
col_metaData[col_metaData$b %in% inputList,]$sample

But since there can be many more columns(hence I can't use if-else), I was looking for a different method to do the same. Can someone please help me do this? Thanks...

A: I solved it. Just in case anyone comes looking for an answer, we can use this:
col_metaData[col_metaData[,b] %in% inputList,]$sample

Notice [,b] instead of $b.


text:
Q: ASP.NET Core not finding npm I have a new Asp.NET Core Web / React application.
When I try to run it I get the error:

An unhandled exception occurred while processing the request.
  AggregateException: One or more errors occurred. (One or more errors
  occurred. (Failed to start 'npm'. To resolve this:.
[1] Ensure that 'npm' is installed and can be found in one of the PATH
  directories.

I have a PATH variable set up:

C:\Program Files\nodejs

In this folder is node.exe
Do I need to install something into the project?
I have made no other changes to the project since creating it from the VS Web Application template. I just want it to run...
The full path error list:

Current PATH enviroment variable is: C:\Program
  Files\Android\jdk\microsoft_dist_openjdk_1.8.0.9\bin;C:\Program
  Files\Microsoft MPI\Bin\;C:\Program Files (x86)\Intel\iCLS
  Client\;C:\Program Files\Intel\iCLS
  Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program
  Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program
  Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files
  (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program
  Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files
  (x86)\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program
  Files (x86)\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files
  (x86)\Microsoft SQL Server\130\DTS\Binn\;C:\Program Files
  (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio\;C:\Program
  Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program
  Files\TortoiseHg\;C:\Program Files (x86)\PKWARE\pkzipc;C:\Program
  Files\Microsoft\Web Platform Installer\;C:\Program
  Files\dotnet\;C:\Program Files\7-Zip;C:\Program
  Files\OpenVPN\bin;C:\Program Files\nodejs\;C:\Program
  Files\Mercurial\;C:\Program Files\Intel\WiFi\bin\;C:\Program
  Files\Common Files\Intel\WirelessCommon\;C:\Program Files\010
  Editor;C:\Program Files (x86)\Microsoft Emulator
  Manager\1.0\;C:\Scripts;C:\Program Files\Microsoft SQL Server\Client
  SDK\ODBC\130\Tools\Binn\;C:\Program Files\Microsoft SQL
  Server\130\DTS\Binn\;C:\Program Files
  (x86)\GtkSharp\2.12\bin;C:\ProgramData\chocolatey\bin;C:\Program
  Files\Java\jdk1.8.0_162\bin;C:\clojure-clr-1.8.0-Release 4.0\Release
  4.0\clojure;C:\Program Files\PuTTY\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\;C:\Program Files\Microsoft SQL
  Server\140\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL
  Server\140\DTS\Binn\;C:\Program Files\Microsoft SQL
  Server\140\DTS\Binn\;C:\Program Files\Git\cmd;C:\Program Files
  (x86)\Windows Kits\10\Windows Performance
  Toolkit\;C:\Users\stuarts.cargo\bin;C:\Program Files (x86)\Elm
  Platform\0.18\bin;C:\Users\stuarts\AppData\Local\Programs\Python\Python35\Scripts\;C:\Users\stuarts\AppData\Local\Programs\Python\Python35\;C:\Users\stuarts\AppData\Local\Microsoft\WindowsApps;C:\Nuget\nuget.exe;C:\utils;C:\Users\stuarts\AppData\Roaming\Python35\Scripts;C:\Program
  Files\7-Zip;C:\Users\stuarts\AppData\Roaming\npm;C:\Program
  Files\Intel\WiFi\bin\;C:\Program Files\Common
  Files\Intel\WirelessCommon\;C:\Users\stuarts\AppData\Local\Programs\Fiddler;C:\Scripts;C:\Nuget;C:\Program
  Files\Microsoft VS
  Code\bin;C:\Users\stuarts.lein\bin;C:\Users\stuarts\AppData\Local\atom\bin;C:\clojure-clr-1.8.0-Release
  4.0\Release 4.0;C:\Users\stuarts.dotnet\tools;C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2
  Tools;C:\Windows\Microsoft.NET\Framework\v4.0.30319;C:\Program
  Files\nodejs;

You can see node is the last one...


text:
Q: Understanding Angular FormBuilder with Groups and ngModel data and how/if they can be used together? I am running into some issues with trying to use FormBuilder in my Angular app and how I can set the default values in the form based on my ngModel data.
In my class, I have the following code:
form: FormGroup;

constructor(
    private fb: FormBuilder,
) { }

ngOnInit() {

    this.form = this.fb.group({
        category: ['', [Validators.required]],
        quantity: [1, [Validators.required]],
        size: ['', [Validators.required]],
        title: ['', [Validators.required]],
    });
}

When I look at the {{ form.value | json }} in my template, it shows the original values with the empty values. So I decided to try to set the default values in the FormBuilder group like this:
    this.form = this.fb.group({
        category: [this.item.category, [Validators.required]],
        quantity: [this.item.quantity, [Validators.required]],
        size: [this.item.size, [Validators.required]],
        title: [this.item.title, [Validators.required]],
    });

But I am given these errors:
ERROR Error: formGroup expects a FormGroup instance.
ERROR TypeError: Cannot read properties of undefined (reading 'category')
ERROR TypeError: Cannot read properties of undefined (reading 'value')

This is my template for the form:
<form [formGroup]="form">
        <ion-item lines="none">
            <ion-label position="stacked">Category</ion-label>
            <ion-select [(ngModel)]="item.category" [ngModelOptions]="{standalone: true}">
                <ion-select-option *ngFor="let category of categories" [value]="category">
                    {{ category }}
                </ion-select-option>
            </ion-select>
        </ion-item>

        <ion-item lines="none">
            <ion-label position="stacked">Title</ion-label>
            <ion-input [(ngModel)]="item.title" [ngModelOptions]="{standalone: true}"></ion-input>
        </ion-item>

        <ion-item lines="none">
            <ion-label position="stacked">Size</ion-label>
            <ion-input [(ngModel)]="item.size" [ngModelOptions]="{standalone: true}"></ion-input>
        </ion-item>

        <ion-item lines="none">
            <ion-label position="stacked">Quantity</ion-label>
            <ion-input type="number" [(ngModel)]="item.quantity" [ngModelOptions]="{standalone: true}"></ion-input>
        </ion-item>

    </form>

Any thoughts what is wrong with my approach and how I can get the default values from my this.item to appear in the form?

A: Zerospi, the problem is that you create the form before you has data in your variable "item" - this is the reason you don't see the value

*

*NEVER Mix together Reactive forms and Template-Driven (ngModel)
The use [(ngModel)]="variable" [ngModelOptions]="{standalone: true} it's ONLY to get an input that not belong to the FormGroup.
e.g you can has a "checkbox" to show a new input. Some like
 movil:boolean=false;
 form=new FormGroup({
   phone:new FormControl()
   mobile:new FormControl()
 })
 <form [formGroup]="form">
   Phone<input formControlName="phone">
   <input type="checkbox" [(ngModel)]="movil"
           [ngModelOptions]="{standalone:true}">Mobile
   <input *ngIf="movil" formControlName="mobile">
 </form>

Well, really we use
   <input type="checkbox" [ngModel]="movil"
           (ngModelChange)="movil=$event;!$event && form.get('mobile').setValue('')
           [ngModelOptions]="{standalone:true}">Mobile

To "clean" the FormControl "mobile" if we uncheck
How control a FormGroup?

*In general we can have a function in the way
getFromGroup(data:any=null)
{
   data=data || {phone:'',mobile:''}
   return this.fb.group({
      phone:[data.phone,Validators.required]
      mobile:data.mobile
   }
}

And use
this.form=this.getFormGroup(this.item) //if we have an object "this.item"
this.form=this.getFormGroup() //if we want an empty Form

*Another approach is create the form an use patchValue()
this.form=this.fb.group({
   phone:['',Validators.required]
   mobile:''
}
this.form.patchValue(this.item)

*To avoid initial errors (e.g. we create the form after a call to an API), sometimes is util use some like
<form *ngIf="form" [formGroup]="form">
...
</form>

*Remember that a FormControl is disabled, don't showed in form.value, you need use form.getRawValue()

A: There are 2 approaches regarding forms: Template driven (more logic in .html and Reactive (more logic and control in .ts). With formBuilder injected and [formGroup]="form" you went for reactive approach which is more spread among experienced devs and tends to be more comfortable since it gives more control over your forms.
It is not a good practice to use two-way data binding with this approach. You should put formControlName="controlNameXYZ" to the according input field and do that for all your input fields defined when building form.
Don't forget to have ReactiveFormsModule inside imports array of your module (or AppModule if you only have one in whole application).


text:
Q: display date from current dateto next six days I am using this code for display dates from current date to next six days.
if any other code for display date like this. please help
Private Sub Displaydate()
    cn.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("DataConnectionString")
    lblDateday.Text = System.DateTime.Now.ToString("dddd")
    lblMonthdate.Text = System.DateTime.Now.ToString("dd MMMM ")
    lblDateday2.Text = System.DateTime.Now.AddDays(1).ToString("dddd")
    lblMonthdate2.Text = System.DateTime.Now.AddDays(1).ToString("dd MMMM ")
    lblDateday3.Text = System.DateTime.Now.AddDays(2).ToString("dddd")
    lblMonthdate3.Text = System.DateTime.Now.AddDays(2).ToString("dd MMMM ")
    lblDateday4.Text = System.DateTime.Now.AddDays(3).ToString("dddd")
    lblMonthdate4.Text = System.DateTime.Now.AddDays(3).ToString("dd MMMM ")
    lblDateday5.Text = System.DateTime.Now.AddDays(4).ToString("dddd")
    lblMonthdate5.Text = System.DateTime.Now.AddDays(4).ToString("dd MMMM ")
    lblDateday6.Text = System.DateTime.Now.AddDays(5).ToString("dddd")
    lblMonthdate6.Text = System.DateTime.Now.AddDays(5).ToString("dd MMMM ")
    lblDateday7.Text = System.DateTime.Now.AddDays(6).ToString("dddd")
    lblMonthdate7.Text = System.DateTime.Now.AddDays(6).ToString("dd MMMM ")
End Sub

the output is
Wednesday    Thursday      Friday      Saturday      Sunday         Monday      Tuesday
21 November  22 November  23 November  24 November  25 November  26 November   27November

A: Put the things you handle into arrays and then do loops instead.
Assign Lists globally
Dim DateDayList as List(of Label) = new List(of Label)
Dim MonthDayList as List(of Label) = new List(of Label)

Add all dateDay labels to list in the correct order inside the Initialize sub.
DateDayList.Add(lblDateDay)
DateDayList.Add(lblDateDay2)
etc.

Do the same with the Month day labels.
Then simply do this:
for i as Integer = 0 To 6
   DateDayList(i).Text = System.DateTime.Now.AddDays(i).ToString("dddd")
   MonthDayList(i).Text = System.DateTime.Now.AddDays(i).ToString("dd MMMM ")
next


text:
Q: Restrict concurrent session and give proper message to the user using Spring Security I want to restrict my second session, while same user try to log in from different machine.
Following is my Spring Security code:
<form-login authentication-success-handler-ref="myAuthSuccessHandler"
        login-page='/login' username-parameter="username"
        password-parameter="password" authentication-failure-url="/loginfailed"/>

<logout logout-success-url="/logout" delete-cookies="JSESSIONID,the_cookie"/>

<session-management>
    <concurrency-control session-registry-alias="sessionRegistry" max-sessions="1"/>
</session-management>

Now using this I can restrict concurrent session but I am not able to give proper message to user like: "USER ALREADY LOGGED IN FROM DIFFERENT MACHINE".

A: Implement or extend an authentication failure handler for e.g. SimpleUrlAuthenticationFailureHandler
public class CustomFailureHandler extends SimpleUrlAuthenticationFailureHandler {

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
    setDefaultFailureUrl("/loginfailed.jsp?status=" + "YOUR CUSTOM MESSAGE HERE");
    super.onAuthenticationFailure(request, response, exception);
}
}


text:
Q: Simple counter button android I want to make a simple counting button, like in picture I have attached below

The simplest way I can imagine is to define two buttons and one textview.
Is there any better solution for this aim?

A:
The simplest way I can imagine is to define two buttons and one
  textview.

If you want to create a "simple counting button" then This is the most obvious way to do it...

A: No there is no such widget available which has such a ui you need to right custom
or do the way you're doing

A: Yes, two ImageButtons and a TextView (along with the counting logic) would be how you should do it.


text:
Q: What is the probability distribution for the squared distance between random points in an $n$-dimensional hypercube? I choose random points $X,\,Y$ in $[0,\,1]^n$ (I assume all $2n$ Cartesian coordinates are $U(0,\,1)$ iids). What is the probability distribution of $\left\Vert X-Y\right\Vert _{2}^{2}$? Even the $n=1$ case requires some care, since if I first fix $X$ then $Y$ has a uniform distribution with extrema of opposite sign.

A: For an approximate cdf, one possibility is the saddlepoint approximation. For that the mgf (moment generating function), or its logarithm, the cgf (cumulant generating function) is needed. For background see How does saddlepoint approximation work?.   So let $X_1, \dotsc, X_n, Y_1, \dotsc, Y_n$ be iid $\mathcal{U}(0,1)$. Then $D^2 = \sum_i (X_i-Y_i)^2$ have mgf
$$ \DeclareMathOperator{\E}{\mathbb{E}} \DeclareMathOperator{\P}{\mathbb{P}}
M_n(t)=M_{\sum_i (X_i-Y_i)^2}(t)=M_{(X_1-Y_1)^2}(t)^n=\left(\E e^{(X_1-Y_1)^2 t}\right)^n
$$ so the cgf is
$$
   K_n(t)=n\cdot \log\left\{ \E e^{(X_1-Y_1)^2 t} \right\}
$$ which in this case is defined for all real $t$.
Without going into details, and with some help from maple, we find that
$$
 \E e^{(X_1-Y_1)^2 t} = {\frac {\sqrt {\pi}{\rm erf} \left(\sqrt {-t}\right){t}^{2}+{{\rm e}^{
t}} \left( -t \right) ^{3/2}- \left( -t \right) ^{3/2}}{ \left( -t
 \right) ^{5/2}}}
$$  or alternatively
$$
 \E e^{(X_1-Y_1)^2 t} = {\frac {-2\,i{{\rm e}^{t}}{\it dawson} \left( i\sqrt {-t} \right) {t}^
{2}+{{\rm e}^{t}} \left( -t \right) ^{3/2}- \left( -t \right) ^{3/2}}{
 \left( -t \right) ^{5/2}}}
$$ but before using this numerically, more work will be needed to find a useful form.
I will come back later to add the resulting approximation.


text:
Q: Homotopy classes of homeomorphisms of a multiple pointed space Let $M$ be a multiple pointed space, i.e. $M$ is a topological space and there is a finite point set $M\supset P=\{p_1,...,p_k\}, k<\infty$. Such a $p_i$ is called a marked point. A map $$\varphi:M,P\to M,P$$ is called a $P$-relative map if
$$\varphi|_P=id|_P.$$
Our question is that
For a disk $D^2$ (moreover we order that all maps are invariant on $S^1=\partial D^2$) or a sphere $S^2$ with a non-empty $P$, if a homeomorphism $h$ relative to $P$ (and $\partial D^2$ for $D^2$ case) is connected to identity via a homotopy $H$ relative to $P$ (and $\partial D^2$ for $D^2$ case), can we improve such homotopy $H$ to an isotopy $I$?
For example, if there is only one marked point, the answer to such question is "Yes" by Alexander, see CURVES ON 2-MANIFOLDS AND ISOTOPIES of Epstein, Section 5.
In generally, we want to study the homotopy classes and the isotopy classes of $P$-relative homeomorphisms for any two dimensional surfaces $S$ (may contain some boundary $\partial S\subset S$ and we order homeomorphisms on boundary are identity, or some puncture points $q\not \in S$). So the question above can be restated as
When the natural corresponding map $T$ from an isotopy class of homeomorphism of $S$ to a homotopy class of homeomorphism of $S$ $$T:[Homeo(S)]_{isotopy}\to[Homeo(S)]_{homotopy}$$
is an injection or an isomorphism (one-one)?

A: The answer is No, a homotopy relative to $P$ cannot in general be improved to an isotopy. To see this, consider the fibration
$$
{\rm HomEq}^+(M\  {\rm rel} \ P)\to {\rm HomEq}^+(M)\to {\rm Map}(P,M)
$$
where ${\rm HomEq}^+$ denotes the space of orientation-preserving homotopy equivalences and ${\rm Map}(P,M)$ is the space of maps $P\to M$. Thus ${\rm Map}(P,M)$ is the product of $k$ copies of $M$, where $k=|P|$. Part of the long exact sequence of homotopy groups for this fibration is
$$
\pi_1{\rm Map}(P,M)\to\pi_0{\rm HomEq}^+(M\  {\rm rel} \ P)\to\pi_0{\rm HomEq}^+(M)
$$
In the special case $M=S^2$ the first and third terms of this three-term exact sequence are zero so the middle term must be zero as well. The natural map
$$
\pi_0{\rm Homeo^+}(S^2\  {\rm rel} \ P)\to \pi_0{\rm HomEq^+}(S^2\  {\rm rel} \ P)
$$
will then have a nontrivial kernel if the domain group is nonzero, which happens when $k\geq 4$ since $\pi_0{\rm Homeo^+}(S^2\  {\rm rel} \ P)$ is the (pure) mapping class group of a $k$-punctured sphere. Elements of this kernel give homeomorphisms that are homotopic to the identity rel $P$ but not isotopic to the identity rel $P$.
The case $M=D^2$ is similar, where homotopy equivalences and homeomorphisms are required to restrict to the identity on $\partial D^2$. In this case one only needs $k\geq 2$. For more complicated surfaces such as closed surfaces of positive genus the map
$$
\pi_0{\rm Homeo^+}(M\  {\rm rel} \ P)\to \pi_0{\rm HomEq^+}(M\  {\rm rel} \ P)
$$
again has a nontrivial kernel as long as $k$ is not too small, but the argument is a little more complicated since the first and third terms in the exact sequence above are no longer zero. The rough idea is that the kernel of the map
$$
\pi_0{\rm Homeo^+}(M\  {\rm rel} \ P)\to \pi_0{\rm Homeo^+}(M)
$$
is bigger than just the product of $k$ copies of $\pi_1M$, due to braiding phenomena in $M$. It shouldn't be too hard to make this precise.
For an explicit example in the case of $D^2$, say, consider the homeomorphism $f$ obtained by dragging the point $p_1$ around a small loop encircling $p_2$. By construction, $f$ is homotopic (and even isotopic) to the identity fixing $ p_2,\cdots,p_k$, and this homotopy can be deformed to fix $p_1$ as well by deforming the loop that $p_1$ traces out to the constant loop, crossing $p_2$ at some time during this deformation. This deformation can be achieved by an ambient homotopy of $M$ fixing $p_2,\cdots,p_k$ but not by an ambient isotopy fixing these points since $p_1$ crosses $p_2$ at some time during the deformation.


text:
Q: SSH Failed password login - log password today I checked the log of my sshd and I have discovered tons of lines like :Oct 12
  Oct 12 12:31:34 my_user sshd[15324]: Failed password for invalid user admin from 104.194.25.135 port 2683 ssh2
Oct 12 12:31:37 my_user sshd[15324]: Failed password for invalid user admin from 104.194.25.135 port 2683 ssh2
Oct 12 12:31:39 my_user sshd[15324]: Failed password for invalid user admin from 104.194.25.135 port 2683 ssh2
Oct 12 12:31:41 my_user sshd[15324]: Failed password for invalid user admin from 104.194.25.135 port 2683 ssh2
Oct 12 12:31:45 my_user sshd[15324]: Failed password for invalid user admin from 104.194.25.135 port 2683 ssh2
Oct 12 12:31:53 my_user sshd[15326]: Failed password for invalid user admin from 104.194.25.135 port 4049 ssh2
Oct 12 12:31:55 my_user sshd[15326]: Failed password for invalid user admin from 104.194.25.135 port 4049 ssh2
Oct 12 12:31:57 my_user sshd[15326]: Failed password for invalid user admin from 104.194.25.135 port 4049 ssh2
Oct 12 12:31:59 my_user sshd[15326]: Failed password for invalid user admin from 104.194.25.135 port 4049 ssh2
Oct 12 12:32:01 my_user sshd[15326]: Failed password for invalid user admin from 104.194.25.135 port 4049 ssh2
Oct 12 12:32:04 my_user sshd[15326]: Failed password for invalid user admin from 104.194.25.135 port 4049 ssh2
Oct 12 12:32:09 my_user sshd[15329]: Failed password for invalid user admin from 104.194.25.135 port 1793 ssh2
Oct 12 12:32:12 my_user sshd[15329]: Failed password for invalid user admin from 104.194.25.135 port 1793 ssh2
Oct 12 12:32:14 my_user sshd[15329]: Failed password for invalid user admin from 104.194.25.135 port 1793 ssh2

I was wondering if it is possible to ask SSH to log the password they tried as well as the username.

A: No openssh can't do it. You may modify sources, but usually for such studies it's useful to set up an honeypot like kippo. You'll be able to watch what attacker is doing if he successfully enters your server.
You may check this good article http://www.adeptus-mechanicus.com/codex/logsshp/logsshp.html
It's about another option - use a non-standard PAM module which logs passwords.
Another great article about Python PAM module http://www.chokepoint.net/2014/01/more-fun-with-pam-python-failed.html
I ended up writing PAM module with Python just because i personally know Python. Honeypot was a little bit overkill for me.


text:
Q: Can relative speeds be greater than the speed of light? I am trying to wrap my mind around special relativity and I have these questions:
If I am moving at 70% of the speed of light (relative to the ground) to the right, and my friend moves at 70% of the speed of light (relative to the ground) to the left, are we moving apart at faster than the speed of light?
Does this mean that from my perspective, he is moving away from me at faster than the speed of light?
How about from the perspective of a third party not moving (relative to the ground). Do they see us moving apart at faster than light?

A: "From my perspective": no, he is seen moving away at less than the speed of light.
"from the perspective of a third party on the ground": Every physical interaction involves 2 parties making an exchange. Therefore, whilst a 3rd party could choose to add .7c and .7c to arrive at a figure of 1.4c, this figure is most definitely not the relative velocity of you and your friend, and will not be relevant to interactions between you and them.

A: Focusing on the 1st question (which is a great place to start if you're trying to wrap your head around SR): You can't add velocities, but you can add "rapidities", which is (with $c=1$):
$ w = \tanh^{-1}{v} $
so you see your friend moving at:
$ v = \tanh{w} = \tanh{(w_1 + w_2)} = \tanh(2\tanh^{-1}{0.7}) = 0.93..$
Of course, now you have to understand why this formula works.

A: Picture an extremely obtuse angle expanding at the speed of light from the point of the observer.
Redshift .7/light speed as seen from observer with relation to each "traveller".


text:
Q: Use ScrollViewer inside another Scrollviewer The structure of my wpf application is like:
<Scrollviewer>
   <Grid>
       <Scrollviewer>
            <DataGrid>

My Goal is, if the DataGrid exceeds the height of the screen to use it's own Scrollviewer. At the Moment only the outside ScrollViewer is used and so i have to scroll the whole Grid.
Can someone please tell me how to do this?

A: You need to set a height on the inner ScrollViewer, otherwise it'll stretch as much as it needs based on it's content's size.
<Window x:Name="RootWindow">
    <ScrollViewer>
        <Grid Height="{Binding ElementName=RootWindow, Path=ActualHeight}">
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="2*" />
            </Grid.RowDefinitions>

            <ScrollViewer Grid.Row="1">
                <DataGrid />
            </ScrollViewer>
        </Grid>
    </ScrollViewer>
</Window>

Also, the DataGrid has built-in properties for it's own ScrollBars which you can use instead of wrapping the DataGrid in a ScrollViewer. This will scroll the data and always leave the headers visible, instead of scrolling the entire datagrid.
<DataGrid HorizontalScrollBarVisibility="Auto"
          VerticalScrollBarVisibility="Auto" />

A: You might want to place the DataGrid outside the Scrollviewer then. Therefore you can set two Grid.Rows, and let it part the available size for you (default would be "equal" or if you use only two rows, 50%-50%). So if the DataGrid exceeds its available size it will use its own ScrollViewer. If the content below is exceeding the size, it will use your manually placed ScrollViewer. At least, that is how i would solved it based on your initial input. Feel free to add code / comments so we might find a better way.
If you place two ScrollViewers plus a datagrid inside each other you will be forced to start passing out concrete Height or Width values if you want that kind of fine grained control.


text:
Q: How to flatten array of arrays in json using jsonata I want to flatten an array of arrays in json data into array of objects.
I am giving input and expected output. I am not familiar with some flattening functions in jsonata and that's where I need help.
Input:
[
  [
    {
      "date": "2022-09-22",
      "name": "modules/dynatrace",
      "count": 60
    },
    {
      "date": "2022-09-22",
      "name": "modules/dynatrace/monitors/http-monitors/basic",
      "count": 4
    }
    ],
    [
    {
      "date": "2022-09-22",
      "name": "modules/splunk/hec-token",
      "count": 14
    },
    {
      "date": "2022-09-22",
      "name": "modules/aws/lambda/logs_streaming_splunk",
      "count": 29
    }
    ]
]

Output:
[
    {
      "date": "2022-09-22",
      "name": "modules/dynatrace",
      "count": 60
    },
    {
      "date": "2022-09-22",
      "name": "modules/dynatrace/monitors/http-monitors/basic",
      "count": 4
    },
    {
      "date": "2022-09-22",
      "name": "modules/splunk/hec-token",
      "count": 14
    },
    {
      "date": "2022-09-22",
      "name": "modules/aws/lambda/logs_streaming_splunk",
      "count": 29
    }
]

A: I used below command as mention in the another ticket and it worked for me.|https://stackoverflow.com/questions/49570172/jsonata-query-to-flatten-array-of-arrays
$reduce($, $append)


text:
Q: Set type to Email Address I'm beginning to work with EF 5 & Lightswitch in VS2012.
I'm modeling a database in EF 5 then creating the database and adding the new data-source to Lightswitch.  I have a contact table that has an Email field which is type string in EF, and I know I can set the type for validation to Email Address in Lightswitch, but it doesn't seem to want to let me.  Here's a picture of it:

What can I do to set the type to Email Address?

A: The lack of "business types" (like Email Address, Image etc), is due to the extension that contains these types not being selected for the project. This extension is ticked by default, but sometimes people untick it, not knowing what it's for.
To fix this for your project:

*

*Right-click your LightSwitch project in Solution Explorer

*Select Properties

*Click on the Extensions tab

*Make sure that the extension called Microsoft LightSwitch Extensions is ticked

You can help to insure that this doesn't happen again with future projects, by ticking Use In New Projects as well.


text:
Q: Why is it considered bad practice to extend natives on javascript but not ruby? Seems to me, extending native ruby classes would be considered more dangerous.

A: Be careful about it in Ruby, too. It's just a matter of the prevailing opinion in the language communities; technically there's no reason it's better in Ruby than in JavaScript.

A: I imagine it has to do mainly with the fact that JavaScript is built into the browser. Browsers already have enough bugs and issues without you making changes to the native objects.  Also, some libraries may have dependencies on core objects that could be affected by your changes.


text:
Q: Why are changes not allowed in Visual Studio 2010? I'm in the process of upgrading from VS 2008 to VS 2010, and for the most part it is going pretty smooth. One problem I'm running into is that if I put a break in the code, and try to make changes, I get an error saying that it's not allowed. This is something that I can't live without, so I'm hoping it can be fixed. Otherwise I'll be sticking with VS 2008 for a while longer.

I have no add-ins, and the only extension I have is the GIT Source Control Manager.
I tried uninstalling the GIT Source Control Manager, but that didn't help the problem.

A: You're probably running a Release build.
Switch to the Debug configuration.

A: For ASP.NET applications, go to Project > App properties > Web > Debugging, and make sure that "enable and continue" is checked.

A: Do you have Edit and Continue in the Options > Debugging > Edit and Continue menu enabled?

A: This problem is due to Intellitrace setting
If Intellitrace is enabled make sure Intellitrace event only is checked
Otherwise this will not allow edit and continue..
If you will click on Intellitrace options you will see the warnings.


text:
Q: How to number equations within theorem-like environments I want to enumerate equations within theorem-like environments.
Example:
\documentclass[a4paper,10pt]{article}
\usepackage{amsmath,amsthm}
\newtheorem{theo}{Theorem}[section]
%
\begin{document}
\section{Natural Numbers}
\begin{theo}
\begin{equation} \label{eq:1}
1+1=2.
\end{equation}
\begin{proof}
The proof of the equation~\eqref{eq:1} is left as an exercise.
\end{proof}
\end{theo}
\end{document}

And produce something like

A: Once amsmath has been loaded, you can use
\numberwithin{equation}{theorem}

A complete example:
\documentclass[a4paper,10pt]{article}
\usepackage{amsmath,amsthm}

\newtheorem{theo}{Theorem}[section]
\numberwithin{equation}{theo}

\begin{document}

\section{Natural Numbers}
\begin{theo}
\begin{equation} \label{eq:1}
1+1=2.
\end{equation}
\begin{proof}
The proof of the equation~\eqref{eq:1} is left as an exercise.
\end{proof}
\end{theo}

\end{document}

A: If you're sure that you'll be using numbered equations only within theorem environments (and other theorem-like environments) and if you're loading the amsmath package, you could issue the command
\numberwithin{equation}{theorem}

where theorem is the environment set up with a \newtheorem statement.
If you have several theorem-like environments, be sure to have them share the same counter. How to do this depends strongly on the theorem package that's in use. For the amsthm package, you'd force the lemma, corollary, etc environments to use the same counter as theorem environments do by issuing commands such as
\usepackage{amsmath,amsthm}
\newtheorem{theorem}{Theorem}
\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{corrolary}[theorem]{Corollary}
\numberwithin{equation}{theorem}

By the way, don't use the deprecated $$ ... $$ method to create unnumbered display-style equations. Instead, use something like \begin{equation*} ... \end{equation*}. Among other good things, the spacing around displayed equations will become much better.


text:
Q: Why won't Java let you inherit from a generic type-variable? public class MyClass<T> extends T {...}

The above declaration will fail to compile with the error:
error: unexpected type
class MyClass<T> extends T {}
                         ^
  required: class
  found:    type parameter T
  where T is a type-variable:
    T declared in class MyClass

I can't really think of a reason for this to happen, so I am wondering if someone can shed some light on why it is that Java won't let you inherit from a generic type-variable.

A: Java has quite a lot of language restrictions unlike C++ for example. What you want is not possible for many reasons listed in the comments (T might be final or have abstract methods). However, you are allowed to extend from a supertype having the generic type parameter:
public class MyClass<T> extends AnotherClass<T>

You might find the following alternative interesting:
public class MyClass<T extends AnotherClass> extends AnotherClass

What you want to do does make not much sense.

A: The most obvious reason I can think of isn't even about type-erasure; it is the fact that when you make A a subclass of B, the Java compiler needs to know what constructors B has. If a class does not have a no-arguments constructor, then its sub-classes must call one of its defined constructors. But when you declare
public class MyClass<T> extends T {...}

It is absolutely impossible for the compiler to know what the super constructors are, since T is not fixed at compile-time (that's the whole point of generics after all), which is a situation that cannot be allowed in Java.

A: Your question is not so weird as it may look like :) Consider how would you deal with following:

*

*Suppose your real class for T has a single constructor with 3 parameters. How would you implement the constructor of inherited class, if you don't know how to call the super constructor?

*Suppose your real class for T has public final methods and you have defined  methods with the same signature in the inherited class. What method would your object have? You cannot resolve such conflict.

A: Simple deductions based on your question.
T is a type.
MyClass extends T - MyClass is enhanced version of T.
MyClass < T> extends T - MyClass is enhanced T, but only for Type T.
there is no reason to state ' I extend T but only for type T'.
If you extend T, MyClass is already a Type of T & definitely not some X,Y or Z.
Generics are needed if you want to ensure Type safety, if you extend it is already type safe.


text:
Q: react-select package not working in build I am facing this error at build time.
When creating a build of react project react-select dropdown is not working, and we have also added some design(CSS) to the react-select dropdown.
Also I want to display error message using redux-form validation.
my error like this:https://cloud.githubusercontent.com/assets/11028434/13355530/26648d8c-dca1-11e5-9776-15c795a8fb2b.gif
My code:
class AddArtwork extends React.Component {
    constructor(props) {
        super(props);
          this.state = {defaultval: "Select material" }
        }
    GetMedium() {
       var =materialArray[];
        materialArray = [{"value":0,"label":"Select material"}
        {"value":1,"label":"aa"},
        {"value":2,"label":"bb"},
        {"value":3,"label":"cc"},
        {"value":4,"label":"dd"},
        {"value":5,"label":"ee"},
        {"value":6,"label":"ff"},
        {"value":7,"label":"gg"}];
         return materialArray;
        }
    MaterialDropdown = ({ input, meta ,options}) => {
    return (<div className="react-select">
            <Select
            {...input}
            onBlur={() => input.onBlur(input.value)}
            placeholder={this.state.defaultval}
            name="material"
            options={this.GetMedium()}
            />
            {
              this.renderError(meta)
            }
            </div>);
}

render(){
 return (<form>
   <Field
     id="material"
     name="material"
     component={this.MaterialDropdown}/>
  </form>)
}
}

A: If I'm reading correctly you are using redux-form. The props for your MaterialDropdown are wrong. redux-form does not wrap the props it gives to the component into another object. They are directly available from the props object:
MaterialDropdown = ({value, onChange, ...props}) => {

    /* ... */

    <Select
        value={value}
        onChange={onChange}
        { ... }
    />

    /* ... */
}

The documentation provides a list of props that are being passed directly to your component.


text:
Q: VPN with wrong subnet mask I followed these instructions  on www.hottonetworking.com to set up VPN on a clean install of Windows Server 2008 SP2 (not R2 yet).
When I then establish a VPN connection to that machine from a client machine (running Windows 7 RC), everything succeeds (it seems since I get a 'Connected' state in the network sharing center window), but I end up with a subnet mask (according to ipconfig /all) of 255.255.255.255 instead of 255.255.255.0. The net effect is that I don't have local network or internet capability.
What additional configuration steps do I have to do to get VPN with the proper subnet mask working?
Update: Using the steps outlined in the Technet article mentioned by Mr. Nimble, I was able to get internet connection. Apparently the subnet mask is not an issue as my coworker was able to connect using his VPN connection and ping the server machine by name as well.

A: I've done some testing with the VPN connections on my laptop, and all of them work and are assigned the 255.255.255.255 subnet mask, so I beleive this is the normal and expected setting. As such, this is most likely not the cause of your connectivity issues.
If you are able to access the internet via the VPN connection, then obviously the VPN connection is working and passing traffic correctly. I suspect your issue lies with DNS/name resolution with respect to your intranet.
A simple test would be to try pinging or browsing to the server via IP address - if this works, then you issue is DNS related. The next step would be to ping the fully qualified domain name of the server (instead of 'server', ping 'server.domainname.local', using the correct values for your network of course).
If both those work, then what you'll need to do is set the DNS suffix in your VPN connection properties.
To do this:
- Goto the properties page for the VPN connection in question (on your client PC)
- Click on the networking tab
- Select IPv4 and click the properties button
- Click the Advanced button
- Click the DNS Tab
- On the DNS settings tab, enter your intranet's DNS suffix (the 'domainname.local' from above that matches your network).
Save all those settings, then reconnect to the VPN and trying pinging your server using the short DNS name now - it should hopefully work.

A: You can configure Routing and Remote Access to either give certain IP, NetMask, and Router information, or you can let it redirect to the DHCP server.
Look at this Technet Article go to the section called "Configure VPN1 to be a VPN server" which is about half way down.
Also make sure the interface (or interfaces) you are using are fully configured for TCP/IP v4 with IPs, Subnet Mask, and a Gateway.
Also see this section on the DHCP relay agent.

A: I have had this issue many times before with the RAS server obtaining wrong subnet for my VPN network. Trying manual IP ranges in RAS also did not work. Still gave different subnet config.
The issue is with the DHCP server and not the RAS server configuration.
This is the solution that I found that works:
1) Remove the DHCP scope that is currently set up for your RAS config,
2) Restart DHCP server ( I stop myself, then start ),
3) Add a new scope with required IP settings for your setup.
4) Voila! :-)
I have only got this working with my set up using Windows Server 2016 DataCentre. If this works for you also using a different version, let me know.
I have had this problem many times but when I have been fiddling with network adapters. So maybe DHCP server config is affected and causes wrong subnet addresses. I was receiving subnet of '255.255.255.255' so VPN was connecting but shares and network access was not available.
Hope this helps someone!


text:
Q: Unable to execute Code on Databricks Community Edition I am training on Event Hubs with Databricks on my Databricks Community Edition. I need to run the following code/Notebook, however I get the error message:
NoSuchElementException: head of empty list

However, when I run the same code/Notebook on my Azure Databricks the code run successfully. Does anyone clues why this won't run on Databricks Community, whereas the code runs without any issues on Azure Databricks?
%scala
val tags = com.databricks.logging.AttributionContext.current.tags

//*******************************************
// GET VERSION OF APACHE SPARK
//*******************************************

// Get the version of spark
val Array(sparkMajorVersion, sparkMinorVersion, _) = spark.version.split("""\.""")

// Set the major and minor versions
spark.conf.set("com.databricks.training.spark.major-version", sparkMajorVersion)
spark.conf.set("com.databricks.training.spark.minor-version", sparkMinorVersion)

//*******************************************
// GET VERSION OF DATABRICKS RUNTIME
//*******************************************

// Get the version of the Databricks Runtime
val runtimeVersion = tags.collect(
  { case (t, v) if t.name == "sparkVersion" => v }).head
val runtimeVersions = runtimeVersion.split("""-""")
val (dbrVersion, scalaVersion) = if (runtimeVersions.size == 3) {
  val Array(dbrVersion, _, scalaVersion) = runtimeVersions
  (dbrVersion, scalaVersion.replace("scala", ""))
} else {
  val Array(dbrVersion, scalaVersion) = runtimeVersions
  (dbrVersion, scalaVersion.replace("scala", ""))
}
val Array(dbrMajorVersion, dbrMinorVersion, _) = dbrVersion.split("""\.""")

// Set the the major and minor versions
spark.conf.set("com.databricks.training.dbr.major-version", dbrMajorVersion)
spark.conf.set("com.databricks.training.dbr.minor-version", dbrMinorVersion)

//*******************************************
// GET USERNAME AND USERHOME
//*******************************************

// Get the user's name
val username = tags.getOrElse(com.databricks.logging.BaseTagDefinitions.TAG_USER,
  java.util.UUID.randomUUID.toString.replace("-", ""))
val userhome = s"dbfs:/user/$username"

// Set the user's name and home directory
spark.conf.set("com.databricks.training.username", username)
spark.conf.set("com.databricks.training.userhome", userhome)

//**********************************
// VARIOUS UTILITY FUNCTIONS
//**********************************

def assertSparkVersion(expMajor:Int, expMinor:Int):Unit = {
  val major = spark.conf.get("com.databricks.training.spark.major-version")
  val minor = spark.conf.get("com.databricks.training.spark.minor-version")

  if ((major.toInt < expMajor) || (major.toInt == expMajor && minor.toInt < expMinor))
    throw new Exception(s"This notebook must be ran on Spark version $expMajor.$expMinor or better, found Spark $major.$minor")
}

def assertDbrVersion(expMajor:Int, expMinor:Int):Unit = {
  val major = spark.conf.get("com.databricks.training.dbr.major-version")
  val minor = spark.conf.get("com.databricks.training.dbr.minor-version")

  if ((major.toInt < expMajor) || (major.toInt == expMajor && minor.toInt < expMinor))
    throw new Exception(s"This notebook must be ran on Databricks Runtime (DBR) version $expMajor.$expMinor or better, found $major.$minor.")
}

//*******************************************
// CHECK FOR REQUIRED VERIONS OF SPARK & DBR
//*******************************************

assertDbrVersion(4, 0)
assertSparkVersion(2, 3)

displayHTML("Initialized module variables & functions...")