text:
Q: Is HTML a context-free language? Reading some related questions made me think about the theoretical nature of HTML.
I'm not talking about XHTML-like code here. I'm talking about stuff like this crazy piece of markup, which is perfectly valid HTML(!)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html
<title//
<p ltr</span

</>

So given the enormous complexity that SGML injects here, is HTML a context-free language? Is it a formal language anyway? With a grammar?
What about HTML5?

I'm new to the concept of formal languages, so please bear with me. And yes, I have read the wikipedia article ;)

A: Context Free is a concept from language theory that has important implications in parser implementation. A Context Free Language can be described by a Context Free Grammar, which is one in which all rules have a single non-terminal symbol at the left of the arrow:
X→δ

That simple restriction allows X to be substituted by the right-hand side of the rules in which appears on the left without regard to what came before or after. For example, if while deriving or parsing one arrives at:
αXλ

one is sure that
αδλ

is also valid. Examples of non-context-free rules would be:
XY→δ
Xa→δ
aX→δ

Those would require knowing what could be derive arround X to determine if a rule applies, and that leads to non-determinism (what's around X would also like to know what it derives to), which is a no-no in parsing, and in any case we want a language to be well-defined.
The only way to prove that a language is context-free is by proving that there's a context-free grammar for it, which is not an easy task. Most programming languages one comes about are already described by CFGs, so the job is done. But there are other languages, including programming languages, that are described using logic or plain English, so work is required to find if they are context-free.
For HTML, the answer about its context-freedom is yes. SGML is a well defined Context Free Language, and HTML defined on top of it is also a CFL. Parsers and grammars for both languages abound on the Web. At any rate, that there exist LL(k) grammars for valid HTML is enough proof that the language is context-free, because LL is a proven subset of CF.
But the way HTML evolved over the life of the Web forced browsers to treat it as not that well defined. Modern Web browsers will go out of their way to try to render something sensible out of almost anything they find. The grammars they use are not CFGs, and the parsers are far more complex than the ones required for SGML/HTML.
HTML is defined at several levels.

*

*At the lexical level there are the rules for valid characters, identifiers, strings, and so on.

*At the next level is XML, which consists of the opening and closing <tags> that define a hierarchical document structure. You can use XML or something XML-like for any purpose, like Apache Ant does for build scripts.

*At the next level are the tags that are valid in HTML, and the rules about which tags may be nested within which tags.

*At the next level are the rules about which attributes are valid for which tags, languages that can be embedded in HTML like CSS and JavaScript.

*Finally, you have the semantic rules about what a given HTML document means.

The syntactic part is defined well enough that it can be verified. The semantic part is much larger than the syntactic one, and is defined in terms of browser actions regarding HTTP, and the Document Object Model (DOM), and how a model should be rendered to the screen.
In the end:

*

*Parsing correct HTML is extremely easy (it's context-free and LL/LR).

*Parsing the HTML that actually exists over the Web is difficult.

*Implementing the semantics (a browser) over HTML/CSS/DOM is extremely difficult.

A: HTML5 is different from previous HTML versions in that it strictly defines the parsing behaviour of code that isn't completely correct. Pre-HTML5 parsers vary and each do their best to 'guess' the intention of the code author.

A: Valid HTML is not a context-free language.
First of all, HTML being an application of SGML is fiction for all practical purposes, so analyzing SGML to answer the question is useless. (However, the SGML fiction probably isn't context-free, either.)
It's more useful to look at the actually defined HTML parsing algorithm. It works on two levels: tokenization and tree building. What HTML calls tokenization is a higher-level operation than what is usually called tokenization when talking about parsers. In the case of HTML, tokenization splits a stream of characters into units like start tags, end tags, comments and text. The tokenizer expands character references. Usually, when talking about parsers, you'd probably treat stuff like the less-than sign as "tokens" and would consider character references to consist of tokens instead of being resolved by the tokenizer.
If you consider the process of splitting the input stream into tokens, that level of the HTML language is regular (except for feedback from the tree builder).
However, there are three complications: The first one is that splitting the input stream into tokens is just the first and then there's the tree builder's side that actually cares about the identifiers in the tokens. The second one is that the tree builder feeds back into the tokenizer so that some state transitions made by the tokenizer depend on the state of the tree builder! The third one is that valid documents in the language are defined by rules that apply to the output of the tree builder stage and those rules are complex enough that they can't be fully defined using tree automata (as evidenced by RELAX NG not being expressive enough to describe all the validity constraints).
This isn't an actual proof, but you can probably develop real proofs by working from complications #2 and #3.
Note that the case of invalid documents is not particularly interesting as a question of whether the language is context-free in the sense of there being a context-free grammar that generates all the possible strings with no regard to the parse tree having some intelligible interpretation in terms of the tree that an HTML parser generates. The HTML parser will successfully consume all possible strings, so in that sense, all possible strings are in the "invalid HTML" language.
Edit: Interesting questions left as exercise to the reader:
Is HTML without parse errors but ignoring validity a context-free language?
Is HTML without parse errors and ignoring general validity but with only valid element names allowed a context-free language?
(Complication #2 applies in both cases.)

A: NO
See Edit Below
It depends.
If you are talking about the subset consisting of only theoretical HTML, then yes.
If you also include real life, working HTML that is accessed and used successfully by millions of people daily on many of the top sites on the internet then NO.
That is what gives HTML flexibility.  The parsing engine adds tags, closes tags, and takes care of stuff that a theoretical CFG can't do.  If you took automata you might remember that a production rule in a formal grammar cannot be empty (aka epsilon/lambda) on the lhs (left-hand side).  Since the parsing engine is basically using knowledge that a formal grammar and automata couldn't have, it isn't restricted by that and the 'grammar' would have epsilon/lambda -> result where the specific epsilon/lambda rule is chosen based on information not available in the grammar.
Since I don't think empty lhs are allowed in any formal grammars, HTML cannot be defined by a formal grammar and is not a formal language at all.
Sure, HTML5 might try to move towards a 'more formal' language description but the likelihood that it becomes a context free language in reality (i.e. strings not matched by the grammar are rejected) is about the likelihood XHTML 2.0 takes the world by storm and replaces HTML altogether (XHTML is the attempt they made to make HTML a formal language...it was rejected en masse due to its fragility).
Noteworthy is the fact that HTML 5 is the FIRST HTML standard to be defined before being implemented!  That's right, HTML 1-4 consist of random ideas someone just implemented in a browser, and were collected into standards after the fact based on which features were popularly used and widely implemented.  Then they tried XHTML, which totally failed to be adopted.  Even 'xhtml' on the web is automatically parsed as HTML under almost every circumstance to prevent stuff from just breaking with a cryptic syntax error.  Now you can see how we got here and why it is unlikely to be formalized any time soon.
Lesson:  "In theory, there is no difference between theory and practice.  In practice, there is." - Yogi Berra
EDIT:
Actually, after reading through the documents it turns out that HTML, even according to the HTML 4.01 specification, doesn't actually conform to SGML.  To see for yourself, view the HTML 4.01 Strict document type definition (doctype) at http://www.w3.org/TR/html4/strict.dtd and note the following lines:

The HTML 4.01 specification includes additional
      syntactic constraints that cannot be expressed within
      the DTDs.

So I would say that it is probably not a CFL due to those features (although it technically it doesn't disprove the hypothesis that there is some possible PDA that accepts HTML 4.01, it does prevent the argument that SGML is a CFL therefore HTML is a CFL).
HTML5 flip-flops, abandoning any implied conformance to SGML, but is presumably describable by a CFG.  However it will still provide best-effort parsing not based on a cfg, so IMO the current situation (i.e. language specification is defined formally, with invalid strings still being accepted, parsed and rendered in a best effort fashion) in this regard is unlikely to change drastically for a long, long, long time.


text:
Q: numpy np.array only returns the first value when asked name.shape I have a question:
I got DICOM files, 171 of them in a directory. I turned them into pixel arrays and put them in a list with this code:
display = []
path = "./path/*.dcm"
for f in glob.iglob(path):
    medical_image = pydicom.dcmread(f)   #pydicom reads the file in f and send it to medical_image
    image = medical_image.pixel_array.astype(float) #turn them one by one into pixel arrays (float)
    display.append(medical_image) #append them to the list

ok, so to confirm that it was really getting the files, I typed a
len(display)

that returned 171, so it's ok
Then, I did
display = display.np.array(display)

to convert the list into a numpy arry so I could see the files, but turns out that I couldn't and when I type .shape it only returns (171,) and I didn't understand why.
I think that if I could see the other variables it would work to display with Matplotlib. Am I right?

A: and thanks for the comments:
@hpaulj and @Pranav Hosangadi
I got the answer:
    folder = './path/'
    imgs = [pydicom.read_file(folder + '/' + s) for s in os.listdir(folder)]
    data = np.stack([i.pixel_array for i in imgs])

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to install prawn gem in rails 3.0.0 I am using rails 3.0.0. I tried to install prawn gem. but i don't know how to install. Please help me to install that gem.

A: You should use the *prawn_rails* gem. You just include it in your Gemfile like this:
gem 'prawn_rails'

and then run bundle install. Take a look at the readme section here: https://github.com/Whoops/prawn-rails


text:
Q: Div to set in center not working On this site deutschepornohd.com is a div element of post:

and I want to make it centered on every screen width, especially in mobile.
I set to it perent div:

text-align:center!important;

but on small screens where it must show only two or one such div, it is not centered. Is it possible to make it centered?

A: Try this:
margin-left:auto; margin-right:auto;


text:
Q: I want to click on tkinter entry to bind even to return three difference values to entry I want to click on tkinter entry to change it's value to three values on each click, Present, Leave, Absent, means how event function will return difference values each time , on first click, Present, next click Absent, next click Leave, and then back Present
I will be vary thankful for your kind support :)

A: I can't figure out any better method. I hope it's good enough. If it's not what you are expecting, let me know in the comment (I'm not sure if I understood you correctly).
import tkinter as tk

def handle_click(event):
    if entry.get() == '':
        entry.delete(0, tk.END)
        entry.insert(0, 'Present')
    elif entry.get() == 'Present':
        entry.delete(0, tk.END)
        entry.insert(0, 'Leave')
    elif entry.get() == 'Leave':
        entry.delete(0, tk.END)
        entry.insert(0, 'Absent')
    elif entry.get() == 'Absent':
        entry.delete(0, tk.END)
        entry.insert(0, '')

    print(event)

root = tk.Tk()
root.geometry('500x500')
entry = tk.Entry(root, width=50)
entry.grid(row=0, column=0, padx=5, pady=5)
entry.bind("<1>", handle_click)

root.mainloop()

A: You can use cycle() from itertools module and next() function to cycle the three values and bind <Button-1> event to change the content of the Entry:
import tkinter as tk
from itertools import cycle

values = cycle(('Present', 'Leave', 'Absent'))

root = tk.Tk()

e_var = tk.StringVar()
# create a Entry that can be changed via mouse click only
entry = tk.Entry(root, textvariable=e_var, state='disabled', disabledforeground='black')
entry.pack()
# bind mouse left click to update the Entry from the cycle list
entry.bind('<Button-1>', lambda e: e_var.set(next(values)))

root.mainloop()


text:
Q: switch case loop with onListItemClick I have a listview, and can start activities with onListItemClick using switch cases manually:
case 0: case 1: case 2: .......
but I want to get count of  listview items dynamicly, and use them like case loop : case i++ .I it possible ?
what I want to make:
...
    setListAdapter(adapter);

      @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
                super.onListItemClick(l, v, position, id);

                final int index = position;
                switch (position) {
                for (int i=0; i< l.getCount(); i++){
                case i:
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), Activity.class);
                    startActivity(intent);
                    break;
                }
    }

A: If you want to call same class on each item click then you dont need for loop.Just pass the intent onItemClickListener() its done.And if you want to pass different classes according to ItemClick then I think everytime you have to check for the position and pass the Intent according to Position.


text:
Q: Type casting pointer when writing to binary file in C++ Today in CS 111 class my instructor ended with a 'brief' look at writing structures to binary files. I say brief because he just included it as a kind of aside, saying it would not be on the final. Problem is, I don't fully understand what's going on in the program example and it is bothering me. Hopefully somebody will take the time to explain it to me. The code is as follows:
#include <iostream>
#include <fstream>
using namespace std;

struct PayStub
{
    int id_num;
    bool overtime;
    float hourly_rate;
};

int main()
{
    PayStub info = {1234, false, 15.45};

    ofstream data_store;

    data_store.open("test.cs111", ios::binary);

    char *raw_data = (char*)&info;
    data_store.write(raw_data, sizeof(PayStub));

    data_store.close();

    return 0;

}

I don't understand what is going on specifically in the statement char *raw_data = (char*)&info; and why it is necessary. I understand a pointer to a char is being declared and initialized, but what exactly is it being initialized to, and how is that being used in the next line?
I hope this isn't a stupid question. Thanks in advance for your help.

A: char *raw_data = (char*)&info; after this line, raw_data will point to the address of the first byte of info.
With data_store.write(raw_data, sizeof(PayStub)); we ask data_store to write  to the file the contents in memory that start at raw_data and end at raw_data + sizeof(PayStub)).
In essence we find the start address and length of PayStub and write it to disk.
It is not a stupid question. Once you read up on pointers, everything will make sense.

