text:
Q: (Proof Verification) Proof regarding connected open sets and analytic functions - Is my understanding correct? Here is the proof for Theorem 1.2 provided by Serge Lang and bellow I have written how I interpret it. I would be very grateful if any of you can check if I am understanding this correctly.
For clarifiction: I have added the statement and proof of 1.2 and other pages that could be relevant to the proof.

The way I understand this is the following,
Assuming that the zeroes of $f$ on $U$ are not discrete we have $S$ open. He afterwards goes to prove that $S$ is closed in $U$. Since $S$ is closed in U we have $U-S=V$ by Lemma 1.5  where $V$ is an open set closed in $U$. But by Theorem 1.6 we have $U$ topologically connected which implies that  $U$ can not be expressed as $U=S ∪ V$ hence there doesn't exist $V$ s.t $U=S+V$ . Hence by contradiction we have $S$ not open and thus $S$ is discrete.
Is my understanding correct?

A: *

*"Assuming that the zeroes of $f$ on $U$ are not discrete we have $S$ open": Actually, $S$ is always open. If the set of all zeroes of $f$ is discrete, then $S=\emptyset$, but it will still be an open set.

*"He afterwards goes to prove that $S$ is closed in $U$. Since $S$ is closed in $U$ we have $U−S=V$ by Lemma 1.5 where $V$ is an open set closed in $U$": Right, except that there is no reason to suppose that $V$ is closed in $U$. And it is better to use the notation $U\setminus V$ instead of $U-V$.

*"But by Theorem 1.6 we have $U$ topologically connected which implies that $U$ can not be expressed as $U=S\cup V$ hence there doesn't exist $V$ s.t $U=S+V$": We just say "connected", not "topologically connected". And you missed an important point here. Having $U$ written has the union of two open sets is not is not a problem, so to say. What is important here is that, since $U$ is connected, it cannot be written as the union of two disjoint and non-empty open sets. And you shouldn't write $U=S+V$.


text:
Q: Problem in write ascii string builder to a file I try to write a string include some character to a file like that:
StringBuilder sb= new StringBuilder();
sb.Append("3S@Þ>‡g3¶UH3úUH3?UH3UH3âUH3ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿUH3ÇUH3ÿÿÿÿUH3EêL3");
File.WriteAllText(outputFilename, sb.ToString());

but in the end, I have a file include this:

3S@Þ>‡g3¶UH3úUH3?UH3UH3âU

I just know my file must be like that:

How can I write this string to a file .bin?

A: Thanks to @Jeroen Mostert.
I use File.WriteAllBytes(new byte[] { 0x33, 0x53, 0x40, 0xde, ...}) and work correctly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: comparing variabel between 2 file C# Im pretty new to C coding and most of all C# so the problem i have is to understand how it works. So what i want really is that when you press on a grid you will get a unique id depending what item is displayed in the grid, and on pressing on the grid you will go to a new page where i want to display the item.id
File 1
foreach (var item in list)
 {
        TapGestureRecognizer gridTap = new TapGestureRecognizer();
        gridTap.Tapped += (sender, e) =>
        {

            Navigation.PushModalAsync(new MarketItemPage());

            item.Id = GridIdentifier.Grid_id; // item.id is the id of the choosen item = static int in class

        };

}

File 2
 public void Update()
    {
        string gridid = GridIdentifier.Grid_id.ToString();

        grid.Children.Add(new Label
        {

            Text = gridid,
            FontSize = 16,
            FontFamily = "Arial",
            TextColor = Color.Red,
            VerticalTextAlignment = TextAlignment.Center,
            HorizontalTextAlignment = TextAlignment.Center,
            HorizontalOptions = LayoutOptions.Center,

        });

    }

Class
public static class GridIdentifier
{
    public static int Grid_id { get; set; }
}

A: There are several ways to achieve this. One way would be to pass the item's Id to the constructor of the MarketItemPage.
For more options, look at the Xamarin information for Passing data when navigating


text:
Q: DM Python template - how do you add ssh access to GCE instances? I'm able to create basic instances using Deployment Manager Python templates but how do you enable ssh access? Using properties/metadata fields? Any examples would be greatly appreciated!

A: If you are not able to SSH into the machine after creating the instances, you might need to add a firewall rule to allow connections on port 22. Something like the below will work.
def GenerateConfig(context):

"""Creates the firewall with environment variables."""

  resources = [{
      'name': context.env['name'],
      'type': 'compute.v1.firewall',
      'properties': {
          'network': '$(ref.' + context.properties['network'] + '.selfLink)',
          'sourceRanges': ['0.0.0.0/0'],
          'allowed': [{
              'IPProtocol': 'TCP',
              'ports': [22]
          }]
      }
  }]
  return {'resources': resources}

Reference: https://github.com/GoogleCloudPlatform/deploymentmanager-samples/blob/master/examples/v2/step_by_step_guide/step7_use_environment_variables/python/firewall-template.py


text:
Q: React Native Hooks - dinamically create an array of refs Introduction
I have an array of data which contains objects with unique ids.
I am trying to create as many references as neccessary. For example, if the array have 4 elements then I will create 4 references. Each reference has to be contained in an array and also, I need to associate it to the unique id of the object.
Here is what I am trying to do in "pseudocode":
Pseudocode
 data = [{id: "10i3298yfrcd", ...}, {id: "y48hfeucldnjs", ...}]

 references = data.map(({id}) => useRef(null))

Problem
I don't know how to associate each created reference to its respective object id (just to access the references like with an array of alphanumeric indexes, or something like this)...
Also, I get an error when creating the references this way:

React has detected a change in the order of Hooks called by %s. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/docs/hooks-rules.html

So I suppose this is not a valid form to create references dynamically.
Any ideas how to do that? Thank you.

A: this is how you can create a useRef depending of data.lenght
import { useEffect, useRef, useState } from react;

const ArrayInputs = () => {
    const inputRef = useRef([]);
    const [data, setData] = useState([]);

    useEffect( () => {
        let data = ['Name', 'Age', 'Gender'];
        inputRef.current = new Array(data.length);
        setData(data);
    }, []);

    useEffect( () => {
        //Example of using inputRef
        if(data.length !== 0) {
            inputRef.current[data.length - 1].focus();
        }
    }, [data]);

    return(
        <View>
            {data.map( (element, i) => <TextInput ref = {el => inputRef.current[i] = el} />)}
        </View>

    );

}


text:
Q: Try to understand normalizr's schema.entity VS Array and Object All:
I am trying to understand the relationship between Entity Array and Object:

*

*Are they just different format to describe diff structure of data? Or Entity is quite diff from the rest two?

*The normalized data result has a structure like {result:,entities:}, are the data structures only defined with schema.Entity put inside entities or so can schema.Array and Object? When I define a schema only use Object and Array, it seems nothing put in entities, I am not sure if it is my schema def fault or this is how normalizr work?

*If only schema.Entity() defined data can put into entities, then how can I put an data array into it, something like {0:.., 1:..,2:,}?

For exmaple, I have data like:
var data = [
    {
        id:"0",
        items:[
            {
                id: "0",
                data: {name:"data-0-0"}
            },
            {
                id: "1",
                data: {name:"data-0-1"}
            }
        ]
    },
    {
        id:"1",
        items:[
            {
                id: "0",
                data: {name:"data-1-0"}
            },
            {
                id: "1",
                data: {name:"data-1-1"}
            }
        ]
    }
]

const normalizedData = normalize(data, [{items:[{data:{}}]}]);

And the normalized data is like:

{
    "entities": {},
    "result": {
        "0": {
            "id": "0",
            "items": [
                {
                    "id": "0",
                    "data": {
                        "name": "data-1-0"
                    }
                }
            ]
        }
    }
}

Thanks

A: Question: Are they just different format to describe diff structure of data? Or Entity is quite diff from the rest two?
Answer: Yes. An Entity is a singular object that has a unique identifier associated with it. Array and Object are more generic structures that can't be uniquely identified. In your case, it looks like you only need to use Array and Entity for the data you're describing.
Question: Are the data structures only defined with schema? Entity put inside entities?
Answer: Yes.


text:
Q: Is it possible to sync data via Foundry Data Connection to a specific branch of a dataset? I'd like to sync data ingested via Foundry Data Connection into a specific branch of a dataset. Is there a way to configure this kind of setup?

A: You can sync data to a specific branch in the Data Connection UI:


text:
Q: PHP security in getting a parameter value I dont know much about PHP so forgive my ignorance. I am trying to have a parameter value entered in the Joomla admin area to append a string to my bootstrap container class to change the page from a fixed to a fluid layout.
I am retrieving the value like this...
$conType = $this->params->get('conType','');

and then simply setting it as follows...
class="container<?php echo "$conType"; ?>

However, I was worried (knowing very little about PHP) if this was a security problem since any value could be set as $conType - is that a problem? If so, would this work instead...?
$conType = (int) $this->params->get('conType','0');

if($conType == "1")
{
 $conType = "-fluid";
}
else
{
 $conType = ' ';
}

And then just echo it again. Is that necessary? is there a better way?

A: Yes, this would work and is secure.
If $conType can be any parameter, it is important to escape it against XSS by using htmlentities():
echo htmlentities($conType)

The way you did it is even better, although it costs more effort. ;-)
Just remember to use htmlentities in future if you need escaping of many parameters and not just one small customization. And as an advise, please inform yourself about php and security before continuing to develop php applications (if you are planning to). As a web developer (especially as php developer), you really should know about topics like "XSS", "SQL Injection" and "CSRF". :-)
[As an alternative to htmlentities, there is htmlspecialchars, which encodes less characters, see htmlentities() vs. htmlspecialchars() for a comparison]


text:
Q: form should not be submitted if any one of the field is empty or not filled correctly using javascript <form>

        Price

        <input type="number" class="form-control" id="add-price" value="0" step="any" min="0" name="number" onfocusout="check(this)" v-model="product.std_rte"/>

<button type="submit" class="btn btn-primary" @click.prevent="createProduct">Create</button>
</form>

above is the HTML code for the question and downwards javascript required for validation.
function check(input){
    if (input.value == 0 || input.value == ""){
        // input.setCustomValidity('The number must not be zero or empty.');
        alert("The number must not be zero or empty.");
        return false;
     }else {
        input.setCustomValidity('');
     }
   return true;
}

the code is running for a input text validation but after i click on save button it is allowing to save the value,when value is zero and empty it is allowing it.i want to trap the form until the value is correctly given according to validation,and it should only allow to submit the form when it is correct.

A: I think something is wrong with this line:
<input type="number" class="form-control" id="add-price" value="0" step="any" min="0" name="number" onfocusout="check(this)" v-model="product.std_rte"/>

You have used onfocusout which is why it is allowing the zero values after submitting. Change it to onclick event and then see the difference.
Hope this helps.

A: What you are doing wrong is that you first check the input field for incorrect input and then the form is submitted which is casing the form to be submitted. The validation is checked before the form submission.
What you need to do is validate the field on the button, so that when ever the button of form submission is clicked it first checks the field before submitting and when the value passes the validation, you can submit the form through javascript.
I have modified the code for the html as :
<form id="form">

                    Price
                     <input type="number" class="form-control" id="add-price" value="0" step="any" min="0" name="number" v-model="product.std_rte"/>

    <button type="submit" class="btn btn-primary" onclick="check(event)">Create</button>
    </form>

