text:
Q: Can I default export constants and type alias from the same module? I have a project with numerous objects containing constant string values in them.
const StringLiterals = {
    a: "LetterA",
    b: "LetterB",
    c: "LetterC"
};

export default StringLiterals;

In many cases, these string constants are used as parameters. I want ensure only strings from these constants are being used, so I define a type alias.
type StringLiteral = keyof typeof StringLiterals;

Right now, I have to redefine this type alias everywhere I want to use it. I'd define the string values and the type alias in the same module such that I can do something like this:
import StringLiteral from "./StringLiteral";

function doSomething(str: StringLiteral) {
    if (str === StringLiteral.a) { ... }
}

Also:

*

*I don't want two different modules, one containing the type and the other containing the string values.

*I don't want enums, because they don't let you map identifiers to string values; they have to be numeric. I also want to avoid a lot of array referencing to translate between string and numeric values.

Is this at all possible?

A: const StringLiterals = {
    a: "LetterA" as "LetterA",
    b: "LetterB" as "LetterB",
    c: "LetterC" as "LetterC"
};

type StringLiterals = (keyof StringLiterals)[keyof typeof StringLiterals];

export default StringLiterals;


text:
Q: Nesting relationship with ElasticSearch I am trying to find revenue per actor in a movie. It is pretty straightforward, but here's an example of what I have now:
// without actor
{
    "ID": 1,
    "Timestamp": "2014-01-01 00:02:12",
    "Title": "Great White Shark",
    "Amount": 4.99
}

It is not an issue if I have, for example, 100M entries in financials and I ask for the aggregate where the title=GreatWhiteShark.
However, when I add in an Actor, the structure becomes extremely verbose, and probably increases my storage size by 10x --
{
    "ID": 1,
    "Timestamp": "2014-01-01 00:02:12",
    "Title": "Great White Shark",
    "Amount": 4.99,
    "Actors": [Christopher Plummer,Andrew Garfield,Heath Ledger,
               Lily Cole,Jude Law,Verne Troyer,Johnny Depp,
               Tom Waits,George MacKay,Tom Holland,Saoirse Ronan,
               Seymour Cassel,Sofia Milos]
}

This is so I can ask a question such as "How much money did movies with Christopher Plummer make in 2011?".
Is there a better way to do the above structure? My main concern is performance, and secondary would be storage size.

A: Performance should be very good, Elasticsearch will build an inverted index for actors array anyway. Querying an actor will return all associated movies instantly.
As for space reduction, you can try encoding each actor name to an integer id instead of actor slug. But you should try slug variant first as this does not destroy readability and integrations to Kibana, etc.
Your proposed structure is perfectly suited for Elasticsearch by all means.

redpajama_set_name: RedPajamaStackExchange


text:
Q: 68000 assembly code memory mapping I need help in this matter.I have to draw a memory map and I have
here is the code
ORG $6080;
CAT EQU 5;
DOG DC.L CAT;
Hourse EQU 1;

I m not getting after ORG line,can anyone tell how can i draw its memory map

A: Let's break it down:
ORG $6080; // Defines the start of data/code
CAT EQU 5;  // Defines a constant with value 5, does not allocate any memory
DOG DC.L CAT;  // Defines a 32bit variable in memory, sets value to CAT (5)
Hourse EQU 1;  // Defines a constant with value 1, does not allocate any memory

So now that you know the start of the block and what is put into memory and what is not, you can draw a memory map of it. It will contain a single 32bit value.

A: This is my attempt at understanding what your Lecturer wants. Their choice of sudo code is interesting.
ORG is probably referring to a number although this could be a Memory address.
CAT is then presumably a  variable in a register. EQU is saying that CAT is equal to 5.
DOG is also then presumably a variable in a register. Absolute far addressing is used to say what DOG is equal to. In other words DOG is equal to DC.L indexed by 5.
Hourse is then another variable in a register and it is equal to 1.
Now a table can be created (Memory Map) where we go
Variable | Value | Address

ORG          1       ?
CAT          5       ?
DOG          ?     DC.L indexed by 5
Hourse       1       ?

You could define what memory locations these are in in the data section of the assembly. Then you can fill out the address question marks. The actual value stored is arbitrary but just included for context.


text:
Q: Scala uses mutable variables to implement its apis I am in the process of learning Scala through Coursera course (progfun).
We are being learned to think functionally and use tail recursions when possible to implement functions/methods.
And as an example for foreach on a list function, we have taught to implement it like:
def foreach[T](list: List[T], f: [T] => Unit) {
    if (!list.isEmpty) foreach(list.tail) else f(list.head)
}

Then I was surprised when I found the following implementation in some Scala apis:
override /*IterableLike*/
  def foreach[B](f: A => B) {
    var these = this
    while (!these.isEmpty) {
      f(these.head)
      these = these.tail
    }
}

So how come we are being learned to use recursion and avoid using mutable variables and the api is being implemented by opposite techniques?
Have a look at scala.collection.LinearSeqOptimized where scala.collection.immutable.List extend. (similar implementation found in the List class itself)

A: Don't forget that Scala is intended to be a multiparadigm language. For educational purposes, it's good to know how to read and write tail-call recursive functions. But when using the language day-to-day, it's important to remember that it's not pure FP.
It's possible that part of the library predated TCO and the @tailrec annotation. You'd have to look at commit history to find out.
That implementation of foreach might use a mutable var, but from the outside, it appears to be pure. Ultimately, this is exactly what TCO would do behind the scenes.

A: There are two parts to your question:

So how come we are being learned to use recursion and avoid using mutable variables

Because the teachers assume that you either already know about imperative programming with mutable state and loops or will be exposed to it sometime during your career anyway, so they would rather focus on teaching you the things you are less likely to pick up on your own.
Also, imperative programming with mutable state is much harder to reason about, much harder to understand and thus much harder to teach.

and the api is being implemented by opposite techniques?

Because the Scala standard library is intended to be a high-performance industrial-strength library, not a teaching example. Maybe the person who wrote that code profiled it and measured it to be 0.001% percent faster than the tail-recursive version. Maybe, when that code was written, the compiler couldn't yet reliably optimize the tail-recursive version.
Don't forget that Iterable and friends are the cornerstone of Scala's collections library, those methods you are looking at are probably among the most often executed methods in the entire Scala universe. Even the tiniest performance optimization pays out in a method that is executed billions of times.


text:
Q: Infinite looping next post link within a certain category on a post I'm looking to create an infinitely looping 'next post' link at the bottom of a post that only links to posts in that category.
So if I have three posts in the same category – 1, 2 and 3 – it should work as follows:

*

*clicking the link on post 1 should take me to post 2

*clicking the link on post 2 should take me to post 3

*clicking the link on post 3 should take me to post 1

I've got code to loop through all posts in this way, but am stuck on how to edit it so that it only loops through posts with the same category as the current post.
if( get_adjacent_post(true, '', false) ) {
next_post_link($format = '%link', $link = 'Next Article', $in_same_term = true);
} else {
$thiscat = get_the_category();
$last = new WP_Query(array('query' => 'posts_per_page=1&order=ASC',
'category_name' => $thiscat)); $last->the_post();
    echo 'Next Article';
wp_reset_query();
};

A: based on the docu:

*

*the $in_same_term parameter in https://developer.wordpress.org/reference/functions/next_post_link/

*the categories' parameters in WP_Query https://developer.wordpress.org/reference/classes/wp_query/#category-parameters

*and how to get a post's category https://developer.wordpress.org/reference/functions/get_the_category/

*and in collaboration with @zackwww;

'infinitely looping 'next post' link at the bottom of a post that only links to posts in that category'
if( get_adjacent_post(true, '', false, 'category') ) {
   next_post_link($format = '%link', $link = 'Next Article', $in_same_term = true, $taxonomy = 'category');
} else {
   $thiscat = get_the_category();
   $catslug = $thiscat[0]->slug;
   $last = new WP_Query( array(
      'posts_per_page' => 1,
      'order' => 'ASC',
      'category_name' => $catslug
    ) );
   $last->the_post();
   echo 'Next Article';
   wp_reset_postdata();
}


text:
Q: jQuery display only pure HTML in HTML excluding htmlentities I'm currently displaying posts from my database, and this is an example of the 'message' field in my database. The Alice hyperlink links to the user's profile, while the ?< etc. are all HTML specified by the user themselves.
Alice Alice, you there?<strong>are you here?</strong>

