text:
Q: Unexpected Python result to Code dictionary = {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'], 'Kenneth Love': ['Python Basics', 'Python Collections'], 'Daniel': ['Python Basics', 'Python Collections', 'test', 'test']}

def most_class(dictionary):
    current_count = 0
    max_count = 0
    best_teacher = "none"
    for key in dictionary:
        for values in dictionary.values():
            current_count += 1
            if current_count > max_count:
                max_count = current_count
                best_teacher = key
    return best_teacher

The goal is to determine which key in the dictionary has the most values. The answer should be Daniel, but I am getting a different answer each time I run the code (presumably due to pythons hashing of the dictionary.
Can anyone explain why I am getting this result, and how it can be fixed?

A: You're iterating over the dictionary more times than you need to, and making this much more difficult than it needs to be. You can do it much more simply by combining the Python built-in max() with comprehensions. Try this instead:
dictionary = {
    'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms',
                     'Technology Foundations'],
    'Kenneth Love': ['Python Basics', 'Python Collections'],
    'Daniel': ['Python Basics', 'Python Collections', 'test', 'test']}

# get maximum number of items any one person has
maximum_len = len(max(dictionary.values(), key=len))

# build a list of everyone with that number of items
most = [name for name, classes in dictionary.items()
            if len(classes) == maximum_len]

print(most)

This code prints:

['Daniel']

Not only does this replace loops with comprehensions, in the event of a tie, you get a list of the names instead of just the first one found. For example, if we change the dictionary definition to this:
dictionary = {
    'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms',
                     'Technology Foundations', 'other_item'],
    'Kenneth Love': ['Python Basics', 'Python Collections'],
    'Daniel': ['Python Basics', 'Python Collections', 'test', 'test']}

Then this will be printed instead:

['Daniel', 'Jason Seifer']

A: You have two problems.

*

*You need to reset current_count each time around, not just at the start.

*dictionary.values() gives you the list of lists of books, not the list of books for that author.

To solve the second one, I would use for author, books in dictionary.items(): rather than for key in dictionary:. Then you won't have to use dictionary[key] each time. After making these changes, we have:
def most_class(dictionary):
    max_count = 0
    best_teacher = "none"
    for author, books in dictionary.items():
        current_count = 0
        for book in books:
            current_count += 1
            if current_count > max_count:
                max_count = current_count
                best_teacher = author
    return best_teacher

Further, I might pull the if out of the loop:
def most_class(dictionary):
    max_count = 0
    best_teacher = "none"
    for author, books in dictionary.items():
        current_count = 0
        for book in books:
            current_count += 1
        if current_count > max_count:
            max_count = current_count
            best_teacher = author
    return best_teacher

At that point, it becomes clear that we don't need a for loop at all, and can just use len:
def most_class(dictionary):
    max_count = 0
    best_teacher = "none"
    for author, books in dictionary.items():
        if len(books) > max_count:
            max_count = len(books)
            best_teacher = author
    return best_teacher

Your code might also benefit from using the max function as others have suggested, although I would probably use it a different way:
def most_class(dictionary):
    return max(dictionary.items(), default=('none', 0),
               key=lambda item: len(item[1]))[0]

A: You have to know how to use dictionary , then I recommend to do:
dictionary = {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'], 'Kenneth Love': ['Python Basics', 'Python Collections'], 'Daniel': ['Python Basics', 'Python Collections', 'test', 'test']}

def most_class(dictionary):
    best_teacher = None
    class_of_best_teacher = 0
    for teacher_name in dictionary.keys():
        class_of_teacher = len(dictionary[teacher_name])
        if class_of_teacher > class_of_best_teacher :
            best_teacher = teacher_name
            class_of_best_teacher = class_of_teacher
    return best_teacher
print most_class(dictionary)

A: you iterates through keys in the dictionary but you for got to reset your current_count back to zero between each key. So current_count and max_count counts up to 9 together and best_teacher will be the last key that the for loop iterates through.
Fix your code like this.
...
for key in dictionary:
    current_count = 0
    ...

It work but I would like to do this instead:
best_teacher = sorted(dictionary.keys(), key=lambda x: len(dictionary[x]))[-1]

A: *

*reset current_count for each key

*should use dictionary[key] instead of dictionary.values()
the following code return Daniel.
dictionary = {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'], 'Kenneth Love': ['Python Basics', 'Python Collections'], 'Daniel': ['Python Basics', 'Python Collections', 'test', 'test']}

def most_class(dictionary):
    current_count = 0
    max_count = 0
    best_teacher = "none"
    for key in dictionary:
        current_count = 0
        for values in dictionary[key]:
            current_count += 1
            if current_count > max_count:
                max_count = current_count
                best_teacher = key
    return best_teacher


text:
Q: Gradient descent optimization I am trying to understand gradient descent optimization in ML(machine learning) algorithms. I understand that there's a cost function—where the aim is to minimize the error $\hat y-y$. In a scenario where weights $w_1, w_2$ are being optimized to give the minimum error, and partial derivatives are being used, does it change both $w_1$ and $w_2$ in each step or is it a combination (e.g., in few iterations only $w_1$ is changed and when $w_1$ isn't reducing the error any more, the derivative starts with $w_2$)? The application could be a linear regression model, a logistic regression model, or boosting algorithms.

A:
When the optimization does occur through partial derivatives, in each turn does it change both w1 and w2 or is it a combination like in few iterations only w1 is changed and when w1 isn't reducing the error more, the derivative starts with w2 - to reach the local minima?

In each iteration, the algorithm will change all weights at the same time based on gradient vector. In fact, the gradient is a vector. The length of the gradient is as same as number of the weights in the model.
On the other hand, changing one parameter at a time did exist and it is called coordinate decent algorithm, which is a type of gradient free optimization algorithm. In practice, it may not work as well as gradient based algorithm.
Here is an interesting answer on gradient free algorithm
Is it possible to train a neural network without backpropagation?

A: Gradient decent is applied to both w1 and w2 for each iteration. During each iteration, the parameters updated according to the gradients. They would likely have different partial derivative.
Check here.

A: Gradient descent updates all parameters at each step. You can see this in the update rule:
$$
w^{(t+1)}=w^{(t)} - \eta\nabla f\left(w^{(t)}\right).
$$
Since the gradient of the loss function $\nabla f(w)$ is vector-valued with dimension matching that of $w$, all parameters are updated at each iteration.
The learning rate $\eta$ is a positive number that re-scales the gradient. Taking too large a step can endlessly bounce you across the loss surface with no improvement in your loss function; too small a step can mean tediously slow progress towards the optimum.
Although you could estimate linear regression parameters using gradient descent, it's not a good idea.
Likewise, there are better ways to estimate logistic regression coefficients.

A: The aim of gradient descent is to minimize the cost function.  This minimization is achieved by adjusting weights, for your case w1 and w2.  In general there could be n such weights.
Gradient descent is done in the following way:

*

*initialize weights randomly.

*compute the cost function and gradient with initialized weights.

*update weigths:
    It might happen that the gradient is O for some weights, in that case
    those weights doesn't show any change after updating.
    for example:  Let say gradient is [1,0]  the W2 will remain
    unchanged.

*check the cost function with updated weights, if the decrement is acceptable enough continue the iterations else terminate.

while updating weights which weight ( W1 or W2) gets changed is entirely decided by gradient. All the weights get updated ( some weights might not change based on gradient).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reducing the length of HTML code I have the following HTML code -

Japan:

        <col width="30%">
        <col width="10%">

           Value1:
           200

           Value2:
           500

           Value3:
           33

           Value4:
           11

           Value5:
           123

China:

        <col width="30%">
        <col width="10%">

           Value1:
           600

           Value2:
           1100

           Value3:
           444

           Value4:
           1112

           Value5:
           123321

The above code works fine and generates an HTML page. But the issue is with the repetition of some of the tags such as -

            <col width="30%">
            <col width="10%">

and
align="right"

I wanted to know if there is anyway to reduce the code by adding these repetitive lines as a class or template.
The code contains only HTML file and no CSS or JS files (I can consider adding these files, if it helps in solving my problem).
Pardon me if this question sounds too trivial for HTML - as I'm new to the language.
Cheers!

A: Yes, you can (and you should) do this with some CSS. It is a good practice to separate HTML and CSS (that is, not write styles inline) :

table {
     width : 100%
}

col:nth-child(1){
        width : 30%
}

col:nth-child(2){
        width : 10%
}

td:nth-child(2){
       text-align : right
}

Japan:

        <col>
        <col>

           Value1:
           200

           Value2:
           500

           Value3:
           33

           Value4:
           11

           Value5:
           123

China:

        <col>
        <col>

           Value1:
           600

           Value2:
           1100

           Value3:
           444

           Value4:
           1112

           Value5:
           123321

A: Yes. you can reduce code by adding css file. or use this code in your head tag:


text:
Q: WORD OLE with TOC I got an interesting problem when using ole-automation to insert content to existing word documents using code like this:
WordApp.Selection.HomeKey(unit := wdStory);
if FileExists(s) then
  WordApp.Selection.InsertFile(Filename := s, ConfirmConversions := false,
  Link := false, Attachment := false);

This works quite well with most word-documents, except those where we got an "automatic table of Content" as first element in the document. In this case the automation crashes with:

This action is not valid outside of a block-level XML

I tried some other functions like:
WordApp.Selection.InsertText('Test') / (#13#10)
WordApp.Selection.InsertBreak(Page/Line)

with the same negative result. It seems that the Cursor Position is invalid when the first element is that automatic table.
Any ideas how I can fix this on my side?

A: You need to make sure that the content is inserted at the very beginning of the document and that the first paragraph does not contain a content control (the thing surrounding the ToC).
The home key doesn't always get you to the very beginning. In the case of a table of contents at the beginning of the document, pressing the home key takes you to the beginning of the content control that contains the table of contents. To get in front you can set the End (and Start) property of the Selection to 0. In addition, you have to insert a paragraph before the table of contents:
WordApp.Selection.Start = 0
WordApp.Selection.End = 0
WordApp.Selection.InsertParagraphBefore


text:
Q: How to match objects with the same key-value pairs passed as arguments? This is a FreeCodeCamp task named Wherefore art thou.
I have to Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching name and value pairs (second argument). Each name and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array.
My solution passes all the checks besides this one: whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3}) should return []. And I wonder why the function returns the given array instead of an empty one. And if there is a way to make my function work eventually. My code is gonna be below. THANK YOU FOR HELP!
function whatIsInAName(collection, source) {
  let arr = [];
  const sourceKeys = Object.keys(source);

  for (let key in sourceKeys) {
    arr = collection.filter(
    obj => (Object.keys(obj).length >= sourceKeys.length) ?
    obj.hasOwnProperty(sourceKeys[key])
    && obj[sourceKeys[key]] === source[sourceKeys[key]] : 0);
  }

  return arr;
}
whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3});