and the javascript function as
    function check(input) {
        var price = document.querySelector('#add-price').value;
        debugger;
        input.preventDefault();
        if (price == 0 || price == "") {
            // input.setCustomValidity('The number must not be zero or empty.');
            alert("The number must not be zero or empty.");
            return false;
        } else {
            input.setCustomValidity('');
        }
        document.querySelector('#form').submit();

        return true;
        }

Hope it helps.

A:        function printError(elemId, hintMsg) {
            document.getElementById(elemId).innerHTML = hintMsg;
        }

       function check(input) {
        var priceErr = true;
        var bt = document.getElementById("btsubmit");
        if (input.value <= 0 || input.value ==="") {
            bt.disabled = true;
            printError("priceErr", "Please enter valid price");
            return false;
        } else {
            bt.disabled = false;
            priceErr = false;
            printError("priceErr", "");
        }
        return true;
        }

and the respective Html code
<input type="number" class="form-control" id="add-price" onkeyup="check(this)" v-model="product.std_rte" required/>

<input class="form-control" id="add-itemgrp1hd" v-model="product.itemgrp1hd"required/>

*Mandatory

<input class="form-control" id="add-name" v-model="product.itemfullhd" required/>

*Mandatory

<input type="file" id="edit-imagemain" v-model="product.Image_file" @change="onFileChanged" required/>

*Mandatory

Thanks All of You who all have responded to my question it was very helpful for me to know what actually was missing.here is the answer which works fine for me

A: The check function is called from onfocusout on teh input box, but that cannot prevent a submit. Instead you should call it from the onsubmit="" on the submit button.

A: this might also help i add a ;
          onfocusout="check(this);"

         function check(input) {
         console.log(typeof input.value); //might be possible that the check func is
                                         //fine but not the data
         console.log(input.value);      //so lets have a look
         var chk=true;
         try{
         if (typeof input.value === "undefined" ){ chk=false;}; //shouldn be but...
         if (input.value === 0 ){ chk=false;}; // more secure with type checking
         if (input.value === "" ){ chk=false;};
         if (parseInt(input.value) === 0 ){ chk=false;};  //if it is "0" - a string
         } catch(ex) {
         chk=false;
         console.log(ex);// just to learn more
         }
         if (chk===false){
            // input.setCustomValidity('The number must not be zero or empty.');
            alert("The number must not be zero or empty.");
            return false;
        } else {
            input.setCustomValidity('');
        }
        return true;
        }


text:
Q: Create a menu dynamically in wpf using sql server I have found an example somewhere on internet of creating a menu dynamically using HierarchicalDataTemplate.
Here is the xaml:
<Window x:Class="WPF_Client.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ERP_Lite" Height="350" Width="525"
        WindowState="Maximized" WindowStyle="None">

    <Grid>

        <Grid.Resources>
            <XmlDataProvider x:Key="src" XPath="/myDoc/item">
                <x:XData>
                    <myDoc xmlns="">
                        <item title="One" />
                        <item title="Two">
                            <item title="First Child" />
                            <item title="Second Child" />
                            <item title="Third Child" />
                            <item title="Fourth Child">
                                <item title="First Grand Child" />
                                <item title="Second Grand Child" />
                                <item title="Third Grand Child" />
                            </item>
                        </item>
                        <item title="Three" />
                        <item title="More" />
                    </myDoc>
                </x:XData>
            </XmlDataProvider>
        </Grid.Resources>

        <Menu DataContext="{StaticResource src}" ItemsSource="{Binding}">
            <Menu.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding XPath=item}">
                    <TextBlock Text="{Binding XPath=@title}" />
                </HierarchicalDataTemplate>
            </Menu.ItemTemplate>
        </Menu>

    </Grid>
</Window>

The above xaml works perfectly well. Now I would like to create the same thing using SQL Server instead of xml datasource.
So, for that I have created a table and added the data as follows:
ID  |  Title                 |   ParentID
----+------------------------+-----------
1   |  One                   |   NULL
2   |  Two                   |   NULL
3   |  Three                 |   NULL
4   |  Four                  |   NULL
5   |  First Child           |   2
6   |  Second Child          |   2
7   |  Third Child           |   2
8   |  Fourth Child          |   2
9   |  First Grand Child     |   8
10  |  Second Grand Child    |   8
11  |  Third Grand Child     |   8

Now can anybody tell me how do I bind this table's data with Menu?
Note: I am using EntityFramework and MVVM.
Update
I am sorry, I have not used your code in this example as I don't understand some things like what is Model, the constructor of Node and also you are not filling the values in Parent or Children properties, so it's everything out of my bounds and I tried to use a somewhat different approach than you. Although you have used a parameterized constuctor but you never supply values to constructor, so I really felt it hard.
Here is what I have tried:
Here is my model class for MenuItem:
public partial class MenuItem
{
    public MenuItem()
    {
        this.MenuItems1 = new HashSet<MenuItem>();
    }

    public int MenuItemID { get; set; }
    public string Title { get; set; }
    public Nullable<int> ParentID { get; set; }

    public virtual ICollection<MenuItem> MenuItems1 { get; set; }
    public virtual MenuItem MenuItem1 { get; set; }
}

Here is the Data Transfer Object that I created for MenuItem class to solve the circular reference error :
public class MenuItemDTO
{
    public int MenuItemID { get; set; }
    public string Title { get; set; }
    public Nullable<int> ParentID { get; set; }
}

Here is the method that I have used in WCF service:
public IEnumerable<MenuItemDTO> GetAllMenuItems()
{
    using (Entities db = new Entities())
    {
        return (from m in db.MenuItems
                select new MenuItemDTO
                {
                    MenuItemID = m.MenuItemID,
                    Title = m.Title,
                    ParentID = m.ParentID
                }).ToList();
    }
}

Here is my MainWindowViewModel:
public class MainWindowViewModel : MainViewModel
{
    public MainWindowViewModel()
    {
        ERP_Lite_ServiceClient client = new ERP_Lite_ServiceClient();

        Parents = new ObservableCollection<MenuItemDTO>
                        (client.GetAllMenuItems().Where(m => m.ParentID == null));
        Children = new ObservableCollection<MenuItemDTO>
                         (client.GetAllMenuItems().Where(m => m.ParentID != null));

        client.Close();
    }

    private ObservableCollection<MenuItemDTO> _parents;
    public ObservableCollection<MenuItemDTO> Parents
    {
        get
        {
            return _parents;
        }
        set
        {
            _parents = value;
            OnPropertyChanged("Parents");
        }
    }

    private ObservableCollection<MenuItemDTO> _children;
    public ObservableCollection<MenuItemDTO> Children
    {
        get
        {
            return _children;
        }
        set
        {
            _children = value;
            OnPropertyChanged("Children");
        }
    }

}

Here is the xaml:
<Menu ItemsSource="{Binding Parents}">
    <Menu.ItemTemplate>
        <HierarchicalDataTemplate DataType="{x:Type Service:MenuItemDTO}"
                                  ItemsSource="{Binding Children}">
            <TextBlock Text="{Binding Title}" />
        </HierarchicalDataTemplate>
    </Menu.ItemTemplate>
</Menu>

But I have got some problem with my code. In output I get all the Parent Items but no child items are displayed. Can you help me?

A: In order to work with HierarchicalDataTemplate your ViewModel needs to be hierarchical too. which means ItemsSource inside HierarchicalDataTemplate is relative to that node. but in your code you've defined Parent and Children in the same ViewModel,
Think of MenuItemDTO as one random node in the tree, so it should have some children with the same type (MenuItemDTO).
if you set the ItemsSource of Menu to "{Binding Parents}" it means top level items of the Menu are Parents.
Now if you set the ItemsSource of the HierarchicalDataTemplate to "{Binding Children}", it can find the children of that node, by looking at its own ItemsSource. which should be set for each node in the tree.
Solution:
Move Children to MenuItemDTO.
then you might need to modify GetAllMenuItems() a little.
Try the code below (it's tested and it works fine). it returns a list of MenuItemDTOs that belong to first level of menu, and each has its Children filled recursively.
first level of tree (menu) = menu items with no parent
public IEnumerable<MenuItemDTO> GetAllMenuItems()
{
  using (Entities db = new Entities())
  {
    //get all items and put them in a simple list
    var allItems = (from m in db.MenuItems
                select new MenuItemDTO
                {
                    MenuItemID = m.MenuItemID,
                    Title = m.Title,
                    ParentID = m.ParentID
                }).ToList();

    //define another list and put "only" root items in it
    //  this will have a hierarchical structure (By correcting the Children)
    //  and it's the output of this function
    var roots = allItems.Where(x => x.ParentID == null);

    //here we correct Children of each item
    //since both allItems and roots share the same elements (call-by-reference)
    //instead of searching through a tree, simply search through allItems
    foreach (var item in allItems)
    {
      //find the correct parent for current item
      var parent = allItems.FirstOrDefault(x => x.MenuItemID == item.ParentID);

      //add the item to Children of its parent
      //   by doing this, one single item in both allItems
      //   and roots (or recursively in roots) will be corrected
      if(parent!=null)
           parent.Children.Add(item);

      //if you don't want to miss any menu item:
      //else roots.Add(item);
    }
    return roots;
  }
}


text:
Q: Visual studio 2010 setup project localization I would like to change localization in visual studio 2010 (setup project properties) setup project to slovak (language)[or any other language, which is not in the menu], but in menu there are only these languages:

*

*neutral

*chinese

*czech

*english

*french

*german

*italian

*japanese

*korean

*polish

*portuguese

*russian

*spanish

*turkish

so my two questions are:

*

*Can i import/add slovak localization into visual studio?

*Or use english localization, but use unicode character set, because when i use english localization, i can't use characters like 'č','ť','ľ' etc.?

A: Basically you can use an MSI editor like Orca in the Windows SDK and use it to edit all the text in the MSI file. Unicode should work fine. To re-use that translation, start the edit with the Transform->New transform on the Orca menu, then make your changes, then Transform->Generate transform to create an mst file.  If you rebuild the MSI file you can do Transform->Apply transform to get your changes back into the MSI file. So basically you create your own translation and import it into the MSI file. In Orca, View->Summary Information you'd need to add the language code.
I don't know the internals of where VS keeps the translations or how you'd make your own.
Or you could look at other tools that create MSI files. VS support for creating MSI files has gone away.


text:
Q: Error: Unexpected token: punc (.) in file node_modules/react-native-gesture-handler/src/handlers/ForceTouchGestureHandler.ts I am setting up Detox e2e test for my new RN app but there is an issue when I build app with mode release
My build command:
xcodebuild -workspace ios/MyApp.xcworkspace -scheme MyApp -configuration Release -sdk iphonesimulator -derivedDataPath ios/build
Error: Error: Unexpected token: punc (.) in file node_modules/react-native-gesture-handler/src/handlers/ForceTouchGestureHandler.ts at 63:60
I am not sure it is issue of react-native-gesture-handler or metro/babel
here is my package.json
"react-native": "0.70.0-rc.4",
"react-native-gesture-handler": "^2.9.0",

my babel.config.js
module.exports = {
 presets: [
   ["module:metro-react-native-babel-preset", {unstable_transformProfile: "hermes-stable"}],
 ],
 plugins: [
   [
     require.resolve("babel-plugin-module-resolver"),
     {
       root: ["./"],
       alias: {
         "@": "./src",
       },
     },
   ],
   "react-native-reanimated/plugin",
 ],
};


text:
Q: serdev not sending when i enable flow control I created a serdev device driver and want to enable the CTS/RTS pins for my hardware flow control. When the flow control is disabled like this: serdev_device_set_flow_control(serdev, false); it is sending. But as soon as I enable it, it will not send anymore.
So i looked at the implementation:
void serdev_device_set_flow_control(struct serdev_device *serdev, bool enable)
{
    struct serdev_controller *ctrl = serdev->ctrl;

    if (!ctrl || !ctrl->ops->set_flow_control)
        return;

    ctrl->ops->set_flow_control(ctrl, enable);
}

Before I call it I verified my controller is there and my property set_flow_control is true. So that looks fine. So it should be set. But it is not sending anymore.
Thanks for the feedback here is my inizialisation:
    struct serdev_controller *ctrl = serdev->ctrl;
    struct stmuart *stm;
    int speed = 3000000u;
    int ret;

    pr_info("Insert Network driver\n");

    stm = devm_kzalloc(&serdev->dev, sizeof(*stm), GFP_KERNEL);

    stm->serdev = serdev;

    INIT_WORK(&stm->tx_work, stmuart_transmit);

    serdev_device_set_drvdata(serdev, stm);
    serdev_device_set_client_ops(serdev, &stm_serdev_ops);

    ret = serdev_device_open(serdev);
    if (ret) {
        dev_err(&serdev->dev, "Unable to open device\n");
        goto free;
    }

    speed = serdev_device_set_baudrate(serdev, speed);
    dev_info(&serdev->dev, "Using baudrate: %u\n", speed);

    serdev_device_set_flow_control(serdev, true);
    dev_info(&serdev->dev, "set_flow_control: %s\n", ctrl->ops->set_flow_control ? "true" : "false");

    return 0;

free:
    return ret;

I checked it with the oszi and it is not not sending and the CTS and RTS pins are not changing.
Here is my Device tree configuration.
usart3: serial@4000f000 {
            compatible = "st,stm32h7-uart";
            reg = <0x4000f000 0x400>;
            interrupts-extended = <&exti 28 IRQ_TYPE_LEVEL_HIGH>;
            clocks = <&rcc USART3_K>;
            wakeup-source;
            power-domains = <&pd_core>;
            dmas = <&dmamux1 45 0x400 0x15>,
                   <&dmamux1 46 0x400 0x11>;
            dma-names = "rx", "tx";
            status = "ok";

            ethernet {
                compatible = "st,stm32_usart_net";
                local-mac-address = [ A0 B0 C0 D0 E0 F0 ];
                current-speed = <38400>;
                };
        };

My other device tree file
&usart3 {
    pinctrl-names = "default", "sleep", "idle";
    pinctrl-0 = <&usart3_pins_c>;
    pinctrl-1 = <&usart3_sleep_pins_c>;
    pinctrl-2 = <&usart3_idle_pins_c>;
    uart-has-rtscts;
    status = "ok";
};

I disabled the hardwareflow control and trieed to set my RTS manually with serdev_device_set_tiocm(serdev, 0, TIOCM_RTS);but its not changing.


text:
Q: Danger to swimmer from lightning? Having been swimming a few times recently when a thunderstorm developed, I've started wondering what the actual dangers are (please note - I'm more interested in this from a science perspective; I get out of the water  if a storm develops, and would advise anyone to do the same). Here's what I think I know of the matter, from some reading on the Internet as well as my own (basic) scientific knowledge, and some questions. Any pointers to research on this would be appreciated.