A: Think of a struct (in plain C) to simply be a way of binding a bunch of objects together with "string".
An int could be represented in memory with 4 bytes. A struct composed of two ints would be 8 bytes, one int next to the other.
In your example code, &info returns the pointer to the beginning of the object in memory, and (char*)&info simply interprets as a pointer to a character instead, so it can be treated as a sequence of binary data. sizeof returns how much memory (in bytes) the struct takes, and with this information the structure is then written directly to a file from memory.
Keep in mind this type of data storage is absolutely not portable. It might vary from a 32-bit to a 64-bit computer!


text:
Q: How to parse JSONArray which is in another JSONArray I am trying to parse a JSONObject.
This JSONObject has a JSONArray in it, and it has another JSONArray inside of JSONArray.
The json form that I am trying to parse is as below.
{
    "phone":"01029093199",
    "store_id":"1",
    "orders":[
        {
            "menu_id":"4",
            "menu_defaultprice":"1500",
            "extraorders":[
                {
                    "extra_id":"1",
                    "extra_price":"0",
                    "extra_count":"1"
                },
                {
                    "extra_id":"38",
                    "extra_price":"300",
                    "extra_count":"2"
                }
            ]
        },
        {
            "menu_id":"4",
            "menu_defaultprice":"1500",
            "extraorders":[
                {
                    "extra_id":"2",
                    "extra_price":"0",
                    "extra_count":"1"
                },
                {
                    "extra_id":"19",
                    "extra_price":"500",
                    "extra_count":"1"
                }
            ]
        },
        {
            "menu_id":"6",
            "menu_defaultprice":"2000",
            "extraorders":[
                {
                    "extra_id":"6",
                    "extra_price":"0",
                    "extra_count":"1"
                },
                {
                    "extra_id":"21",
                    "extra_price":"500",
                    "extra_count":"1"
                },
                {
                    "extra_id":"41",
                    "extra_price":"300",
                    "extra_count":"1"
                }
            ]
        }
    ]
}

The code below is what I have tried before.
@RestController
public class OrderApiController {

    private OrderService orderService;

    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    @PostMapping("/OrderInsert.do")
    public void insertOrder(@RequestBody JSONObject jsonObject) {
        JSONParser jsonParser = new JSONParser();

        System.out.println(jsonObject);
        System.out.println(jsonObject.get("phone")); // phone 가져오기 성공
        System.out.println(jsonObject.get("store_id"));  // store_id 가져오기 성공
        System.out.println("==========JSONArray Parsing start=========");
        ArrayList<JSONArray> jsonArrayList = (ArrayList<JSONArray>)jsonObject.get("orders");
        for(int i = 0; i < jsonArrayList.size(); i++) {
            System.out.println(jsonArrayList.get(i));  // SUCCESS

            String temp = jsonArrayList.get(i).toJSONString(); // WHERE ERROR HAPPENS
            System.out.println(temp);

            // Tried below code to remove "[", "]" from JSONArray, but not working.
            // Error message was same as the message shown from line 37.
            //String jsonString = temp.substring(1, temp.length()-1);
            //System.out.println(jsonString);

            // org.json.JSONObject jTemp = new org.json.JSONObject(jsonArrayList.get(i));
            // System.out.println(jTemp);  --> prints {} (empty JSONObject)
            // System.out.println("menu_id : " + jTemp.getInt("menu_id")); // Not Working
        }
    }
}

The error shown is ..
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.json.simple.JSONArray

Additionally, I am using this json module dependency.
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20200518</version>
</dependency>

I knew that if I print something on console using System.out.println(OBJECT), the OBJECT's toString()
method is called. So I tried to call toString() , and that gave me the ClassCastException exception.

A: Error is in fact at ArrayList<JSONArray> jsonArrayList = (ArrayList<JSONArray>)jsonObject.get("orders");
Instead of casting JSONArray to ArrayList, you can traverse JSONArray and read its attributes. Your code can be changed something like.
    @PostMapping("/OrderInsert.do")
    public void insertOrder(@RequestBody JSONObject jsonObject) {
        System.out.println(jsonObject);
        System.out.println(jsonObject.get("phone")); // phone 가져오기 성공
        System.out.println(jsonObject.get("store_id"));  // store_id 가져오기 성공
        System.out.println("==========JSONArray Parsing start=========");
        JSONArray orders = jsonObject.getJSONArray("orders");
        for(int i = 0; i < orders.length(); i++) {
            System.out.println(orders.get(i));  // SUCCESS

            String temp = orders.get(i).toString();
            System.out.println(temp);

            // Travserse further json
            JSONObject order = orders.getJSONObject(i);
            System.out.println(order.get("menu_defaultprice"));
            System.out.println(order.get("menu_id"));
            JSONArray extraorders = order.getJSONArray("extraorders");
            for(int j = 0; j < extraorders.length(); j++) {
                JSONObject extraOrder = extraorders.getJSONObject(j);
                System.out.println(extraOrder.get("extra_id"));
                System.out.println(extraOrder.get("extra_price"));
                System.out.println(extraOrder.get("extra_count"));
            }
        }
    }

A: You are incorrectly fetching the orders. It should be stored in JSONArray, and NOT ArrayList
Replace:
ArrayList<JSONArray> jsonArrayList = (ArrayList<JSONArray>)jsonObject.get("orders");

With:
JSONArray jsonArrayList = jsonObject.getJSONArray("orders");

Now, you can iterate JSONArray like this
for(int i = 0; i < jsonArrayList.length(); i++) {
   System.out.println(jsonArrayList.get(i));  // SUCCESS

   String temp = jsonArrayList.get(i).toJSONString();
   System.out.println(temp);
}


text:
Q: How to call public method jquery plugin from outside? I read a lot about it but what i undertand is not working.
I'm using this jquery plugin boilerplate.
i have a plugin called "defaultPluginName" and  i have a public method inside plugin:
sayHey: function(){
  alert('Hey!');
}

i want call this method outsise, something like that:
$('#test').defaultPluginName('sayHey');

but is not working, follow here a fidle link to give you a better view about my issue:
http://jsfiddle.net/TCxWj/

A: The method your are trying to call is not public so you need to alter your plugin in order to trigger it from outside the plugin.
See here how you can do that: https://github.com/jquery-boilerplate/jquery-boilerplate/wiki/Another-extending-jQuery-boilerplate.
Basically you need to change
$.fn[ pluginName ] = function ( options ) {
    return this.each(function() {
        if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
        }
     });
};

To
 $.fn[pluginName] = function ( arg ) {
    var args, instance;

    // only allow the plugin to be instantiated once
    if (!( this.data( 'plugin_' + pluginName ) instanceof Plugin )) {

        // if no instance, create one
        this.data( 'plugin_' + pluginName, new Plugin( this ) );
    }

    instance = this.data( 'plugin_' + pluginName );

    /*
     * because this boilerplate support multiple elements
     * using same Plugin instance, so element should set here
     */
    instance.element = this;

    // Is the first parameter an object (arg), or was omitted,
    // call Plugin.init( arg )
    if (typeof arg === 'undefined' || typeof arg === 'object') {

        if ( typeof instance['init'] === 'function' ) {
            instance.init( arg );
        }

    // checks that the requested public method exists
    } else if ( typeof arg === 'string' && typeof instance[arg] === 'function' ) {

        // copy arguments & remove function name
        args = Array.prototype.slice.call( arguments, 1 );

        // call the method
        return instance[arg].apply( instance, args );

    } else {

        $.error('Method ' + arg + ' does not exist on jQuery.' + pluginName);

    }

};

Then it will pick up your method.
Hope it helps.


text:
Q: IOException that when I try to catch says will never be thrown? This is my code:
    @Override
    public void start(Stage primaryStage) throws FileNotFoundException {
        System.out.print("Url gui successfully started.");
        final HBox hBox = new HBox();
        hBox.setSpacing(5);

        final TextField urlTextField = new TextField();
        urlTextField.setPromptText("Type Url Here");
        Button unblock = new Button("Unblock");
        Button block = new Button("Block");

        String hostsFile = BlockAndUnblock.getHostsFile();
        String blockedUrls = BlockAndUnblock.getBlockedUrls();
        boolean inSession = InSession.inSession > 0;
        try {
            unblock.setOnAction(event -> BlockAndUnblock.blockSite(hostsFile,blockedUrls,urlTextField.getText(), inSession));
            block.setOnAction(event -> BlockAndUnblock.unBlockSite(hostsFile,blockedUrls,urlTextField.getText(), inSession));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("You encountered an IOException when trying to initiate the block and unblock buttons.");
        }

        ArrayList<String> urls = new ArrayList<String>();
        urls = readUrls();
        ListView listView = new ListView();
        listView.setId("Listview");
        for (String s: urls) {
            listView.getItems().add(s);
        }

        hBox.getChildren().add(listView);
        hBox.getChildren().add(urlTextField);
        hBox.getChildren().add(block);
        hBox.getChildren().add(unblock);
        hBox.setAlignment(Pos.CENTER_LEFT);
        hBox.setId("Urls");

        Scene scene = new Scene(hBox, 750, 500);
        scene.getStylesheets().addAll(this.getClass().getResource("../style.css").toExternalForm());
        primaryStage.setTitle("Urls");
        primaryStage.setScene(scene);

        primaryStage.show();
    }