A: You could create a simple implementation using Object.keys() and Array.every().
This means each returned item must include each key and value from the source, but may include extra keys and values:

function whatIsInAName(collection, source) {
  return collection.filter(obj => Object.keys(source).every(key => obj[key] === source[key]));
}

console.log(whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3}));
console.log(whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 2, "c": 3}));
console.log(whatIsInAName([{"a": 1, "b": 2, "c": 3, "d": 4 }], {"a": 1, "b": 2, "c": 3}));
console.log(whatIsInAName([{"a": 1, "c": 3, "d": 4 }], {"a": 1, "b": 2, "c": 3}));
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: The following should work:

function fltArr(collection, p) {
  const tst=Object.entries(p);
  return [...collection].filter(o=>
    tst.every(([k,v])=>o[k]==v)) // check for each key and value of p
}                                // that they are the same in o[k]

const arr=[{a: 1, b: 2, c:3, d:7},{a: 1, b: 2, d: 3}],
 patterns=[{a: 1, b: 9999, c: 3},{a: 1, b: 2, c: 3},{a: 1, b: 2, d: 3}];

patterns.forEach(p=>console.log(fltArr(arr,p)))

As far as I understand the question, the collection object can have extra properties (not specified in p) and still be a match. For this reason the first element is a match with the second test pattern.


text:
Q: Meaning of "a priori" in this context
This objection has become questionable in view of the
fact that, in advanced industrial society, the technical apparatus of production and distribution functions, not as a sum total of mere instruments
which can be isolated from the social and political context without losing
their identity, but rather as an apparatus which determines a priori
the product as well as the individual and social operations of servicing and
extending it, that is to say, determines the socially needed demands,
occupations, skills, attitudes – and thus the forms of social control and social
cohesion.

I have tried referring to https://www.merriam-webster.com/dictionary/a%20priori, the closest possible definition I got is

2 b: formed or conceived beforehand

Thus, can a priori in the aforementioned text be interpreted as:

... determines beforehand the product as well as the individual...

Edit:
Source of aforementioned text: Towards a Critical Theory of Society Collected Papers of Herbert Marcuse, specifically from the paper The Problem of Social Change in the Technological Society

A: I think the sentence should be taken out and shot, but I might be able to answer the question.
If I remove extraneous clauses, I get:
This objection has become questionable in view of the fact that ... the technical
apparatus of production and distribution functions ... as an apparatus which
determines a priori the product as well as ...

When I see 'a priori', "without prior knowledge" as you say, I think of something that someone knows without context, without background, etc. It seems that this "technical apparatus" the writer is talking about is, according to him, the thing which determines the product. I do not think it's a particularly good use of the phrase; I mean, I don't think it's a common or normal way to use it.
I think a main point of confusion in the sentence is the word "functions", which looks, on being read, like it is part of a noun phrase with "distribution", but in fact is meant here as a verb. "The technical apparatus ... functions ... as an apparatus", in other words.
Anyway. I don't think there's any larger meaning than this.