*

*As a swimmer, you're a bit higher than the surrounding water, but not by much, particularly if there's waves. So the risk of a direct strike is probably not significantly increased.

*The electric current dissipates outwards, near the surface of the water, and can spread some distance (not sure how much)

*Fresh water is a worse conductor than salty water, so swimming in a lake/pool is more dangerous (in a storm, than in seawater), since the electric current will prefer better conductors.

*Lightning is extremely loud at the strike zone; the noise alone could cause deafness/ear damage.

*Being on land (exposed) during a storm is probably more dangerous than being in the water - you're taller, and not surrounded by a conductive medium.

*How much does the temperature of the water/air increase near a lightning strike?

*My main question is, if you are in the presence of a direct lightning strike at sea, would the sea water all around you act like a Faraday cage, and take the electric current around your body rather than through it?

A: It does not appear that if you're in salt water you will be safe due to the fact that the sea water is conductive and will somehow protect a person from lightning. Since the human body is itself conductive, it seems that as the electrical energy passes through the water, enough of it should also pass through the person, making it harmful or lethal.
While it might be the case that a person in fresh water is in more danger than someone swimming in salt water (as you stated, fresh water is a poor conductor meaning a human body will absorb the electrical energy of close-by lightning strike) an actual researcher in lightning states that:
"the horizontal distance that the lightning energy [in water] would travel across the surface would depend on the intensity (current) of the lightning and how deep the water is where the stroke hit the water. Water is a fairly good conductor of electrical energy. If you dropped a 120 volt AC line into an 18 foot diameter, 3 foot deep home swimming pool, you very well may be killed. In the case of lightning, multiply the electrical current by thousands, and for the ocean multiply the volume by as much as millions.
My guess is that the average lightning strike would electrify a few hundred feet worth of water from it's strike point sufficiently to electrocute someone. However, some current is probably for up to a mile before it is fully dissipated."