Existing js
$.get('/getUserPosts?id=2', function(data) {
    $.each(data, function(){
        $("#posts").append('
'+this.content+'
');
    });
});

As seen above, the link part is in pure html, while the section behind are some html entities. When I'm displaying my code on my webpage via jQuery, it's showing all HTML content.
How can I make it such that it only displays the pure HTML above (Alice hyperlink), and the html entities (?<are you here?<) remain in text form? (But still visible)

Current display [Note that @Alice is a hyperlink]: @Alice Alice, you
  there? are you here?
Expected display [Note that @Alice is a hyperlink]: @Alice Alice, you
  there? are you here?

Thanks!
Edit: I'm using append to include them in divs.

A: It consist in doing this :
$('#test').each(function(){
    var $this = $(this);
    var t = $this.text();
    $this.html(t.replace('&lt','<').replace('&gt', '>'));
});

Here you go : (made by Jared Farrish)
http://jsfiddle.net/XS5kY/


text:
Q: Device ID in a UWP app (threshold 1) In Phone 8.1 you could get the device ID using HardwareIdentification, and even though the documentation says it exists for Desktop apps, it does not exist for a UWP app.

What is the alternative or a way to get a hardware ID for a UWP?

A: You're running into a common issue when migrating an app from Windows (Phone) 8(.1) to the Windows Universal Platform.
The reason you're not seeing the HardwareIdentification is pretty simple: You don't reference the required sources!
You only see AnalyticsInfo and AnalyticsVersionInfo. This is because they are part of the Universal Device Family, as stated on the documentation page (https://msdn.microsoft.com/en-us/library/windows/apps/windows.system.profile.analyticsinfo.aspx) at the very bottom.
The HardwareIdentification however is not part of the Universal Device Family, it's part of the Desktop and Mobile family, as Adriano alread stated in his comment.
To make the info available, you have to add the references to the specific extensions:

After that, make sure to check if the type exists, before calling it:
if (Windows.Foundation.Metadata.ApiInformation
    .IsTypePresent("Windows.System.Profile.HardwareIdentification"))


text:
Q: How to make html table take up 100% of parent element width? My table has a nested table for one of its rows. I would like both tables to take up 100% of the parent element width. How do I do that?
Demo
HTML

    row 1

            Headingname

            name
            date
            age

            gg
            dd
            ee

A: Drawing on the other answers, in a roundabout way, yes they do have an element of correctness, unfortunately none of them has the full story.
As Justinas points out, you're not nesting tables, what you're nesting are rows.  While row nesting will indeed work, it is actually now not supported under the new HTML5 schemes.
This means that trying to do what you're doing, will simply not validate, and worse will refuse to render correctly on mobile devices.
Working with your existing code:

      row 1

          Headingname

          name
          date
          age

      gg
      dd
      ee

You can achieve what you're trying to do by adding a width of 100% to the table's style as others have already pointed out, and by adding a width:100% to requestDetailsHeading class.
However, I'm going to take a guess here, and looking at your other class names (specifically container and row) I suspect you might actually be using the Bootstrap CSS framework. If you're not then perhaps you might want to consider doing so, as it will make the task you're trying to do much easier and you'll have less fiddling about to do.
You can download the various CSS files from
http://getbootstrap.com/

And once you have a page set-up with BS in place, you can get the exact effect you want by using the following HTML

        row 1

      HeadingName

      Name
      Date
      Age

      gg
      dd
      ee

Even without bootstrap added however, you'll notice that I've simplified the HTML.
To get the effect you're looking for of a 100% row, above each row of data, you don't need to nest things the way you did, you simply just need to tell the td element how many columns it has to span, and as long as that is equal to the rest of the table, you'll end up with a 100% width header across separate columns. If you decide to use Bootstrap, then BS will take care of giving you a 100% table width, otherwise as others have mentioned simply add a width of "100%" to a class that controls the table itself.
Additional (But not required to solve your problem)
If you decide to use Bootstrap as your CSS framework, there is another way that you can achieve what you're trying to achieve, and that's to use the BS3 grid system.
Using 'container' s, 'row' s and 'col-md-xx' style classes, you could very easily do something like the following:

      Row Header Text Goes Here

Name

Date

Age

gg

dd

ee

Because of the way Bootstrap works, the container will automatically take up 100% of the center column (approx 1024 pixels) and each of your rows will take up the appropriate space in the 12 column grid that's available by default.
Your data rows are set to column widths of 4 grids, as 3 times 4 is 12, and it's easy to repeat the 'div' sections as needed in order to produce as many rows as needed.
Finally, if you use 'container-fluid' rather than 'container' in your outermost div, then your layout will span the entire width of the visible page.
The best part about going the bootstrap route however, is that everything you do using it is automatically responsive, and so will adapt and resize automatically for mobile and desktop as needed, especially if you start using a mixture of 'col-xx-yy' column types, where xx represents the device target size, and yy the number of grid columns you wish to consume.

A: Fiddle
table{
    background-color:white;
    width:100%;
}

A: You don't have nested tables. You have tr > td > tr > td that I think is not valid.
Also, first row don't have td element.
Simply apply width: 100% to all tables:

table {
  background-color: white;
  width: 100%;
}
.requestDetails {
  background-color: red;
}
.container {
  width: 600px;
  background-color: green;
}
.row {
  width: 100%;
  background-color: blue;
}

      row 1

          Headingname

          name
          date
          age

      gg
      dd
      ee

A: Just add width: 100%; to the table in CSS.
Updated jsFiddle
Readup: CSS width | MDN

A: Just update your css like below:
.container table{
    background-color:white;
    width:100%;
}

A: If the width attribute is not set, table takes up the space it needs to display the table data. so you have to define the width of table.
so just define the width for table in CSS.
.row, table{
width:100%;
background-color:blue;
 }


text:
Q: How to get two variables from the string? I have this string: 'foo = bar; this = is; not = necessary'
I would like to get this result: {"name" : "foo", "value" : "bar"}
It is not necessary, what is after the ;
I know, I should use some regexp, but I don't really understand how regexp works.
Thanks is advance,

A: You could use:
var values='foo = bar; this = is; not = necessary'.split('; ')[0].split(' = ');
var obj={"name" : values[0], "value" : values[1]}

This way you do:

*

*'foo = bar; this = is; not = necessary'.split('; '), which returns ['foo = bar','this = is','not = necessary']

*You want just the first element, so 'foo = bar; this = is; not = necessary'.split(';')[0] gives 'foo = bar'

*Then you split again: 'foo = bar; this = is; not = necessary'.split(';')[0].split(' = '), which gives ['foo','bar']

*And finally you create the object

A: An approach that uses regular expressions to search in a particular string, for a specified name, which will match the foo = bar portion of the string:
function getNameValuePair(string, needle) {
    if (!string || !needle) {
        return false;
    }
    else {
        var newNeedle = needle + '\\s+\\=\\s+\\w+',
            expr = new RegExp(newNeedle),
            parsed = string.match(expr).join(),
            parts = parsed.split(/\s+\=\s+/),
            returnObj = {'name' : parts[0], 'value' : parts[1]};

        return returnObj;
    }
}

var string = 'foo = bar; this = is; not = necessary',
    nameValueObj = getNameValuePair(string, 'foo');

console.log(nameValueObj);

JS Fiddle demo.
This could, of course, be adapted to more suit your requirements.
As it is, however:

*

*The function checks that both parameters are present and, if not, simply returns false.

*Creates a regular expression pattern consisting of the needle ('foo' in this case), followed by one, or more, units of white-space followed by a single = character, followed by one, or more, white-space characters. If the white-space may not always be present, it might be better to change to newNeedle = needle + '\\s*\\=\\s*\\w+' (the + matches 'one-or-more', the * matches 'zero-or-more').

*creates a RegExp from that pattern,

*tests the given string to see if it matches the pattern and, if it does, stores that match in the parsed variable,

*splits the parsed variable with another regular expression, effectively splitting on a pattern of zero-or-more white-space followed by an = followed by zero-or-more white-space, storing the separated parts in the parts array variable,

*constructs the object from the parts variable.

*Returns that variable.

Updated the above, slightly, because two lines to create one RegExp was just silly:
function getNameValuePair(string, needle) {
    if (!string || !needle) {
        return false;
    }
    else {
        var expr = new RegExp(needle + '\\s+\\=\\s+\\w+'),
            parsed = string.match(expr).join(),
            parts = parsed.split(/\s+\=\s+/),
            returnObj = {'name' : parts[0], 'value' : parts[1]};

        return returnObj;
    }
}

var string = 'foo = bar; this = is; not = necessary',
    nameValueObj = getNameValuePair(string, 'foo');

console.log(nameValueObj);

JS Fiddle demo.
References:

*

*JavaScript Regular Expressions.

*string.match().

*string.split().


text:
Q: How can I make this JEditorPane display the way I want? It starts off displaying like this:

Then as expected, when you fill it with text beyond the bottom limit it looks like this:

But the text trails off the side a bit, which definitely has something to do with the horizontal scroll bar it activates, but it looks really weird. So how can I disable the horizontal scroll bar and have the text display cleanly without it trailing off to the right a bit?
JEditorPane editorPane = new JEditorPane();
    scrollPane.setViewportView(editorPane);
    editorPane.setLineWrap(true);

editorPane.setLineWrap(true); does not work, it says "The method setLineWrap(boolean) is undefined for the type JEditorPane" If there's a way to use HTML in a JTextArea tell me; but I don't think that'll work. I need to be able to add HTML later.
Full code:
import java.awt.EventQueue;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class MainGUI {

private JFrame frame;
private JTextField textField;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MainGUI window = new MainGUI();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public MainGUI() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
//  frame.setLocationRelativeTo(null);
    frame.setBounds(500, 200, /*W*/600, /*H*/435);
//  frame.setSize(/*W*/600, /*H*/435);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(10, 11, 564, 337);
    frame.getContentPane().add(scrollPane);

    JEditorPane editorPane = new JEditorPane();
    scrollPane.setViewportView(editorPane);

    textField = new JTextField();
    textField.setBounds(10, 365, 564, 20);
    frame.getContentPane().add(textField);
    textField.setColumns(10);
}

}

A: If the editor pane contains HTML, the natural behavior is to wrap when it gets to the maximum width. The trick is to tell the scroll pane not to display a horizontal scroll bar, so it suggests to the view component to limit the size to whatever width it is (damn well) given by the view.
E.G. (an actual MCVE)
import java.awt.*;
import javax.swing.*;

public class MainGUI {

    private JFrame frame;
    private JTextField textField;
    private String[] loremIpsum = {
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer ut nulla egestas arcu rhoncus molestie. Mauris eget consequat sem, a accumsan eros. Praesent sem massa, dignissim sit amet porta ut, interdum sit amet ligula. Pellentesque cursus odio vel vestibulum vulputate. Donec facilisis ex sed pellentesque laoreet. Praesent ut sem id lectus suscipit pulvinar. Mauris a eros dui. Nulla ultrices est eu lacinia sagittis. Vivamus ac erat sit amet dolor ultricies euismod. Curabitur condimentum in ante id mattis. Pellentesque non sagittis diam. Nulla dapibus lacus sagittis turpis vehicula, vitae eleifend odio euismod. Sed elementum facilisis nisl. Donec lectus nulla, rutrum ac sollicitudin pulvinar, tempus ut arcu. Maecenas ut vulputate purus. In luctus cursus magna sit amet facilisis.",
        "Morbi vitae dictum enim, quis porttitor elit. Nam quis accumsan leo, id rhoncus tortor. Praesent tellus magna, ultrices quis nulla vel, fringilla ultricies purus. In hendrerit volutpat elit a posuere. Duis scelerisque, sapien eu faucibus eleifend, lectus lacus interdum diam, sed bibendum orci est ut urna. Quisque a sem iaculis ex aliquam tempor. In id dictum ex, non gravida lacus. Integer neque mauris, tristique eu ultrices quis, tristique pellentesque nunc. Donec egestas tristique dolor, ac sagittis ante elementum non.",
        "Mauris sit amet ullamcorper erat. Nunc non condimentum augue. Vivamus et odio eget massa convallis vulputate nec ut lacus. Donec sapien dolor, facilisis sit amet venenatis sit amet, suscipit ut nisi. Praesent vitae lorem lacinia orci volutpat fermentum. Nullam dolor erat, facilisis vitae volutpat id, feugiat et augue. Nunc congue, lectus a vehicula lacinia, est libero volutpat quam, nec maximus ante mauris eu urna. Etiam nunc dolor, auctor et orci vitae, pulvinar pretium orci. Nam et est rhoncus, pharetra mauris id, condimentum leo. In fermentum non urna sed imperdiet. Cras sit amet nulla eget purus convallis accumsan. Donec dictum eget magna pulvinar scelerisque. Fusce efficitur nisl sed nibh vestibulum laoreet.",
        "Morbi tincidunt eleifend nisl. Nullam libero massa, imperdiet vitae egestas eu, sodales ac lacus. Donec eu commodo dui. Suspendisse potenti. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aenean vel diam volutpat, gravida quam vitae, tristique dui. Cras aliquet gravida massa eget lobortis. Donec ullamcorper eu purus eget iaculis. Ut id leo erat. Etiam iaculis ante eu mi molestie suscipit.",
        "Quisque dapibus consectetur mauris eu faucibus. Etiam ac varius odio. Nulla non elit velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vivamus est leo, ultricies quis sem ut, euismod vestibulum augue. Donec auctor eu nisi a aliquam. Integer libero sapien, fringilla ac posuere ut, malesuada ut leo. Maecenas ut ante non arcu molestie gravida nec eu neque. Vivamus elit nisi, auctor at luctus eget, accumsan id dolor."
    };

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainGUI window = new MainGUI();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public MainGUI() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame("HTML in editor pane");
        frame.setLocationByPlatform(true);
        //frame.setBounds(500, 200, /*W*/ 600, /*H*/ 435); this is guessing!
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        StringBuilder sb = new StringBuilder(
                "<html><body style='width: 400px;'>");
        for (String s : loremIpsum) {
            sb.append("<p>");
            sb.append(s);
        }
        JEditorPane editorPane = new JEditorPane();
        editorPane.setContentType("text/html");
        editorPane.setText(sb.toString());
        JScrollPane scrollPane = new JScrollPane(
                editorPane,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                // this is an important line!
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        editorPane.setCaretPosition(0);
        frame.getContentPane().add(scrollPane);
        frame.pack();
        // it should be the correct size needed to display the content,
        // but now let's make it half that height.
        Dimension d = frame.getSize();
        d = new Dimension(d.width, d.height/2);
        frame.setSize(d);
    }
}


text:
Q: How to fix m2e error in pom.xml: plugin execution not covered by lifecycle configuration? I am having the title mentioned error in my Maven Java project. Below is a comparison of a good project and my troubled project.

*

*How to fix these 2 errors?

*And in the upper good one why there're so many configurator, configurator,...?  It looks weird even if there are no error marks.

I have read the thread: How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds.
But it doesn't provide a clean shot. It's full of explanations but without canonical solutions.
BTW, I am so frustrated by the Maven XML mess that I have to find some alternative.
ADD 1  -- issue partially fixed, but not sure about root cause, and the so many configurators.
OK, I noticed in the Installation Details of eclipse, there's no m2e items. Strange how can I import maven projects without installing it. Anyway I install the latest 1.6.2 from http://www.eclipse.org/m2e/. And the above issue is gone.
But this is just a solution. I still don't know why there're so many configurator...
ADD 2  -- add my pom.xml, it is not the effective pom.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.its</groupId>
    <artifactId>cloud</artifactId>
    <name>MyCloud</name>
    <packaging>war</packaging>
    <version>1.0.0-BUILD-SNAPSHOT</version>
    <properties>
        <java-version>1.7</java-version>
        <org.springframework-version>4.2.2.RELEASE</org.springframework-version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <org.slf4j-version>1.6.6</org.slf4j-version>
        <org.apache.logging.log4j-version>2.4.1</org.apache.logging.log4j-version>
    </properties>
    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                 </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <!-- AspectJ -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>

        <!-- Logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>

        <!-- @Inject -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${org.apache.logging.log4j-version}</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

A: M2Eclipse requires explicit instructions what to do with all Maven plugins bound to certain phases of a project build lifecycle. Such instructions are referenced as "lifecycle mapping" because they define how m2e maps information from the project pom.xml file to Eclipse configuration. One action that M2Eclipse can be instructed to do with a plugin execution is delegation to a project configurator.
Quoting this reference page:

A configurator mapping tells M2Eclipse to delegate workspace project configuration mapping for matching plugin execution to an implementation of AbstractProjectConfigurator registered with m2e using projectConfigurators extension point.

Those extension points are located inside each Eclipse plugins. If you take a look inside ${ECLIPSE_HOME}\plugins, you will notice a couple of jars whose name begin with org.eclipse.m2e. These are the M2Eclipse plugins.
Let's take the example of some of the configurators of the maven-war-plugin. To see where the configurators are declared, you can unzip org.eclipse.m2e.wtp_1.2.1.20150819-2220.jar (the name might be different according to your M2Eclipse version) and open the file lifecycle-mapping-metadata.xml. For the war packaging, this is what I have:
<lifecycleMapping>
  <packagingType>war</packagingType>
  <lifecycleMappingId>org.maven.ide.eclipse.wtp.WarLifecycleMapping</lifecycleMappingId>
  <pluginExecutions>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <versionRange>[2.0.1,)</versionRange>
        <goals>
          <goal>war</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <configurator>
          <id>org.maven.ide.eclipse.configuration.wtp.configurator</id>
        </configurator>
      </action>
    </pluginExecution>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <versionRange>[2.0.1,)</versionRange>
        <goals>
          <goal>war</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <configurator>
          <id>org.maven.ide.eclipse.configuration.wtp.warmanifest.configurator</id>
        </configurator>
      </action>
    </pluginExecution>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <versionRange>[0.0.1,2.0.1)</versionRange>
        <goals>
          <goal>war</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <error>
            <message>maven-war-plugin prior to 2.0.1 is not supported by m2e-wtp. Use maven-war-plugin version 2.0.1 or later</message>
        </error>
      </action>
    </pluginExecution>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <versionRange>[2.0.1,)</versionRange>
        <goals>
          <goal>war</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <configurator>
          <id>org.maven.ide.eclipse.configuration.wtp.overlay.configurator</id>
        </configurator>
      </action>
    </pluginExecution>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <versionRange>[1.0,)</versionRange>
        <goals>
          <goal>inplace</goal>
          <goal>exploded</goal>
          <goal>manifest</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <ignore>
            <message>maven-war-plugin goals "inplace", "exploded", "manifest" are ignored by m2e</message>
        </ignore>
      </action>
    </pluginExecution>
  </pluginExecutions>
</lifecycleMapping>

You can see that this declares configurators. All of those configurators are the ones that you see in the dialog box picture in your post.
Depending on your Eclipse installation, other configurators for maven-war-plugin can be declared:

*

*For JSF, they are declared in org.eclipse.m2e.wtp.jsf_1.2.1.20150819-2220.jar

*For JAX-RS, they are declared in org.eclipse.m2e.wtp.jaxrs_1.2.1.20150819-2220.jar
The M2Eclipse extension development page documents how to create new m2e extensions and takes the example of antlr3-maven-plugin.

A: You can also add special m2e comments in your pom.xml execution section. I found this way is way cleaner than creating a custom lifecycleMapping.
<execution>
  <?m2e ignore?>
  …

or
<execution>
  <?m2e execute?>
  …

See https://www.eclipse.org/m2e/documentation/release-notes-17.html for details.

A: you can use plugin for this
Basically not a proper configuration This type of error generate..

     org.eclipse.m2e
     lifecycle-mapping
     1.0.0

               some-group-id
               some-artifact-id
               [1.0.0,)

                 some-goal


text:
Q: How to split terminal in Ubuntu 16.04? I've seen in some video that it is possible to split terminal window into several areas (not tabs), but can't found those video and can't understand how to do it.

A: The default gnome-terminal doesn't support splitting,it only allows using tabs. What you want is either Terminator , byobu,or screen.
In the first case, Terminator is a standalone terminal emulator.

Byobu and screen are terminal multiplexers , which are basically apps that run inside terminal emulator.
Any of these can be installed via sudo apt-get install <app-name>


text:
Q: QuiltView Error: No resource identifier found for attribute 'scrollOrientation' I want to use the QuiltView lib in my Android project.
When I try the demo, I've no problems, but when I want to use it in my project I've got this error :
error: No resource identifier found for attribute 'scrollOrientation' in package 'com.jake.quiltview'

I've just include libs (QuiltViewLib & GridLayoutV7) in my project...
So, have you got an idea ?

A: You have to fix the namespace. The XML he used references his own project. You have to change it to reference yours. I had this issue too.
Change
xmlns:app="http://schemas.android.com/apk/res/com.jake.quiltviewsample

To:
xmlns:app="http://schemas.android.com/apk/lib/com.package.class

Obviously changing it to match your project package. :)