The block and unblock methods it calls are these:
    public static void unBlockSite(String hostsFile, String blockedUrls, String url, boolean inSession) throws IOException {
        String file = Files.readString(Paths.get(hostsFile));
        file = file.replace("0.0.0.0 " + url.substring(url.indexOf("//") + 2,url.length()-1) +"\n","");
        file = file.replace("::0 " + url.substring(url.indexOf("//") + 2,url.length()-1) +"\n","");
        Files.writeString(Paths.get(blockedUrls), file, StandardOpenOption.TRUNCATE_EXISTING);
        if (inSession) {
            unBlock(hostsFile);
            block(hostsFile, blockedUrls);
        }
    }
    public static void blockSite(String hostsFile, String blockedUrls, String url, boolean inSession) throws IOException {
        if (inSession) unBlock(hostsFile);
        Files.writeString(Paths.get(blockedUrls), "0.0.0.0 " + url.substring(url.indexOf("//") + 2,url.length()-1) +"\n", StandardOpenOption.APPEND);
        Files.writeString(Paths.get(blockedUrls), "::0 " + url.substring(url.indexOf("//") + 2,url.length()-1) +"\n", StandardOpenOption.APPEND);
        if (inSession) block(hostsFile, blockedUrls);
    }

This is the error I'm getting:

site\java\BlockUrlsMenu.java:37: error: unreported exception IOException; must be caught or declared to be thrown
unblock.setOnAction(event -> BlockAndUnblock.blockSite(hostsFile,blockedUrls,urlTextField.getText(), inSession));
^

site\java\BlockUrlsMenu.java:38: error: unreported exception IOException; must be caught or declared to be thrown
block.setOnAction(event -> BlockAndUnblock.unBlockSite(hostsFile,blockedUrls,urlTextField.getText(), inSession));
^

site\java\BlockUrlsMenu.java:39: error: exception IOException is never thrown in body of corresponding try statement
} catch (IOException e) {
^

3 errors

What confuses me is that apparently BlockAndUnblock require me to catch or throw the IOException beforehand, but when I surround them in a try{} catch{} method it says they'll never throw an IOException. I also tried putting all the content of the start() method into a try{} catch{} block and it still gave me the first two errors.
Why is it telling me to catch an IOException and then saying it won't throw one?
Thanks for the help, I know this is a lot of code to go over.

A: It's a lot of code so my analysis may be superficial, but I think it happens because .setOnAction() takes a Lambda expression.
Lambdas can't throw checked exceptions like IOException (hence the catch block becomes invalid and you get the third error, since the two lambdas can't actually throw), but at the same time your lambdas are calling two functions which throw themselves an IOException and you're not catching them inside the lambda (so you get the first and second error).
Try to change this:
try {
    unblock.setOnAction(event - > BlockAndUnblock.blockSite(hostsFile, blockedUrls, urlTextField.getText(), inSession));
    block.setOnAction(event - > BlockAndUnblock.unBlockSite(hostsFile, blockedUrls, urlTextField.getText(), inSession));
} catch (IOException e) {
    e.printStackTrace();
    System.out.println("You encountered an IOException when trying to initiate the block and unblock buttons.");
}