text:
Q: Equivalent to Windows Error Codes in .NET Microsoft provides a bunch of standardized error codes for Windows (http://msdn.microsoft.com/en-us/library/ms681381(VS.85).aspx).  When applicable I find them useful to reference in my own applications, instead of creating my own.  Is there something similar but specific to .NET?

A: .NET discourages the use of error codes.  Instead, focus on using, or deriving from, the standard Exception classes.
Exceptions should be preferred to error codes in .NET development.

A: I agree with Reed Copsey, error codes are "remainings" from the past error handling methods.
The new way of doing i is Exception Handling.


text:
Q: Erlang : Mnesia : Updating a single field value in a row I have an mnesia table with three fields, i, a and b, created using the record
-record(rec, {i, a,b}).

Now I insert a row into the table as:
mnesia:transaction( fun() -> mnesia:write("T", #rec{i=1, a=2, b=3}, write) end ).

Now what do I do if I want to update this row, and change only the value of a to 10, while leaving i and b with the same values? Is there any SQL equivalent like "UPDATE T SET a=10 WHERE i=1"?
If I do something like this:
mnesia:transaction( fun() -> mnesia:write("T", #rec{i=1, a=10}, write) end )

The row is stored as:
{rec,1,10,undefined}

A: I believe you need to read the "row", update whatever field you need, and then write back the result and all of these operations within a "transaction".

A: The value of this function will update a if used in a mnesia:transaction
update_a(Tab, Key, Value) ->
  fun() ->
    [P] = mnesia:wread({Tab, Key}),
    mnesia:write(P#pixel{a=Value})
  end.

Suggestion: have a peek at QLC if you want some syntax sugar that is more like the SQL syntax.
The performance is of course best benchmarked, but QLC has overhead, I'm not sure they are relevant compared to the other details. I just figured that the SQL example you gave would update all records that have i=1. Using QLC to extract that set of records is prettier than mnesia calls.
Also to notice, wread claims a write lock on the record directly, because we know ahead of time that we will update that record. That's a micro-optimization to avoid first a read lock, then change our mind and get a write lock. I haven't benchmarked that in a long time though.
If performance is still an issue you should look at various approaches where you use dirty operations. But you really should try to figure out how many transactions per second you need, to be 'fast enough'.


text:
Q: updatepanel trigger cause fullpostback instead partial postback I want partial postback(asyncpostback) instead fullpostback.but it's not working.  Dynamically created checkbox where check or unchecked checkbox cause fullpostback
but it should be asyncpostback.Here is my code.....
<asp:CheckBoxList ID="chkList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="chkList_SelectedIndexChanged"
                ClientIDMode="AutoID">
            </asp:CheckBoxList>

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                <ContentTemplate>

                    <asp:Label ID="lblMessage" runat="server" Visible="false"></asp:Label>
                </ContentTemplate>
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="chkList" EventName="SelectedIndexChanged" />
                </Triggers>
            </asp:UpdatePanel>

C# code:
private static readonly string constring = ConfigurationManager.ConnectionStrings["ConnectionStrRead"].ToString();

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
        {
            SqlConnection con = new SqlConnection(constring);
            SqlCommand com = new SqlCommand("Select * from Category");
            com.Connection = con;
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataTable dt = new DataTable();
            da.Fill(dt);

            int dtRows = dt.Rows.Count;
            List<string> itemList = new List<string>();
            for (int i = 0; i < dtRows; i++)
            {
                //itemList = new List<string>();
                string item = dt.Rows[i]["CategoryName"].ToString() + "(" + dt.Rows[i]["CreateUser"].ToString() + ")";
                itemList.Add(item);
            }
            chkList.DataSource = itemList.ToArray();
            chkList.DataBind();
            con.Close();
        }
    }

 protected void chkList_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblMessage.Visible = true;
        lblMessage.Text = string.Empty;
        foreach (ListItem item in chkList.Items)
        {
            if (item.Selected)
            {
                lblMessage.Text += item.Text + "<br/>";
            }
        }
    }

A: Can u check your scriptmanager EnablePartialRendering attribute. It must be EnablePartialRendering="true"
 <asp:ScriptManager ID="ScriptManager1" runat="server" EnableViewState="False" EnablePartialRendering="true" EnableScriptGlobalization="true" > </asp:ScriptManager>

If problem is not about that u can try add AsyncPostBackTrigger in code behind
 ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(chkList);


text:
Q: Can't access PHP array inside script localization from javascript I have a loop to retrieve all users with the specific meta_key user values from wp_user_meta database and then put it in wp_localize_script array so I could access the data with Javascript and do my thing with it. Unfortunately, when I run the loop and put all the results to the variable, and try to console.log the results, I get just the string "Array" out in the console 3 times in one line, instead of the real values.

Here is my code:
functions.php
add_action('wp_enqueue_scripts','Load_Template_Scripts_wpa83855');
function Load_Template_Scripts_wpa83855(){

    $args = array(
        'meta_key' => 'quiz_scores'
    );

    $users = get_users($args);
    foreach($users as $user){
            echo "<pre>";
        print_r(get_user_meta ($user->ID));
                $veik .= get_user_meta ($user->ID);
            echo "</pre>";
    }
    if ( is_page_template('page-quiz.php') ) {
        wp_enqueue_script( 'quiz', get_template_directory_uri() . '/js/script.js', array(), '20151215', true );
                wp_localize_script('quiz', Questions_list, array(
                    'siteUrl' => get_option("question"),
                    "ans" => get_option("answer"),
                    'ajax_url' => admin_url( 'admin-ajax.php' ),
                    'usr_scr' => $veik
                ));
        }
}

print_r(get_user_meta ($user->ID)); works just fine, I get my all 3 users printed out with the meta_key "quiz_scores". But when I put it in the variable and then use it inside script localize like this: 'usr_scr' => $veik and try to console.log it in my other script.js file console.log(Questions_list.usr_scr); like I said, I get only string "Array" out in the console 3 times (as many times as there is users in database with that specific meta_key instead of the real value). I tried using toString() but it doesn't do anything. Any ideas?

A: get_user_meta returns an array, so to get an array containing an array of each user's data, use [] to append:
foreach( $users as $user ){
    $veik[] = get_user_meta( $user->ID );
}


text:
Q: Can I add Task List items to csHTML in Visual Studio 2010? Background:
I am fairly new to Visual Studio 2010 (worked on Lua, LIMSBasic (Labware) and a few others that didn't use decent IDEs and love the idea of task lists being pulled out of the comments I write right in the code.
I have worked out how to use comments to generate all manner of "// TODO:" and other task list and found some good lists on stackoverflow for what type I can do but I can't establish (no mater how hard I abuse google) even if it's possible to add them to csHTML files nevermind how!
I have tried using all of the following:
<!--// TODO: Work out how to add todo stuff to the tasklist!-->
// TODO: Work out how to add todo stuff to the tasklist!
<!--TODO: Work out how to add todo stuff to the tasklist!-->
<!-- TODO: Work out how to add todo stuff to the tasklist!-->
@// TODO: Work out how to add todo stuff to the tasklist!

...but nothing was added to the Task List.
Question:
So my question(s) is/are: Is it possible to add "TODO:" and other task list item to csHTML (MVC 3 using razor) and if so HOW?

A: The following should work.
@{
    //TODO: do stuff here
 }

or
@{/* TODO: do stuff here */}

As it first has to go into "code" mode, and then you can use a task comment.
But apparently the following does not work (in my visual studio):
@*TODO: do stuff here *@


text:
Q: Примитивные типы Java float и double Кто может подсказать максимальные размеры для float и double по вики:
float   32  от 3.4е-038 до 3.4е+038
double  64  от 1.7е-308 до 1.7е+308
По этому коду:
   System.out.println("MAX FLOAT : "+Float.MAX_VALUE);
   System.out.println("MIN FLOAT : "+Float.MIN_VALUE);
   System.out.println("MAX Double : "+Double.MAX_VALUE);
   System.out.println("MIN Double : "+Double.MIN_VALUE);

MAX FLOAT : 3.4028235E38
MIN FLOAT : 1.4E-45
MAX Double : 1.7976931348623157E308
MIN Double : 4.9E-324
Вопрос следующий, где правда?

A: Смотрите.
Есть разница между минимальным нормализованным и ненормализованным значениями. 1.1754943508222875E-38f — это минимальное нормализованное, 1.401298464324817E-45f — минимальное ненормализованнoе значение для float.
Вот официальная документация.

Немного теории. Обычно числа с плавающей запятой записываются внутри в виде мантисса + экспонента, где мантисса — это число от 0.1 до 1, а экспонента — показатель степени десятки. Например, число 0.0015 содержится как 0.15 + степень 10^-2, 44 — как 0.44 и степень 10^2. (На самом деле там то же самое в двоичном виде, степени двойки и числа между 1 и 2^-1. Но важен принцип.)
Под мантиссу отводится фиксированное количество разрядов, стартовая цифра выбрасывается для экономии (потому что она должна быть равна 1 в двоичной системе).
Так вот: можно немного выйти за нижнюю грань, используя денормализованные числа — числа наподобие 0.0000156 * 10^-38. У них точность хуже, чем у нормальных чисел, т. к. старшие разряды мантиссы используются для укказания величины. Но это лучше, чем просто 0.


text:
Q: Unable to manage existing recaptcha my captcha keys are working, however, unable to add new domains or manage existing keys.
when accessing the site i receive an error "You don't have any sites registered to use the reCAPTCHA API"
has anyone faced a similar issue?

A: Unfortunately it wasn't clear that you must keep your own email address in order to view all your keys. When we generated these keys, we removed our personal accounts and used a distribution group so that the distribution group would receive notifications. Make sure you keep your own email address as well.


text:
Q: Show Galois extension with $[K : F] = n$ has an intermediate filed with $L$ with $[K : L] = p$, where $p$ is a prime divisor of $n$ It is a two part question.
Let $K/F$ be a Galois extension with $[K : F] = n$. If $p$ is a prime divisor of $n$, prove there is an intermediate field $L$ with $[K : L] = p$.
Prove or disprove that there is an intermediate field $M$ with $[M : F] = p$.
Could anyone help me for some hints please, Thanks a lot!

A: For the second part, you'd want a subgroup with index $p$,and these will not necessarily exist, as, for instance, when $p=2$ and your Galois group is simple and noncyclic. For, a subgroup of index $2$ has to be normal.

A: Hint. For the first part, use Cauchy's theorem and Galois' correspondence theorem.
Let me know if you need a more detailed answer.


text:
Q: dpkg: invoke-rc.d: initscript mysql, action "start" failed I have read a number of the posts here and they all state to run the following commands:

*

*Apt-get -f remove **

*apt-get update

*apt-get upgrade

*apt-get -f install **

I have seen these in various order etc, and none are resolving, my issue. No matter what I try I get:
 apt-get -f install mysql-server                              Reading package
lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
mysql-server-5.5 mysql-server-core-5.5
Suggested packages:
tinyca mailx
The following NEW packages will be installed:
mysql-server mysql-server-5.5 mysql-server-core-5.5
0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/14.9 MB of archives.
After this operation, 53.0 MB of additional disk space will be used.
Do you want to continue [Y/n]? y
Preconfiguring packages ...
Selecting previously unselected package mysql-server-core-5.5.
(Reading database ... 83134 files and directories currently installed.)
Unpacking mysql-server-core-5.5 (from .../mysql-server-core-5.5_5.5.29-
0ubuntu0.12.04.1_amd64.deb) ...
Selecting previously unselected package mysql-server-5.5.
Unpacking mysql-server-5.5 (from .../mysql-server-5.5_5.5.29-0ubuntu0.12.04.1_amd64.deb)
...
Selecting previously unselected package mysql-server.
Unpacking mysql-server (from .../mysql-server_5.5.29-0ubuntu0.12.04.1_all.deb) ...
Processing triggers for man-db ...
Processing triggers for ureadahead ...
Setting up mysql-server-5.5 (5.5.29-0ubuntu0.12.04.1) ...
Setting up mysql-server-5.5 (5.5.29-0ubuntu0.12.04.1) ...
invoke-rc.d: initscript mysql, action "start" failed.
invoke-rc.d: initscript mysql, action "start" failed.
dpkg: error processing mysql-server-5.5 (--configure):
 subprocess installed post-installation script returned error exit status 1
dpkg: dependency problems prevent configuration of mysql-server:
 mysql-server depends on mysql-server-5.5; however:
  Package mysql-server-5.5 is not configured yet.
dpkg: error processing mysql-server (--configure):
No apport report written because the error message indicates its a followup error from a
No apport report written because the error message indicates its a followup error from a
previous failure.
                   Errors were encountered while processing:
 mysql-server-5.5
 mysql-server

I have tried several things over the past week and cannot get this to resolve, any assistance would be appreciated. I did notice the message:
Package mysql-server-5.5 is not configured yet.
and i have yet to get this configured so I am working on that aspect. Any other assistance will be very appreciated.

A: Solution from Titanicx worked for me. Ran
dpkg -S etc/mysql

to see that mysql-common was the problem. Removed MySQL completely:
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean

A: I had this problem before. MySQL Daemon will be started just right after configuring the package, and if there is any errors in MySQL configuration or problems with accessing data directory, then the job will fail.
Checking MySQL error log on /var/log/mysql/error.log can help you in this case.
In my case, there was an access error caused by apparmor:
150131 19:38:23  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
InnoDB: File name ./ibdata1
InnoDB: File operation call: 'open'.
InnoDB: Cannot continue operation.

And it just solved by editing appropriate apparmor file.

A: My issue was that I had /tmp sym-linked elsewhere and Apparmor didn't like it.
Editing /etc/apparmor.d/abstractions/user-tmp and adding the real path to /tmp fixed it and allowed MySQL to start successfully.
(Source of inspiration)

A: If nothing at all helps try this one. I downloaded the deb package from the mysql site. then
sudo apt-get purge mysql-server mysql-client mysql-common mysql-client-5.5 mysql-server-5.5
sudo dpkg -i mysql-5.6.13-debian6.0-i686.deb
sudo apt-get install mysql-server

Big thanks to Ingo.

A: For me it was very simple
apt-get autoremove

Got:
Setting up mysql-server-5.5 (5.5.38-1~dotdeb.0) ...
update-rc.d: warning: /etc/init.d/mysql missing LSB information
update-rc.d: see <http://wiki.debian.org/LSBInitScripts>
mysql start/running, process 21373

A: Seems like no need to do all these purges and removals.
All you need to do is to remove the server, and execute:
rm /etc/mysql/ -R

And then install the server.
The idea was from the external link referenced from the answer at this thread:
https://askubuntu.com/a/448249/109764

A: Clean your os from all mysql install and add ppa    from there https://launchpad.net/~ondrej/+archive/ubuntu/mysql-5.6


text:
Q: How to segment ROI using SIFT/SURF SIFT is used for feature extraction. Most of the tutorials that I have seen out there only show the features detected using SIFT. I need to identify ROI using SIFT. Images look like this but in worse condition (taken from different angles, some are blur, with more texts and numbers in other places too)

I need to extract this and then perform digit recognition:

What are the ways to segment this part? I was going for SIFT/SURF but couldn't find any tutorial to segment out the ROI. If there are any other suggestions then please provide the link.
Edit: Images that I have are grayscale
Edit1: this is just an example image I got from Google, My dataset only has grayscale images not colored


text:
Q: How is Kohana different from CodeIgniter? I've been using CodeIgniter for a long time, however lately I've been feeling the need to move to a more advanced/more OOP framework. Kohana seems to be an often recommended option, my question is, how exactly is Kohana different from CodeIgniter? A list of differences, particularly syntax differences, would be great.

A: I'll be writing about Kohana 3.1 and main advantages I've seen over CodeIgniter 2 so far. Before Kohana 3.0 (year and a half ago), I used CodeIgniter, ZF, Symfony, Cake and tried many others (at the moment trying to do Yii only because I have to). I'm aware that many will spit on me for "being subjective". Go ahead.
Strict PHP 5.2
Kohana doesn't use any of the old code (meaning 2.x or CodeIgniter's) in the current version. It was totally rewritten to be fully object oriented and not to get in developer's way. Simply put, it feels natural to develop with it, like it's "the way" for PHP development.
This is a framework built "by the community, for the community", not for promotional purposes. And not by / for any community but a very leet one.
CodeIgniter stood still for way too long hanging on PHP4. Looking at the CI2s' source, I can't say they've fully moved on to PHP5 (let's say PHP 5.1 isn't really ... PHP 5). I've seen FuelPHP, which seems to be more like a mashup of CI2 with Kohana than a CI2 branch, though I have to say it definitely has potential.
HMVC
The main reason for Kohana to feel natural was born out of this pattern. The idea was to isolate every request to respect the pattern and it ended up with respecting the RFC 2616. Now you have a separate Response object for each Request, being able to reuse your code in a really neat way. Right now I'm working on a web service which is used with iPhone, Android and the web app. I can't describe what a privilege it is to call the API "on the inside". Raw example:
public function action_delete()
{
    $deleted = Request::factory('api/route')
        ->method(Request::DELETE)
        ->headers('Accept', 'text/html')
        ->execute();

    $this->response->body($deleted);
}

No handicaps
The team behind Kohana is dedicated to making the framework "the best it can be", not "everything it can be, because we .. have too much spare time". Each maintenance version is backward compatible with previous ones (e.g. 3.1.2 with 3.1.0), having all "major" changes wait for the minor versions (e.g. 3.1 isn't fully backward compatible with 3.0 "out of the box"). Previous minor versions are maintained for 6 months after the new one is released.
Exten(ding|sions)
Kohana's Cascading File System makes it extremely easy to extend existing components, or even the ones used by vendors. You can override everything on application / module level, without thinking about setting include / load paths manually anywhere (because all files and folders respect the same convention).
There is a whole bunch of modules, including Zend Framework. How's that? Simply put, you can even use ZF or any other library as a module inside of your Kohana app.
Besides all the community built modules, every Kohana installation includes a few which almost every application can benefit from:

*

*Auth
A simple, yet very powerful, authentication library. The module itself provides file auth driver only but enabling ORM gives us a more powerful one.

*Cache
Caching library with drivers for most popular caching techniques: APC, eAccelerator, file, memcache, SQLite, Wincache and Xcache. It is extremely easy to implement and change (even later changes of the cache driver are a one-liner).

*Codebench
If you need to benchmark some code, Codebench provides you a very simple way of doing it.

*Database
As everything else in Kohana, database module is also fully object-oriented and extendable. Comes with full MySQL and PDO support.

*Image
A simple module for easy image manipulation

*ORM
Default ORM based on ActiveRecord pattern, fully using the advantages of the Database module combined with PHP 5 magic methods. Besides this one you can use Jelly, Sprig, AutoModeler or any other custom PHP lib like Doctrine.

*Unittest
Kohana comes pre-packed with a great unit testing module. It's based on PHPUnit and fully "integrates" with your app, allowing you very easy TDD. Besides, the whole framework is unit tested.

*Userguide
Altough ignored by most developers, this module is one of the most powerful Kohanas' features. It provides the easiest possible way of tracking your API and the rest of Kohana documenation. Why wouldn't your application have its' own guide as well? You don't even have to think about it! As long as you keep track of comments / conventions in your code, this module will take care of the rest.
Code examples
Code is neater than CI's, having all classes autoloaded, though conventions are very similar.
Update example (using ORM):
public function action_update($post_id)
{
    $post   = ORM::factory('post', $post_id);
    $errors = array();

    if ($values = $this->request->post())
    {
        try
        {
            $post->values($values)->update();

            $this->request->redirect('post');
        }
        catch (ORM_Validation_Exception $e)
        {
            $errors += $e->errors();
        }
    }

    $this->template->content = View::factory('post/update', array(
        'post'  => $post,
        'errors'=> $errors,
    ));
}

In this example ORM is used to update a row, having update() call it's check() method to validate it's values. In case that validation fails, ORM_Validation_Exception is caught and the rest of try block isn't executed (i.e. redirection to /post). In the end, both the post object (Model_Post) and errors array are passed to View where they can be accessed directly.
Notice that all Database_Query_Builder methods are available inside of ORM, so you can also do 'fancy' stuff like:
ORM::factory('post')
    ->where('user_id','=',$user_id)
    ->join('users','INNER')
    ->on('users.id','=','posts.user_id')
    ->find_all();

Or (with relations):
$user = ORM::factory('user', $id);

foreach ($user->posts->find_all() as $post)
{
    foreach ($post->quotes->find_all() as $quote)
    {
        if ($quote->illegal())
        {
            $quote->delete();
        }
    }
}

Where illegal() can be some custom model-level method with fancy joins and stuff. I'm aware how inefficient this chunk looks like, it's just a code example, not "are JOINs better than additional queries" :)

A: Please have a look at https://stackoverflow.com/questions/717836/kohana-or-codeigniter where the link - http://onwired.com/blog/exploring-kohana-as-an-alternative-to-codeigniter/ - answered most of this very same question to me.


text:
Q: How to install Ubuntu Budgie over Ubuntu 18.04 I did that command but only installed some applications but not installed Budgie.
I did "sudo apt-get install ubuntu-budgie-desktop" as said by Rosamunda.
What can I do now? Any body could help please?

A: Budgie Desktop environment is located in standard Ubuntu universe repository since Ubuntu 18.04 LTS. So you do not need any third-party repositories or PPAs to install it.
You can install the Budgie desktop as task with
sudo add-apt-repository universe
sudo apt-get update
sudo apt-get install ubuntu-budgie-desktop^

In the last command note ^ in the end, it means installing of task with all necessary dependencies.
Then logout and select Budgie session on login screen

and login to it.

If this does not help - reinstall the following packages manually:
sudo apt-get install --reinstall budgie-core budgie-desktop \
budgie-desktop-common budgie-desktop-environment \
budgie-dropby-applet budgie-hotcorners-applet budgie-indicator-applet \
budgie-keyboard-autoswitch-applet budgie-lightdm-theme \
budgie-lightdm-theme-base budgie-previews-applet budgie-quicknote-applet \
budgie-rotation-lock-applet budgie-showtime-applet budgie-wallpapers \
budgie-wallpapers-bionic gir1.2-budgie-1.0 libbudgie-plugin0 libbudgietheme0 \
libraven0 plymouth-theme-ubuntu-budgie-text plymouth-theme-ubuntu-budgie-logo \
ubuntu-budgie-desktop ubuntu-budgie-themes

Then configure LightDM as login screen with:
sudo dpkg-reconfigure lightdm # select lightdm

reboot and login to Budgie session.


text:
Q: Copy a range from another spreadsheet to another I stumbled upon a code here a while ago which works to copy a range from one sheet to another within the same spreadsheet.
var source_sheet = ss.getSheetByName("Sheet1");
var target_sheet = target.getSheetByName("Sheet2");

var url = "#gid=" + newSheet.getSheetId()

var source_range = source_sheet.getActiveRange();
source_range = source_sheet.getRange(source_range.getRow(), 1, 1, 3);
source_sheet.getRange("I" + source_range.getRow()).setFormula('=IFERROR(Sheet2!C4," ")')
source_sheet.getRange("K" + source_range.getRow()).setFormula('=HYPERLINK("' + url + '","Generated Sheet")')
var target_range = target_sheet.getRange("B4");

source_range.copyTo(target_range);

The script works as intended but now I want to copy from one spreadsheet to another. And when I set the a sheet from a different spreadsheet as the target sheet, I get the error of source and target must be within the same spreadsheet.
Therefore, is there any workaround for this? I was think maybe using importrange, but how do I specify the URL and that selected range in the source range to be imported using the insert function script. If you can think of any other solution, please do let me know.

A: source_range.copyTo(target_range);
You're getting this error message because copyTo() method is based on a range AND assumes that the source and target are in the same spreadsheet.
The more straightforward method to copy a range is to use setValues, even though there are two spreadsheets and two different sheets. The following script demonstrates this.

function so5894550501() {

  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sourcesheetname = "sourcesheet";
  var source = ss.getSheetByName(sourcesheetname);

  var targetid = "<insert targetid>";
  var ts = SpreadsheetApp.openById(targetid);
  var targetsheetname = "targetsheet";
  var target = ts.getSheetByName(targetsheetname);

  var sourceRange = source.getRange(1,1,source.getLastRow(),source.getLastColumn());
  Logger.log("the source range = "+sourceRange.getA1Notation())
  var sourceValues = sourceRange.getValues();
  Logger.log(sourceValues);
  Logger.log(sourceValues.length)

  var targetRange = target.getRange(1,1,source.getLastRow(),source.getLastColumn());
  targetRange.setValues(sourceValues);// this works

}


text:
Q: Android, Edit Auto Value parameter value I'm using google Auto-value for my objects and also I used Builder class and create method to initialize my object, so how can I edit specific parameter of my object without initializing it again?
@AutoValue
public abstract class test implements Parcelable {
public abstract String name();

public abstract int age();

public static test create(String name, int age) {
    return builder()
            .name(name)
            .age(age)
            .build();
}

public static Builder builder() {
    return new AutoValue_test.Builder();
}

@AutoValue.Builder
public abstract static class Builder {
    public abstract Builder name(String name);

    public abstract Builder age(int age);

    public abstract test build();
  }
}

Now in my code I want change the name property (t contains data):
test t = test.Builder.name("Ali").age(26).build();
/*how to change name value*/

A: Without initializing it again, you CAN NOT edit specific parameter of your object with @AutoValue annotation (value-typed object); this immutability is what AutoValue aims to provide for your object, because the main purpose of AutoValue is to create immutable objects without writing boilerplate codes.
If you want to know more about AutoValue and what this library aims to achieve the below links may be helpful:

*

*http://ryanharter.com/blog/2016/03/22/autovalue

*https://speakerdeck.com/shaunkawano/introduction-to-autovalue
Also, if you want to initialize new object with different parameter value(s), the with-er library may be useful.

*

*https://github.com/gabrielittner/auto-value-with
I hope it helps.


text:
Q: Key management on repeating elements in React I need a component that, given some children, it will repeat this children over and over to fill the screen. Let's say it has a simple markdown like this:
<FillScreen items={[
    { id: 'one', content: 'foo' },
    { id: 'two', content: 'bar' }
]} />

Internally, this component will get the screen size, and will eventually fill the screen with these items. The resulting DOM will look like this:

foo

bar

foo

bar

foo

bar

foo

The problem I have is that when this element has calculated that it needs to render 7 elements, I can't directly use items[i].id as a key for each element because there will be repeated keys.
I'm not sure what's the best pattern for this problem, I've thought two possible solutions which I don't fully like:
Solution A
Append  a loop index on every key, so the array in render contains the following JSX:

foo

bar

foo

bar

foo

bar

foo

Edit - note that these elements are being generated into an array, that's why we need to specify a key
I see two issues with this approach:

*

*At this point I may just get rid of the original key and just use an index, something that's absolutely discouraged.

*My real-life component, the way you give items to this component is through children (I oversimplified in here to get the point across), so I would have to clone each element just to change the key.

Solution B
Use fragments to separate between loops
   <Fragment key={0}>

foo

bar

   </Fragment>
   <Fragment key={1}>

foo

bar

   </Fragment>
   <Fragment key={2}>

foo

bar

   </Fragment>
   <Fragment key={3}>

foo

   </Fragment>

In here it feels more clean, but at the same time this is not the reason Fragments were added in the first place, so maybe it's misusing them?.
Is there a better solution to this problem? What's the community standard?

A: Since you are using Fragment I assume that you are using version >16. In that case I think that there is another (perhaps better) way of solving this problem, which is returning an Array of Arrays. Something like this:
[
  [

foo
,

bar
,
  ],
  [

foo
,

bar
,
  ],
  [

foo
,
  ],
]

Actually this is "equivalent" to your "Solution B", but IMHO is less "hacky" because I think that Fragment is not meant to be used like that. Let me extend on that:
Before version 16 the render function couldn't return an Array of React Elements, which was something quite annoying. On version 16 that started being possible, however the elements of the Array must always have a key so that the React's reconciler works properly, meaning that returning  this from a render function is bad:
[
  foo,
  bar,
]

and this is correct:
[
  foo,
  bar,
]

But doing that is a bit weird and annoying. That's why Fragment was invented, so that we can just return this:
<Fragment>
  foo
  bar
</Fragment>

So, the big advantage of Fragment is that we don't have to assign keys to their children elements. That's why I find it a bit hacky to see a Fragment with "keyed" children.
Also, I wanted to say that I don't think that there is anything wrong with your "Option A". However, I think that in most cases the solution that I'm proposing will be a lot easier to implement.

A: The right thing to use as key depends on what can change over the lifecycle of the parent component (FillScreen).
Using index as key is usually frowned upon because if items props changes during the lifecycle of FillScreen, then the same index can now point to another item but the component will not re-render because key remains the same.
In this case you can simply use a combination of id and index as the key but keep in mind that if the items get reshuffled in the array then the components for presenting every item will get remounted. The same is the case with the other approach using index keys on fragments (there is no particular advantage of using fragments here).
Similarly if you inject an item in between the array, then the components for presenting all subsequent items will get discarded and recreated.
If you do want to optimize for the above cases, you can construct the key by appending occurance index of that id.

foo

bar

foo

bar

foo

bar

foo

React elements are fairly lightweight so cloning does not incur a significant cost overhead.


text:
Q: Area of Infinite Shaded Regions I recently came across this WISCONSIN STATE MATHEMATICS MEET problem and solution.
The solution reads that one of the larger triangles has an area of 1/16 th of whole square. How is that?

A: Your question has been well-answered. So we concentrate on giving a different solution of the original problem.
Assume without loss of generality that the big square has area $1$. Let the  area of the shaded region be $A$.
Then the shaded region consists of our two big shaded triangles, with combined area $\dfrac{1}{8}$, plus the area of the rest of the shaded stuff.
This rest of the area is the original shaded stuff, scaled down by a linear scaling factor $\dfrac{1}{2}$, and therefore by an area scaling factor $\left(\dfrac{1}{2}\right)^2$. Thus we obtain the equation
$$A=\frac{1}{8}+\frac{A}{4}.$$
Solve this linear equation for $A$. We get $A=\dfrac{1}{6}$. No infinite series!

A: Say the area of the largest square is $A$, the area of the next smaller square is $A/4$, the area of half that square (a rectangle, if cut along a median of the square) is $A/8$, so the area of the shaded right-angled triangle is half that, namely $A/16$
Since there are two such triangles for each square size, the total area of the shaded region will be:
$$S=\frac{A}{8}\sum_{n=0}^{\infty} \frac{1}{4^n}=\frac{A}{8}\cdot\frac{4}{3}=\frac{A}{6}$$

A: If we denote the side of the largest square by $x$, it is obvious by symmetry that the base of one of the right triangles is $x/2$, and the height is $x/4$. Since $A=bh/2$ for a triangle, the area is $x^{2}/16$ which is one sixteenth the area of the square.

A: Just take the size of square as 1, and try to find the dimensions of big triangle and then find the area. now try to use this fraction to make a series whose sum gives you the answer.


text:
Q: Physics Standard Deviation I am a physics enthusiast and I have a question: Why is it meaningless to express the '$\pm$' (standard deviation) value as a percentage?

A: Standard deviation adds uncertainties to the measured value: $23.3\pm 0.4\,{\rm m}$. One can quickly look at the error (which has units of ${\rm  m}$ in my case) and think, The value could be as low as $22.9\,{\rm m}$ or as high as $23.7\,{\rm m}$ without much thinking. Modifying this to being a percentage of the value would be confusing.
Plus it would be arbitrary. As Martin Beckett points out, since the Celsius and Kelvin scales have identical temperature spacing but differing 0-points, making the error (std. dev.) scale to the value would be ridiculous:
$$20.0\pm0.1\,{\rm C} \to 20.0\,{\rm C}\pm0.5\%$$
$$293.0\pm0.1\,{\rm K}\to293.0\,{\rm K}\pm0.034\%$$
Same value in units systems would lead to differing uncertainties; this would bring about more confusion.

A: Depends what you are measuring.
If you are measuring the temperature of a glass of water to 20C +- 0.1C what would the percentage be?
Now what would it be if you measured it as 293Kelvin +- 0.1K


text:
Q: How to hover over the word in word cloud I have created a word cloud from the text file using python by using the module called (pytagcloud),but I have created it as .jpeg file. But i want to make the words in the cloud to be active when I hover the cursor over the words in cloud.
When I click the particular word in word cloud, the corresponding sentence in the passage should be highlighted.How to do that ? please help me. I have project work in this topic.
I created a gui in which i have options to import the text file and read a text file. after reading text file, I need to produce the word cloud from the passage in .txt file.
def wordcloud(self):

        from pytagcloud import create_tag_image, create_html_data, make_tags, LAYOUT_HORIZONTAL, LAYOUTS, LAYOUT_MIX, LAYOUT_VERTICAL, LAYOUT_MOST_HORIZONTAL, LAYOUT_MOST_VERTICAL
        from pytagcloud.lang.counter import get_tag_counts
        from pytagcloud.colors import COLOR_SCHEMES
        import webbrowser

        #import Tkinter
        #from tkFileDialog import askopenfilename
        #filename=askopenfilename()

        #with open(filename,'r') as f:
        #    text=f.read()

        #def create_tag_cloud(text):
        words = nltk.word_tokenize(self._contents)
        doc = " ".join(d for d in words[:70])
        tags = make_tags(get_tag_counts(doc), maxsize=100)
        create_tag_image(tags, 'sid.jpeg',size=(1600, 1200),fontname='Philosopher',layout=LAYOUT_MIX,rectangular=True)
        webbrowser.open('sid.jpeg')

A: Without seeing your code there is nothing to correct.
However the best approach to this is to output your tag cloud in HTML and CSS so you end something like their demo.
After you have your HTML code one approach to take is to use Javascript to react on a word clicked and highlight every occurrence of that word in your body.
However there are many other approaches that may be better suited but without any context it's impossible to comment I'm afraid. Regardless of this don't render your tag cloud as a jpeg. This is static and will not have the capability to be interactive.
Edit1: Code provided
Have a look at the test_create_html_data(self): function in the PyTagCloud tests available on github to get an idea of how to output HTML and CSS.
Just a quick note on your code, Python will be importing all those packages upon every run of your wordcloud() method. Pull them out to something like this (I started the adaption for you):
from pytagcloud import (create_tag_image, create_html_data,
    make_tags, LAYOUT_MIX)
from pytagcloud.lang.counter import get_tag_counts
from pytagcloud.colors import COLOR_SCHEMES
import webbrowser

# ...the rest of your code...

def wordcloud(self):
    words = nltk.word_tokenize(self._contents)
    doc = " ".join(d for d in words[:70])

    tags = make_tags(get_tag_counts(doc), maxsize=100)
    data = create_html_data(tags, (1600,1200), layout=LAYOUT_MIX, fontname='Philosopher', rectangular=True)


text:
Q: Can you use Lasso for variable selection of fixed effects, then run a mixed model using the fixed effects from Lasso? I have a mixed model with many fixed effects, and two random variables (the data is made up of repeat observations of a number of individuals, and has a random intercept and a random slope parameter associated with each individual). The model will be used for prediction. I want to use a regularisation technique to reduce the number of fixed effects as the model is likely overfitted at present.
Would it be valid to run a Lasso analysis on a model which excludes the random effects and use the outcome of this to choose the fixed effects to keep in my mixed model? As in:

*

*Run a number of Lasso regressions on a training set where the tuning parameter (lambda) is varied

*Calculate the RMSE of an (unseen) test set

*Find the value of lambda which gives the best RMSE in the test set

*Find the variables for which the coefficient is set to zero for the value of lambda that produces the best RMSE in the test set

*Exclude these variables from a subsequent mixed model.

I've found that there are lots of papers for different lasso-type things that people do for mixed models, but I'm struggling to find a clear, reliable, reference that explains why you couldn't just do the steps above... My intuition is that this would not be valid because the Lasso wouldn't know about the structure in the model that the random effects capture... is that right? And if so, could you point me to a nice reference that makes this clear? Or, if it is ok, could anyone point me to a nice reference that makes that clear?
I hope this makes sense, and sorry if it's a simple answer!

A: There doesn't appear to be a consensus on how to perform variable selection on both fixed and random effects. There are technical papers proposing solutions to this problem, like this paper from Fan and Li.
Bondell et al. argue against separating the fixed and random when performing variable selection, as the structure of the random effects will affect which fixed effect variables are selected. I am not an expert at variable selection or mixed models, but Bondell's claims and your intuition seem correct to me. Since this problem doesn't seem to be fully solved, I don't think you'll find the clear resource you want. You will find many technical arguments like those papers or their references.
It is straightforward to produce an example where temporarily ignoring the random effects will not work. Imagine you have a longitudinal study and a random effect for each person. It wouldn't make any sense to omit the random effects because that is how you model within-person correlation.


text:
Q: How to use External Procedures in Triggers on Oracle 11g I want to fire a trigger whenever an insert command is fired..
The trigger will access a pl/sql file which can change anytime..
So the query is, if we design the trigger, how can we make sure this dynamic thing happens.. As during the stored procedure, it is not working..
I think - it should work for
1) External Procedures
2) Execute Statement

Please correct me, if I am wrong.. I was working on External Procedures but i am not able to find the way to execute the external procedure from here on..
SQL> CREATE OR REPLACE FUNCTION Plstojavafac_func (N NUMBER) RETURN NUMBER AS
  2  LANGUAGE JAVA
  3  NAME 'Factorial.J_calcFactorial(int) return int';
  4  /

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
SQL> CREATE OR REPLACE TRIGGER student_after_insert
  2  AFTER INSERT
  3  ON student
  4  FOR EACH ROW

How to call the procedure from heree... And does my interpretations are right,, plz suggest..
Thanks.

A: either use procedure for inserting where you will handle your data and then quit procedure (cancel insert) or make successful insert, or do your data handling in trigger not in procedure


text:
Q: Integrate $\frac{1}{\sqrt{6x-x^2-5}}$ Question: Integrate $\frac{1}{\sqrt{6x-x^2-5}}$
My Working:
$$\int{\frac{1}{\sqrt{6x-x^2-5}}} = \int{\frac{1}{\sqrt{-(x^2-6x+5)}}} = \int{\frac{1}{\sqrt{-((x-3)^2-3^2+5)}}} = \int{\frac{1}{\sqrt{-((x-3)^2-4)}}}$$
Is it right so far? Because I think I should be using the formula
$$\int{\frac{1}{\sqrt{a^2-(x+b)^2}}} = \sin^{-1} \left( \frac{x+b}{a} \right)+c$$
$-4$ can't fit into $a^2$ can it? I haven't covered complex numbers yet, so I must have made a mistake?

A: Your derivation is correct, but you aren't looking at the last line correctly. Notice that
$$-((x-3)^2-4)=4-(x-3)^2,$$
so your parameters are $a=2$ and $b=-3$ to plug into the formula. We rule out $a=-2$ because the square root function is always nonnegative, and so following holds only for $a$ positive:
$$\frac{d}{dx}\sin^{-1}\left(\frac{x+b}{a}\right)=\frac{1}{a\sqrt{1-(x+b)^2/a^2}}=\frac{1}{\sqrt{a^2-(x+b)^2}}.$$

A: You are doing just fine. You completed the square, which is the key step, and ended up with
$$\int \frac{dx}{\sqrt{4-(x-3)^2}}.$$
Now you have a formula that you want to use. It may be better not to try to remember too many formulas. We will instead find a substitution that gives us a very familiar integral.
The above integral looks kind of like
$$\int \frac{dw}{\sqrt{1-w^2}}.$$
We look for a substitution that brings out the resemblance.
Suppose that we let $x-3=2u$. Then the bottom will look like $\sqrt{4-4u^2}$, which is good, because we can then "take the $4$'s out."
So let's do it. Let $x-3=2u$, or if you prefer, let $(x-3)/2=u$.  Then $dx=2\,du$ and our integral becomes
$$\int\frac{2u}{\sqrt{4-4u^2}}.$$
But $\sqrt{4-4u^2}=2\sqrt{1-u^2}$. So our integral simplifies to
$$\int \frac{du}{\sqrt{1-u^2}}=\arcsin u +C.$$
Finally, replace $u$ by $(x-3)/2$.
Another way to get to the right substitution is to note that
$$\sqrt{4-(x-3)^2}=2\sqrt{1-((x-3)/2)^2},$$
 which makes letting $u=(x-3)/2$ very natural.


text:
Q: 'Invalid hostname' response from http.sys We have web service running hosted on an OwinHttpListener (http.sys behind the scenes). Whenever we send requests to the app on the IP address, it responds with 'Invalid hostname'.
After much trawling of stack overflow and google, im not really any closer to a solution. The requests are getting through to http.sys, as i can see them in the HTTP error log. I can log onto the server in question and access the service locally (using localhost or 127.0.0.1) and i can use the server name to successfully get through, the only failure condition is using the servers IP address.
Ive tried the following:

*

*Ensure the app is listening on all interfaces (http://+:8080)

*Ensure IIS is not trying to use the port (it isnt)

*Ensure windows firewall is configured to allow traffic on that port (it is)


text:
Q: html onchange event not working after form submit. Ajax/html/javascript I have a testing form that is not working quite how I thought. We have two versions one with all questions on one page and one that is timed and you get one question at a time via ajax.  i have cookies being created to store questions and test progress so the users can come back to it later. this works fine on the static test but the timed one is having issues.  I have an onchange event that updates the cookie but the problem I have is on the timed one that only on the first question or if the page is refreshed does it have the onchange event, if i just submit answer and new question appears it does not have the event for some reason.  Hoping someone more familiar with ajax can point out what is wrong.
here is the code:
//Submits individual simulation exam questions and loads the next one.
function submitSimulation () {
    $('input:radio').removeAttr('disabled');
    var params = $('form').serialize();
    $('#spinner').show();
    $.ajax({
      url: "simulation.php",
      data: params,
      type: "POST",
      success: function(data){
        $('#simexam').fadeOut(400, function(){$('#simexam').html(data).fadeIn(400);});
      }
    });
}

here is what the questions look like"
<input id="q{$question.question_id}answer4" type="radio" value="4" name="answer[{$question.question_id}]" onchange="cookieupdate('q{$question.question_id}answer4')"/>

this is the button code
<input type="button" name="next_question" class="submit" value="Next Question" onclick="submitSimulation();" />

this is what the next question looks like after the submit:
<input id="q{$question.question_id}answer4" type="radio" value="2" name="answer[{$question.question_id}]">


text:
Q: Hide html h3 links via custom CSS in Joomla I wanted to hide that in Joomla using the custom CSS
This is the link to my site:
http://guamlfp.org/test
I am trying to remove the title of the articles "About" and "Vision"
I need the CSS code to hide the following HTML:

About

Vision

A: add this css in your css
css
.sppb-article-info-wrap h3{
   display:none;
}

A: there are a lot of different ways to hide it. you can do it directly to the html or you can use css.
1. Using HTML

    Vision

2. Using CSS
HTML Code

    Vision

CSS Code
.header--vision {
    display: none;
}


text:
Q: Nodejs bot return 404 when deployed to Azure app service I tried to run the bot and deploy it to azure: https://github.com/microsoft/BotBuilder-Samples/tree/main/samples/javascript_nodejs/05.multi-turn-prompt
I followed this doc to do deployment: https://learn.microsoft.com/en-us/azure/bot-service/provision-and-publish-a-bot?view=azure-bot-service-4.0&tabs=multitenant%2Cjavascript
After setup the identity, the bot works well locally, but when I test it from web chat, there is no response, and if I access by https://0915-bots-app-service.azurewebsites.net/api/messages I got this error: The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
I suspect this is caused by the generated web.config file, but seems there is no issue in it.
picture from wwwroot
The MicrosoftAppId and password are set correctly for both the Azure bot and app service.
Does anyone have some clue? Thanks!


text:
Q: i am using paypal rest api of billing plans i need to know were will the api billing plans will affect     ##Here i used rest api##
    curl -v -X POST https://api.sandbox.paypal.com/v1/payments/billing-plans/ \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer Access-Token" \
     -d '{
      "name": "Plan with Regular and Trial Payment Definitions",
     "description": "Plan with regular and trial payment definitions.",
      "type": "FIXED",
       "payment_definitions": [
     {
      "name": "Regular payment definition",
      "type": "REGULAR",
      "frequency": "MONTH",
      "frequency_interval": "2",
      "amount": {
        "value": "100",
        "currency": "USD"
      },
      "cycles": "12",
      "charge_models": [
        {
          "type": "SHIPPING",
          "amount": {
            "value": "10",
            "currency": "USD"
          }
        },
        {
          "type": "TAX",
          "amount": {
            "value": "12",
            "currency": "USD"
          }
        }
      ]
    },
    {
      "name": "Trial payment definition",
      "type": "TRIAL",
      "frequency": "WEEK",
      "frequency_interval": "5",
      "amount": {
        "value": "9.19",
        "currency": "USD"
      },
      "cycles": "2",
      "charge_models": [
        {
          "type": "SHIPPING",
          "amount": {
            "value": "1",
            "currency": "USD"
          }
        },
        {
          "type": "TAX",
          "amount": {
            "value": "2",
            "currency": "USD"
          }
        }
      ]
    }
  ],
  "merchant_preferences": {
    "setup_fee": {
      "value": "1",
      "currency": "USD"
    },
    "return_url": "https://example.com",
    "cancel_url": "https://example.com/cancel",
    "auto_bill_amount": "YES",
    "initial_fail_amount_action": "CONTINUE",
    "max_fail_attempts": "0"
  }
}"

i got the successful response of status created ,...but when i move to the paypal developer account and checked ,..i cant find any new payments,
can u please tell me were will the particular code reflected ,can u please help me to find were will the paypal billing plans request will be reflected .i have attached the following api request above ...

A: After created a billing plan, you have to do followings.

*

*Activate that plan

*Create an agreement

*Get customer approval

*Execute an agreement

https://developer.paypal.com/docs/subscriptions/


text:
Q: LSTM predictions are one time step lagging My problem involves electricity prediction (time-series problem) for 1-hour ahead. I am using LSTM to forecast.

*

*Length of Dataset: 1 year at one-hour interval

*Input: Outdoor Temperature (Ot), Relative Humidty (RHt), historical electricity (Et)

*Output: Electricity (Et+1)

The pearson correlation between (Et) and (Et+1) is ~95%.  However, my forecast is lagging by 1-hour (one timestep) i.e. it is predicting Et at time (t+1).
Network Architecture:
epoch = 400
batch_size = 24
lr = 0.001

model = Sequential()

model.add((LSTM(units=20, return_sequences=True, input_shape=(look_back, X_train.shape[2]), activation='relu')))
model.add((LSTM(units=10, return_sequences=True, activation='relu')))
# model.add(Dropout(0.2))

model.add(Flatten())
model.add(Dense(units = 1,activation='sigmoid'))

adam = optimizers.Adam(lr=lr)
model.compile(loss = 'mean_squared_error', optimizer = adam)

history = model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=epoch, batch_size=batch_size,verbose=1, shuffle = False)
model.summary()

Model loss graph

Predictions Graph

The left-sided figure is the actual prediction where as the right-sided figure is one-hour shifted. As could be seen the actual predictions are one-hour lagging.
I have done hyper-parameter tuning as well using grid search.
Can anyone help me out on how to improve the performance? Is it because of the very low loss values ( in range of 1e-3) after 10-20 epochs and the incentive to learn is quite low?
Any thoughts?


text:
Q: Keep count of occurrences in a truncating file Let's say I have a file called data.log.
Data constantly gets appended to it which can contain 'flag' and it gets truncated by an external script:

[13/Jan/2015:11:11:53 +0000] curabitur flag lacinia nibh in feugiat mollis
tail: data.log: file truncated
[13/Jan/2015:11:11:53 +0000] dapibus enim sagittis efficitur
[13/Jan/2015:11:11:54 +0000] iaculis non flag ac urna.

After declaring counter=0, I want to increment it with the amount of found occurrences. I came up with something like this, which uses wc -l to count the lines in data.log containing 'flag':
counter=$(($counter+$(cat data.log | grep s | wc -l)))
echo $counter

Now there's only one problem left: the truncating. How would I approach this? I thought of doing a watch, but how do I pick up on the truncating event? Or is there another direction I should be heading altogether?

A: This should work for you:
$ tail -F data.log | grep --line-buffered s | while read match ; do ((counter++)) ; done

The -F flag for tail is the same as --follow --retry. --retry is the magic bit here:
   --retry
          keep trying to open a file even when it is or becomes inaccessi‐
          ble; useful when following by name, i.e., with --follow=name

I also used --line-buffered with grep, to avoid the while loop needing to wait for output.
One problem with this that I've just realised: if flag appears more than once for every line, $counter will still only be incremented by 1. But that issue is in your solution as well.


text:
Q: How to get specific tag from XML to place it in HTML by using XSLT? I need to transform the XML, to get 'fig' tag from XML and it placed on corresponding cross-ref.
Input:
<floats>
  <fig id="fig1">

First figure

    <link locator="fig1.tif"/>
  </fig>
  <fig id="fig2">

Second figure

    <link locator="fig2.tif"/>
  </fig>
</floats>

Paragraph 1<cross-ref refid="fig1">Fig. 1</cross-ref><float-anchor refid="fig1" />

Paragraph 2<cross-ref refid="fig2">Fig. 2</cross-ref><float-anchor refid="fig2" />

Output:

Paragraph 1Fig. 1

First figure

Paragraph 2Fig. 2

Second figure

Could you please suggest me on this. Thanks in advance.

A: Try whether the following transformation suits your needs. It does not yet take into account the comment of Joel M. Lamsen regarding cross-ref and float-anchor. Update: Now it does.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()" /></xsl:copy>
</xsl:template>

<xsl:template match="/">
    <xsl:apply-templates select="//body" />
</xsl:template>

<xsl:template match="p">
    <xsl:copy>
        <xsl:attribute name="class">text</xsl:attribute>
        <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
    <xsl:apply-templates select="float-anchor" mode="float" />
</xsl:template>

<xsl:template match="cross-ref">
    <xsl:variable name="refid" select="@refid" />
    <xsl:element name="a">
        <xsl:attribute name="href">
            <xsl:value-of select="concat('#', $refid)" />
        </xsl:attribute>
        <xsl:value-of select="." />
    </xsl:element>
</xsl:template>

<xsl:template match="float-anchor" />

<xsl:template match="float-anchor" mode="float">
    <xsl:variable name="refid" select="@refid" />
    <xsl:element name="div">
        <xsl:attribute name="id"><xsl:value-of select="$refid" /></xsl:attribute>
        <xsl:attribute name="class">figure</xsl:attribute>
        <xsl:apply-templates select="//floats/fig[@id=$refid]/*" mode="float" />
    </xsl:element>
</xsl:template>

<xsl:template match="p" mode="float">
    <xsl:copy>
        <xsl:attribute name="class">fig</xsl:attribute>
        <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
</xsl:template>

<xsl:template match="link" mode="float">
    <xsl:element name="img">
        <xsl:attribute name="src"><xsl:value-of select="@locator" /></xsl:attribute>
    </xsl:element>
</xsl:template>
</xsl:transform>

A: try the following stylesheet:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

    <xsl:strip-space elements="*"/>

    <xsl:output indent="yes" omit-xml-declaration="yes"/>

    <xsl:variable name="Fig" select="root/floats"/>

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="p">

            <xsl:apply-templates select="@*|node()"/>

        <xsl:if test="float-anchor">
            <xsl:for-each select="float-anchor">
                <xsl:apply-templates select="$Fig/fig[@id=current()/@refid]" mode="transfer"/>
            </xsl:for-each>
        </xsl:if>
    </xsl:template>

    <xsl:template match="floats|float-anchor"/>

    <xsl:template match="root|body">
        <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="fig" mode="transfer">

            <xsl:apply-templates/>

    </xsl:template>

    <xsl:template match="link">

    </xsl:template>

    <xsl:template match="cross-ref">

            <xsl:apply-templates/>

    </xsl:template>

</xsl:stylesheet>

since your input XML is invalid (missing a root node), consider the following input XML:
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <floats>
        <fig id="fig1">

First figure

            <link locator="fig1.tif"/>
        </fig>
        <fig id="fig2">

Second figure

            <link locator="fig2.tif"/>
        </fig>
    </floats>

Paragraph 1<cross-ref refid="fig1">Fig. 1</cross-ref><float-anchor refid="fig1" />

Paragraph 2<cross-ref refid="fig2">Fig. 2</cross-ref><float-anchor refid="fig2" />

</root>

when applied to the stylesheet above, the output is:

Paragraph 1Fig. 1

First figure

Paragraph 2Fig. 2

Second figure


text:
Q: null is not an object in getInitialState() react-native Im new to react native and getting one error as 'null is not object (evaluating 'this.state.pan')'
and the code for that is :
getInitialState: function(){
return{
  pan : new Animated.ValueXY(),
  panResponder: PanResponder.create({
    onStartShouldSetPanResponder: () => true,
    onPanResponderMove: Animated.event([null,{
      dx : this.state.pan.x,
      dy : this.state.pan.y
    }]),
    onPanResponderRelease: (e,gesture)
  })
}
}

Can anybody tell me what is wrong with bold text ?

A: You are referring to this.state in the 'getInitialState method. But 'this.state' only has a value after 'getInitialState' has been called. You can however do something like this.
getInitialState: function(){
  var panValue = new Animated.ValueXY();
  return{
    pan : panValue,
    panResponder: PanResponder.create({
    onStartShouldSetPanResponder: () => true,
    onPanResponderMove: Animated.event([null,{
      dx : panValue.x,
      dy : panValue.y,
    }]),
    onPanResponderRelease: (e,gesture)
  })
}
}


text:
Q: PHP Notice: String offset cast occurred line 251 & 258 i get php notice with this
$code = "";
while ($id > $length - 1) {
    // determine the value of the next higher character
    // in the short code should be and prepend
    $code = self::$chars[fmod($id, $length)] . $code; //<-- line 251
    // reset $id to remaining value to be converted
    $id = floor($id / $length);
}

// remaining value of $id is less than the length of
// self::$chars
$code = self::$chars[$id] . $code; //<-- line 258

return $code;

The NOTICE code is this part:
$code = self::$chars[fmod($id, $length)] . $code;
$code = self::$chars[$id] . $code;

How to fix it? I can't find it, please your help all.. :)

A: Using intval should fix it:
..$chars[intval(fmod($id, $length))]..

That is caused because fmod returns a float, and it casts it to integer. See this example:
$a = 'abcdef';
$b = $a[1.0];
echo $b;

And the output:

E_NOTICE : type 8 -- String offset cast occurred -- at line 3
  b

If you think about it (at least in this case), you can either be at position 1, or at position 2, for example. You can't be at position 1,5. So when you try to access something float, it automatically casts the value to integer and lets you know that it did that.


text:
Q: if G is abelian group and it has cyclic subgroup of order 5 and 4 then what are d other sizes of cyclic group that G must have? As G hs cyclic subgroup of order 4 then as 2 divides 4 so it must have cyclic subgroup of order 2. BUt in text it is given that G olso have cyclic subgroup of order 20.
How please explain?

A: Hint: Let $a$ and $b$ are generators of cyclic subgroups of order $4$ and $5$ respectively then $ab$ is of order $20.$

A: For general case -
If $G$ is an abelian group and contains cyclic subgroups of order n and m ,it will contain a cyclic subgroup of order $lcm(n,m)$
If $G$,an abelian group has cyclic subgroups of order 4 and 5 ,it will contain a cyclic subgroup of order 20 .
And by fundamental theorem of cyclic groups ,it will contain subgroups of orders 1,2,4,5,10,20.
Note - For abelian group ,converse of Lagrange's theorem is true.


text:
Q: Issues with initializing new object When I try to construct the following object:
Tijdschrift tijdschrift = new Tijdschrift
{
    Id = "ID01",
    Titel = "Scientific American",
    Datum = new DateTime(2014, 8, 1),
    Uitgeverij = "Scientific American"
};

I get the following error:

Error CS7036  There is no argument given that corresponds to the required formal parameter 'Id' of 'Tijdschrift.Tijdschrift(string, string, DateTime, string)'    Catalogus   C:\Users\Robiin\Documents\Labo03\Labo03\Program.cs  13

I have no idea why honestly, my constructor is written as below.
public Tijdschrift(string Id, string titel, DateTime datum, string uitgeverij)
{
    Datum = datum;
    this.Id = Id;
    Titel = titel;
    Uitgeverij = uitgeverij;
}

A: You're using object initializer syntax. The code you posted first tries to call parameterless constructor, then sets properties. Use parenthesis () to pass constructor parameters:
Tijdschrift tijdschrift = new Tijdschrift ("ID01",
    "Scientific American",
    new DateTime(2014, 8, 1),
    "Scientific American");

A: Another solution to your problem would be to add a parameterless constructor. Then your object initializer works fine.
public class Tijdschrift {
    public DateTime Datum {get;set;}
    public string Id {get;set;}
    public string Titel {get;set;}
    public string Uitgeverij {get;set;}

    public Tijdschrift(){}

    public Tijdschrift(string Id, string titel, DateTime datum, string uitgeverij)
    {
        Datum = datum;
        this.Id = Id;
        Titel = titel;
        Uitgeverij = uitgeverij;
    }
}

A: Try calling the constructor like this instead:
Tijdschrift tijdschrift = new Tijdschrift ("ID01",
                                           "Scientific American",
                                            new DateTime(2014, 8, 1),
                                            "Scientific American");


text:
Q: Why bootstrap 3 is not loading in django Why bootstap is not loading
I have provided the template code.
{% extends "posts/base.html" %}

{% load bootstrap3 %}

{% block content %}

Create New Post

<form method="POST" id="postForm">
    {% csrf_token %}
    {% bootstrap_form form %}
    <input type="submit" value="Post" class="btn btn-primary btn-large">
</form>
{% endblock %}

This is showing like this :
enter image description here
why bootstrap is not loading. How can I do it?

A: add these line
{% bootstrap_css %}
{% bootstrap_javascript %}


text:
Q: how do i trigger the javascript event with dropdown and change the values? I am creating a form where the users will have to select the country from the drop down list. as soon as they selects it should activate another drop down list where it should show the states belonging to the country and hence it should process the value from country Id of  element. and as soon as the user selects the states another drop down list  should activate listing the cities belonging to that particular states, and hence so on to areas.
for that i have written the php and html code like this.
Select Countries : <select name="countries">

<?php
foreach($property->getAllCountries() as $countries)
{
?>
    <option value="<?php echo $countries['id']; ?>"><?php echo $countries['name']; ?></option>
<? } ?>
</select>

Select State : <select name="state">
<?php
foreach($property->getStatesFromCountryId($countryId) as $states)
{
?>
    <option value="<?php echo $states['id']; ?>"><?php echo $states['name']; ?></option>
<? } ?>
</select>

the javascript should automatically insert $countryId from  and populate the states after the user selects it.
i am noob at javascript i would appreciate if someone could guide me how to achieve this?
thank you.

A: sorry for bad english.
you should add onchange="showstates()" to select countries and a div to add states of country  to it
function showstates()
{
var country=document.getElemtById("countries").value;
if (country=="anywhere")
{
document.getElemtById("statesofcountries").innerHTML='
"states list"
';
}
}

check this link

A: You can always google it up:
http://roshanbh.com.np/2007/12/change-dropdown-list-options-values-from-database-with-ajax-and-php.html


text:
Q: Dymanic Block based on Segments in phtml I created 2 dynamic cms blocks in BE with different Customer Segment,
How can I call to them from phtml file?
Please note that dynamic cms block != cms block

tried
$block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('block_identifier_cms_block')->toHtml();

But it works for static cms block

A: <?php echo $block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('block_identifier_cms_block')->toHtml();?>


text:
Q: BeforeSend passed to Backbone's Fetch not allowing events to be triggered I have a Backbone collection. I'm using fetch to lazy load Facebook posts into a model on initialization.
https://gist.github.com/2271437
exports.Collection = class Posts extends Backbone.Collection
  initialize: (models, options) =>
    @id = options.id
    @activeDetails = false
    @on "loadDetails", @loadDetails
    @on "detailsLoaded", @logger
    debug "initialized posts"
    @fetch
      beforeSend: () =>
        console.log "about to fetch..."
        @trigger "postsLoading"
      success: (collection, response) =>
        debug "successfully loaded ajax"
        @trigger "postsLoaded"
      error: (collection, response) => @trigger "postsLoadingError"

For some strange reason, when I try to trigger events using the beforeSend handler, events don't trigger. I can call any functions, but if any functions try to use @trigger "eventName", the event never fires in a way which I've been able to observe. In the example above, the console.log function works just fine, but the trigger fails.
Any ideas? The success and error handlers work splendidly.

A: You're calling fetch inside your initialize method so nothing will have a chance to bind to that collection before the events are triggered. The initialize method is called while an instance of your collection is being created and that means that you're calling fetch before the constructor returns, but you need an instance of the collection before you can bind to its events.
Consider something that looks more like this:
class Posts extends Backbone.Collection
  do_things: ->
    @fetch
      beforeSend: () =>
        console.log "about to fetch..."
        @trigger "postsLoading"
      success: (collection, response) =>
        debug "successfully loaded ajax"
        @trigger "postsLoaded"
      error: (collection, response) => @trigger "postsLoadingError"

Then if you do this:
p = new Posts
p.on('postsLoading', -> console.log('loading'))
p.do_things()

you will see that your postsLoading event is indeed triggered.
Demo: http://jsfiddle.net/ambiguous/PDeFg/
The moral of the story is simple:

Don't call fetch inside your constructor if you care about event listeners.


text:
Q: How do i make a layer PUSH layers below? im in the midst of building a website, and i ran into this structural problem and i think im going to need a little help here.
the basic structure is this :

you can check my website for more information if you need exact structure of my website :http://xestudio.xco.kr/ (it's safe from malware if your extension adblock blocks you from entering)
Now, the container is the main navigation div,
and the fluid_container is the image slider.
the body main is then of course the body.
I created this function that if i click on the toggle button,
it toggles the image slider to open and close. (if you click on the cog button on the leftside of my website, you can see the toggle switch)
what i was trying to make out of it originally is that when i click on the toggle button, it should completely hide the image slider and push the content upward so that the .body main takes the place of where the slider was.
But as you can see, all i see is white space that was underneath the image slider.
I think it's because the image slider and the .body main were overlapping each other in the first place.
Is there anyway I can make the slider take place in the document so that the image slider actually 'pushes' the .body main below?
and same goes to the menu bar (.container)
and here are the css codes.
.fluid_container {
margin: 0 auto;
width: 100%;
height: 400px;
transition: all 200ms ease-in-out;
}

.fluid_container.hide {
height: 0;
}

.body{background-color: #fff;
 position:relative;
padding:30px 0}

And the toggle switch function -

  <input id="cmn-toggle-1" class="cmn-toggle cmn-toggle-round"     type="checkbox" checked>


text:
Q: Drive mappings from login script do not work I have about Windows 2008 R2 Remote Desktop Servers in farm. To the best of my knowledge they are all have the same update status and they are also goverened by the same GPO. Among others, users logging in via RDP execute a login skript mylogin.cmd  that maps a drive I: unless for some individual reasons they already have such a drive:
if exist I:\*.* goto havei
eventcreate /ID 1 /L APPLICATION /T INFORMATION /SO LogOnOffDebug /D "Try Map I:"
NET USE I: \\myserver\myshare /persistent:no
eventcreate /ID 2 /L APPLICATION /T INFORMATION /SO LogOnOffDebug /D "errorlevel = %errorlevel%"
if exist I:\*.* goto havei
eventcreate /ID 3 /L APPLICATION /T WARNING /SO LogOnOffDebug /D "This is bad"
:havei

As you see, I already added some lines to debug the problem, and this is what I observe:
I find events 1 and 2 in Event Log, but not event 3. So apparently,

*

*the NET USE was executed because no I: files were seen,

*the command executed without error,

*and after execution I: is visible.

That is precisely what should happen and it does happen so on all farm members.
However, on two of the machines the users do not see drive I: in their sessions afterwrads! The same drive that was checked to be visible during login script execution just as on the other farm members! This looks to me as if the drives mapped during script execution are not "exported"(?) to the normal session. Simply executing the very same login script afterwards during their running session helps and gives them their drives, but this is of course not a suitable remedy.
What could even be the difference between the many good and the few bad servers that causes such behaviour? (I might add, that this phenomenon has crept up recently and had not existed for several years before - so something must have been done to the bad servers recently , but I have no idea what)

A: If your users have existing network connection to other devices, most likely this will also affect your script when it comes to mapping. You can try disconnect all existing mapped drives from the script first
Net Use * /delete

Then you add your new mapped drives commands.

A: I suggest this to solve this eitger by this two Options
Batch
Script 1;
net use Z:
if %errorlevel% EQU 0 net use I: /delete
net use I: \\path

Or, regardless map it every time again
Script 2
if exist i:\ (
    net use i: /delete
)
net use i: \\path

The other Option is to map via gpo
https://activedirectorypro.com/map-network-drives-with-group-policy/
I hope that this can fiy your issue
Since you did not told which serverfarm u use, ease Update US With more Informations. (sry cant comment yet)

A: if it's the script that start at logon of the user you could just put your batch in each server "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup " it will do the trick .
>

What could even be the difference between the many good and the few bad servers that >causes such behaviour? (I might add, that this phenomenon has crept up recently and had >not existed for several years before - so something must have been done to the bad >servers recently , but I have no idea what)

i personally got the same issue with a windows 2008R2 share in local network on local win 8.1 and 10 client they got the desktop services running but it was starting before the network one (as you imagine the share if persistent exist but with the red box, if not persistent i was simply not there because couldn't not connect with the net use cmdlet)
sorry for the typos or less than detailed name of the services couldn't find the right name of the services back in English (got my  win 2008R2 upgraded)


text:
Q: Evaluate integral over triangle with stokes' theorem The sides of a triangle $D$ are described by the intersections of plane $x + 3y + 4z = 6$ with the planes $x = 0, y = 0 $ and $z = 0$.

Determine the integral over the triangle $D$ using Stokes' theorem.
$\int_{\partial D}^{} \! -2y^2 dx+zdy +x dz \, =$
My question:
I know that Stokes' theorem is defined as $\int_{C}^{} \! F\cdot ds \, =\int_{}^{} \! \int_{S}^{} \! (\nabla \times F) \,   \, ds   $. But I dont understand what excatly is $F$ in my example?

A: Let me rewrite Stokes' theorem as
$$ \int_{D} \boldsymbol{\nabla \times F \cdot dS} = \oint_{\partial D} \boldsymbol{F \cdot dr}.  $$
In your case,
$$\boldsymbol{F \cdot dr} = -2y^2 dx + z dy + x dz = (-2y^2, z, x) \cdot (dx, dy, dz) $$
so $\boldsymbol{F}(x,y,z) = (-2y^2, z, x)$. Thus, in order to solve the question, you need to calculate $\boldsymbol{\nabla \times F}$ and then perform the surface integral of $\boldsymbol{\nabla \times F}$ over the (two-dimensional) triangle $D$.


text:
Q: How to create sticky table header and Freeze first two Columns in HTML Table Using CSS3 I am facing the issue on MUI data table.
scroll should be use of browser for vertical and horizontal scroll we can use table. when i am using the browser scroll with freez two column and sticky header so header does not sticky with browser scroll if anybody have any solution please give me.
sticky header with freez column.


text:
Q: Get Id from Array inside function I have an problem with an for loop in an LeafletJs map, for some reason i can't get it give me the correct Id from a array, instead it give me the last id on all clickevent's. Outside the $.get() the Id is displayed correct. But inside i just get the last in the Array. Are it possible to Exend the option to get an custom one ore are there other ways to do it.
for (var i = 0; i < myColumnDefs.length; i++) {
      var obj = myColumnDefs[i];
     // obj.id = i;
      var latitude = obj.GisLatitude.toFixed(5);
      var longitude = obj.GisLongitude.toFixed(5);

    //The correct id
      console.log(obj.Id);

      var m = L.marker([latitude, longitude], { icon: greenIcon }).on('click', function (e) {
        var markeren = this;
        debugger;

        $.get(ol.url('~/Map/MapContent/'), {id: m.id }, function(data) {
          L.popup()
        .setLatLng(markeren.getLatLng())
        .setContent(data)
        .openOn(map);
        });
      }).addTo(map);
      m.id = obj.Id;
      console.log('Latitude: '+latitude + ' - Longitude: ' + longitude);
    }

A: In success/error handler of $.get the context bound is of event.target and the loop you are iterating is long finished before the event handler is called. Hence, you get the last ID on click handlers.
log this @ var markeren = this; on the console. The context is what you require.
Again log markeren inside $.get and it will not be what you expected!
Bind the function context appropriately and your issue will go away.


text:
Q: Error adding cart item to database I'm writing a commerce application and am running into a frustrating error that doesn't tell me what the actual error is.

This is the code that is being run
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddToCart(int product_ID)
{
    if (db.Products.Any(product => product.Product_ID == product_ID))
    {
        //var successfulAddToCart = false;
        var cartItem = new Cart();

       // cartItem.CartID = Guid.NewGuid();

        if (Request.IsAuthenticated)
        {
            var Customer = db.Customers.FirstOrDefault(customer => customer.Email == User.Identity.Name);
            cartItem.Customer = Customer;
            cartItem.CustomerID = Customer.Customer_ID;
        }
        else//not logged in, need to remember them somehow
        {
            // add a cookie for a guest user so we can save their cart for some time.
            var CartCookie = new HttpCookie("Cart", Guid.NewGuid().ToString());
            CartCookie.Expires.AddDays(2);
            Request.Cookies.Add(CartCookie);
            cartItem.Customer = new Customer();
            cartItem.CustomerID = null;
        }

        //obviously not checked out since we just added to cart
        cartItem.IsCheckedOut = false;
        cartItem.Quantity = 1;
        //one to one with product, so grab the first sku you find.
        var Sku = db.SKU_Table.SingleOrDefault(sku => sku.Product_ID == product_ID);
        cartItem.Sku = Sku;
        cartItem.SkuID = Sku.SKU_ID;
        //if everything is okay, save the changes to the database
        if (ModelState.IsValid)
        {
            db.Cart.Add(cartItem);
            db.SaveChanges();
        }

        //return a content string that displays success or failure
        return Content("Add to cart was successful");
    }
    return Content("Add to cart was not successful");//unsuccessful add
}

Now as far as I can tell, my model is perfectly valid and I don't know what the source of the issue is. I can post values of the cart item object if that will be helpful. The error message doesn't really help and I don't see anything wrong with my modelstate, especially since it's passing.
Here is the cart model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace SeniorProjectMVC.Models
{
    [Table("Cart")]
    public class Cart
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }
        public Guid CartID { get; set; }
        public int SkuID { get; set; }
        public virtual Sku Sku { get; set; }
        [Required]
        public int Quantity { get; set; }
        public int? CustomerID { get; set; }
        public virtual Customer Customer { get; set; }
        public bool IsCheckedOut { get; set; }
    }
}

A: I can see that you've made CustomerID in model nullable but also Try making your Customer ID field Nullable in your Database as well or allow the Customer ID field to take null values.


text:
Q: Edit/Save Loses the "Edit Tags" Link Steps to reproduce:

*

*Browse to a question

*Mouse over to the right of the tags to confirm there is an "edit tags" link

*Click the "edit" link (not "edit tags")

*Click "Save edits"

*Mouse over to the right of the tags to confirm there is no longer an "edit tags" link

A: Thanks for bringing this up. I cannot reproduce this issue in the current build of our network sites. If it remains a problem please let me know.