text:
Q: Running spark-submit from pycharm I am trying to figure out how to develop apache-spark program in PyCharm.
I have followed article in this link.
I define SPARK_HOME and add pyspark to Python path well. There is no error
in importing pyspark modules and autocomplete works fine.
However I get an error on defining SparkContext when I run the program in PyCharm.
Error: Must specify a primary resource (JAR or Python or R file)
Run with --help for usage help or --verbose for debug output
...
...
Exception: Java gateway process exited before sending the driver its port number

I managed to run the program on terminal with submit-spark.
Do I need to change the configuration on PyCharm or Is there anyway to run
submit-spark instead of python in PyCharm?

A: If you are fine by terminal submit-spark you can add a run configuration that does that for you. Otherwise you can see some configuration in Edit Run/Debug Configurations window as well. This post in particular can you get you there.


text:
Q: How to setup semantic-release without the need for npm? I have a C# project and would like to add semantic versioning to it. So whenever I push to the main branch I want to create a new release and autogenerate a new version number based on the commit types. I think semantic-release does the job very well since I'm already using commitlint with husky.
For reproduction:

*

*Create a new repository on Github

*Inside the repo create a new C# project (you may skip this step)

*Run npm init -y to setup npm

*Follow https://commitlint.js.org/#/guides-local-setup to setup commitlint and husky