... into this:
try {
    unblock.setOnAction(event - > {
            try {
                BlockAndUnblock.blockSite(hostsFile, blockedUrls, urlTextField.getText(), inSession));
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    block.setOnAction(event - > {
            try {
                BlockAndUnblock.unBlockSite(hostsFile, blockedUrls, urlTextField.getText(), inSession));
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
} catch (RuntimeException e) {
    e.printStackTrace();
    System.out.println("You encountered an IOException when trying to initiate the block and unblock buttons.");
}

With the above, inside each lambda you catch IOException and you wrap it inside a RuntimeException (which is unchecked so can be thrown by the lambda).
In the outer catch, you catch the RuntimeException and do whatever you wanted to do initially with the IOException


text:
Q: run SIFT on every image in a folder and store descriptors I'm trying to get descriptors for every image in a folder and store them. I want to be able to use them with vl_kmeans so I can cluster them and then build histograms based on the number of visual words for every image.
Here's the code i have so far, but descrs gives me back an empty matrix.
conf.dataDir = 'data\Samples' ;
N_WORDS = 400;

images = {} ;
filelist = dir(fullfile(conf.dataDir, '*.jpg'));
descrs = {} ;
parfor i=1:(size(filelist,1)-100)
    fname = filelist(i).name;
    images=imread(fname);
    [F, descrs{i}] = vl_dsift(single(images(i)),'Step', 10, 'Fast');
    descrs{i} = single(descrs{i});
end

A: I had a lot of mistakes, found them out and fixed them. Here's the code:
conf.dataDir = 'data\Samples' ;
N_WORDS = 400;

images = {};
filelist = dir(fullfile(conf.dataDir, '*.jpg'));
descrs = {};
parfor i=1:(size(filelist,1)-100)
    fname = filelist(i).name;
    images{i} = single(rgb2gray(imread(fname))) ;
    [f{i}, d{i}] = vl_dsift(images{i},'Step', 10, 'Fast');
end


text:
Q: 2 is not a valid direct i/o file descriptor resources php We are trying to read and write from RFID using php, currenctly we are able to set things such as baudrate and pirity but unable to write to RFID nor read from RFID
Below is my php code :
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
{
    echo "hi Windows/n";
    $bbSerialPort = dio_open($portName, O_RDWR);

    if($bbSerialPort){
        dio_close($bbSerialPort);
    }

    exec("mode {$portName} baud={$baudRate} data={$bits} stop={$spotBit} parity=n xon=on");
    $bbSerialPort;
    echo '/nsuccessfull exec';
}

if(!$bbSerialPort)
{
    echoFlush( "Could not open Serial port {$portName} ");
    exit;
}

$dataToReboot = pack("H*","0205F08A7E");
$bytesSent    = dio_write($bbSerialPort, $dataToReboot );

$runForSeconds = new DateInterval("PT5S"); //5 seconds
$endTime = (new DateTime())->add($runForSeconds);
echoFlush(  "Waiting for {$runForSeconds->format('%S')} seconds to recieve data on serial port" );

while (new DateTime() < $endTime) {

    $data = dio_read($bbSerialPort, 256); //this is a blocking call
    echo "<br>"."number";
    if ($data) {
        echoFlush(  "Data Recieved: ". $data );

    }
}
echoFlush(  "Closing Port" );

dio_close($bbSerialPort);

A: You're calling dio_close on $bbSerialPort at the top of the script. Meaning, you're closing the connection to the RFID. You can't send it a message after closing the connection.


text:
Q: Duplicate input unix stream to multiple TCP clients (using socat) I have a syslog server which writes to a unix stream /tmp/syslog.socket.
I need to duplicate this stream to multiple TCP clients. Is there a way to achieve this using socat?

A: I think I just accomplished this, especially the duplicating part, with the help of Some Helpful socat Commands.
socat TCP-LISTEN:4444,reuseaddr,fork SYSTEM:"tail -f ~/.tail-error-logs/*",pty

fork is important on the left side, pty is important on the right side.
What didn't work, was netcat style:
tail -f ~/.tail-error-logs/* | socat STDIO TCP-LISTEN:4444,fork,reuseaddr

It had the effect of output alternating between multiple attached clients, which is also documented on above website.

A: syslogd has a facility for redistributing the logs via udp, see the man page for syslogd, ie
http://linux.about.com/od/commands/l/blcmdl8_syslogd.htm
I believe that syslog-ng also supports tcp sockets for log redistrubution as well as udp
http://www.syslog.org/syslog-ng/v2/
I would guess that you don't need a hack with socat?


text:
Q: How to do single-bit bitwise logic operation in C Basically, I want to do single-bit bitwise logic operation in C that is basically binary boolean algebra. But it seems that in C,
unsigned int a = 0;
unsigned int c = ~a;

results in variable c exploding.
What should I do?
Edit: I just realized that ~ Was the problem. My intention is, basically making inverting a single bit.

A: $ cat pru.c
#include <stdio.h>
int
main()
{
    unsigned int a = 0;
    unsigned int b = 1;
    unsigned int c = a | b;

    printf("a = %u; b = %u; c = %u\n", a, b, c);
} /* main */

$ pru
a = 0; b = 1; c = 1


text:
Q: How do I retrive 1st value of group Id from Json I have my data coming as below
[
  {
    "GroupID": 1,
    "Title": "Group Name"
  },
  {
    "GroupID": 3,
    "Title": "Group Name 1"
  },
  {
    "GroupID": 10,
    "Title": "group Name 10"
  },
  {
    "GroupID": 12,
    "Title": "Group Name 11"
  },
  {
    "GroupID": 13,
    "Title": "Group Name 12"
  },
  {
    "GroupID": 5,
    "Title": "Group Name 3"
  },
  {
    "GroupID": 6,
    "Title": "Group Name 4"
  },
  {
    "GroupID": 7,
    "Title": "Group Name 7"
  },
  {
    "GroupID": 8,
    "Title": "Group Name 8"
  },
  {
    "GroupID": 9,
    "Title": "Group name 9"
  }
]

from below code
$.ajax({
        url: '/Property/GetGroup',
        type: 'GET', // You can use GET
        data: '{}',
        dataType: "json",
        context: this,
        success: function (data) {
            //$('#GroupDropdown').empty().append('<option selected="selected" value="">Please select</option>');
            //console.log(res);
            $.each($.parseJSON(data), function (key, item) {
                $('#GroupDropdown').append(
                    $("<option></option>")
                      .attr("value", item.GroupID)
                      .text(item.Title)
                      );
            });
            alert(data.item[0].GroupID);
            alert(GroupID);
            //$('#SubGroupDropdown').empty().append('<option selected="selected" value="">Please select</option>');
        },
        error: function (request) {
            console.log(request);
            // alert("Some error");
        }
    });

over there I am trying putting alert(data.item[0].GroupID);
                alert(GroupID); to get the 1st value of groupid as value 1.
How should I get it?

A: Try data[0].GroupID .Because data is an array not an object.And also you are calling the value out of the each function, so no need add item .And parse the json data with some variable.You could call object from the variable
$.ajax({
        url: '/Property/GetGroup',
        type: 'GET', // You can use GET
        data: '{}',
        dataType: "json",
        context: this,
        success: function (data) {
            //$('#GroupDropdown').empty().append('<option selected="selected" value="">Please select</option>');
            //console.log(res);
            var datas = $.parseJSON(data); //parsing json
            $.each(datas, function (key, item) {
                $('#GroupDropdown').append(
                    $("<option></option>")
                      .attr("value", item.GroupID)
                      .text(item.Title)
                      );
            });
            alert(datas[0].GroupID);

            //$('#SubGroupDropdown').empty().append('<option selected="selected" value="">Please select</option>');
        },
        error: function (request) {
            console.log(request);
            // alert("Some error");
        }
    });


text:
Q: How to prompt Date and Time and then alert with that date and time minus 40 minutes I am doing work for a class and the question is asking us to prompt the user for their flight departure date, then the next prompt asks the user to enter the departure time, and then we need an alert telling them the last possible time of check-in (40 minutes before).
I've got the prompts and alert to work but I am struggling to find a way to minus the 40 minutes. I have tried using the get function but I don't know if it's incorrect or if I'm doing it wrong.

var day = prompt("When is your departure date? (eg. 2019-10-12):", "2019-10-12");

var tim = prompt("When is your departure time? (eg. 10:30):", "10:30");

var time = tim - 40;
var check = alert("The check in counter closes:" + day + " " + time);

I know that the time should show as 40 minutes before but If the flight leaves at 00:30 I don't know how to make it use the previous date and 23:50.

A: You can create a new Date() object with the first prompt return, then set hour and minute of this object with the second prompt value.
Then compute the time difference like so :
let diff_ms = Date.now() - (new Date(<promptvalue...>).now());

and check if the diff is under 40 mn assuming diff is in ms :
let fortyMn_ms = 1000 * 60 * 40;
if(diff_ms < fortyMn_ms) { /*... */ }

A: Convert your strings to a Date() and then do: date.setMinutes(date.getMinutes() - 40) and convert back to a string to print.
Example:

var day = prompt("When is your departure date? (eg. 2019-10-12):", "2019-10-12");

var tim = prompt("When is your departure time? (eg. 10:30):", "10:30");

let date = new Date(day + 'T' + tim);
date.setMinutes(date.getMinutes() - 40);

let formatted_date = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes();

var check = alert("The check in counter closes: " + formatted_date);


text:
Q: How to fix to use TLS 1.2 I am using Windows 10, Visual Studio 2017, .Net 4.7.
And using DocuSign SOAP APIs to send an envelope. My code is using .NET 4.7 - checked in web.config and confirmed in project properties > Application tab.
And yet, I keep getting the error from DocuSign that I need to use TLS 1.2 and that I am using TLS 1.
What else can I do to fix this?

A: You can always force the TLS version yourself with:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

However, this shouldn't be necessary under .NET Framework 4.7.  TLS 1.2 is the default.
See also this blog post from Docusign.


text:
Q: KnockoutJS - Assign Observable value to JavaScript variable I am trying to see if I can assign a JavaScript variable to the value of a value of a KO Observable.
The reason for this is I want to assign it to a jquery module, as a property.
I know I can do:
    var viewModel = {
    firstName : ko.observable("Bert"),
    lastName : ko.observable("Smith"),
    pets : ko.observableArray(["Cat", "Dog", "Fish"]),
    type : "Customer"
};
viewModel.hasALotOfPets = ko.computed(function() {
    return this.pets().length > 2
}, viewModel)

var jsonData = ko.toJSON(viewModel);

But, what if I don't want everything that is in the view model?  Can i just only select n number of items?

A: There two concepts here:

*

*Retrieving the object from a Knockout observable

*Manipulating a JavaScript array

Code:
var start = 1; // index of Dog
var n = 1; // just one item
var jsonData = ko.toJSON(viewModel.pets().slice(start, start + n));

In Knockout, observables are functions. To set its value you call it with a parameter. To get its value, you call it.
JavaScript arrays have a slice function that can be used to get a smaller array.
UPDATE based on comments on the question:
If you want to take n fields from viewModel, ko.toJSON will work on a subsetted view model:
var n = 2;
var count = 0;
var subModel = {};
for (var k in viewModel) {
    if (count >= n) break;
    if (viewModel.hasOwnProperty(k)) {
        subModel[k] = viewModel[k];
        count++;
    }
}

var jsonData = ko.toJSON(subModel);

If you want specific fields only, create a subsetted model with those:
var jsonData = ko.toJSON({
    firstName: viewModel.firstName,
    type: viewModel.type
});


text:
Q: Ubuntu server, PHP - Apache: Permission Denied I've done a server, but I'm receiving a bad message when I try to create a php file in "/var/www/html". It says: permission denied.
I've looked for a solution, but I don't want make "myuser" permission like "root" amd I have also read that it is a bad practice.
I've tried, with PHPStorm, to access to the server with SFTP, but in the end I however can't upload a file or create it.
Thank you before!

A: By default the owner of the files within /var/www/html is the www:data group. All you have to do is add your self to the www-data group.
sudo adduser <username> www-data
sudo chown -R www-data:www-data /var/www

The first line adds you to the www-data group, the second line clears up any files with messed up ownership.
See more about best practices here https://askubuntu.com/questions/46331/how-to-avoid-using-sudo-when-working-in-var-www
Hope this helps!


text:
Q: How to view thumbnail in Android jiecao video player I'm a beginner in Android development. I want to add a thumbnail for my video player. I'm using Android jiecao video player in my android app. With that player, I want to add a drawable image for the starting screen of the jiecao players, but there are no methods to add a thumbnail as an Android drawable image.
This is my code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:padding="10dp">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fillViewport="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello world"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard
                    android:id="@+id/videoplayer"
                    android:layout_width="match_parent"
                    android:layout_height="200dp" />

            </LinearLayout>

        </LinearLayout>

    </ScrollView>
</LinearLayout>

MainActivity.java
package com.example.theace.bestvedioplayer;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

public class MainActivity extends AppCompatActivity {

    private JCVideoPlayerStandard jcVideoPlayerStandard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initUi();
    }

    public void initUi(){

        jcVideoPlayerStandard = (JCVideoPlayerStandard) findViewById(R.id.videoplayer);
        jcVideoPlayerStandard.setUp("http://2449.vod.myqcloud.com/2449_22ca37a6ea9011e5acaaf51d105342e3.f20.mp4", JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, "");

    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }
    @Override
    protected void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
    }
}


text:
Q: React Native: Why does a valid Javascript regex pattern not work on Android? Here is a regex:
const pattern = /\d+\s*\.\s*((.+?\n)+?(?=[aA]\)))/;
const str = `8. X-XIII asrlarda barpo etilgan inshootlar to'g'ri berilgan qatorni aniqlang.
1) Ismoil Somoniy maqbarasi, 2) Masjidi Kalon,
3) Namozgoh, 4) Minorayi Kalon, 5) Vobkent minorasi, 6) Ahmad Yassaviy maqbarasi, 7) Jarqo'rg'on minorasi, 8) Kaltaminor.
A) 1, 2, 3, 6, 7
B) 1, 3, 4, 5, 7
C) 1, 2, 4, 6, 8
D) 2, 3, 4, 6, 7`

const m = pattern.exec(str);
console.log(m) // outputs null when run on Android

Here is the exact same thing running on a browser console:

const pattern = /\d+\s*\.\s*((.+?\n)+?(?=[aA]\)))/;
const str = `8. X-XIII asrlarda barpo etilgan inshootlar to'g'ri berilgan qatorni aniqlang.
1) Ismoil Somoniy maqbarasi, 2) Masjidi Kalon,
3) Namozgoh, 4) Minorayi Kalon, 5) Vobkent minorasi, 6) Ahmad Yassaviy maqbarasi, 7) Jarqo'rg'on minorasi, 8) Kaltaminor.
A) 1, 2, 3, 6, 7
B) 1, 3, 4, 5, 7
C) 1, 2, 4, 6, 8
D) 2, 3, 4, 6, 7`

const m = pattern.exec(str);
console.log(m)

I assume react native is failing to compile my javascript pattern to native code.
What am I missing?
dev environment

*

*Android 10 Q API 29

*Windows 10 Pro

*expo managed react-native app

*expo: 4.13.0

*react-native: 0.64.3

A: It appears the line endings in the target environment are CRLF.
In an ECMAScript regex flavor, a . by default does not match carriage return symbols. So, \n is not enough to match a line break.
There are several ways to fix this issue. You can modify your current regex to make sure you match CRLF/LF/CR line endings:
/\d+\s*\.\s*((?:.+(?:\r\n?|\n))*?(?=[aA]\)))/

See this regex demo. Here, (?:\r\n?|\n) matches CR and an optional LF char sequence, or a single LF char.
Or, you may just match any zero or more chars:
/\d+\s*\.\s*([\w\W]*?)(?=[aA]\))/

See this regex demo.
Note I replaced the +? with *?, just in case there can be empty values between the number with a dot and a). The [\w\W]*? is a common workaround to match any zero or more chars.


text:
Q: How to refactor a large set of queries used by 3 view methods? Rails 2.3.5
I have a report being created on 3 different views (main, pre-view, and a layout-free plain HTML version for an auto email).   The report uses about 28 queries and for some of those queries I'm doing some logic before the query:
  sunday_this_week = (Time.now.beginning_of_week - 1.days).strftime("%Y-%m-%d")
  sunday_1_week_ago = (Time.now.beginning_of_week - 8.days).strftime("%Y-%m-%d")
  sunday_2_week_ago = (Time.now.beginning_of_week - 15.days).strftime("%Y-%m-%d")
  sunday_3_week_ago = (Time.now.beginning_of_week - 22.days).strftime("%Y-%m-%d")
  sunday_4_week_ago = (Time.now.beginning_of_week - 29.days).strftime("%Y-%m-%d")
  @sunday_dates = [sunday_this_week,sunday_1_week_ago,sunday_2_week_ago,sunday_3_week_ago,sunday_4_week_ago ]

  sql = %Q{
           SELECT * FROM report_notes
           WHERE week_of IN(?)
           ORDER BY week_of ASC, market ASC, measure ASC
          }
  @performance_metric_notes = RptNote.find_by_sql([ sql, @sunday_dates ])

Some of the queries are really large and since 3 views need them, I have the same queries listed under three differenct controller mthods. There's a lot of lines in the controller (~1400 lines).
What would you do to refactor something like ( is it possible to have a single controller method with all the query setup logic and queries, that the 3 different view methods can call instead of each view method having a copy )?
Thanks!

A: I would extract all of this code in a separate Report class.
Moving it to another controller action would still result in a huge controller. Plus, if there is a lot of logic to generate the report, the controller action is not the right place for it. It's a lot better if you can keep your controllers clean, just preparing variables for the views.
Just put your class in /lib, and in your controller actions you can call something like
report = Report.new params
@performance_metric_notes = report.performance_metric_notes
@other_performances = report.other_performances
...

You get the idea.

A: Why not put it in the Report Model as a Method?
@performance_metric_notes = RptNote.get_my_custom_report