text:
Q: Bounding a value of holomorphic function Let $f$ be a holomorphic function such that $|f(z)+4| \leq | z^2 + 2 |$ for $|z|=1$
It is asked to prove that $2 \leq  |f(0)| \leq 6$
Truth is I'm not sure if it is true :
First, using the mean formula we have $|f(0) + 4| \leq \dfrac{1}{2 \pi} \int_{0}^{2 \pi} |f(\exp(it) + 2| dt \leq \int_{0}^{2 \pi} |\exp(2it) + 2 | dt \sim 2.12 $
I want somehow to bound $|f(0) + 4|$ by $2$ but I can't because $|z^2+2|$ is not holomorphic
Any ideas ?

A: Here I expect that $f$ is holomorphic on the unit disc and continuous at least on the circle for the problem to make sense.
Let $g(z)=\frac{f(z)+4}{z^2+2}, |z| \le 1$. Clearly $g$ is analytic on the unit disc and continous on the boundary, and by hypothesis $|g(z)| \le 1$ on the unit circle, so by maximum modulus that holds inside the unit disc so $|g(0)| \le 1$ which translates as $|f(0)+4| \le 2$; this implies the required result by the triangle inequality


text:
Q: How to parser XML exactly XLIFF files and get the *source* content in PHP How to parser XML exactly XLIFF files and get the source content in PHP.
how to get the source content of the xml file http://docs.oasis-open.org/xliff/v1.2/cs02/Sample_AlmostEverything_1.2_strict.xlf

A: In XQuery //xliff means any xliff element in the document. /xliff means from the root of the document. ./xliff or or xliff gets children of the current node.

A: //xliff finds all <xliff> tags at any depth of nesting within the document.  /xliff finds them (it) only at the root level.


text:
Q: GTM create new variables in dependence to existing variable (WPForms tracking) I track the values of a WPForms form with GTM and with the following code I get the selected values from a multiselect dropdown:
  function() {
  var selectList = {{wpFormElement}}.querySelector('#wpforms-1397-field_16');
  var options = selectList ? selectList.options : [];
  var vals = [];
  var i, len;
  for (i = 0, len = options.length; i < len; i++) {
    if (options[i].selected) {
      vals.push(options[i].value);
    }
  }
  return vals.length ? vals.join(' ') : undefined;
}

The output are the product-id's:
'2705 1446 2772'

I would like to submit the products with the real name to analytics and not the id. How do I get a new variable (each) with the real product name depending on the product-id's?
var1: 2705 = product 1
var2: 1446 = product 2
var3: 2772 = product 3
thx

A: It sounds like you need an array of product names.  The easiest way to go from one value to another is by using an object like the productIdNameMap variable in the example below.  This modified code will return a list of product names, so you can use a for loop to do something with each one if you want.

(function() {
  var selectList = document.querySelector('#wpforms-1397-field_16');
  var options = selectList ? selectList.options : [];
  var productIdNameMap = {
    2705: 'product 1',
    1446: 'product 2',
    2772: 'product 3',
    2020: 'product 4'
  };

  var vals = [];
  var i, len, productId;
  for (i = 0, len = options.length; i < len; i++) {
    if (options[i].selected) {
      productId = options[i].value
      vals.push(productIdNameMap[productId]);
    }
  }

  console.log(vals);
  return vals;
})();
<select multiple id="wpforms-1397-field_16">
  <option selected>2705</option>
  <option selected>1446</option>
  <option selected>2772</option>
  <option>2020</option>
</select>


text:
Q: Using tool from ArcToolbox gives error? I have problem with ran tool from ArcToolbox. When I run any tool, I get error:

Content within this application coming from the website listed is
  being blocked by Internet Explorer Enhanced Security Configuration.

I work on Windows Serwer 2012 R2 and use ArcGis for Desktop 10.3.1
I try:

*

*reinstall ArcGis for Desktop 10.3.1

*to activate ActiveX (http://support.esri.com/technical-article/000011895)

*add http://localhost to trusted sites (http://www.makeuseof.com/tag/configure-trusted-sites-internet-explorer-group-policy/)

But problem still exists.
How to fix this?

A: Option 1:  Remove IE enhanced security configuration
https://4sysops.com/archives/how-to-disable-internet-explorer-enhanced-security-configuration-ie-esc-in-windows-server-2012/
Option 2:  Adjust Active X filtering in IE settings:
http://support.esri.com/technical-article/000011895
Option 3:  Since adding localhost didn't work, do you need to add a server address? (do you have ArcGIS server installed?)
http://support.esri.com/technical-article/000010629


text:
Q: Breaking a string along whitespace once certain width is exceeded (Python) I am rendering text atop a base image.
One core requirement is for the string to wrap to the next line(s) whenever the total width of characters exceeds the width of the base image. I accomplish this via the following correctly-working snippet:
base_width, base_height = base_img.size
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", font_size)
line_width = 0
line_count = 1
lines = []
string = ""
for c in text:
    line_width += font.getsize(c)[0]
    string+=str(c)
    if line_width > base_width:
        lines.append(string)
        string = ""
        line_width = 0
        line_count += 1
if string:
    lines.append(string)

The result lines is a list of substrings gotten via breaking up the original string.
Now I need to improve this algorithm.
The problem is that it breaks the line mid-word. E.g. The string lorem ipsum could end up as lines = ['lorem ip','sum']. Instead, the ideal break-up for me is the much more human readable lines = ['lorem ','ipsum'], or lines = ['lorem',' ipsum'].
In other words, I want to break the lines along white spaces, and not mid-word. Can someone give me an illustrative example of how I can accomplish that? Can't seem to wrap my head around it.

A: There is a python module textwrap specifically for this:
In [1]: import textwrap

In [2]: textwrap.wrap('x lorem ipsum', width=5)
Out[2]: ['x', 'lorem', 'ipsum']

edit:
I misunderstood the author's purpose. The problem is that the width of a line is not defined as the number of characters but as the width of the image containing the rendered text. I came up with a hacky method by implementing a custom string class with correct width definition and modifying the TextWrapper class slightly:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import textwrap

class MyTextWrapper(textwrap.TextWrapper):

    def _split(self, text):
        assert isinstance(text, StringWithWidth)
        return [StringWithWidth(i) for i in super()._split(text._str)]

    def _wrap_chunks(self, chunks):
        # only modify ''.join in the original code
        """_wrap_chunks(chunks : [string]) -> [string]

        Wrap a sequence of text chunks and return a list of lines of
        length 'self.width' or less.  (If 'break_long_words' is false,
        some lines may be longer than this.)  Chunks correspond roughly
        to words and the whitespace between them: each chunk is
        indivisible (modulo 'break_long_words'), but a line break can
        come between any two chunks.  Chunks should not have internal
        whitespace; ie. a chunk is either all whitespace or a "word".
        Whitespace chunks will be removed from the beginning and end of
        lines, but apart from that whitespace is preserved.
        """
        lines = []
        if self.width <= 0:
            raise ValueError("invalid width %r (must be > 0)" % self.width)
        if self.max_lines is not None:
            if self.max_lines > 1:
                indent = self.subsequent_indent
            else:
                indent = self.initial_indent
            if len(indent) + len(self.placeholder.lstrip()) > self.width:
                raise ValueError("placeholder too large for max width")

        # Arrange in reverse order so items can be efficiently popped
        # from a stack of chucks.
        chunks.reverse()

        while chunks:

            # Start the list of chunks that will make up the current line.
            # cur_len is just the length of all the chunks in cur_line.
            cur_line = []
            cur_len = 0

            # Figure out which static string will prefix this line.
            if lines:
                indent = self.subsequent_indent
            else:
                indent = self.initial_indent

            # Maximum width for this line.
            width = self.width - len(indent)

            # First chunk on line is whitespace -- drop it, unless this
            # is the very beginning of the text (ie. no lines started yet).
            if self.drop_whitespace and chunks[-1].strip() == '' and lines:
                del chunks[-1]

            while chunks:
                l = len(chunks[-1])

                # Can at least squeeze this chunk onto the current line.
                if cur_len + l <= width:
                    cur_line.append(chunks.pop())
                    cur_len += l

                # Nope, this line is full.
                else:
                    break

            # The current line is full, and the next chunk is too big to
            # fit on *any* line (not just this one).
            if chunks and len(chunks[-1]) > width:
                self._handle_long_word(chunks, cur_line, cur_len, width)
                cur_len = sum(map(len, cur_line))

            # If the last chunk on this line is all whitespace, drop it.
            if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
                cur_len -= len(cur_line[-1])
                del cur_line[-1]

            if cur_line:
                if (self.max_lines is None or
                    len(lines) + 1 < self.max_lines or
                    (not chunks or
                     self.drop_whitespace and
                     len(chunks) == 1 and
                     not chunks[0].strip()) and cur_len <= width):
                    # Convert current line back to a string and store it in
                    # list of all lines (return value).
                    lines.append(StringWithWidth(
                        indent + ''.join(map(_as_str, cur_line))))
                else:
                    while cur_line:
                        if (cur_line[-1].strip() and
                            cur_len + len(self.placeholder) <= width):
                            cur_line.append(self.placeholder)
                            lines.append(StringWithWidth(
                                indent + ''.join(map(_as_str, cur_line))))
                            break
                        cur_len -= len(cur_line[-1])
                        del cur_line[-1]
                    else:
                        if lines:
                            prev_line = lines[-1].rstrip()
                            if (len(prev_line) + len(self.placeholder) <=
                                    self.width):
                                lines[-1] = prev_line + self.placeholder
                                break
                        lines.append(indent + self.placeholder.lstrip())
                    break

        return lines

def _make_str_fwd(name):
    def func(self, *args, **kwargs):
        return StringWithWidth(getattr(self._str, name)(*args, **kwargs))
    func.__name__ = name
    return func

def _as_str(val):
    if isinstance(val, StringWithWidth):
        val = val._str
    assert isinstance(val, str)
    return val

class StringWithWidth:
    char_width = {
        'x': 1,
        's': 2,
        ' ': 1
    }

    def __init__(self, s):
        self._str = s

    expandtabs = _make_str_fwd('expandtabs')
    translate = _make_str_fwd('translate')
    strip = _make_str_fwd('strip')
    __getitem__ = _make_str_fwd('__getitem__')

    def __eq__(self, rhs):
        return self._str == _as_str(rhs)

    def __add__(self, rhs):
        return StringWithWidth(self._str + _as_str(rhs))

    def __len__(self):
        return sum(map(self.char_width.__getitem__, self._str))

    def __repr__(self):
        return repr(self._str)

def main():
    print(MyTextWrapper(width=8).wrap(StringWithWidth('x ss s')))

if __name__ == '__main__':
    main()

A: Here's an attempt to get your code working with minimal changes, and lots of debug output:
#!python3
#coding=utf-8
""" Line break demo 2 """

text = "lorem ipsum dolor sit amet blablah"

for wmax in [10,25,55,80,100,120]:

    print(wmax)

    base_width, base_height = (wmax,None)#base_img.size
    #font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", font_size)
    line_width = 0
    line_count = 1
    lines = []
    string = ""
    for c in text:
        line_width += 5#font.getsize(c)[0]
        string += c
        if line_width > base_width:

            print("text  ", text)
            print("string", string)

            s = string.rsplit(" ", 1)
            print("split ", s)

            string = s[0]
            lines.append(string)

            try:
                string = s[1]
                line_width = len(string) * 5
            except:
                string = ""
                line_width = 0

            print("lines ", lines)
            print("string", string)

            line_count += 1
            print()

    if string:
        lines.append(string)

    print(lines)
    print()

Output:
10
text   lorem ipsum dolor sit amet blablah
string lor
split  ['lor']
lines  ['lor']
string

text   lorem ipsum dolor sit amet blablah
string em
split  ['em', '']
lines  ['lor', 'em']
string

text   lorem ipsum dolor sit amet blablah
string ips
split  ['ips']
lines  ['lor', 'em', 'ips']
string

text   lorem ipsum dolor sit amet blablah
string um
split  ['um', '']
lines  ['lor', 'em', 'ips', 'um']
string

text   lorem ipsum dolor sit amet blablah
string dol
split  ['dol']
lines  ['lor', 'em', 'ips', 'um', 'dol']
string

text   lorem ipsum dolor sit amet blablah
string or
split  ['or', '']
lines  ['lor', 'em', 'ips', 'um', 'dol', 'or']
string

text   lorem ipsum dolor sit amet blablah
string sit
split  ['sit']
lines  ['lor', 'em', 'ips', 'um', 'dol', 'or', 'sit']
string

text   lorem ipsum dolor sit amet blablah
string  am
split  ['', 'am']
lines  ['lor', 'em', 'ips', 'um', 'dol', 'or', 'sit', '']
string am

text   lorem ipsum dolor sit amet blablah
string ame
split  ['ame']
lines  ['lor', 'em', 'ips', 'um', 'dol', 'or', 'sit', '', 'ame']
string

text   lorem ipsum dolor sit amet blablah
string t b
split  ['t', 'b']
lines  ['lor', 'em', 'ips', 'um', 'dol', 'or', 'sit', '', 'ame', 't']
string b

text   lorem ipsum dolor sit amet blablah
string bla
split  ['bla']
lines  ['lor', 'em', 'ips', 'um', 'dol', 'or', 'sit', '', 'ame', 't', 'bla']
string

text   lorem ipsum dolor sit amet blablah
string bla
split  ['bla']
lines  ['lor', 'em', 'ips', 'um', 'dol', 'or', 'sit', '', 'ame', 't', 'bla', 'bla
string

['lor', 'em', 'ips', 'um', 'dol', 'or', 'sit', '', 'ame', 't', 'bla', 'bla', 'h']

25
text   lorem ipsum dolor sit amet blablah
string lorem
split  ['lorem', '']
lines  ['lorem']
string

text   lorem ipsum dolor sit amet blablah
string ipsum
split  ['ipsum', '']
lines  ['lorem', 'ipsum']
string

text   lorem ipsum dolor sit amet blablah
string dolor
split  ['dolor', '']
lines  ['lorem', 'ipsum', 'dolor']
string

text   lorem ipsum dolor sit amet blablah
string sit am
split  ['sit', 'am']
lines  ['lorem', 'ipsum', 'dolor', 'sit']
string am

text   lorem ipsum dolor sit amet blablah
string amet b
split  ['amet', 'b']
lines  ['lorem', 'ipsum', 'dolor', 'sit', 'amet']
string b

text   lorem ipsum dolor sit amet blablah
string blabla
split  ['blabla']
lines  ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'blabla']
string

['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'blabla', 'h']

55
text   lorem ipsum dolor sit amet blablah
string lorem ipsum
split  ['lorem ipsum', '']
lines  ['lorem ipsum']
string

text   lorem ipsum dolor sit amet blablah
string dolor sit am
split  ['dolor sit', 'am']
lines  ['lorem ipsum', 'dolor sit']
string am

text   lorem ipsum dolor sit amet blablah
string amet blablah
split  ['amet', 'blablah']
lines  ['lorem ipsum', 'dolor sit', 'amet']
string blablah

['lorem ipsum', 'dolor sit', 'amet', 'blablah']

80
text   lorem ipsum dolor sit amet blablah
string lorem ipsum dolor
split  ['lorem ipsum', 'dolor']
lines  ['lorem ipsum']
string dolor

text   lorem ipsum dolor sit amet blablah
string dolor sit amet bl
split  ['dolor sit amet', 'bl']
lines  ['lorem ipsum', 'dolor sit amet']
string bl

['lorem ipsum', 'dolor sit amet', 'blablah']

100
text   lorem ipsum dolor sit amet blablah
string lorem ipsum dolor sit
split  ['lorem ipsum dolor', 'sit']
lines  ['lorem ipsum dolor']
string sit

['lorem ipsum dolor', 'sit amet blablah']

120
text   lorem ipsum dolor sit amet blablah
string lorem ipsum dolor sit ame
split  ['lorem ipsum dolor sit', 'ame']
lines  ['lorem ipsum dolor sit']
string ame

['lorem ipsum dolor sit', 'amet blablah']

A: Maybe this simple approach helps, although I assume recursion may be more elegant. Note that the fixed value for character width needs to be replaced with the corresponding function call.
#!python3
#coding=utf-8
""" Line break demo """

text = "lorem ipsum dolor sit amet blablah"
print("breaking", text)

words = text.split()
widths = [sum( [5 for c in w] ) for w in words]
#print(words)
#print(widths)
print(len(words), "words")

for wmax in [10,25,55,80,100,120]:

    print("\nmax line width:", wmax)
    lines = []
    li = 0
    r = range(len(widths))  # 0...5
    for i in r:
        w = sum(widths[li:i+1])
        if w >= wmax and i>0:
            lines.append( " ".join(words[li:i]) )
            li = i
            print("    ---")
            w = sum(widths[li:i+1])

        print( "  ", i, words[i], widths[i], w )
    # remainder
    lines.append( " ".join(words[li:]) )

    print(lines)

Output:
breaking lorem ipsum dolor sit amet blablah
6 words

max line width: 10
   0 lorem 25 25
    ---
   1 ipsum 25 25
    ---
   2 dolor 25 25
    ---
   3 sit 15 15
    ---
   4 amet 20 20
    ---
   5 blablah 35 35
['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'blablah']

max line width: 25
   0 lorem 25 25
    ---
   1 ipsum 25 25
    ---
   2 dolor 25 25
    ---
   3 sit 15 15
    ---
   4 amet 20 20
    ---
   5 blablah 35 35
['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'blablah']

max line width: 55
   0 lorem 25 25
   1 ipsum 25 50
    ---
   2 dolor 25 25
   3 sit 15 40
    ---
   4 amet 20 20
    ---
   5 blablah 35 35
['lorem ipsum', 'dolor sit', 'amet', 'blablah']

max line width: 80
   0 lorem 25 25
   1 ipsum 25 50
   2 dolor 25 75
    ---
   3 sit 15 15
   4 amet 20 35
   5 blablah 35 70
['lorem ipsum dolor', 'sit amet blablah']

max line width: 100
   0 lorem 25 25
   1 ipsum 25 50
   2 dolor 25 75
   3 sit 15 90
    ---
   4 amet 20 20
   5 blablah 35 55
['lorem ipsum dolor sit', 'amet blablah']

max line width: 120
   0 lorem 25 25
   1 ipsum 25 50
   2 dolor 25 75
   3 sit 15 90
   4 amet 20 110
    ---
   5 blablah 35 35
['lorem ipsum dolor sit amet', 'blablah']

A: Here's how I've approached the problem's solution (re-wrote my original code):
def break_lines(img, text, font_size):
    base_width = img.size[0]
    font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", font_size)
    line = ""
    lines = []
    width_of_line = 0
    number_of_lines = 0
    # break string into multi-lines that fit base_width
    for token in text.split():
        token = token+' '
        token_width = font.getsize(token)[0]
        if width_of_line+token_width < base_width:
            line+=token
            width_of_line+=token_width
        else:
            lines.append(line)
            number_of_lines += 1
            width_of_line = 0
            line = ""
            line+=token
            width_of_line+=token_width
    if line:
        lines.append(line)
        number_of_lines += 1
    return lines, number_of_lines

A: I couldn't get this out of my head, so here it is a little more compact:
#!python3
#coding=utf-8
""" Line break demo 3 """

def charwidth(char):
    return 5

def stringwidth(string):
    return sum( [charwidth(char) for char in string] )

text = "lorem ipsum dolor sit amet blablah"
limit = 60
words = text.split()
lines = [[]]
while( words ):
    word = words.pop(0)
    if stringwidth( " ".join(lines[-1]) ) + 1 + stringwidth(word) < limit:
        lines[-1].append(word)
    else:
        lines.append( [word] )

print( [" ".join(words) for words in lines ] )

A: Here's a modified version of @handle's third answer that also allows splitting long words.
This function also allows one to specify a maximum number of lines and truncate with "..." when over the limit.
def text_width(text, font):
    return font.getsize(text)[0]

# Set max_lines to 0 for no limit
def wrap_text(text, font, max_width, max_lines=0):
    words = text.split()
    lines = []
    while(words):
        word = words.pop(0)
        # Append word if it's not too long
        if len(lines) > 0 and (text_width(" ".join(lines[-1]), font) + 1 + text_width(word,font)) < max_width:
            lines[-1].append(word)
        else:
            # Brute-force: chunkify word until it fits
            chunk = len(word)
            while chunk > 0:
                while (text_width(word[:chunk],font) > max_width and chunk > 1):
                    chunk -= 1
                lines.append( [word[:chunk]] )
                word = word[chunk:]
                chunk = len(word)
    lines = [" ".join(words) for words in lines]
    if max_lines and len(lines) > max_lines:
        lines[max_lines-1] = lines[max_lines-1][:-1] + "..."
    return "\n".join(lines[:max_lines])


text:
Q: NodeJs VM - save compiled code... to disk? From http://nodejs.org/api/vm.html:

JavaScript code can be compiled and run immediately or compiled, saved, and run later. [...] The returned script is not bound to any global object. It is bound before each run, just for that run.

And then in the API, no method that returns any bytes, nothing. Just a "Script" object.
So, before I politely tear down this desk beneath my arms, is there any way that I can actually SAVE the compiled script, to disk? I figure it's just ordinary raw binary data, maybe a syntax tree or whatever.

A: The functions you reference are for javascript being run by javascript in a new context (so it can be secure, have new features, etc)... not so much saving a pre-compiled binary...
If you want details on how to actually reload a precompiled script, you can look at the node.js source. The 'node.js' file itself, is precompiled and loaded as a binary (if you build it with this option). In doing so, it makes node start faster.
What you should bear in mind, however, is there is little advantage to this, unless you conceive a particular process (such as node.js) using the V8 library that will run/stop/run/stop... etc. Reason being, the V8 library will only compile your script once - and will then execute it as machine code each time thereafter, or as long as the V8 library is running.
Precompiling, and loading as a binary, will bring some significant disadvantages, including making your program architecture dependent (even across x86 32-bit versus x86_64) and so forth. So - this may not be the best design decision.


text:
Q: How to solve case insensitive conflict name in COM while I using a case sensitive language This question is an extension of this article.
In the same case, I created a instance of WMP ActiveX by its ProgID.
protected const string WMP_PROG_ID = "WMPlayer.OCX.7";

private dynamic _wmp;

protected virtual bool init(){
    try{
        _wmp = Activator.CreateInstance(Type.GetTypeFromProgID(WMP_PROG_ID));
    }
    catch{ return false; }
    return connectEvent();
}

According the MSDN document, there are an Error event and an error property in WMPlayer object.
So, I try to attach events like this way.
protected bool connectEvent(){
    try{
        _wmp.PlayStateChange += new StateHandler(_wmp_PlayStateChange);
        //_wmp.Error += new Action(_wmp_ErrorEvent);
    }
    catch { return false; }
    return true;
}

protected void _wmp_PlayStateChange(WMPlayerState state){
    //do something I like
}

protected void _wmp_ErrorEvent(){
    //do some error handling
}

If I keep //_wmp.Error += new Action(_wmp_ErrorEvent) commented,
there's no compile error and PlayStateChange works pretty good.
However, if I remove the comment mark, there's a runtime exception.
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: can not apply operator "+=" between 'System.__ComObject' and 'System.Action'
It seems the two "error" are conflicted because COM is case insensitive. How can I solve it?
My goal is that attach to "Error" event without using AxWindowsMediaPlayer.

A: I ran in to a very similar problem as you but mine was with Size. The strongly typed ActiveX control redefined Size so I needed to cast it back to Control when the forms designer wanted to size the control on my form.
((Control)this.axLEAD1).Size = new System.Drawing.Size(298, 240);

If you can get a strongly typed class for the com object (by adding a reference or using tlbimp.exe) you may be able to cast to the strongly typed com object instead of __ComObject and have it use the correct method.


text:
Q: I am having issues with a repeating while loop in a switch statement, the loop continues to repeat I'm a newbie coder and for a class I was required to make a vending machine-like code. However, I used a switch statement as part of it. An issue I faced is that in those if statements I added a check.  The check was to ask if the user would like to continue or not, but for some reason it repeats even after an input. I wasn't entirely sure if this question was asked before, but a lot of my friends share the issue.
import java.util.Scanner;
public class hw52 {
public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    String choice;
    String answer = "";
    int cr = 0;
    int wb = 0;
    int ch = 0;
    int k = 0;
    int j = 0;
    boolean check =  true;
    double cost2;
    double discount;
    double change = 0;
    double cost = 0;
    double money = 0;
    int counter = 0;
    do {
        answer = "";
        System.out.println("Select an option in the vending machine. \n
Crunch:$1.50 \n Water bottle:$2.00 \n Chips:$1.00 \n Ketchup:$4.00 \n
Juice:$2.50");
        choice = keyboard.nextLine();
        switch(choice.toUpperCase()){
        case "CRUNCH":
            cost += 1.5;
            cr ++;
            counter ++;
            System.out.println("Cost: " + cost);
            while(check = true) {
            System.out.println("Do you want to continue? Yes or no?");
            answer = keyboard.nextLine();
            if (answer.equalsIgnoreCase("Yes")) {
                check = false;
            }else if(answer.equalsIgnoreCase("Yes")) {
                check = false;
            }else {
                System.out.println("Bad input.");
            }
            }
        case "WATER BOTTLE":
            cost += 2.00;
            wb++;
            counter ++;
            System.out.println("Cost: " + cost);
            while(check = true) {
                System.out.println("Do you want to continue? Yes or no?");
                answer = keyboard.nextLine();
                if (answer.equalsIgnoreCase("Yes")) {
                    check = false;
                }else if(answer.equalsIgnoreCase("Yes")) {
                    check = false;
                }else {
                    System.out.println("Bad input.");
                }
                }
        case "CHIPS":
            cost += 1.00;
            ch++;
            counter ++;
            System.out.println("Cost: " + cost);
            System.out.println("Cost: " + cost);
            while(check = true) {
                System.out.println("Do you want to continue? Yes or no?");
                answer = keyboard.nextLine();
                if (answer.equalsIgnoreCase("Yes")) {
                    check = false;
                }else if(answer.equalsIgnoreCase("Yes")) {
                    check = false;
                }else {
                    System.out.println("Bad input.");
                }
                }
        case "KETCHUP":
            cost += 5.00;
            k++;
            counter ++;
            System.out.println("Cost: " + cost);
            while(check = true) {
                System.out.println("Do you want to continue? Yes or no?");
                answer = keyboard.nextLine();
                if (answer.equalsIgnoreCase("Yes")) {
                    check = false;
                }else if(answer.equalsIgnoreCase("Yes")) {
                    check = false;
                }else {
                    System.out.println("Bad input.");
                }
                }
        case "JUICE":
            cost += 2.50;
            j++;
            counter ++;
            System.out.println("Cost: " + cost);
            while(check = true) {
                System.out.println("Do you want to continue? Yes or no?");
                answer = keyboard.nextLine();
                if (answer.equalsIgnoreCase("Yes")) {
                    check = false;
                }else if(answer.equalsIgnoreCase("Yes")) {
                    check = false;
                }else {
                    System.out.println("Bad input.");
                }
                }
        default:
            System.out.println("Not a choice! Use exact names.");
            answer = "yes";
        }
    }while(!answer.equalsIgnoreCase("no"));
    counter /= 3;
    for (int i = 0; i < counter;i++) {
        discount = (double)(Math.random()*.1)+.1;
        cost2 = cost * discount;
        cost -= cost2;
    }
    while(money < cost) {
    System.out.println("How much money would you like to use to pay?");
    money = keyboard.nextDouble();
    if (money < cost) {
        System.out.println("That's not enough money.");
    }
    }
    double Q = cost / .25;
    double D = (cost % .25) / .10;
    double N = ((cost % .25) % .10) / .05 ;
    double P = (((cost % .25) % .10) %.05) /.01;
    System.out.println("The items you bought are: \n Crunch Bars: " + cr +
"\n Water Bottles: " + wb + "\n Chips: " + ch + "\n Ketchup: " + k + "\n
Juice: " + j);
    System.out.println("Your change is: $" + ((Q * .25) + (D * .1) + (N *
.05) + (P*.01)));
    }

}

Please excuse my messy coding style. I personally like it better, but I know a lot of people find it strange.

A: Your code never allows the user to input "no" into the answer variable. So your code always forces the user to intput "yes" or it shows the message "Bad Input".
You have this if statement in each one of your while loops. Both if and else if check the exact same condition. I assume you were probably wanting one of them to check for the answer "no" and the check variable never gets assigned to false unless "yes" is chosen:
answer = keyboard.nextLine();
if (answer.equalsIgnoreCase("Yes")) {  //this is same condition as next if line.
    check = false;
}else if(answer.equalsIgnoreCase("Yes")) { //this is same condition as prior if line.
    check = false;
}else {
    System.out.println("Bad input.");
}

Also, this is your main issue. You are ALWAYS assigning check to true in the while loop condition. you want to use the == operator.
This assigns true to the check variable in your code:
while(check = true) {

You actually want to do this:
while(check == true) {

I recommend using an IDE with a debugger that allows you to systematically step through your code and see what is happening with each line of code as it executes. It will help you find logic problems like this one.


text:
Q: Finding the nth largest in an int array I need to be able to find the nth largest numbers in an int array, I already have a linq statement that returns something but it's not passing the used cases that are set up. The array is:
var numbers = new[] { 5, 7, 5, 3, 6, 7, 9 };

My code is:
  var result = numbers.GroupBy(x => x)
                .OrderByDescending(group => group.Key)
                .SkipWhile(group =>
                {
                    n -= group.Count();
                    return n > 0;
                })
                .First()
                .ToArray();

I don't understand why I'm not getting the expected results?
  result[0] == 9
  result[1] == 7

A: You can just use Take() to get the n largest items after the collection is ordered descending :
var result = numbers.GroupBy(x => x)
                    .OrderByDescending(group => group.Key)
                    .Take(n)
                    .Select(group => group.Key)
                    .ToArray();

dotnetfiddle demo
or use Skip(n-1).Take(1) if you mean to get only the nth item instead.


text:
Q: How to update local files on all the postgres nodes I have a multi-node Postgres cluster running in High availability mode following the primary-standby architecture.
postgres-0                                               5/5     Running            0          111s
postgres-1                                               5/5     Running            0          3m4s
postgres-monitor-0                                       4/4     Running            0          13m

One of the pod is primary and the other pod is in standby mode which gets replicated from primary in a synchronous manner, while standby remains in the read-only mode.
I am running the following CRUD commands to update a local file:
-- Update pg_config to allow access to the users
create table hba ( lines text );
copy hba from '/pgsql/data/pg_hba.conf';

insert into hba (lines) values ('host     all              all       0.0.0.0/0    md5');
insert into hba (lines) values ('host     all              all       ::/0         md5');

copy hba to '/pgsql/data/pg_hba.conf';

-- reload the config
select pg_reload_conf();

The issue is, the file /pgsql/data/pg_hba.conf is getting updated on the primary node and not on the standby node (as all queries go to master), this means when the primary node goes down and standby becomes a new primary the config changes will be missing.

A: I must add that this approach does not look very secure to me.
You cannot use tables (even temporary ones) on a standby server.
I think the easiest way to approach this is to write a PL/PerlU or PL/PythonU to do the necessary file modifications. You also have to call the function pg_reload_comf() to activate the modifications.

A: The copy command can be executed on all the Postgres nodes:
psql -U postgres -h postgres-0.postgres-agent.default -c "copy hba to '/pgsql/data/pg_hba.conf'"
psql -U postgres -h postgres-1.postgres-agent.default -c "copy hba to '/pgsql/data/pg_hba.conf'"

The copy command can be executed on the standby node even though it's in ready-only mode.

Below are the complete sequence of steps after verifying all the nodes have joined the cluster and replication have started:
Step 1: (Execute on Primary node, this will get replicated to all the standby nodes)
-- Update pg_config to allow access to the users
create table hba ( lines text );
copy hba from '/pgsql/data/pg_hba.conf';

insert into hba (lines)
    select 'host     <database>              all       0.0.0.0/0    scram-sha-256'
        where not exists (
            select 1 from hba where lines = 'host     <database>              all       0.0.0.0/0    scram-sha-256'
            );

insert into hba (lines)
    select 'host     <database>              all       ::/0         scram-sha-256'
        where not exists (
            select 1 from hba where lines = 'host     <database>              all       ::/0         scram-sha-256'
            );

Step 2: (Depends on the number of replicas)
psql -U postgres -h postgres-0.postgres-agent.default -c "copy hba to '/pgsql/data/pg_hba.conf'"
psql -U postgres -h postgres-1.postgres-agent.default -c "copy hba to '/pgsql/data/pg_hba.conf'"

Step 3:
-- reload the config
select pg_reload_conf();


text:
Q: Understanding interface and abstract classes I am practising some exercises, and one question asked, name three differences between interface and abstract classes.
I wrote that interfaces are implementable and those classes that implement them than share a commonality. Interfaces contain abstract methods with no implementation. Therefore when classes implement interfaces must provide implementation for each of their methods. Classes can than be reused so long as they share those same methods, but not necessarily have any other commonalities other than that.
abstract classes can contain abstract and non abstract methods. However if one abstract method exists the entire class is considered abstract. Abstract classes are involved with inheritance and subclasses can extend from it, these subclasses can than contain any non abstract methods, and provide their own unique implementation for those abstract methods..
Not a 10/10 answer, but I'd like feedback on where I am right and obviously where I'm wrong. Thank you
interfaces can be implemented by any class, while abstract classes can only be extended from
interfaces contain methods where there is no implementation (aka abstract method) in any of the methods while abstract classes can contain abstract and non abstract methods
interfaces allow for unique classes to share a commonality while abstract classes only share commanlities with those subclasses they extend to


text:
Q: C++: 1-What is a different between define a variable to keep and print the answer ,2-and just print the answer? What is the difference between :
#define PI 3.14
using namespace std;

int main()
{
    int r;
    float area;
    cout << "Enter the radius:";
    cin>>r;
    area=r*r*PI;
    cout << area << endl;
}

and
#define PI 3.14
using namespace std;

int main()
{
    int r;
    cout << "Enter the radius:";
    cin>>r;
    cout << r*r*PI <<endl;
}

A: The answer is in your case it changes nothing.
You can always use godbolt to take a look at the asm.
https://godbolt.org/z/wkFHM5
As you can see
area=r*r*PI;
cout << area << endl;

produces the same code as
cout << r*r*PI << endl;

The intermediate variable is a way and storing data that you want to reuse that is all.


text:
Q: What is a bitcoin? The critical word in my question title is a.
I am not asking "what is bitcoin?". There are numerous articles that show up when a Google search is performed with that question, and they all involve in summarizing what decentralized currency means, what the blockchain is, how mining generally works etc.
However I find that none actually answer the question of "what is a bitcoin"?
If my child were to ask me "what is a dollar"?, I can pull out a one dollar bill or coin for him to hold and examine.
What can I give him to examine when he asks me what a bitcoin is? (Not counting the physical bitcoin makers) Is there a string of digits I can print out and say "this! this is a bitcoin!" , or do I point to some entry on a public ledger and say "there! That's a record of Dad's bitcoin!"
Essentially, I would like to know, what is the actual tangible representation of a bitcoin, or any cryptocurrency unit?

A: Bitcoin is generated as a compensation for mining (running cryptographic calculations to maintain the integrity of transactions within the bitcoin network).
Every block in the blockchain has a specific value (in amounts of bitcoin) and this value is attributed to the bitcoin address(es) who submitted this block successfully.
From the bitcoin wiki:

The number of Bitcoins generated per block starts at 50 and is halved every 210,000 blocks (about four years).

Their value to the outside world depends on what people agree it's worth (free market if you will).

A: Basically, a bitcoin can be seen as a measure of work - of "mining" - done by other users. As you probably already know, the entire bitcoin system is pretty much depends on it's users constantly doing difficult computations, sealing and ensuring transactions between users. To ensure that users keep doing those computations (which are quite expensive, by the way, mostly due to electricity and hardware costs), for every block made it's creators are awarded a certain amount of bitcoins, simply for the mere presence of their block in the blockchain. To own a bitcoin is to being able to say "I've been given this bitcoin by that guy, who got it from that guy, who got it from that guy, who got it from lets-skip-these-hundreds-of-transactions from the guy who made that block (very deeply buried inside the blockchain by now) which means he was either very lucky or had a lot of computing power to make that lucky hash and release the block before others could do it". And since every user has a full copy of blockchain on their computer (hopefully correct and agreed by majority), every single transaction ever made can be traced to the source - to the bitcoins awarded for mining a block - and your claim can be easily verified.
Although that's a little bit simplified - since, as in practice, transactions are done in tiniest fractions of bitcoins, the bitcoins you have will most likely originate from different block makers, but in general the concept is the same.


text:
Q: How can I make user-defined highlight for C# in VS Code Recently I installed VS Code and C# plugin for it. I must say that I really like the editor. It is very lightweight and highly customizable. However I haven't found how can I redefine several colorization options such as highlighting classes inside field definitions or local variables?
I already use standard C# colorizer. I just want to customize the color of some lexemes, not everything.

A: Checkout the docs here:
https://code.visualstudio.com/Docs/customization/colorizer
You basically either get one from the marketplace or generate a basic editable file with yeoman.
You can also add themes even from color sublime as described here:
https://code.visualstudio.com/docs/customization/themes

A: Install theme from extensions from which you wish to start.
Then find where the theme got installed. On Windows it would be %USERPROFILE%\.vscode\extensions, see details in Installing extensions.
There you'll find folder with theme, inside is themes folder and <something>.tmTheme file which is actually xml file. Open it inside VSCode and start editing :)
You'll find items and colors, syntax is described elsewhere, but common sense will help you.
To test change, open desired .cs file in same editor. Changes are applied after restart, so it's also good to make key shortcut to restart the editor:
keybindings.json
...
{
   "key": "ctrl+shift+alt+r",
   "command": "workbench.action.reloadWindow"
}
...

Then try color, restart, see result, continue...


text:
Q: Has Ubuntu gone case-insensitive? So, I have a folder on my computer which contains these two files (and other files)
disc membership.pdf
disc membership.pdf (Case Conflict 1)

And I have a folder on an external drive which contains the file
DISC membership.pdf

I copy the file from the external drive to the computer harddrive, and find that it is renamed
disc membership.pdf (Case Conflict 2)

Why?
The folder on the computer is contained within a Dropbox folder. Could that be a reason?

A: Dropbox is doing this, not Ubuntu, because it would cause problems if you synced with a Windows machine at some point as Windows is case-insensitive.
From Dropbox help:

Case conflicts
Linux computers allow you to have two files or folders with the same name but different capitalization. However, Mac and Windows won't differentiate file or folder names by case. Therefore, if Dropbox comes across linux directories named "Sample folder" and "sample folder" (lowercase "s"), it will still sync both folders to Mac and Windows computers, but one will appear as a copy of the original file and appended with case conflict.


text:
Q: How can I contribute and add a new feature in Magento 2 via github? I want the Magento 2 \Magento\Framework\HTTP\Client\Curl class to handle all http methods.
I have added as a feature request in magento/community-feature repo on github. How can I add the feature myself ?
https://github.com/magento/community-features/issues/101


text:
Q: Html.CheckBoxFor TypeConversition Error I have a view model:
public class RegisterModel
{
   ...
   public bool Confirmation{ get; set; }
}

I use checkbox helper on my view:
@model RegisterModel

......
@Html.CheckBoxFor(m => m.Confirmation)

This checkbox html helper creates:
<input id="Confirmation" name="Confirmation" value="true" type="checkbox">
<input name="Confirmation" value="false" type="hidden">

On Controller
[HttpPost]
[ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
{
   if (!ModelState.IsValid)
                return View(model);
.....
}

Let's say some user changes values of inputs to 'xxx' and posts it. Therefore, Model is not valid and we return view. After that, Html.CheckBoxFor gives this error:

The parameter conversion from type 'System.String' to type
  'System.Boolean' failed.

Inner Exception:

System.FormatException: xxx  is not a valid value for Boolean

When we return view: Model.Confirmation value is false but Request["Confirmation"] value is 'xxx'.
This error comes from ValueProviderResult class on ConvertSimpleType method. I think, it tries to convert Request["Confirmation"] value to boolean and it gives error.
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Conversion failure is not fatal")]
private static object ConvertSimpleType(CultureInfo culture, object value, Type destinationType)
{

.....
    TypeConverter converter = TypeDescriptor.GetConverter(destinationType);
    bool canConvertFrom = converter.CanConvertFrom(value.GetType());
    if (!canConvertFrom)
    {
        converter = TypeDescriptor.GetConverter(value.GetType());
    }
    if (!(canConvertFrom || converter.CanConvertTo(destinationType)))
    {
        // EnumConverter cannot convert integer, so we verify manually
        if (destinationType.IsEnum && value is int)
        {
            return Enum.ToObject(destinationType, (int)value);
        }
             string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ValueProviderResult_NoConverterExists,
                                           value.GetType().FullName, destinationType.FullName);
        throw new InvalidOperationException(message);
    }

.....
}

How can I fix or avoid this error?

A: According to @StephenMuecke this is default behavior. You can check detailed answer
According to @ataravati we should handle this on model.IsValid==false. If model is not valid, We remove the value of checkbox and assign new one. Therefore We don't get any error when we return view.
 if (!ModelState.IsValid)
            {
                bool confirmation;

                bool.TryParse(Request["Confirmation"],out confirmation);
                ModelState.Remove("Confirmation");
                request.Confirmation = confirmation;
                return View(request);
            }

According to @StephenMuecke if checkbox input value is not boolean, the user is malicious for sure. Therefore we redirect user to another action which has tracking/blocking ip algorithm and returns 404 as a view.
  if (!ModelState.IsValid)
            {
                bool confirmation;
                if (bool.TryParse(Request["Confirmation"], out confirmation))
                    return View(request);
                return RedirectToAction("Http404", "Errors"); //This not just redirecting 404, it has also tracking/blocking ip algorithm.
            }


text:
Q: Why I'm getting different BigDecimal rounding results? Why I'm getting following output:
1.11
1.13
when run below code:
public static void main(String[] args) {

    double aDouble = 1.115;
    double bDouble = 1.125;

    System.out.println(roundTo2Decimal(aDouble));
    System.out.println(roundTo2Decimal(bDouble));
}

public static BigDecimal roundTo2Decimal(double doubleToRound){
    BigDecimal bigDecimal = new BigDecimal(doubleToRound);
    return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
}

instead of expected result:
1.12
1.13 ?

A: This occurs due to precision loss when representing 1.115 as double:
1.115 = 1.114999999999999991118215803E0
1.125 = 1.125E0

A: Pretty sure this is just standard floating point imprecision. 0.125 = 1/8 which is exactly expressible in binary. 0.115 isn't so it's not stored exactly, and, apparently, is stored as something that rounds away from what you expect. Try System.out.println the double itself.

A: <code>
//to achieve what u need change your method to
    public static BigDecimal roundTo2Decimal(double doubleToRound) {
        BigDecimal bigDecimal = new BigDecimal(doubleToRound);
        return bigDecimal.setScale(2, RoundingMode.CEILING);
    }

</code>


text:
Q: Trying to understand FormSet ManagementForm data (because error = "it's missing") I'm trying to implement Nicole Harris' example of formsets in my own project. Whereas she uses a formset to add a variable number of Links to a User profile, I'm trying to add a variable number of questions to a survey. My code is hence syntactically extremely similar (except I don't use a jquery plugin to dynamically add <input> fields to the webpage, I use my own javascript).
I'm getting a ManagementForm data is missing or has been tampered with error on form submission, at the line in my view where I try to call survey_formset.is_valid(). Here's the view:
def create_survey(request):
    #create the formset, specifying the form and formset we want to use
    SurveyFormSet = formset_factory(SurveyQuestionForm,
                                        formset=BaseSurveyFormSet)
    survey_formset = SurveyFormSet(request.POST)
    #THE BELOW CALL THROWS A VALIDATION ERROR: ManagementForm data missing...
    if survey_formset.is_valid():
        print("survey_formset is valid!")
    else:
        print("survey_formset is invalid. Here are the errors:")
        for k, v in survey_form.errors.items():
            print(k, ": ", v)

Excuse the brevity; I don't really know what causes the error and I'm trying not to post tens of lines of irrelevant view/form code. I will add any additional code requested.
Including {{ survey_formset.management_form }} in the template doesn't make a difference.
From the docs, the ManagementForm needs form-TOTAL_FORMS, form-INITIAL_FORMS and form-MAX_NUM_FORMS  . Nicole's code doesn't seem to have this except in the test code. However, if I just artificially inject it into the view with the below lines, it doesn't help (same error), so I don't know what I'm doing wrong:
data = {'form-TOTAL_FORMS': '1',
        'form-INITIAL_FORMS': '0',
        'form-MAX_NUM_FORMS': ''
       }
survey_formset = SurveyFormSet(request.POST, data)

A: Firstly, you must include the management form inside the form tag your template if you are using a formset.
{{ survey_formset.management_form }}

Next, if you add forms to the formset or remove them, then you need to increment/decrement the value of the management form's form-TOTAL_FORMS input. The django-dynamic-formset jQuery plugin takes care of doing this for you. If you don't use it, then you'll have to do this yourself.
Finally, this line does not make sense.
survey_formset = SurveyFormSet(request.POST, data)

The fields from the form data should be in request.POST, you can't add additional data with the second argument like that.


text:
Q: Is this sentence grammatically wrong?
Had Nick been here on time, we would not have missed the train. [Introduction]
  Had Nick been here on time, we would not miss the train.

Is the second sentence grammatically wrong, or are the two sentences different just in their nuance?

A: Standing on the train platform today, waiting for Nick, you might say, anxiously:

"If Nick is here we will not miss the train."

If you narrate this tomorrow, you will backshift the tenses:

"Yesterday I said that if Nick was here we would not miss the train."

Now suppose that in fact Nick is not on time. Now your condition, your IF clause,  is an irrealis or counterfactual. Just before the train leaves you might say, despairingly:

"If Nick were here we would not miss the train."

And afterwards, as the train pulls out of the station, leaving you on the platform, you might say bitterly:

"If Nick had been here we would not have missed the train."

What is confusing here is that would does double duty: it may act as either the past indicative form or the present conditional form of will. You have to figure out which is in play from the context.

A: The second is an ungrammatical way of expressing the first. The first part of the sentence imagines something that didn't happen in the past, whereas we would not miss the train envisages some present or future event. An example of its use might be If you weren't so late getting to the station every day, we wouldn't miss the train so often.

A: {Had it been} {that would have} - is the rule.
Hence the first sentence is correct and the second one is not.


text:
Q: Why do all circles passing through $a$ and $1/\bar{a}$ meet $|z|=1$ are right angles? In the complex plane, I write the equation for a circle centered at $z$ by $|z-x|=r$, so $(z-x)(\bar{z}-\bar{x})=r^2$. I suppose that both $a$ and $1/\bar{a}$ lie on this circle, so I get the equation
$$
(z-a)(\bar{z}-\bar{a})=(z-1/\bar{a})(\bar{z}-1/a).
$$
My idea to show that the circles intersect at right angles is to show that the radii at the point of intersection are at right angles, which is the case when the sum of the squares of the lengths of the radii of the circles is the square of the distance to the center of the circle passing through $a$ and $1/\bar{a}$. However, I'm having trouble finding a workable situation, since I don't think there is not a unique circle passing through $a$ and $1/\bar{a}$ to give a center to work with. What's the right way to do this?

A: Let the circle be $|z-b|=r$.  Then $$|a-b|^2 = |1/\bar a - b|^2 = r^2.$$ Expand to get $$ |a|^2 - 2 \Re(\bar ab) + |b|^2 = r2,\qquad 1/|a|^2 - 2\Re(b/a) + |b|^2 = r^2.$$
Compare to get
$$ 2\Re[(|a|^2-1)b/a] = 2\Re(\bar ab - b/a) = |a|^2 - 1/|a|^2.$$
It is clear that $|a|\neq 1$; otherwise $a = 1/\bar a$.  So
$$ 2\Re(b/a) = 1+ 1/|a|^2.$$
Substitute back to see
$$|b|^2 = r^2+1.$$
On the other hand, let $z_0$ be an intersection of the two circles:
$$ |z_0-b|=r,\qquad |z_0|=1.$$
Expand to get
$$ r^2 = |z_0|^2 - 2\Re(\bar z_0b) + |b|^2 = 1 -2\Re(b/z_0) + |b|^2.$$
It follows that
$$ \Re[(z_0-b)/z_0] = 1-\Re(b/z_0) = 1 + (r^1-1-|b|^2)/2 = 0.$$
The radii from $z_0$ to $0$ and from $z_0$ to $b$ are orthogonal. So the two circles intersect at right angles.

A: This is a basic property of Inversion of a point through a circle.
Suppose you are given a circle of radius $r$ with center $O$ (called the reference circle) and a point $P$ not on the circle, then the inverse of $P$ with respect to the reference circle is given by the point $P'$ which is collinear with $O$ and $P$ (on the ray $\overrightarrow{OP}$) such that $OP \times OP' = r^2$. Points on the circle get mapped to themselves.
A property of inversion is that a circle orthogonal to the reference circle is its own inverse and a circle which is its own inverse is orthogonal to the reference circle.
This follows easily from the Intersecting Secants Theorem (see the link for a nice applet), whose proof only uses the fact that the angle subtended by a chord on any point on the major(minor) arc of the circle is constant, and thus the triangles formed are similar. A proof can be found here. These proofs are very simple and do not require any cumbersome analytic geometry and is usually taught in high school geometry courses.
Now $a$ and $\frac{1}{\overline{a}}$ are inverse points with respect to the circle $|z| = 1$ and thus any circle passing through those two points is its own inverse (why?), and as a consequence, is orthogonal to the unit circle.

A: Building on Isaac's answer, I think you can get the identity you're looking for by doing this:
\begin{eqnarray*}
1+|c-a|^2 &=& 1+(c-a)(\overline{c}-\overline{a})\\
&=& 1+|c|^2+|a|^2-2\operatorname{Re}(c\overline{a}) \\
&=& 1+|c|^2+|a|^2-2\operatorname{Re}\left[\overline{a}\left(\frac{1}{2}\left(a+\frac{1}{\overline{a}}\right)+ik\left(a-\frac{1}{\overline{a}}\right)\right)\right] \\
&=& 1+|c|^2+|a|^2-2\operatorname{Re}\left[\frac{1}{2}\left(|a|^2+1\right)+ik\left(|a|^2-1\right)\right]\\
&=& 1+|c|^2+|a|^2-2\left[\frac{1}{2}(|a|^2+1)\right] \\
&=& 1+|c|^2+|a|^2-|a|^2-1 \\
&=& |c|^2
\end{eqnarray*}

A: I have a solution that relies on converting the complex numbers into ordered pairs although I believe there must be a solution with just the help of complex numbers.
Two circles intersect orthogonally, if their radii are perpendicular at the point of intersection. So, using this we can have a condition for orthogonality.
$\hskip 2.5in$
Here's a trick of how you will get a condition. Let us consider two circles,
$$C_1,A:x^2+y^2+2g_1x+2f_1y+c_1=0$$
$$C_2,B:x^2+y^2+2g_2x+2f_2y+c_2=0$$
From your high school course in analytical geometry in high school, it must be clear that the centres $A$ and $B$ are $A(-g_1,-f_1)$ and $B(-g_2,-f_2)$. And the radii of such a circle is $r_1=\sqrt{g_1^2+f_1^2-c_1}$ and similarly $r_2=\sqrt{g_2^2+f_2^2-c_2}$.
Now invoke Pythagoras here, I'll leave the actual computation to you, the condition would turn out to be, $$2g_1g_2+2f_1f_2=c_1+c_2$$
Now, find a parametric equation for a circle passing through the complex numbers $a$ and $\dfrac{1}{\bar a}$. How do you do this?
Since the circle always passes through, $a\cong(l,m)$ and $\dfrac{1}{\bar a}=\dfrac{a}{|a|^2}\cong\left(\dfrac{l}{l^2+m^2},\dfrac{m}{l^2+m^2}\right)$, you have the following will be the equation of the circle:
$$(x-l)\left(x-\dfrac{l}{l^2+m^2}\right)+(y-m)\left(y-\dfrac{m}{l^2+m^2}\right)+\lambda(ly-mx)=0$$
The second circle is, $$x^2+y^2-1=0$$
So, you should now see that $g_2=f_2=0$ and $c_2=-1$. Also, after a little inspection, note that we need not care for what those $g_1$ and $f_1$ are. And, thankfully, $c_1=1$. So, you have the required condition for orthogonality.
I know this is lengthy and not instructive, but this is all I can recollect from high school geometry. So, I only hope this is of some help!

A: You are correct that there isn't a unique circle passing through $a$ and $\frac{1}{\bar{a}}$, but the center of such a circle has to be equidistant from those two points, so on the perpendicular bisector of the segment between them.  Such a point can be described by $$c=\frac{1}{2}\left(a+\frac{1}{\bar{a}}\right)+ki\left(a-\frac{1}{\bar{a}}\right)$$ for some $k\in\mathbb{R}$ (that's the midpoint of the segment plus a scalar multiple of a $\frac{\pi}{2}$-rotation of the vector along that segment).  This can be simplified to $$c=\frac{1}{2}\left(a(1+2ik)+\frac{1}{\bar{a}}(1-2ik)\right).$$
The radius of the circle is $$\begin{align}
r=|c-a|&=\left|\frac{1}{2}\left(a(1+2ik)+\frac{1}{\bar{a}}(1-2ik)\right)-a\right|
\\
&=\frac{1}{2}\left|a(-1+2ik)+\frac{1}{\bar{a}}(1-2ik)\right|
\\
&=\frac{1}{2}\left|\frac{1}{\bar{a}}\left(a\bar{a}(-1+2ik)+(1-2ik)\right)\right|
\\
&=\frac{1}{2}\left|\frac{1}{\bar{a}}(1-a\bar{a})(1-2ik)\right|
\\
&=\frac{1}{2}\left|\frac{1}{\bar{a}}\right|\cdot|1-a\bar{a}|\cdot|1-2ik|
\\
&=\frac{|1-a\bar{a}|}{2|a|}\sqrt{4k^2+1}
.\end{align}$$
So now, as you suggested, we can use the converse of the Pythagorean Theorem: if the sum of the squares of the radii of the unit circle and our new circle is equal to the square of the distance between their centers, then they meet at right angles.  Mathematica tells me that the algebra works out and it's true, but I can't quite get there by hand.  Below is what I've got so far.
$$\begin{align}
\text{sum of squares of radii}&=1^2+\left(\frac{|1-a\bar{a}|}{2|a|}\sqrt{4k^2+1}\right)^2
\\
&=1+\frac{(1-a\bar{a})^2}{4a\bar{a}}(4k^2+1)
\end{align}$$
$$\begin{align}
(\text{distance }&\text{between centers})^2=|c-0|^2
\\
&=\left|\frac{1}{2}\left(a(1+2ik)+\frac{1}{\bar{a}}(1-2ik)\right)\right|^2
\\
&=\frac{1}{4}\left|a(1+2ik)+\frac{1}{\bar{a}}(1-2ik)\right|^2
\\
&=\frac{1}{4|\bar{a}|^2}|a\bar{a}(1+2ik)+(1-2ik)|^2
\\
&=\frac{1}{4a\bar{a}}|a\bar{a}(1+2ik)+(1-2ik)|^2
\end{align}$$

A: Without lost of generality, we might suppose that $a$ is real, because we can roteate the plane as we want. By this suppose, $\frac{1}{\overline{a}}$ is also real since it is equal to $\dfrac{a}{|a|}$.
It was already said that there are many circles passing for $a$ and $\frac{1}{\overline{a}}$ then we only can determine generically its centre $C$; $C=\frac{a+\frac{1}{a}}{2}+it$ for any $t\in \mathbb R$. Now we can write the equation $r^2=|z-\frac{a+\frac{1}{a}}{2}-it|^2(1)$.
Let $w=\frac{a+\frac{1}{a}}{2},z=a$ and notincing that $\frac{1}{\overline{a}}=\frac{1}{a}$; we get from (1):
$$r^2=(a-w-it)(a-w+it)$$ $$=a^2-aw+ait-wa+w^2-wit-ait+iwt+t^2$$ $$=a^2-aw-wa+w^2+t^2$$ $$r^2=(a-w)^2+t^2.\quad(2)$$
As $|a|$ or $\frac{1}{a}|$ is less than 1, the circle $C_1:r^2=|z-\frac{a+\frac{1}{a}}{2}-it|^2$ intersects the unit circle $C_2:|z|=1$, so we can assume that there exists a $z\in C_1\cap C_2 \subset \mathbb C.$
Then for (1) and (2): $$(a-w)^2+t^2=(z-w-it)(\overline{z}-w+it)$$ $$(a-w)^2+t^2=|z|^2-zw+izt-\overline{z}w+w^2-iwt-i\overline{z}t+iwt+t^2$$ $$(a-w)^2=|z|^2-zw-\overline{zw}+w^2+izt+\overline{izt}$$ $$(a-w)^2=2|z|^2-zw-\overline{zw}+izt+\overline{izt}+w^2-|z|^2$$ $$(a-w)^2-w^2+|z|^2=2Re(|z|^2-zw +izt).$$
For the left side,
$$(a-w)^2-w^2+|z|^2=\frac{a^2-2+(\frac{1}{a})^2}{4}-\frac{a^2+2+(\frac{1}{a})^2}{4}+1=0$$
$\Rightarrow$ $$Re(|z|^2-zw +izt)=0$$
Remebering that the normal vector to the unit circle at the point $z$ is exactely $z$ and for $C_1$ at $z$ it is $z-\frac{a+\frac{1}{a}}{2}-it$. Let, $z,w\in \mathbb C$ the inner product in complex sense is $Re(z.\overline{w})$. Finally, $$Re((z-\frac{a+\frac{1}{a}}{2}-it ).(\overline{z}))=Re(|z|^2-zw -i\overline{z}t)=Re(|z|^2-zw +izt)=0.$$ Showing that the normal vector are making a right angle and so the tangents. $\Box$


text:
Q: c freeing char pointer not working after first time I am trying to free a char pointer wich was allocated by the function copyCharNumber. The first time the free call in the function works fine. The second time it doesn´t work any more and Visual Studio throws an error. I don`t get it why there is an error the second time. The second time calling free on the char pointer returned by the copyCharNumber anywhere in the code allways throws an error.
Code:
char* copyCharNumber(char *oldNumber, char *newDigit, int newLen){
    char* newNumber = malloc(newLen * sizeof(char) +1);
    if (oldNumber != NULL){
        strcpy(newNumber, oldNumber);
        free(oldNumber);
    }
    *(newNumber + (newLen - 1)) = *newDigit;
    *(newNumber + newLen) = "\0";
    return newNumber;
}

double* getNumbers(int max, int maxValue, int minValue, char* filenameRead){
    double* numbers = malloc(max * sizeof(double));
    FILE* fp = fopen(filenameRead, "r");
    char ch = NULL;
    int i = 0;
    int numberLen = 0;
    boolean isNegative = 0;
    int hasPoint = 0;
    for (; i < max && fp != NULL && ch != EOF; i++){
        isNegative = 0;
        numberLen = 0;
        hasPoint = 0;
        char* number = NULL;

        if (ch == NULL)
            ch = fgetc(fp);

        if (ch == '-') isNegative = 1;
        if (ch == '.' || ch == ',' && numberLen > 0) hasPoint++;

        while (isdigit(ch)>0 || (isNegative && numberLen == 0) || (hasPoint == 1 && numberLen>0)){
            numberLen++;
            number = copyCharNumber(number, &ch, numberLen);
            ch = fgetc(fp);
        }

        if (number != NULL){
            double newNumber = strtod(number, NULL);
            free(number);
            if (newNumber <= maxValue && newNumber >= minValue){
                if (isNegative) newNumber = -newNumber;
                numbers[i] = newNumber;
            }

        }
        else
            ch = NULL;
    }
    return numbers;
}


text:
Q: HTML select element phantom padding in Chrome http://jsfiddle.net/7nudw/2/
The following select element and div should look exactly the same. Somehow the select has both extra horizontal and vertical padding. What did I miss? Thanks.
browsers tesed (chrome version seems to matter):

*

*Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36

*Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/34.0.1847.116 Chrome/34.0.1847.116 Safari/537.36

<select class="test"><option>option 1</option></select>

option 1

.test {
    display: inline-block;
    font-size: 30px;
    font-family: monospace;

    background-color: blue;
    border: 1px solid red;
    border-radius: 0;
    padding: 0;
    margin: 0;
    -webkit-appearance: none;

    padding-left: 0;

    margin-bottom: 1px;
}

EDIT #1:
http://jsfiddle.net/7nudw/5/
add line-height still doesn't work.
EDIT #2:
works on Mac OS with a newer chrome/webkit build:

*

*Mozilla/5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53

*could there be a bug fix from 537.36 to 537.51.1?

A: Browsers often have their own (slightly different) ways of rendering <select> elements, which can make it frustrating to get them to appear exactly as desired using only CSS.
In your example, I think Chrome's rendering method is what's leading to the extra horizontal padding. However, the vertical padding can be removed by ensuring the line-height in <select> is exactly the font size:
select{
    line-height:1em;
}

Here's an updated JSFiddle to show that. If you want a <select> to look a certain way across all browsers, you may want to consider creating one yourself using JavaScript. (There are just some considerations to take into account when you do that.)
Hope this helps! Let me know if you have any questions.


text:
Q: Handling multiple Xib or fixing collapse and expand button on multiple Xib file Now the situation is illustrated in this image:

I have an app having multiple Xib files calling in one main Xib and its class. I have added expand and collapse view which works on particular xib expand and collapse subviews as required and reduces/Expands Height too.
This works well for one xib section when all tabs of xib files are collapsed and the second xib won't change its y-coordinates, but I'm having a white space between. I want to fix it.
Note: Every xib contains a class referring to it. The whole app won't use auto-resize.
How can I solve this?