*Create a new personal access token for your account

*Add a new Github secret to your repository, name it SEMANTIC_RELEASE and add the access token as the value for it

*Based on https://semantic-release.gitbook.io/semantic-release/usage/getting-started create a new Github workflow

.
name: Release

on:
  push:
    branches:
      - `main`

jobs:
  release:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2

      - name: Setup Node
        uses: actions/setup-node@v2
        with:
          node-version: 14.x

      - name: Install dependencies
        run: npm install

      - name: Release
        env:
          GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE }}
        run: npx semantic-release

*

*After pushing it the workflow should fail with the following error message

[2:51:48 PM] [semantic-release] › ✔  Completed step "fail" of plugin
"@semantic-release/github" An npm token
(https://github.com/semantic-release/npm/blob/master/README.md#npm-registry-authentication)
must be created and set in the NPM_TOKEN environment variable on your
CI environment.
Please make sure to create an npm token
(https://docs.npmjs.com/getting-started/working_with_tokens#how-to-create-new-tokens)
and to set it in the NPM_TOKEN environment variable on your CI
environment. The token must allow to publish to the registry
https://registry.npmjs.org/.
AggregateError:
SemanticReleaseError: No npm token specified.
at module.exports (/home/runner/.npm/_npx/1561/lib/node_modules/semantic-release/node_modules/@semantic-release/npm/lib/get-error.js:6:10)
at module.exports (/home/runner/.npm/_npx/1561/lib/node_modules/semantic-release/node_modules/@semantic-release/npm/lib/set-npmrc-auth.js:45:31)
at module.exports (/home/runner/.npm/_npx/1561/lib/node_modules/semantic-release/node_modules/@semantic-release/npm/lib/verify-auth.js:17:9)
at verifyConditions (/home/runner/.npm/_npx/1561/lib/node_modules/semantic-release/node_modules/@semantic-release/npm/index.js:36:13)
at async validator (/home/runner/.npm/_npx/1561/lib/node_modules/semantic-release/lib/plugins/normalize.js:34:24)
at async /home/runner/.npm/_npx/1561/lib/node_modules/semantic-release/lib/plugins/pipeline.js:37:34
at async Promise.all (index 0)
at async next (/home/runner/.npm/_npx/1561/lib/node_modules/semantic-release/node_modules/p-reduce/index.js:16:18)
at /home/runner/.npm/_npx/1561/lib/node_modules/semantic-release/lib/plugins/pipeline.js:54:11
at async Object.pluginsConf. [as verifyConditions] (/home/runner/.npm/_npx/1561/lib/node_modules/semantic-release/lib/plugins/index.js:80:11)
at async run (/home/runner/.npm/_npx/1561/lib/node_modules/semantic-release/index.js:95:3)
at async module.exports (/home/runner/.npm/_npx/1561/lib/node_modules/semantic-release/index.js:260:22)
at async module.exports (/home/runner/.npm/_npx/1561/lib/node_modules/semantic-release/cli.js:55:5)
Error: Process completed with exit code 1.

I don't want to publish to the npm registry, it should just create a new release version.
Did I miss something or is semantic-release the wrong tool for my project?

A: You don't have to publish to the npm registry. You can set that up in the .releaserc.
{
  "plugins": [
    ["@semantic-release/npm", {
      "npmPublish": false,
    }],
  ]
}

A: I realize this is an old question, yet maybe someone will find my solution usefull. I adapted it from this blog post by Sohrab Hosseini
\\ .gitlab-ci.yml
cut-version:
  image: node:16-alpine3.13
  stage: publish
    - npm i -g semantic-release @semantic-release/gitlab
  artifacts:
    reports:
      dotenv: vars.env
  script:
    - |-
      cat > .releaserc <<RELEASERC
      {
        "plugins": [
          "@semantic-release/commit-analyzer",
          "@semantic-release/release-notes-generator",
          "@semantic-release/gitlab",
          [
            "@semantic-release/exec", {
              "successCmd": "echo \"VERSION=\${nextRelease.version}\" >> vars.env"
            }
          ]
        ]
      }
      RELEASERC
    - semantic-release
  only:
    - main

publish-build:
  stage: publish
  needs:
    - job: cut-version
  script:
    - echo "$VERSION"

A: Instead of using hacks to achieve your desired usage, I can recommend using an alternative to semantic-release
called atomic-release.
It's an SDK to create atomic releases which ensure a failure during a release rolls back any previous actions taken.
You can create your own release strategy and utilize gitSemanticRelease
Disclaimer: I'm the author of atomic-release.


text:
Q: html input name="foo[]" in ng-model Sorry cant think of a more valid title. In HTML when we want multiple values for a given name we use this name="foo[]" attribute.
When the data is posted it comes as an array. What I want is this functionality with ng-model in angular.
Reason: I have a form that has multiple fields with same name, like in a CV when we write our past experiences.
NB: Before saying this is a duplicate, please read this properly. I have seen valid questions being marked as duplicate and not constructive.

A: If in your angular controller you have something like this:
$scope.foo = []; //your values in the array

You can have in your view something like this:
<dd ng-repeat="item in foo">
    <input type="text" ng-model="foo[$index]" value="{{item}}" required/>
</dd>

This is what you need? No need for name if you use ng-model you have the data in the model on form submit.


text:
Q: Unable to Unmarshall the data correctly in golang from a map to a structure I am currently unable to unmarshall the data correctly from a map into a structure. Following is a code snippet (Brief Code at playground):
Request you to kindly provide the reason of getting default values on unmarshlling back the data.
package main

import (
    "fmt"
    "encoding/json"
    "os"
    )

func main() {
    fmt.Println("Hello, playground")
    type PDPOffer struct {
        cart_value            int    `json:"cart_value"`
        discount_amount_default int    `json:"discount_amount_default"`
        max_discount           string `json:"max_discount"`
        }

        a:= map[string]interface{} {
        "cart_value"              : 1,
        "max_discount"            : 2,
        }
        var pdf PDPOffer
        b, err := json.Marshal(a)
        if err != nil {
            fmt.Println("error:", err)
        }
        os.Stdout.Write(b)//working
        err1 := json.Unmarshal(b, &pdf)
        if err1 != nil {
            fmt.Println("error:", err)
        }
        fmt.Printf("%+v", pdf)//displaying just the defualt values????????
}

A: json.Marshal and json.Unmarshal can only work on exported struct fields. Your fields aren't exported and aren't visible to the json code.

A: The reason for your unmarshal not working is that you need to expose fields of the struct and for doing that you need to start field name with Capital letters. Something has below:
type PDPOffer struct {
        Cart_value            int    `json:"cart_value"`
        Discount_amount_default int    `json:"discount_amount_default"`
        Max_discount           string `json:"max_discount"`
        }

A: Also, you were trying to marshal an int value into a string for "max_discount", you need to store it as a string in your map that you're marshaling:
a := map[string]interface{}{
    "cart_value":   1,
    "max_discount": "2",
}

The error handling had a bug checking for err1 != nil then printing err which was hiding the message error: json: cannot unmarshal number into Go value of type string
Working example with all the fixes: http://play.golang.org/p/L8VC-531nS


text:
Q: Green screen while pushing view controller i have a login screen view controller (nib), when user logs in it instantiates storyboard and pushes initial view controller, but while transitioning  to this initial vc there is green screen, when transition done main screen appears normally.
![enter image description here][1]
DMapViewController *mapVC = [[UIStoryboard storyboardWithName:@"DMapViewController"
                                                       bundle:nil] instantiateInitialViewController];
[self.navigationController pushViewController:mapVC
                                     animated:YES];

A: Solved.
Problem was in calling [self.view layoutIfNeeded]; in viewDidLoad of DMapViewController;


text:
Q: Source Control System Setup I am looking for a good source control system. I would like to use git but I need something with a good user interface. I know Tortoise SVN has a nice user interface. Are there any others like tortoise SVN that has a nice user interface.

A: I would highly suggest GIT over SVN as GIT is better for collaboration and its also better when merging changes.
There is a nice tutorial here on how to setup a git server:
http://tumblr.intranation.com/post/766290565/how-set-up-your-own-private-git-server-linux
its pretty simple
It can be setup on any OS.
Mike

A: I use tortoise myself and it is really good, it just had a new update which made the commit manager a lot easier and smoother to use. Definitely recommend tortoiseSVN for large groups and git for smaller groups.


text:
Q: Central limit Theorem with sample <30
From a population $A$ which follows a normal distribution with mean $μ= 100$ and standard deviation $σ = 5$ we take a sample
  $n(A) = 164$.
  From a population B which follows a normal distribution with mean $μ= 102$ and standard deviation $σ = 10$ we take a sample
  $n(B)= 25$
  Calculate the probability that the mean of the sample from population $A$ is larger from the mean of the sample from population $B$?

Because the sample is less than $30$ I guess normal rules of Central Limit Theory do not apply. This plus the fact that I can only find solved examples of problems that calculate greater/less than about one population have me at a loss.
Can anyone help me solve this? I am severely stuck. Thank you for any help.

A: Slightly bigger hint: The mean of a sample of normally distributed values is again normally distributed, now with $\mu_M = \mu$ and $\sigma_M = \frac{\sigma}{\sqrt{n}}$. If we do this for both we now have two new normal distributions, let's call them $X_A$ and $X_B$. We are looking for $P(X_A>X_B)$ which is the same as $P(X_A-X_B>0)=P(X_B-X_A<0)$.
$X_A\sim N\left(100,\left(\frac{5}{\sqrt{164}}\right)^2\right), X_B\sim N\left(102,\left(\frac{10}{\sqrt{25}}\right)^2\right)$
$X_B-X_A$ is again normally distributed. $X_B-X_A = X_C \sim N\left(2,\left(\frac{5}{\sqrt{164}}\right)^2+\left(\frac{10}{\sqrt{25}}\right)^2\right)$
We are looking for $P(X_A>X_B) = P(X_C<0)$


text:
Q: problem with registration and login php,will you check my code?if there is an error I have a problem with either registration and login shows (undefined offset) and look at registration is there some problem with my code?it is the registration form the problem it sometimes saves the existing email in spite of the fact that I wrote a function for not submitting the existing email which is inside my data.txt. shortly the functions do not work properly
<?php
if(isset($_POST['submit_reg'])){
    $var=file("data.txt");
    $userData = $_POST['email'] . " " . $_POST['password'] . "\r\n";
    $lines=0;
        $db = fopen("data.txt", "a+");
        foreach($var as $key=>$value){
            $user = (explode(' ', $value));
            if ($_POST["password"] === $_POST["confirm_password"]) {
                    //print_r($value);
                if (trim($user[0]) == $_POST['email']) {
                    $lines++;
                }
                break;

            }
        }
            if($lines){
                    echo "The email is already exists ";
                }else{
                 fwrite($db,$userData."\r\n");
                 fclose($db);
                 echo "you are registered successfully ";
              }
}
?>

and it is my login form the problem with login is it gives an error undefined offset 12
<?php
if (isset($_POST['submit_log'])) {
    $email =isset($_POST['email']);
    $password =isset($_POST['password']);
    $file = explode( PHP_EOL, file_get_contents( "data.txt" ));
    $auth = false;
 foreach( $file as $line ) {
    list($email, $password) = explode(" ", $line);

    if ($_POST['email'] == $email && $_POST['password'] == $password) {
        $auth =true;
        break;
    }
}
        if($auth) {
            echo "Login successfull!";
        } else {
            echo "Invalid username or password";
        }
    }
?>

A: Let me say first off, storing plaintext passwords in a .txt file is probably not the best way of building a longin system. (that's the disclaimer anyway).
Undefined offset (just a guess)
That said I see a few places to improve your code.  My guess without more specifics about the error, is you may be pulling a empty array at the end of the file, it's typical to leave a hanging line return at the end (a new line with nothing else for the last line).  Which may turn into something like this once you explode it for the second time on the space [''].  And then you try to access it using list which gives you undefined offsets.
You could use array_filter and maybe trim but instead of doing this:
 $file = explode( PHP_EOL, file_get_contents( "data.txt" ));

You could try (which you should know as you use this function already)
 $file = file( "data.txt", FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES ));

The file function, takes a file and breaks it into an array based on the line returns.  So this takes the place of both explode and file_get_contents.
Then it has 2 (bitwise) flags which you could make use of:

array file ( string $filename [, int $flags = 0 [, resource $context ]] )
Reads an entire file into an array.
FILE_IGNORE_NEW_LINES
Omit newline at the end of each array element
FILE_SKIP_EMPTY_LINES
Skip empty lines

http://php.net/manual/en/function.file.php
These take the place of filtering the data for empty lines (something you weren't doing).  Granted this is a file you created but you never know when a errant line return could creep in there.
Non-unique entries
if(isset($_POST['submit_reg'])){
    $var=file("data.txt");
    $userData = $_POST['email'] . " " . $_POST['password'] . "\r\n";
    $lines=0;
    $db = fopen("data.txt", "a+");
    foreach($var as $key=>$value){
        $user = (explode(' ', $value));
        if ($_POST["password"] === $_POST["confirm_password"]) {
   //NOTE: the uniqueness check only happens when the confirm password matches
            if (trim($user[0]) == $_POST['email']) {
                $lines++;
            }
            break;

        }
    }
    if($lines){
        echo "The email is already exists ";
    }else{
  //NOTE:yet you save it no matter if that is the case
        fwrite($db,$userData."\r\n");
        fclose($db);
        echo "you are registered successfully ";
    }
}

Your uniqueness check only works when the confirm password matches the password, however when it comes time to save the data, there is no check.  Instead of just adding that check in around the saving bit, it would be better to wrap the whole thing inside this confirm test, as both pieces of that are known before touching the file:
Here I reworked this a bit for you
if(isset($_POST['submit_reg'])){
    if ($_POST["password"] === $_POST["confirm_password"]) {

        //VERIFY AND SANITIZE user input, if you put junk in you get junk out

        $password = trim($_POST['password']);
         //again use something better then die
        if(empty($password))die('Password cannot be empty');
         //because you split on space, you cannot allow it in inputs
        if(preg_match('/\s+/', $password)) die('Password cannot contain spaces');

        $email = trim($_POST['email']);
        if(empty($email))die('Email cannot be empty');
        //you may want to validate using something better
        if(preg_match('/\s+/', $email )) die('Email cannot contain spaces');

        //Use the flags
        $var=file("data.txt", FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES);

        //for duplication we only care if there is 1 previous entry
        //which is enough to say its a duplicate
        $exists=false;

        foreach($var as $key=>$value){
            $user = explode(' ', $value);
            if (trim($user[0]) == $email) {
                //we found a match this is enough to call it a duplicate
                $exists = true;
                break;
            }

        }

        if($exists){
            echo "The email is already exists ";
        }else{
            file_put_contants("data.txt", $email." ".$password.PHP_EOL, FILE_APPEND);
            echo "you are registered successfully ";
        }
    }else{
        echo "Confirm password must match password";
    }
}

Other stuff
These are also incorrect:
$email =isset($_POST['email']);
$password =isset($_POST['password']);

Isset returns a boolean value, so you are assigning true or false to those two variables. This doesn't matter as you never check them and in your loop you  overwrite with the call to list().  But just because someting "doesn't matter" doesn't mean it's correct.
These really should be something like this:
if(!isset($_POST['email']))
    die("no email"); //dont use die but do some kind of error message

if(isset($_POST['password']))
    die("no password"); //dont use die but do some kind of error message

SUMMERY
Really it's quite a mess. What I mean by this is you used 3 different ways to open and access the file data. You used the PHP line constant in some places but not all. You had code that was somewhat haphazardly thrown around, where you were setting things long before you need them, and in some cases you may not have needed them, so you were wasting resources setting them.
Please don't take the criticism hard, as I am not trying to offend.  Simply pointing out places you could improve the flow of the code and simplify things.  The big thing is don't get discouraged, in order to program effectively you have to have a no-quite attitude and the drive for continuous self improvement.  Even after 9 years of PHP programing I still learn new things all the time, I learned (and wrote a library around it) something new just 2 days ago...
As I said at the beginning and to be honest a database would actually reduce the amount of code you need.  It might be intimidating at first to use a database but you'll find that it's easier then doing this.  An example is your check for uniqueness, you can set a field to be unique in the Database then you never need to worry about duplicates, only catching the errors for them.
I would suggest looking into PDO and prepared statements, password_hash and password_verify.
A final word of warning is I didn't test any of this so forgive me if there are any typos...
Hope it helps.


text:
Q: ActionBar Tab indicator getting stuck between tabs I have implemented ActionBar tabs following this guide: github. However I have a problem with the tab indicator getting stuck between the 2nd and 3rd tab. Like there is 4 tabs, but only 3 shown. Looks like this:

It's only when I slide from the 3rd tab to the 2nd. It just stays there, and if i slide left again, it goes to the 2nd tab. So it basically just feels like there is 4 tabs.
My FragmentPagerAdapter Class looks like this

    public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
    final int PAGE_COUNT = 3;
    private static Context context;
    private String tabTitles[];

    public SampleFragmentPagerAdapter(FragmentManager fm, Context context) {
    super(fm);
        this.context = context;
        Resources resources = context.getResources();
        tabTitles = new String[] { resources.getString(R.string.recent),
            resources.getString(R.string.popular),
            resources.getString(R.string.my) };
    }

    @Override
    public int getCount() {
        return PAGE_COUNT;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
        case 0:
            return new RecentFragment();

        case 1:
            return new PopularFragment();

        case 2:
            return new MyFragment();

        }
        return null;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        // Generate title based on item position
        return tabTitles[position];
    }

    public static class RecentFragment extends Fragment implements OnItemClickListener {

        ListView listView;
        List<RowItem> rowItems;

        public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.custom_list, container, false);
            String[] titles = { "titleA", "titleB", "titleC" };
            String[] descriptions = { "a", "b", "c" };
            Integer[] images = { R.drawable.christoffer, R.drawable.frede, R.drawable.sofie };

            rowItems = new ArrayList<RowItem>();
            for (int i = 0; i < titles.length; i++) {
                RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
                rowItems.add(item);
            }

            listView = (ListView) rootView.findViewById(R.id.list);
            CustomListViewAdapter adapter = new CustomListViewAdapter(context,
                    R.layout.list_item, rowItems);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(this);

            return rootView;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // TODO Auto-generated method stub

    }

    }

    public static class PopularFragment extends Fragment {

    }

    public static class MyFragment extends Fragment {

    }

}