A: as @Christoph said, if there is a lot of logic involved, implement this as a method in the model ; moreover you could implement this as a scope :
class RptNote < ActiveRecord::Base

  def self.performance_metric_notes( past_weeks = 4 )
    # this will calculate the last sundays for this week +
    # the nth past weeks, defaults to 4 :
    last_sundays = (0..past_weeks).map do |n|
      (Time.now.beginning_of_week - (1+n*7).days).strftime("%Y-%m-%d")
    end
    # this will return a relation. Using an array in a where clause
    # renders a SQL IN selector.
    self
      .where( week_of: last_sundays )
      .order( :week_of, :market, :measure )
  end

end

... this would even let you refine the results by adding other clauses :
RptNote.performance_metric_notes.where( measure: something )

see Railscasts #215 for more info about relations and queries in rails 3
edit : wooops, my bad, just saw your question was on rails 2. The logic stays the same, except for the query.
There is more : if your controller actions use this a lot, you can set a before_filter on the controller to auto-fetch the records :
before_filter :fetch_notes

def fetch_notes
  @notes = RptNote.performance_metric_notes
end

A: In your model :
scope :by_dates, lambda { |dates|
  where("week_of IN (#{sunday_dates.join(,)})").
  order_by("week_of ASC, market ASC, measure ASC")
}

def self.sunday_dates
  sunday_this_week = (Time.now.beginning_of_week - 1.days).strftime("%Y-%m-%d")
  sunday_1_week_ago = (Time.now.beginning_of_week - 8.days).strftime("%Y-%m-%d")
  sunday_2_week_ago = (Time.now.beginning_of_week - 15.days).strftime("%Y-%m-%d")
  sunday_3_week_ago = (Time.now.beginning_of_week - 22.days).strftime("%Y-%m-%d")
  sunday_4_week_ago = (Time.now.beginning_of_week - 29.days).strftime("%Y-%m-%d")
  [sunday_this_week,sunday_1_week_ago,sunday_2_week_ago,sunday_3_week_ago,sunday_4_week_ago]
end

And in your controller :
RptNote.by_dates(RptNote.sunday_dates)


text:
Q: Django Migrating to a new Database I just joined a project using Django, and am attempting to initialize my own development server. When I attempt to do so, the migration fails for one of my apps. A model for this app has a sorl.thumbnail.ImageField, to add a logo. When the migration is attempted, I get the following error message:
FATAL ERROR - The following SQL query failed: ALTER TABLE "accounts_account" ADD CONSTRAINT "logo_id_refs_file_ptr_id_7c3d1997" FOREIGN KEY ("logo_id") REFERENCES "filer_image" ("file_ptr_id") DEFERRABLE INITIALLY DEFERRED;
The error was: relation "filer_image" does not exist

I'm not sure what the problem could be, as apparently there was no problem in creating the production database or subsequent migrations.
I believe I have correctly installed sorl-thumbnail, and all of its dependencies.
Your help would be much apperciated.

A: I'm pulling the answer provided by Johndt6 from a comment to this answer for future search-ability.
The solution is to add filer to the INSTALLED_APPS tuple.


text:
Q: Show that $(A / \mathfrak{a}) \otimes_A M \cong M / \mathfrak{a} M$ for a ring $A$, ideal $\mathfrak{a}$, $A$-module $M$. This is Atiyah-Macdonald Exercise 2.2

Exercise: Let $A$ be a ring, $\mathfrak a$ an ideal, $M$ an $A$-module. Show that $(A/\mathfrak a) \otimes_A M$ is isomorphic to $M/\mathfrak aM$. [Tensor the exact sequence $0 \to \mathfrak a \to A \to A/\mathfrak a$ with $M$.]

I would like to verify my proof. It will be posted as a community wiki. Leave comments or edit, but if you edit, make the text red or at least make the edit obvious to distinguish my original approach, with what is incorrect or can be better written, etc.
Also, feel free to post alternate proofs.

A: Reposting from my comments since other proofs have already been posted.
By tensoring the exact sequence $0 \to \mathfrak a \to A \to A / \mathfrak a \to 0$ with $M$, we get the exact sequence
$$
\mathfrak a \otimes_A M \to A \otimes_A M \to A / \mathfrak a \otimes_A M \to 0.
$$
Consider the canonical isomorphism $A \otimes_A M \cong M$. By composing the arrows going in and out of $A \otimes_A M$ in the exact sequence above with the arrows of this isomorphism, we get the exact sequence
$$
\mathfrak a \otimes_A M \xrightarrow{\varphi} M \xrightarrow{\psi} A / \mathfrak a \otimes_A M \to 0.
$$
It is straightforward to verify that this sequence is indeed exact. We have
$$
\ker \psi = \operatorname{im} \varphi = \mathfrak a M.
$$
Thus, the first isomorphism theorem gives $A / \mathfrak a \otimes_A M \cong M / \mathfrak a M$.

A: I would like to post an alternative proof:
By Proposition 2.12 of the ops answer (in other words by the universal property of tensor product)  the following bilinear map
\begin{eqnarray*}
\psi:A/\mathfrak{a}\times M & \to & M/\mathfrak{a}M \\
            (x+\mathfrak{a},M) & \mapsto & xm+\mathfrak{a}M
\end{eqnarray*}
induces the unique linear map
\begin{eqnarray*}
\Psi:A/\mathfrak{a}\otimes_A M & \to & M/\mathfrak{a}M \\
            x+\mathfrak{a}\otimes M & \mapsto & xm+\mathfrak{a}M
\end{eqnarray*}
(that is $\Psi\otimes=\psi$, where $\otimes:A/\mathfrak{a}\times M\to A/\mathfrak{a}\otimes M$ is the tensor map with the universal property)
On the other hand, there is a linear map
\begin{eqnarray*}
\phi: &  M \to & A/\mathfrak{a}\otimes_A M \\
            & m  \mapsto & (1+\mathfrak{a})\otimes m
\end{eqnarray*}
with $\mathfrak{a}M\subseteq$ ker$\phi$, since for $x\in\mathfrak{a}$ and $m\in M$ we have  $\phi(xm)=(1+\mathfrak{a})\otimes xm=(x+\mathfrak{a})\otimes m=0$
Therefore, $\phi$ induces the following linear map
$$\Phi:M/\mathfrak{a}M \to  A/\mathfrak{a}\otimes_A M$$
with the property $\Phi \pi=\phi$, where $\pi: M\to M/\mathfrak{a}M$ is the natural projection map.
Next we show that $\Psi$ and $\Phi$ are inverses of each other.
$\Psi\Phi(m+\mathfrak{a}M)=\Psi((1+\mathfrak{a})\otimes m)= m+\mathfrak{a}M$
and
$\Phi\Psi((\sum_i\alpha_ix_i+\mathfrak{a})\otimes\sum_j\beta_jm_j)=\Phi\Psi((1+\mathfrak{a})\otimes\sum_{i,j}\alpha_i\beta_jx_im_j)=\Phi(\sum_{i,j}\alpha_i\beta_jx_im_j+\mathfrak{a}M)=$$(1+\mathfrak{a})\otimes \sum_{i,j}\alpha_i\beta_jx_im_j=(\sum_i\alpha_ix_i+\mathfrak{a})\otimes\sum_j\beta_jm_j$, where $\alpha_i,\beta_j\in \mathbb{N}$ and they are zero for all but finitely many $i,j$.

A: This is mostly similar to your argument, but much easier.

From the exact sequence $0\to\mathfrak{a}\to A\to A/\mathfrak{a}\to 0$ we get the commutative diagram with exact rows
$$\require{AMScd}\def\ma{\mathfrak{a}}
\begin{CD}
{} @. \ma\otimes_AM @>>> A\otimes_AM @>>> A/\ma\otimes_AM @>>> 0 \\
@. @VVV @VVV @VVV \\
0 @>>> \ma M @>>> M @>>> M/\ma M @>>> 0
\end{CD}
$$
where the leftmost vertical arrow is surjective and the middle vertical arrow is an isomorphism. A standard diagram chasing shows that the arrow
$$
A/\ma\otimes_AM\to M/\ma M,
$$
defined by $(a+\ma)\otimes x=ax+\ma M$ so as to make the diagram commutative, is an isomorphism too.

A: Proposition 2.12: Let $M, N$ be $A$-modules. Then there exists a pair $(T, g)$ consisting of an $A$-modules $T$ and an $A$-bilinear mapping $g : M \times N \to T$, with the following property:
Given any $A$-module $P$ and any $A$-bilinear mapping $f : M \times N \to P$, there exists a unique $A$-linear mapping $f' : T \to P$ such that $f = f' \circ g$ (in other words, every bilinear function on $M \times N$ factors through $T$).
Moreover, if $(T, g)$ and $(T', g')$ are two pairs with this property, then there exists a unique isomorphism $j : T \to T'$ such that $j \circ g = g'$.

Proposition 2.18: Let $$M' \xrightarrow f M \xrightarrow g M'' \to 0$$ be an exact sequence of $A$-modules and homomorphisms, and let $N$ be any $A$-module. Then the sequence $$M' \otimes N \xrightarrow{f \otimes 1} M \otimes N \xrightarrow {g \otimes 1} M'' \otimes N \to 0$$ (where $1$ denotes the identity mapping on $N$) is exact.