My SlidingTabLayout and SlidingTabStrip classes looks excatly like the one in the guide. And in the MainActivity I have added this code to implement the tabs:
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new SampleFragmentPagerAdapter(
            getSupportFragmentManager(), MainActivity.this));

// Give the SlidingTabLayout the ViewPager
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
// Center the tabs in the layout
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setViewPager(viewPager);
// Customize tab color
slidingTabLayout
        .setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return Color.RED;
            }
        });

A: Please load fragment XML into all tabs through java file and it will solve..


text:
Q: Should I use " European Union's " or "European Union"? Here are my constructions:

*

*As I said, I am present in territory of the European Union's ,
  therefore, please contact me only via e-mail at [email address].

*As I said, I am present in territory of the European Union,
  therefore, please contact me only via e-mail at [email address].

So my question is, should I use 'the European Union's' or 'the European Union'?

A: Apostrophe ('s) talks about possession. Looking at your sentence, I don't think you mean that. Check out two sentences to clear whether to use it or not.

This is the territory of the European Union

And...

This is the European Union's territory

Broadly, when you use '...of the...', it won't take apostrophe. Because you already said that possession.

However, there's something called double genitive/possessive, that uses 'of...'s' constructions. Merriam-Webster describes it.

a syntactic construction in English in which possession is marked both by the preposition of and a noun or pronoun in the possessive case (as in "A friend of Bob's is a friend of mine") —called also double possessive.

[But again, to stay unambiguous, I'd prefer to avoid this usage].
Good read here.

A: Compare:

*

*(?)That is the book of Peter.

*(*)That is the Peter's book.

*That is Peter's book.

*(?)That is the book of Peter's.

*(*)That is a book of Peter.

*(*) That is a Peter's book.

*That is a book of Peter's.
We normally use the 's structure, rather than of when we talk about possessions, relationships and physical characteristic, especially when the  'possessor' noun refers to a person, animal or to a country, organisation or other group of creatures [see  Swan (2005.440), Practical English Usage]. That is why sentence 3 is natural and sentences 1 and 5 are not. However when the 'possessor' noun is not a person but one of the other types mentioned, both the of and the 's constructions are possible: The President of Russia and Russia's President.
We cannot usually put a possessive between another determiner and a noun. Instead, we use a structure with of + possessive (Swan p.443). Sentences 2 and 6 are therefore incorrect English. Sentence 7 is natural.  The definite article defines its noun, and sentence 4 is therefore unnatural, though That is the book of Peter's that I was talking about is acceptable, as the definite article defines one of several of Peter's books.
So, That is the territory of Canada/ the European Union/the United Kingdom and That is Canada's/ the European's Union's/The United Kingdom's territory are possible as is That is Canadian/European Union/United Kingdom territory. In that last sentence, 'European Union' and 'United Kingdom' function adjectivally.


text:
Q: Mysql Select All from one table, and some from another table Using Aliases I'm posting this question because I did manage to find a similar question, but they weren't using aliases.
I have two tables - I want to grab everything from table1 and just grab the user_name and Team from table2.
My original query is grabbing everything from table2
SELECT *
FROM qabin.allqas t1
JOIN login.users t2
ON (t1.Submitter = t2.user_name)
WHERE t1.Status='Complete'

That's all well and good and works fine, but I would like to just get the user_name and the Team
To make things more interesting, they are in different databases, though it hasn't been an issue.
One is in the qabin database and the other is in the login database.
I have tried:
SELECT
  qabin.allqas.* AS t1,
  login.users.Team,
  login.users.user_name
JOIN login.users t2
ON (t1.Submitter = t2.user_name)
WHERE t1.Status='Complete'

I need the t1 and t2 aliases because they are used elsewhere for building a larger query string.
Thanks in advance!

A: Why not use a subquery?
SELECT *
FROM qabin.allqas t1
JOIN (SELECT user_name, Team FROM login.users) t2
ON (t1.Submitter = t2.user_name)
WHERE t1.Status='Complete'

A: You cant use one alias (t1) for a set of columns. I guess what you are looking for is something like:
SELECT t1.*, t2.team, t2.user_name
FROM qabin.allqas t1
JOIN login.users t2
    ON (t1.Submitter = t2.user_name)
WHERE t1.Status='Complete'

I would recommend using the real column names from t1 instead of t1.*

A: Try This query :
SELECT t1.*, t2.user_name, t2.Team
FROM qabin.allqas t1
JOIN login.users t2
ON t1.Submitter 1= t2.user_name
WHERE t1.Status='Complete'


text:
Q: Why is CKEditor not showing up? Here's my html:

    {% for simpler in post.simpler_set.all %}
        {% if simpler.coeficient == i %} {% autoescape off %}

{{simpler.author}}:

            {{simpler.simpler}}

                <button type="button" class = "btn btn-success reqsimp" id="{{simpler.id}}">Ask for Simpler.</button>

                <textarea class="ckeditor" cols="80" rows="8" style='display:none;'></textarea></input>{% csrf_token %}

                <button type="button" data-post='{{post.id}}' class="btn-primary addsimp" id="{{simpler.id}}" align="center" style="display:none;">Add Simpler.</button>

 {% endautoescape %}

I have included ckeditor.js in this django template.
I have added the class ckeditor to the text area.
Why does the CKeditor text area not show up?

A: Did you add this script in html?

and


text:
Q: using Union types in GraphQL typedDefs I am typing out my typedDefs and for one property it can return either String or Boolean.
const typeDefs = `
    type Analysis {
    id: String
    analysisName: String
    creator: String
    description: String
    datesValid: String
}
`

I want datesValid to be either String or Boolean. I tried:
const typeDefs = `
    ...
    datesValid: boolString
}

union boolString = String | Boolean
`

But this resulted in a 500 internal server error when trying to query via GraphiQL.
My end goal here is to type it as either String | Boolean

A: According to the GraphQL specification type unions can only be created from object types. This means what you want to do is not possible.
I am sure there is a different way of solving you issue. Maybe a nullable date type is solving you problem? Or an enum that could have multiple values (e.g. VALID, INVALID, PENDING)? In extreme cases you own scalar type could serve the purpose.
Usually these limitations in the specifications are also meant to help people build consistent and simple to use APIs.


text:
Q: Regarding periodic functions and their domain of definition Suppose we have a periodic function $f$ defined on R. I want to show that any periodic and continuous function attains its maximum and minimum on R. I suspect that it suffices to consider a compact subset $C = [x,x+p]$, s.t: $p>0$ is the period of $f$. My justification for this is that $f(x+p) = f(x)$ $\forall x \in R$, however, I am having trouble formalizing this. Any tips are appreciated. Thanks.

A: Let $M$ and $m$ be the maximum and the minimum of $f$ on $[0,p]$. Let $x\in\mathbb R$. Then there are $u\in [0,p]$ and $k\in\mathbb Z$ such that $x = u + kp$. Hence, $f(x) = \ldots\,\le\,M$ and $f(x) = \ldots\,\ge\,m$.


text:
Q: Entry point errors when running OpenCV projects with MingW I have installed MingW C++ compiler on Windows 10. I built the OpenCV libraries successfully.
Then I wrote a test project as follows.
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

using namespace std;
using namespace cv;

int main()
{
    Mat input = imread("lenna.jpg", IMREAD_GRAYSCALE);
    //Mat input(100, 200, CV_8UC(1), Scalar(100));

    if (input.empty())
    {
        cout << "Image is empty" << endl;
        return -1;
    }

    unsigned short rows = input.rows;
    unsigned short cols = input.cols;

    for (unsigned short i = 0; i < cols / 4; i++)
        for (unsigned short j = 0; j < rows / 4; j++)
            input.at<uchar>(j, i) = 0;

    const string wnd = "input";

    namedWindow(wnd, WINDOW_NORMAL);
    imshow(wnd, input);

    waitKey();
    destroyWindow(wnd);

    return 0;
}

The compilation is done successfully but if I run it, the following errors occur in the given order (from top to bottom one by one).

My task.json:
{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++.exe build active file",
            "command": "\"${env:WINLAB_CPP}\\g++.exe\"",
            "args": [
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe",
                "-I",
                "c:\\opencv_z\\build\\include",
                "-L",
                "c:\\opencv_z\\releases\\bin",
                "-llibopencv_core451",
                "-llibopencv_highgui451",
                "-llibopencv_imgcodecs451",
                "-llibopencv_imgproc451",
            ],
            "options": {
                "cwd": "${workspaceFolder}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Is there any hint to solve it?

A: The culprit is:
There are two 64-bit libstdc++-6.dll files in my PATH. The older one unfortunately is on the top so any request to 64b-bit libstdc++-6.dll will be bounded to the top one.
As a result, my applications that need the new one gets crashed. Swapping them solves the problem.
Using 32-bit version of MinGW can solve this issue as well, but it is a very controversial  option!


text:
Q: Flutter CustomScrollView best practices I have some code like the following:
return CustomScrollView(
  children: [
    SliverPadding(
      padding: EdgeInsets.only(left: 8),
      sliver: Container(/* */),
    ),
    SliverPadding(
      padding: const EdgeInsets.only(left: 8),
      sliver: Text(/* */),
    ),
    SliverList(
      delegate: SliverChildBuilderDelegate((context, idx) => /* */),
    ),
  ],
);

Is it more performant to convert my box widgets slivers (via SliverToBoxAdapter) and have them be children of the CustomScrollView or should I have two SliverLists in my CustomScrollView?


text:
Q: HEAP CORRUPTION DETECTED in C I am having some problems with my program and getting this error :
HEAP CORRUPTION DETECTED: before Normal block (#9873672) at 0x00968988.
CRT detected that the application wrote to memory before start of heap buffer.
I have tried to look for fixes but I can't figure out what it wrong with my program, what to fix and where :(
Here is the function I'm using and that is causing me problems :
What I am doing is basically look into a file for a specific keyword (argument of the function getText) and printing its matching value.
Sorry if most of the variables are in French, it's a project for school and our teacher require us to use French names >_<
#include "getText.h"
#include "main.h"
#include <stdlib.h>

texteLangue* ressourcesTexteLangue = NULL;
int compteur = 0;

char* getText(char* clef)
{
    char* texte = NULL;
    texte = clef; //clef is the keyword passed in the function as argument
    texteLangue temp;
    temp.clef = clef;
    texteLangue* resultat = (texteLangue*) bsearch(&temp, ressourcesTexteLangue, compteur, sizeof(texteLangue), comparerClef); //returns the value associated with the key

    if (clef != NULL)
    {
            if (resultat != NULL)
            texte = resultat->valeur;
    }
    return texte;
}

void lectureTexte(char* langue)
{
    char nomFichierRessources[64];
    sprintf(nomFichierRessources, "ressources_%s.txt", langue); //give the file name a specific ending depending on the language chosen
    FILE* FichierRessources = fopen(nomFichierRessources, "r");
    if (FichierRessources == NULL)
    {
        system("cls");
        perror("The following error occured ");
        system("PAUSE");
        exit(42);
    }

        //allocates memory for the language resources
    int taille = 10;
    ressourcesTexteLangue = (texteLangue *) calloc(taille, sizeof(texteLangue));
    if (ressourcesTexteLangue == NULL)
        printf("Pas assez de place mémoire pour les ressources texte");

        //gives a value to TextResource.key and TextResource.value for each line of the file
    char* ligne;
    while ((ligne = lectureLigne(FichierRessources)))
    {
        if (strlen(ligne) > 0)
        {
            if (compteur == taille)
            {
                taille += 10;
                ressourcesTexteLangue = (texteLangue *) realloc(ressourcesTexteLangue, taille * sizeof(texteLangue));
            }
            ressourcesTexteLangue[compteur].clef = ligne;

            while (*ligne != '=')
            {
                ligne++;
            }

            *ligne = '\0';
            ligne++;
            ressourcesTexteLangue[compteur].valeur = ligne;
            compteur++;
        }
     }
         //sorts out the values of TextResource obtained
     qsort(ressourcesTexteLangue, compteur, sizeof(texteLangue), comparerClef);

     fclose(FichierRessources);
}

 //reads a line and returns it
 char* lectureLigne(FILE *fichier)
 {
    int longeur = 10, i = 0, c = 0;
    char* ligne = (char*) calloc(longeur, sizeof(char));

    if (fichier)
    {
        c = fgetc(fichier);
        while (c != EOF)
        {
            if (i == longeur)
            {
                longeur += 10;
                ligne = (char*) realloc(ligne, longeur * sizeof(char));
            }
            ligne[i++] = c;
            c = fgetc(fichier);
            if ((c == '\n') || (c == '\r'))
                break;
        }

        ligne[i] = '\0';

        while ((c == '\n') || (c == '\r'))
            c = fgetc(fichier);
        if (c != EOF)
            ungetc(c,fichier);

        if ((strlen(ligne) == 0) && (c == EOF))
        {
            free(ligne);
            ligne = NULL;
        }
    }
    return ligne;
}

//frees the TextRessources
void libererTexte()
{
    if (ressourcesTexteLangue != NULL)
    {
        while (compteur--)
        {
            free(ressourcesTexteLangue[compteur].clef);

        }
        free(ressourcesTexteLangue);
    }
}

//compares the keys
int comparerClef(const void* e1, const void* e2)
{
    return strcmp(((texteLangue*) e1)->clef, ((texteLangue*) e2)->clef);
}

the structure of RessourceTextelangue (TextResources) look like this :
typedef struct texteLangue {
    char* clef;
    char* valeur;
} texteLangue;

A: Is your input guaranteed to contain a '=' in each line?
while (*ligne != '=') // if not, this will fly off the end of your buffer...
{
    ligne++;
}

*ligne = '\0'; // ...and write to unallocated heap memory

Edit
Given @Heath's comment, if your input contains a blank line (including ending with a single blank line) then the above would most certainly be triggered.
c = fgetc(fichier); // reads '\n'
while (c != EOF)
{
    ...

    ligne[i++] = c;

    ...

    ligne[i] = '\0';

ligne now contains "\n" and is returned. later it is used:
if (strlen(ligne) > 0) // strlen("\n") is greater than 0
{
    ...

    while (*ligne != '=') // oops! loop until we find a '=' somewhere
                          // in the heap or crash trying.
    {
        ligne++;
    }

    *ligne = '\0'; // corrupt the heap here

A: There are several potential problems with your code that could be causing the error report you see.
Here is one:
    if (i == longeur)

should be:
    if ((i+1) == longeur)

otherwise,
    ligne[i] = '\0';

can occur in conditions when
        ligne[i++] = c;

has caused i to become equal to longeur.
Here is another:
        while (*ligne != '=')
        {
            ligne++;
        }

        *ligne = '\0';

the above code should be:
        while (*ligne != '=' && *ligne != '\0')
        {
            ligne++;
        }

        *ligne = '\0';

otherwise, you will corrupt memory in the case when there is no '=' to be found in the string.
Although either of these could cause the symptom you report, I see some other oddities that make me think there is more wrong than I have seen so far.  Nevertheless, fixing those two problems will at least reduce the number of possibilities you have to consider.


text:
Q: Why doesn't soda go flat immediately after opening? So, soda is under pressure and has gas dissolved in it. But, when you open it, the gas is still dissolved in it. But, if we wait a few hours, the gas has escaped into the atmosphere.
What factors determine the rate at which gas escapes the soda-gas solution?

A: When you open the bottle and reduce the pressure you now have a supersaturated solution of carbon dioxide in water so it is energetically favourable for the gas to come out of solution.
However for the gas to come out of solution you have to form a bubble and the mechanism by which this happens is called nucleation. But there is an energy barrier that prevents tiny bubbles from forming, and as a result bubbles will only form when there is something to help them nucleate. For more on this see:

*

*Why does soda fizz when it meets ice?

*Why are coke bottles that much fizzier if you shake them?
Anyhow, if you look carefully at the bubbles coming out of an opened bottle of soda you'll see they aren't forming randomly. Typically you'll see streams of bubbles coming from an area where there is some aid to nucleation e.g. a defect on the glass wall of the bottle.
This means the escape of the gas involves two steps:

*

*formation of bubbles at a nucleus

*diffusion of the carbon dioxide through the water to the nucleus
And it's step 2 that makes the escape of the carbon dioxide take a while. Where an aid to nucleation exists, e.g. at a defect on the glass wall, formation of a bubble will be very quick. However formation of the bubble will quickly use up the dissolved carbon dioxide in its vicinity and formation of further bubbles has to wait for more carbon dioxide to diffuse to the nucleation site. Diffusion of gases dissolved in water is surprisingly slow, and even though the gases typically only have to diffuse a few millimetres they still take a while to do it.
If you want to get the carbon dioxide out quickly the best way to do it is to increase the number of nucleation sites so you get many more nuclei and hence reduce the distance the dissolved gas has to diffuse. The traditional way to do this is to drop a mint into the bottle of soda, but stand well back when you do it.


text:
Q: Problems with scrollbar in IE9, position: fixed, overflow: auto I've encountered a strange issue with the vertical scroll bar on IE9 when using a div with a fixed position and overflow: auto set on the div.
See the case here using IE9 and shrink the window height down to a small size.
http://bytiger.com/add/ie9_div_test.html
I can confirm that this doesn't occur on IE8.
Does anyone know a reasonable hack around this?  I've tried setting the width to the window width, but it seems that it purposesfully subtracts a scrollbar width from the size of the div.  I would like to see if there is a solution that doesn't have to calculate this constant or hardcode it and adding this back to the calculated width.
Cheers!
EDIT: Jsfiddle doesn't seem to exhibit the problem... so that can be a big hint as to what might be going on.
http://jsfiddle.net/dvAKW/

A: Seems like IE9 doesn't handle the box-sizing property correctly - changing it from "border-box" to "content-box" or leaving it blank will fix your problem.


text:
Q: Why does the TOP function not function as I expect in SQL? I thought I knew how the TOP function works, but with this code below I'm not sure.
Please can someone tell me why it returns fruit:b ordinal:9, instead of the expected fruit:b ordinal:8?
;WITH CTE
AS (
 SELECT fruit, ordinal, row_number() OVER (
   ORDER BY (
     SELECT 1
     )
   ) AS rn
 FROM (
  VALUES (1, 'a'), (2, 'b'), (3, 'b'), (4, 'c'), (5, 'c'), (6, 'a'), (7, 'a'), (8, 'b'), (9, 'b')
  ) fruits(ordinal, fruit)
 ), CTE2
AS (
 SELECT fruit, ordinal
 FROM cte AS cteouter
 WHERE rn = 1
  OR fruit != (
   SELECT fruit
   FROM cte AS cteinner
   WHERE cteinner.rn = cteouter.rn - 1
   )
 )
--SELECT * FROM CTE2
SELECT TOP 1 *
FROM cte2
ORDER BY ordinal DESC

A: row_number() OVER (ORDER BY (SELECT 1)) (as well as over (order by 1) or over (order by 1/0)) does not guarantee stable reproducible numbering of the incoming rows. Quite opposite, it effectively switches off the order by clause and makes it random.
When you run the top query with TOP 1, you get one execution plan, and when without TOP, you get another. These plans happen to randomly result in a different ordering of the rows in CTE, which in turn changes which rows are returned from CTE2.


text:
Q: problem running docker image using jupyter notebook I have a jupyter notebook and a data file in a folder. I made a Dockerfile and wrote the following lines
FROM jupyter/base-notebook

ARG export_file=FooD_Kind.csv

RUN pip install jupyter

RUN pip install numpy

RUN pip install matplotlib

RUN pip install pandas

RUN pip install pulp

COPY $export_file FooD_Kind.csv

COPY task_4kind.ipynb /

CMD ["jupyter notebook", "task_4kind.ipynb"]

I can successfully build an image using docker build -t nameofimage But when I do docker run -it nameofimage. I get an error [FATAL tini (7)] exec jupyter notebook failed: No such file or directory .
How do I run this jupyter notebook in docker?
EDIT:
I tried two replacements on the last line,
I replaced the last line with
# Start the jupyter notebook
ENTRYPOINT ["jupyter", "notebook", "--ip=*"]

It runs and gives a token on the screen but when I paste the token on localhost, It gives invalid credentials error
then I replaced the last line with
CMD jupyter notebook --port=8888 --no-browser --ip=0.0.0.0 --allow-root

It runs and gives a token on the screen but when I paste the token on localhost, It gives invalid credentials error

A: If you check the original Dockerfile, you will find the following;
ENTRYPOINT ["tini", "-g", "--"]
CMD ["start-notebook.sh"]

# Add local files as late as possible to avoid cache busting
COPY start.sh /usr/local/bin/
COPY start-notebook.sh /usr/local/bin/
COPY start-singleuser.sh /usr/local/bin/

start-notebook.sh will get you a valid token. Subsequent files allow to interact with the image, these options are described in the docs.
Mind that there are more caveats, e.g. which user is running commands described in Dockerfile: root or  jovyan (Jupyter user)? Commands executed by root may set permissions in a way that won't allow jovyan to e.g. load given package. To fix this, there's an extra line in all Jupyter (base notebook and derived) Dockerfiles:
RUN fix-permissions /etc/jupyter/

Here is an example how a derived notebook could look like.
In essence, either remove your custom ENTRYPOINT / CMD and use the original ones or make sure you e.g. get the token right. Also, fix permissions.


text:
Q: How to edit/save multiple fields at once using JQuery+JEditable? I have a set of texts on a page (for simplicity's sake, let's assume I have two), which I'd like to be editable individually, in place, so I'm using JEditable to achieve that and it works perfect - I click one text, it converts to a drop down, I change the value, click outside and it's saved. I click another, it converts to an input field, I type in something else, click outside of it - and it is also saved. Great.
Now I need to have a button (image, link - whatever), clicking on which would switch both of my editable fields to the editing mode. I.e., I click this "Edit" control, and now instead of my two texts I would see a drop-down and an input field, I would be able to edit values in both places, and then either click outside of both of them (ideal) or click another button/image/link, "Save" to, well, save it (not so good, but can live with that).
Is it possible to achieve? If so... how?
And no, I wouldn't want to use jqGrid or something similar here.

A: I'm working on something similar. You can create a custom input for jEditable, which can have multiple input fields.
This tutorial from the creator of jEditable does a decent job walking you through creating a time picker (which uses two dropdown inputs for hours and minutes). Here's another from someone else, but it seems a bit more confusing.
Like I say I'm working through this right now myself, might be able to give you more help when I get mine working.


text:
Q: Workaround a null value when I delete an item in React When I delete an item in my react component, some code in another component turns null and the react application crashes. Is there any workaround to this or any way I could implement this way instead of getting an error? Please see the code below.
When I delete an item in a component, some external code renders to null I guess, because I am getting the error:
TypeError: Cannot read property 'type' of undefined
  114 | class AccountActivity extends Component {
  115 |   static getDerivedStateFromProps(props, state) {
  116 |     const { currentAccountId, accounts } = props;
> 117 |     const currentAccountType = currentAccountId ? accounts.filter(acc => acc.id === currentAccountId)[0].type : null;
  118 |
  119 |     const { currentTab } = state;
  120 |     if (currentAccountType === ACCOUNT_TYPES.MANUAL && (currentTab === ACTIVITY_TABS.OPEN_ORDERS || currentTab === ACTIVITY_TABS.ORDER_HISTORY)) {


text:
Q: Why "to" isn't an infinitive indicator in this sentence?
The late Mr Lee Kuan Yew has been hailed by many as "Singapore's Chief Gardener" for his vision and single-minded commitment to transforming our country into a lush garden city and creating the best possible living environment for all citizens to enjoy.

I have tried referring to these links but to no avail:

*

*When is "to" a preposition and when the infinitive marker?  This link only explains about want to see you which is helpful, and the "look forward to seeing you" is common on Internet. But both explanations are specific to the said grammatical instances only, not general.

*"To hear" or "to hearing"?  This link only explains about look forward to hearing, which is again specific and special grammatical instance.

*How to know if I should use verb+ing after the word 'to'?  This link mentions transitivising particle, but without elaboration and lacks citation.

No matter how much I try to use inductive reasoning, I can't figure out why using "...to transform our country..." is wrong.

A: "To transform our country" is wrong because of the word "commitment".
If you think of the verb "to commit to something/doing something", the to is not an indiciator of the infinitive but rather a preposition pointing to the commitment. Therefore, we use the gerung (ING) after a preposition.
Hope it helps!

A: We are commited to "something" generally,which normally is a noun or nominal phrase, but when the goal is to show that we are commited to an action, we use a verb+ing to have the function of a noun, therefore the sentens makes sens.


text:
Q: Is it possible to enhance the default appearance of svg title tooltip I would like to change the default appearance of tooltip in svg elements (title) by any means such as js or css.
I even tried stuff like this:
var title = document.createElementNS('http://www.w3.org/2000/svg','title');
title.textContent='<foreignObject width="100" height="50" requiredExtensions="http://www.w3.org/1999/xhtml">
'+arr[j].ypos+'
<foreignObject>';
rect.appendChild(title);

but regardless of whatever i insert as the textContent of title, its simply rendered as a string.
Is there any way to style the default tooltip? Other simple and straightforward alternatives for creating tooltips in svg without using any plugins are also welcome...

A: You could try this: How to change the style of Title attribute inside the anchor tag?. I didn't test it, so I don't really know if it works.
But since you are using SVG, you can do better than that since you can draw tooltips with any color and shape, even animated. Since you are generating it dynamically with a script, you can calculate the size based on the content and alter the height and width accordingly.
Here is an example of a tooltip using a rounded rectangle in SVG:
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
    <g id="component">
        <rect id="content" width="50" height="50">
        </rect>
        <g class="tooltip" transform="translate(20,20)" opacity="0.9">
            <rect rx="5" width="100" height="25"></rect>
            <text x="15" y="16">Hello</text>
        </g>
    </g>
</svg>

I used CSS hover to make it appear and disappear:
#component .tooltip {visibility: hidden}
#component:hover .tooltip {
    visibility: visible;
}
.tooltip text {
    fill: black;
    font-size: 12px;
    font-family: sans-serif;
}
.tooltip rect {
    fill: yellow;
    stroke: blue;
}

You can experiment with it in this JSFiddle.
You can also store your tooltips in a <defs> block and reuse it in different objects.