Proof of Exercise 2.2:
$\newcommand{im}{{\operatorname{im}}}$
Consider $$ 0 \to \mathfrak a \xrightarrow i A \xrightarrow \pi A / \mathfrak a \to 0$$ where $i : \mathfrak a \to A$ is the inclusion map: $x \mapsto x$, and $\pi : A \to A / \mathfrak a$ is the quotient map: $x \mapsto x + \mathfrak a$. This is a short exact sequence. By Proposition 2.18, $$\mathfrak a \otimes M \xrightarrow{i \otimes 1} A \otimes M \xrightarrow{\pi \otimes 1} (A/\mathfrak a) \otimes M \to 0$$ is exact. This means that $\ker \pi \oplus 1 = \im i \otimes 1$ and $\pi \otimes 1$ is surjective. By the fundamental theorem of module homomorphisms , $(A \otimes M) / \ker (\pi \otimes 1) \cong (A/\mathfrak a) \otimes M$. We show that $(A \otimes M) / \ker (\pi \otimes 1) \cong M/\mathfrak a M$.
Define $f : A \times M \to M/\mathfrak aM$ by $(a, m) \mapsto am + \mathfrak aM$ and $g : A \times M \to A \otimes M$ by $(a, m) \mapsto a \otimes m$. By Proposition 2.12, there exists a unique $f'$ such that $f = f' \circ g$: $$%\xymatrix{A \times M \ar[r]^g \ar[dr]_{f} & A \otimes M \ar[d]^{f'}\\ & M / \mathfrak aM }$$ Observe that $f'$ is surjective, since given any $\overline m = m + \mathfrak aM \in M/ \mathfrak aM$, we have $f'(1 \otimes m) = m + \mathfrak aM$. By the fundamental theorem of module homomorphisms, it follows that $A \otimes M / \ker f' \cong M/ \mathfrak aM$.
We show that $\ker f' = \ker (\pi \otimes 1)$: Let $\sum_{k = 1}^n a_k \otimes m_k \in \ker (\pi \otimes 1) = \im (i \otimes 1)$ and observe that $$f' \bigg( \sum_{k = 1}^n a_k \otimes m_k \bigg) = \sum_{k = 1}^n f'(a_k \otimes m_k) = \sum_{k = 1}^n a_k m_k + \mathfrak aM = 0$$ and therefore $\sum_{k = 1}^n a_k \otimes m_k \in \ker f'$. Hence we have $\ker(\pi \otimes 1) \subseteq \ker f'$. Let $x \in \ker f'$ and suppose, without loss of generality, that the element we chose is $1 \otimes m$ (we can do this since $\sum a_k \otimes m_k = 1 \otimes \sum a_k m_k$). Hence we have $f'(1 \otimes m) = 1\cdot m + \mathfrak aM = m + \mathfrak aM = 0$. Thus $m \in \mathfrak aM$, so $m = \sum_{k = 1}^n a_i m_i$ where $a_i \in \mathfrak a$ and $m_i \in M$. It follows immediately that $1 \otimes m = 1 \otimes \sum_{k = 1}^n a_k m_k = \sum_{k = 1}^n a_k \otimes m_k \in \im (i \otimes 1) = \ker (\pi \otimes 1)$. Hence we have $\ker f' \subseteq \ker (\pi \otimes 1)$ and thus $\ker f' = \ker (\pi \otimes 1)$.


text:
Q: Footer doesn't extend to the edge of the screen - not a duplicate I've seen a few of these on Stack Overflow, but the questions that have been asked don't lead to an answer which solves my issue. Please take the time to look over my code before marking it down or flagging it as a duplicate.
I'm working through a book called "Beginning django CMS". I'm finding that a few parts are out of date, and that might be the issue here. It's tough for me to say because I'm new to web design.
The footer isn't in a
, and I've gone over the padding to see if that helps. Those are the kinds of issues that come up as answers to questions that have previously been posted on Stack Overflow.
I'm being left with a footer which begins about an inch in from the left of the screen and seems to be in line with the blog title. Does anyone know what might be causing this?
I've checked this in Chrome and Edge so far, both come up with the indent.
Here's the HTML:
{% load cms_tags staticfiles sekizai_tags menu_tags %}
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv"X-UA-Compatible" Content = "IE=Edge">
    <meta name = "viewport" content="width=device-width", initial-scale=1>

    <link rel="icon" href="favicon.ico">

    <title>{% block title %}MyBlog Title{% endblock title %}</title>

    <link href="https://cdnjs.cloudfare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel = "stylesheet">

    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css">

    <link href="{% static "myblog.css" %}" rel="stylesheet">

    {% render_block "css" %}

    {% cms_toolbar %}

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>

                    {% show_menu 0 1 0 100 "menu.html" %}

Patch's Soapbox

The political system is broken; it could do with a Patch

        {% block content %}{% endblock content %}

{% block footer %}My Blog©2015{%endblock footer%}

    {% render_block "js" %}

And the CSS:
html {
    position : relative;
    min-height: 100%;
}

body {
    /* Margin bottom by footer height */
    margin-bottom: 60px;
    font-family : Georgia, "Times New Roman", Times, serif;
    color #555;
}
h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6 {
    margin-top: 0;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serfi;
    font-weight: normal;
    color: #333;
}
.footer {
    position: absolute;
    margin-left : 0px
    bottom: 0;
    width: 100%;
    height: 60px;
    background-color: #f5f5f5;
}
.blog-header {
    padding-top: 20px;
    padding-bottom: 20px;
}

.blog-title {
    margin-top: 30px;
    margin-bottom: 0;
    font-size: 28px;
    font-weight: normal;
}
.blog-description{
    font-size: 20px;
    color: #999;
}
.sidebar-module{
    padding: 15px;
    margin: 0 -15px 15px;
}
.sidebar-module-inset {
    padding: 15px;
    background-color: #f5f5f5;
    border-radius: 4px;
}
.sidebar-module-inset p:last-child,
.sidebar-module-inset ul:last-child,
.sidebar-module-inset ol:last-child{
    margin-bottom: 0;
}
.pager {
    margin-bottom: 60px;
    text-align: left
}
.pager > li > a {
    width: 140px;
    padding: 10px 20px;
    text-align: center;
    border-radius: 30px;
}
.blog-post{
    margin-bottom: 60px;
}
.blog-post-title{
    margin-bottom: 5px;
    font-size: 40px;
}
.blog-post-meta {
    margin-bottom: 20px;
    color : #999;
}
body > container {
    padding: 0px 0px 0;
}
.container .text-muted {
    margin: 20px 0;
}
.footer > .container {
    padding-right: 15px;
    padding-left: 0;
}
.row {
    margin-right: 0px!important;
}

A: I found the issue. I needed to use the "container-fluid" class, rather than the "container" class.
This increased the width of the container in-line with the device.
I then had to remove bootstrap's default padding using:
.container-fluid{margin:0 auto}


text:
Q: Superscript in legends in R I'm trying to get this text output in the legend:

I tried the following:
lab1 <- c(expression((CD44 (lo)^2 T Cells)]),
          expression((CD44 (hi)^2 CD69 (lo)^2 T Cells)]),
         expression((CD44 (hi)^2 CD69 (hi)^2 CD103 (lo)^2 T Cells)
expression(CD44 (hi)^2 CD69 (hi)^2 CD103 (hi)^2 T Cells))

lab2 <- c(expression(paste(CD44 (lo)^2 T Cells)]),
          expression(paste(CD44 (hi)^2 CD69 (lo)^2 T Cells)]),
         expression(paste(CD44 (hi)^2 CD69 (hi)^2 CD103 (lo)^2 T Cells)
           expression(paste(CD44 (hi)^2 CD69 (hi)^2 CD103 (hi)^2 T Cells))

lab3 <- c(bquote((CD44 (lo)^2 T Cells)),
               bquote((CD44 (hi)^2 CD69 (lo)^2 T Cells)),
                 bquote((CD44 (hi)^2 CD69 (hi)^2 CD103 (lo)^2 T Cells)),
                bquote((CD44 (hi)^2 CD69 (hi)^2 CD103 (hi)^2 T Cells)))

My code:
library(dplyr, warn.conflicts = FALSE)
library(tidyverse, warn.conflicts = FALSE)
library(stringr, warn.conflicts = FALSE)
library(matrixStats, warn.conflicts = FALSE)
library(pheatmap, warn.conflicts = FALSE)
library(heatmaps, warn.conflicts = FALSE)
library(ggplot2, warn.conflicts = FALSE)

dfc <- read.csv(url("https://github.com/learnseq/learning/raw/main/GSE133399_Fig2_FPKM.csv"))

values <- c('S100a10', 'Esm1', 'Itgb1', 'Anxa2', 'Hist1h1b',
                                                'Il2rb', 'Lgals1', 'Mki67', 'Rora', 'S100a4',
                                                'S100a6', 'Adam8', 'Areg', 'Bcl2l1', 'Calca',
                                                'Capg', 'Ccr2', 'Cd44', 'Csda', 'Ehd1',
                                                'Id2', 'Il10', 'Il1rl1', 'Il2ra', 'Lmna',
                                                'Maf', 'Penk', 'Podnl1', 'Tiam1', 'Vim',
                                                'Ern1', 'Furin', 'Ifng', 'Igfbp7', 'Il13',
                                                'Il4', 'Il5', 'Nrp1', 'Ptprs', 'Rbpj',
                                                'Spry1', 'Tnfsf11', 'Vdr', 'Xcl1', 'Bmpr2',
                                                'Csf1', 'Dst', 'Foxp3', 'Itgav', 'Itgb8',
                                                'Lamc1', 'Myo1e', 'Pmaip1', 'Prdm1', 'Ptpn5',
                                                'Ramp1', 'Sdc4')

dfg <- dfc[match(rev(values), dfc$tracking_id), ]

dfg$CD44low_rep <- rowMeans(dfg[,c('CD44low_rep1', 'CD44low_rep2')], na.rm=TRUE)
dfg$CD44hi_CD69low_rep <- rowMeans(dfg[,c('CD44hi_CD69low_rep1', 'CD44hi_CD69low_rep2')], na.rm=TRUE)
dfg$CD44hi_CD69hi_CD103low_rep <- rowMeans(dfg[,c('CD44hi_CD69hi_CD103low_rep1', 'CD44hi_CD69hi_CD103low_rep2')], na.rm=TRUE)
dfg$CD44hi_CD69hi_CD103hi_rep <- rowMeans(dfg[,c('CD44hi_CD69hi_CD103hi_rep1', 'CD44hi_CD69hi_CD103hi_rep2')], na.rm=TRUE)
rownameshm <-paste(dfg[,1])
colnameshm <- paste(dQuote(colnames(dfg[0, 10:13])), collapse = ", ")
dfg$Mean <- rowMeans(dfg[,10:13])
dfg$sd <- rowSds(as.matrix(dfg[,10:13]))

zScore <- function(p){
for(n in 10:13){
    p[[n]]=(as.numeric(p[[n]])-as.numeric(p[[14]]))/as.numeric(p[[15]])
    }
return(p)
}

Matrix_zScore <- t(apply(dfg,1,zScore))

Matrix_zScore_temp <- mapply(Matrix_zScore[,10:13], FUN=as.numeric)
Matrix_zScore_temp <- matrix(data=Matrix_zScore_temp, ncol=4, nrow=57)
Matrix_zScore_temp1<-as.data.frame(Matrix_zScore_temp)

rownames(Matrix_zScore_temp) <- dfg$tracking_id
plot_frame <- reshape2::melt(Matrix_zScore_temp)

library(repr, warn.conflicts = FALSE)
options(repr.plot.width=5, repr.plot.height=8)

#lab1 <- c(expression((CD44 (lo)^2 T Cells)]),
#          expression((CD44 (hi)^2 CD69 (lo)^2 T Cells)]),
#         expression((CD44 (hi)^2 CD69 (hi)^2 CD103 (lo)^2 T Cells)
#  expression(CD44 (hi)^2 CD69 (hi)^2 CD103 (hi)^2 T Cells))

lab2 <- c(expression(paste(CD44 (lo)^2 T Cells)]),
          expression(paste(CD44 (hi)^2 CD69 (lo)^2 T Cells)]),
         expression(paste(CD44 (hi)^2 CD69 (hi)^2 CD103 (lo)^2 T Cells)
           expression(paste(CD44 (hi)^2 CD69 (hi)^2 CD103 (hi)^2 T Cells))

#lab3 <- c(bquote((CD44 (lo)^2 T Cells)),
#               bquote((CD44 (hi)^2 CD69 (lo)^2 T Cells)),
#                 bquote((CD44 (hi)^2 CD69 (hi)^2 CD103 (lo)^2 T Cells)),
#                bquote((CD44 (hi)^2 CD69 (hi)^2 CD103 (hi)^2 T Cells)))

ggplot(plot_frame, aes(Var2, Var1, fill = value)) +
  geom_tile(color = "white", position = position_dodge(), show.legend = TRUE) +
  geom_point(data = data.frame(Var2 = 1:4, Var1 = "", value = 0), size = 5,
             aes(color = factor(Var2))) +
  geom_point(data = data.frame(Var2 = 1:4, Var1 = " ", value = 1), alpha = 0) +
  scale_color_manual(values = c("black", "forestgreen", "red4", "blue4"),
                     labels = (lab2,
                     guide = guide_legend(override.aes = list(fill = NA))) +
  scale_y_discrete(position = "right") +
  labs(y = "", fill = "", color = " ", x = "")  +
  scale_fill_gradientn(colors = c("#3C57A8", "white", "#DE2D29"),
                       breaks = c(1.5, 0, -1.5),
                       labels = c("1.0", "0", "-1.0"),
                       limits = c(-1.5, 1.5),
                       space = "Lab",
                       na.value = "grey50",
                       guide = "colourbar",
                       aesthetics = "fill") +
  theme_minimal() +
theme (panel.grid.major = element_blank(), axis.text.y.right = element_text(margin = margin(l = unit(-5, "cm")))) +
theme (axis.text.y = element_text(face="italic", size=7, color="black")) +
    guides(
        fill = guide_colourbar(
            title = "Relative gene expression \n (z score)",
            title.position = "right",
            title.theme = element_text(angle = -90, size = 7.5),
            direction = "vertical",
            ticks = TRUE
        )) +
theme(
    legend.justification = c(-0.9, 0),
    legend.direction = "vertical",
    legend.key.size = unit(0.6, "cm"),
    legend.key.width = unit(0.2,"cm"),
    legend.title.align = 0.5,
    axis.text.x = element_blank())

I tried these based on some question in this community.

A: The example seemed unnecessarily complex for just creating a legend. Here's a simplified example
library(ggplot2)
labs <- expression(
  CD44^{lo}~"T Cells",
  CD44^{hi}~CD69^{lo}~"T Cells",
  CD44^{hi}~CD69^{hi}~CD103^{lo}~"T Cells",
  CD44^{hi}~CD69^{hi}~CD103^{hi}~"T Cells")

dd <- data.frame(x=1:4, y=1:4, z=letters[1:4])
ggplot(dd) +
  aes(x,y, color=z) +
  geom_point() +
  scale_color_manual(
    values = c("black", "forestgreen", "red4", "blue4"),
    labels=labs)

Note that expression() actually returns a container object so you can just pass in all your expressions in a single call to expression(). Also, review the syntax allowed on the ?plotmath help page.
This will return a legend that looks like


text:
Q: using tensorflow functions with tf.keras I have a question regarding tf.keras and tf functions in tf 2.0.
If i have a model like this:
 inputdata = keras.Input(shape=(2048, 1))
    x = layers.Conv1D(16, 3, activation='relu')(inputdata)
    x = layers.Conv1D(32, 3, activation='relu')(x)
    x = layers.Conv1D(64, 3, activation='relu')(x)

and I want to add a custom function like this which is a 1D SubPixel Layer:
def SubPixel1D(I, r):
  with tf.name_scope('subpixel'):
  X = tf.transpose(I, [2,1,0]) # (r, w, b)
  X = tf.batch_to_space_nd(X, [r], [[0,0]]) # (1, r*w, b)
  X = tf.transpose(X, [2,1,0])
  return X

can I include this layer in keras without problems? Since tensorflow 2.0 is so much easier then the previous tensorflow versions iam not sure about it if this is not mixing up the backends and the sessions?
inputdata = keras.Input(shape=(2048, 1))
  x = layers.Conv1D(16, 3, activation='relu')(inputdata)
  x = layers.Conv1D(32, 3, activation='relu')(x)
  x = SubPixel1D(x,2)
  x = layers.Conv1D(64, 3, activation='relu')(x)

after that compile and fit model will work? If
tensorflow and keras is imported
 import tensorflow as tf
 from tensorflow import keras

similar to the a custom loss function in keras.
If I define a custom loss function like this:
def my_loss(y_true, y_pred):
 # compute l2 loss/ equal to Keras squared mean
    sqrt_l2_loss = tf.reduce_mean((y_pred-y_true)**2, axis=[1, 2])
    avg_sqrt_l2_loss = tf.reduce_mean(sqrt_l2_loss, axis=0)
    return avg_sqrt_l2_loss

and use tf. operations or functions, can i just pass this function to keras as usual?
Can i just use it in Keras loss?

A: Just subclass tf.keras.Layer and you will be good to go. Great reference here: https://www.tensorflow.org/guide/keras/custom_layers_and_models. Your layer should look something like this:
class SubPixel1D(tf.keras.layers.Layer):
  def __init__(self, r)
      super(SubPixel1D, self).__init__()
      self.r = r

  def call(self, inputs):
      with tf.name_scope('subpixel'):
          X = tf.transpose(inputs, [2,1,0]) # (r, w, b)
          X = tf.batch_to_space_nd(X, [self.r], [[0,0]]) # (1, r*w, b)
          X = tf.transpose(X, [2,1,0])
     return X

and then call it when defining your model
inputdata = keras.Input(shape=(2048, 1))
  x = layers.Conv1D(16, 3, activation='relu')(inputdata)
  x = layers.Conv1D(32, 3, activation='relu')(x)
  x = SubPixel1D(2)(x)
  x = layers.Conv1D(64, 3, activation='relu')(x)

I don't know how tf.name_scope will behave, but I don't see any immediate issues.


text:
Q: Trouble with interfaces and parameters of objects This is a difficult problem to describe so I will do my best.
Basically my program has two concrete classes: MovablePoint and MovableCircle. Both implement the interface Movable which has four methods: moveUp Down left right.
Now where I am stuck is that when I am constructing my MovableCircle I need to use an instance variable of MovablePoint to represent the center of the circle. However I also need the constructor of MovableCircle to take in 5 params: int x, int y, int xSpeed, int ySpeed, int radius. The first 4 params are the "center" of the circle and they should be instantiated by the MovablePoint.
Here is what I have:
public class MovableCircle implements Movable {
private int radius;
private int y;
private int x;
private int xSpeed;
private int ySpeed;
public MovablePoint circleCenter;

public MovableCircle (int x, int y, int xSpeed, int ySpeed, int radius) {
    this.radius = radius;
    this.x = circleCenter.getX();
    this.y = circleCenter.getY();
    this.xSpeed = circleCenter.getxSpeed();
    this.ySpeed = circleCenter.getySpeed();
}

Here also is the MovablePoint code if that helps:
public class MovablePoint implements Movable{
private int x;
private int y;
private int xSpeed;
private int ySpeed;

public MovablePoint(int x, int y, int xSpeed,
        int ySpeed) {
    this.x = x;
    this.y = y;
    this.xSpeed = xSpeed;
    this.ySpeed = ySpeed;
}

Obviously there is more code beyond what I have posted but I am fairly positive I have coded the class methods properly.. I believe my problem lies in the fact that I need to instantiate the MovableCircle's center with a MovablePoint but I'm not sure how to remedy it. Thanks for your help and I apologize if this problem is easily solved and I am just oblivious..

A: How about something like:
public class MovableCircle implements Movable {
    private int radius;
    private MovablePoint circleCenter;

    public MovableCircle (int x, int y, int xSpeed, int ySpeed, int radius) {
        this.radius = radius;
        this.circleCenter = new MovablePoint(x, y, xSpeed, ySpeed);
    }


text:
Q: Find multiple subdocuments match in Meteor i cannot find anything related to that.
I need to find(ON METEORJS MONGO, WHO DONT HAVE AGGREGATION), some subdocuments, the rule to that is, if type is equal to 2, get these subdocument.
The problem is, on server we have projection ($) and ($elemMatch) operator, but these give only the first match subdocument and i need all the subdocuments who have these value.
The example document
"Users":{
   "Example" : [
    {
        "type" : "1",
        "title" : "All Included",
        "_id" : "11a4e0ab6f136ddc8870dc95"
    },
    {
        "type" : "2",
        "title" : "Other sub",
        "_id" : "123asddc8870dc95"
    },
    {
        "type" : "2",
        "title" : "More type 2",
        "_id" : "cxzcasdo2"
    },
   ]
}

But when i do the
var data = Users.find({'Example.type':'2'}, {fields:{'Example.$':1}});

The returned values is only the first matched element _id = 123asddc8870dc95 and not the two how has type 2.
I have no idea how to do that, Meteor dont have aggregation and i cannot do a map before publish to find all subdocuments and remove mannualy.
:/
Edited:
I know that meteor has a hack to do aggregation, but i dont want to use this, to avoid dependencies

A: You can do aggregation with meteor using meteorhacks:aggregate. Here's a tutorial.
Since you don't want to use another package, you can access the raw collection using:
myCollection.rawCollection()

I believe rawCollection will have the aggregate function on it as well.


text:
Q: What does "falling and missing the ground" mean? I don't understand the use of the phrase "falling and missing the ground". How can one fall and miss the ground? What does it mean?
Update
Apologies. I found the use of the phrase at http://www.scq.ubc.ca/how-to-fly/

A: That's either a sarcastic comment, or a paradox or an absurdity.

*

*A form of wit that is marked by the use of sarcastic language and is intended to make its victim the butt of contempt or ridicule.

*An assertion that is essentially self-contradictory, though based on a valid deduction from acceptable premises.

If you read it in reference to orbiting a planet, it's a paradox. If you fall, gravity will always bring you to the ground. Some say that orbiting is falling (because you are subject to the Earth's gravitational field), but not hitting the ground, because velocity keeps you from doing so.
Some pilots like to joke that flying is easy; what's hard is learning how to miss the ground. It's kind of an absurdity. It's reducing the very complex to a simple untruth.
So one of Douglas Adams' characters (Arthur Dent) manages to learn to fly by falling and missing the ground. (Life, the Universe and Everything, book 3 of 5 in Hitchhiker's Guide to the Galaxy)
If it was said sarcastically, it can mean a stupefying degree of ineptness:
"He can't do anything. He could fall and miss the ground."
Conversely, it could indicate a great success from what was surely considered by most to be a failing:
He fell and missed the ground. (It looked bad but he ended soaring to great heights.)


text:
Q: Comparing lines in a file with perl Ive been trying to compare lines between two files and matching lines that are the same.
For some reason the code below only ever goes through the first line of 'text1.txt' and prints the 'if' statement regardless of if the two variables match or not.
Thanks
use strict;
open( <FILE1>, "<text1.txt" );
open( <FILE2>, "<text2.txt" );
foreach my $first_file (<FILE1>) {
    foreach my $second_file (<FILE2>) {
        if ( $second_file == $first_file ) {
            print "Got a match - $second_file + $first_file";
        }
    }
}
close(FILE1);
close(FILE2);

A: If you compare strings, use the eq operator. "=="  compares arguments numerically.

A: A better and faster (but less memory efficient) approach would be to read one file into a hash, and then search for lines in the hash table. This way you go over each file only once.
# This will find matching lines in two files,
# print the matching line and it's line number in each file.

use strict;

open (FILE1, "<text1.txt") or die "can't open file text1.txt\n";
my %file_1_hash;
my $line;
my $line_counter = 0;

#read the 1st file into a hash
while ($line=<FILE1>){
  chomp ($line); #-only if you want to get rid of 'endl' sign
  $line_counter++;
  if (!($line =~ m/^\s*$/)){
    $file_1_hash{$line}=$line_counter;
  }
}
close (FILE1);

#read and compare the second file
open (FILE2,"<text2.txt") or die "can't open file text2.txt\n";
$line_counter = 0;
while ($line=<FILE2>){
  $line_counter++;
  chomp ($line);
  if (defined $file_1_hash{$line}){
    print "Got a match: \"$line\"
in line #$line_counter in text2.txt and line #$file_1_hash{$line} at text1.txt\n";
  }
}
close (FILE2);

A: Here is a way to do the job if your files aren't too large.
#!/usr/bin/perl
use Modern::Perl;
use File::Slurp qw(slurp);
use Array::Utils qw(:all);
use Data::Dumper;

# read entire files into arrays
my @file1 = slurp('file1');
my @file2 = slurp('file2');

# get the common lines from the 2 files
my @intersect = intersect(@file1, @file2);

say Dumper \@intersect;

A: You must re-open or reset the pointer of file 2. Move the open and close commands to within the loop.
A more efficient way of doing this, depending on file and line sizes, would be to only loop through the files once and save each line that occurs in file 1 in a hash. Then check if the line was there for each line in file 2.

A: If you want the number of lines,
my $count=`grep -f [FILE1PATH] -c [FILE2PATH]`;

If you want the matching lines,
my @lines=`grep -f [FILE1PATH]  [FILE2PATH]`;

If you want the lines which do not match,
my @lines = `grep -f [FILE1PATH] -v [FILE2PATH]`;

A: This is a script I wrote that tries to see if two file are identical, although it could easily by modified by playing with the code and switching it to eq. As Tim suggested, using a hash would probably be more effective, although you couldn't ensure the files were being compared in the order they were inserted without using a CPAN module (and as you can see, this method should really use two loops, but it was sufficient for my purposes). This isn't exactly the greatest script ever, but it may give you somewhere to start.

use warnings;

open (FILE, "orig.txt") or die "Unable to open first file.\n";
@data1 = ;
close(FILE);

open (FILE, "2.txt") or die "Unable to open second file.\n";
@data2 = ;
close(FILE);

for($i = 0; $i < @data1; $i++){
    $data1[$i] =~ s/\s+$//;
    $data2[$i] =~ s/\s+$//;
    if ($data1[$i] ne $data2[$i]){
        print "Failure to match at line ". ($i + 1) . "\n";
        print $data1[$i];
        print "Doesn't match:\n";
        print $data2[$i];
        print "\nProgram Aborted!\n";
        exit;
    }
}

print "\nThe files are identical. \n";

A: Taking the code you posted, and transforming it into actual Perl code, this is what I came up with.
use strict;
use warnings;
use autodie;

open my $fh1, '<', 'text1.txt';
open my $fh2, '<', 'text2.txt';

while(
  defined( my $line1 = <$fh1> )
  and
  defined( my $line2 = <$fh2> )
){
  chomp $line1;
  chomp $line2;

  if( $line1 eq $line2 ){
    print "Got a match - $line1\n";
  }else{
    print "Lines don't match $line1 $line2"
  }
}

close $fh1;
close $fh2;

Now what you may really want is a diff of the two files, which is best left to Text::Diff.
use strict;
use warnings;

use Text::Diff;

print diff 'text1.txt', 'text2.txt';


text:
Q: how to get desired output in python from following output I am getting this output as pasted below .

[{'accel-world-infinite-burst-2016': 'https://yts.mx/torrent/download/92E58C7C69D015DA528D8D7F22844BF49D702DFC'}, {'accel-world-infinite-burst-2016': 'https://yts.mx/torrent/download/3086E306E7CB623F377B6F99261F82CC8BB57115'}, {'accel-world-infinite-burst-2016': 'https://yifysubtitles.org/movie-imdb/tt5923132'}, {'anna-to-the-infinite-power-1983': 'https://yts.mx/torrent/download/E92B664EE87663D7E5EC8E9FEED574C586A95A62'}, {'anna-to-the-infinite-power-1983': 'https://yts.mx/torrent/download/4F6F194996AC29924DB7596FB646C368C4E4224B'}, {'anna-to-the-infinite-power-1983': 'https://yts.mx/movies/anna-to-the-infinite-power-1983/request-subtitle'}, {'infinite-2021': 'https://yts.mx/torrent/download/304DB2FEC8901E996B066B74E5D5C010D2F818B4'}, {'infinite-2021': 'https://yts.mx/torrent/download/1320D6D3B332399B2F4865F36823731ABD1444C0'}, {'infinite-2021': 'https://yts.mx/torrent/download/45821E5B2E339382E7EAEFB2D89967BB2C9835F6'}, {'infinite-2021': 'https://yifysubtitles.org/movie-imdb/tt6654210'}, {'infinite-potential-the-life-ideas-of-david-bohm-2020': 'https://yts.mx/torrent/download/47EB04FBC7DC37358F86A5BFC115A0361F019B5B'}, {'infinite-potential-the-life-ideas-of-david-bohm-2020': 'https://yts.mx/torrent/download/88223BEAA09D0A3D8FB7EEA62BA9C5EB5FDE9282'}, {'infinite-potential-the-life-ideas-of-david-bohm-2020': 'https://yts.mx/movies/infinite-potential-the-life-ideas-of-david-bohm-2020/request-subtitle'}, {'the-infinite-man-2014': 'https://yts.mx/torrent/download/0E2ACFF422AF4F62877F59EAE4EF93C0B3623828'}, {'the-infinite-man-2014': 'https://yts.mx/torrent/download/52437F80F6BDB6FD326A179FC8A63003832F5896'}, {'the-infinite-man-2014': 'https://yifysubtitles.org/movie-imdb/tt2553424'}, {'nick-and-norahs-infinite-playlist-2008': 'https://yts.mx/torrent/download/DA101D139EE3668EEC9EC5B855B446A39C6C5681'}, {'nick-and-norahs-infinite-playlist-2008': 'https://yts.mx/torrent/download/8759CD554E8BB6CFFCFCE529230252AC3A22D4D4'}, {'nick-and-norahs-infinite-playlist-2008': 'https://yifysubtitles.org/movie-imdb/tt0981227'}]

As you can see each movie have multiple links and for each link movie name is repeating .I want all links related to same movie must appeared as same object e.g

[{accel-world-infinite-burst-2016:{link1,link2,link3,link4},........]

for item in li:
            # print(item.partition("movies/")[2])
                movieName["Movies"].append(item.partition("movies/")[2])

                req=requests.get(item)
                s=soup(req.text,"html.parser")

                m=s.find_all("p",{"class":"hidden-xs hidden-sm"})
                # print(m[0])
                for a in m[0].find_all('a', href=True):
                    #  movieName['Movies'][item.partition("movies/")[2]]=(a['href'])
                     downloadLinks.append ( {item.partition("movies/")[2]:a['href']  })

A: you can try this,
# input = your list of dict
otp_dict = {}
for l in input:
  for key, value in l.items():
    if key not in otp_dict:
      otp_dict[key] = list([value])
    else:
      otp_dict[key].append(value)

print(otp_dict)

otp: {'accel-world-infinite-burst-2016':[link1,link2],...}
output is dict containing list of links if you want set as you mentioned in your desired op try this
for l in input:
  for key, value in l.items():
    if key not in otp_dict:
      otp_dict[key] = set([value])
    else:
      otp_dict[key].add(value)

otp: {'accel-world-infinite-burst-2016':{link1,link2},...}


text:
Q: Как зациклить таймер обратного отсчета? Имеется такой код
function CountdownTimer(elm,tl,mes){
 this.initialize.apply(this,arguments);
}
CountdownTimer.prototype={
 initialize:function(elm,tl,mes) {
 this.elem = document.getElementById(elm);
 this.tl = tl;
 this.mes = mes;
},countDown:function(){
var timer='';
var today=new Date();
var day=Math.floor((this.tl-today)/(24*60*60*1000));
var hour=Math.floor(((this.tl-today)%(24*60*60*1000))/(60*60*1000));
var min=Math.floor(((this.tl-today)%(24*60*60*1000))/(60*1000))%60;
var sec=Math.floor(((this.tl-today)%(24*60*60*1000))/1000)%60%60;
var me=this;

if( ( this.tl - today ) > 0 ){
timer += '

DAYS
'+day+'';
timer += '

HOURS
'+hour+'';
timer += '

MINS
'+this.addZero(min)+'

SECS
'+this.addZero(sec)+'';
this.elem.innerHTML = timer;
tid = setTimeout( function(){me.countDown();},10 );
}else{
this.elem.innerHTML = this.mes;
return;
}
},addZero:function(num){ return ('0'+num).slice(-2); }
}
function CDT(){

// Set countdown limit year mounth date
var tl = new Date('2014/03/30 00:00:00');

// You can add time's up message here
var timer = new CountdownTimer('CDT',tl,'

Time is up!      ');
 timer.countDown();
}
window.onload=function(){
 CDT();
}

как зациклить его на определенном времени, например на 00 дней 18 часов 00 минут 00 сек, и чтобы по прошествию этого времени происходил ресет и все начиналось заново.
A: Поправил ошибку, можно посмотреть целиком здесь


text:
Q: DB2 giving nio.unsupportedcharsetexception CP836 while trying to access date fields DB2 giving nio.unsupportedcharsetexception CP836 while trying to access date/timestamp fields. I am using db2jcc4.jar as driver for DB2.
Am getting the below exception
java.nio.charset.UnsupportedCharsetException: Cp836
I am trying with both  DBeaver and Squirrel both are giving only this much stacktrace.
and am using z/os platform
java version: 1.8
able to select column value, if that column is not of date/timestamp type
connection string : jdbc:db2://********:451/***B

A: This is a configuration matter.
Check whose jre you are using with DBeaver (Oracle/Sun, IBM, or other).
See https://www.ibm.com/support/pages/errorcode-4220-received-when-using-ccsid-13124cp836-connect-as400-db-using-db2-jcc-type-4-driver
Specifically this advice:

IBM has a charset support for every CCSID IBM machines deal with.

Oracle/Sun JDK/JRE uses charsets.jar to provide character mapping
between UTF-8 and various code pages.
Oracle/Sun jre has separate international installations and that
localized install would not have all conversion classes.  So you will
need to obtain a full JDK installation.
It is best to use latest IBM JDK. It contains both rt.jar and
charsets.jar containing the class file ByteToCharCp836.class.
Download here:

https://www.ibm.com/developerworks/java/jdk/index.html