text:
Q: Prevent join table being empty Relationships
class Promotion < ActiveRecord::Base
  has_many :promotion_sweepstakes,

  has_many :sweepstakes,
    :through => :promotion_sweepstakes
  end

class PromotionSweepstake < ActiveRecord::Base
  belongs_to :promotion
  belongs_to :sweepstake
end

class Sweepstake < ActiveRecord::Base
  # Not relevant in this question, but I included the class
end

So a Promotion has_many Sweepstake through join table PromotionSweepstake. This is a legacy db schema so the naming might seem a bit odd and there are some self.table_name == and foreign_key stuff left out.
The nature of this app demands that at least one entry in the join table is present for a promotionId, because not having a sweepstake would break the app.
First question
How can I guarantee that there is always one entry in PromotionSweepstake for a Promotion? At least one Sweepstake.id has to be included upon creation, and once an entry in the join table is created there has to be a minimum of one for each Promotion/promotion_id.
Second question (other option)
If the previous suggestion would not be possible, which I doubt is true, there's another way the problem can be worked around. There's a sort of "default Sweepstake" with a certain id. If through a form all the sweepstake_ids would be removed (so that all entries for the Promotion in the join table would be deleted), can I create a new entry in PromotionSweepstake?
pseudo_code (sort of)
delete promotion_sweepstake with ids [1, 4, 5] where promotion_id = 1
if promotion with id=1 has no promotion_sweepstakes
  add promotion_sweepstake with promotion_id 1 and sweepstake_id 100
end
Thank you for your help.

A: A presence validation should solve the problem in case of creation and modification of Promotions.
class Promotion < ActiveRecord::Base
  has_many :promotion_sweepstakes
  has_many :sweepstakes,
    :through => :promotion_sweepstakes
  validates :sweepstakes, :presence => true
end

In order to assure consistency when there's an attempt to delete or update a Sweepstake or a PromotionSweepstake you'd have to write your own validations for those two classes. They would have to check whether previously referenced Promotions are still valid, i.e. still have some Sweepstakes.
A simple solution would take and advantage of validates :sweepstakes, :presence => true in Promotion. After updating referenced PromotionSweepstakes or Sweepstakes in a transaction you would have to call Promotion#valid? on previously referenced Promotions. If they're not valid you roll back the transaction as the modification broke the consistency.
Alternatively you could use before_destroy in both PromotionSweepstake and Sweepstake in order to prevent changes violating your consistency requirements.
class PromotionSweepstake < ActiveRecord::Base
  belongs_to :promotion
  belongs_to :sweepstake
  before_destroy :check_for_promotion_on_destroy

private

  def check_for_promotion_on_destroy
    raise 'deleting the last sweepstake' if promotion.sweepstakes.count == 1
  end
end

class Sweepstake < ActiveRecord::Base
  has_many :promotion_sweepstakes
  has_many :promotions, :through => :promotion_sweepstakes
  before_destroy :check_for_promotions_on_destroy

private

  def check_for_promotions_on_destroy
    promotions.each do |prom|
      raise 'deleting the last sweepstake' if prom.sweepstakes.count == 1
    end
  end

end


text:
Q: AngularJS stops working as soon as I include a controller I'm trying to learn AngularJS and I'm running into a road block.   As soon as I include a controller on my form tag, any remaining angular JS stops functioning.
eg:
start {{ 1 + 1 }}
<form id="contact-form" ng-controller="messagingController">
</form>
end {{ 1 + 1 }}

What I will see is:
start 2
end {{ 1 + 1 }}

I have ng-app on the body tag.
I have angular script included at the top of my page.
I include a js for the controller
If you need to see the entire source, just go to http://tatmanblue.com/.  Scroll to the bottom.
Any ideas what is wrong?
Thnx
Matt

A: in the body tag you need to write the module name with ng-app
<body ng-app="messagingForm" ...

A: please see here https://docs.angularjs.org/error/ng/areq?p0=messagingController&p1=not%20a%20function,%20got%20undefined which means there is no function messagingController,
You missed js for controller

redpajama_set_name: RedPajamaStackExchange


text:
Q: WPF DataGrid Binding and CheckBox I have a fundamental question:
Let's say I have a List of elements of some class. And I also have a DataGrid that displays the properties of the items of this list. I want a user to select some items via the extra checkbox column (datagridtemplatecolumn in fact). Then he presses the button and only selected items are processed by some function.
How should I implement the logic of this checkbox?

*

*Should I add a boolean property to my class and bind it to the checkbox column? (I think, it's not good to add an extra property to my core class just for the sake of UI)

*Should I make some wrapper class that has a boolean property and bind DataGrid to the list of wrapper class? (Better complies to the OOP rules than the first variant)

*Make an unbound checkbox column. And then check the datagrid rows in the loop to gather selected items before processing. (This is what I wanted to do, but unbound checkbox column behaves really strange : when I toggle one checkbox, a couple of others are toggled as well. And I also didn't find a way to look through all the Rows of the DataGrid).

*Your variant...
And I want to do that stuff according to OOP rules. This is the main requirement. That's why I cannot accept the first variant, unless you say me that it's OK and commonly used.

A: I vote for #2; it gels with the MVVM pattern which I think is the only way to do straight-forward development in WPF. In this way you would make a view-model class that wraps your domain object to handle the communication between checking boxes and changing properties, etc., all the while firing PropertyChanged events and keeping your UI up-to-date.

A: guys I just try this solution and work great, maybe is not the best but it work.
bool? valor = false;
                foreach (var d in DetalleFactura.Items)
                {
                    DataGridRow row = (DataGridRow)DetalleFactura.ItemContainerGenerator.ContainerFromItem(d);
                    if (DetalleFactura.Columns[0].GetCellContent(row) is CheckBox)
                    {
                        valor = ((CheckBox)DetalleFactura.Columns[0].GetCellContent(row)).IsChecked;

                    }

                }

A: We had struggled with the same dilemma and ultimately ended up with option #1 of adding a boolean property to the class of IsSelected  Why? When it really came down to it:

*

*it was the easiest

*could be re-purposed for any type of binding

*and finally... because Josh Smith uses IsSelected*

Sure, this may violate some golden MVVM rule, but sometimes, rules are meant to be broken.

*I can't recall the exact example Josh provided, but you can see his usage in one of his blog posts: The Initially Selected Item when Binding to a Grouped ICollectionView


text:
Q: How to know the ranking of a certain question in the hot question list?
Possible Duplicate:
How are "Hot" Questions Selected?

Is there a way to know the ranking (appearance) of a certain question on Stack Overflow in the hot questions list?


text:
Q: Access deep nested node from document.xml using nokogiri I am using nokogiri to access a docx's document xml file.
here is a sample of it:
<w:document>
    <w:body>
        <w:p w:rsidR="00454EDC" w:rsidRDefault="00454EDC" w:rsidP="00454EDC">
                <w:drawing>
                    <wp:inline distT="0" distB="0" distL="0" distR="0">
                        <wp:extent cx="1926590" cy="1088571"/>
                        <wp:effectExtent l="0" t="0" r="0" b="0"/>
                        <wp:docPr id="1" name="Picture 1"/>
                        <wp:cNvGraphicFramePr>
                            <a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/>
                        </wp:cNvGraphicFramePr>
                        <a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
                            <a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
                                <pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
                                    <pic:nvPicPr>
                                        <pic:cNvPr id="0" name="Picture 1"/>
                                        <pic:cNvPicPr>
                                            <a:picLocks noChangeAspect="1" noChangeArrowheads="1"/>
                                        </pic:cNvPicPr>
                                    </pic:nvPicPr>
                                    <pic:blipFill>
                                        <a:blip r:embed="rId5" cstate="print">
                                            <a:extLst>
                                                <a:ext uri="{28A0092B-C50C-407E-A947-70E740481C1C}">
                                                    <a14:useLocalDpi xmlns:a14="http://schemas.microsoft.com/office/drawing/2010/main" val="0"/>
                                                </a:ext>
                                            </a:extLst>
                                        </a:blip>
                                        <a:srcRect/>
                                        <a:stretch>
                                            <a:fillRect/>
                                        </a:stretch>
                                    </pic:blipFill>
                                    <pic:spPr bwMode="auto">
                                        <a:xfrm>
                                            <a:off x="0" y="0"/>
                                            <a:ext cx="1951299" cy="1102532"/>
                                        </a:xfrm>
                                        <a:prstGeom prst="rect">
                                            <a:avLst/>
                                        </a:prstGeom>
                                        <a:noFill/>
                                        <a:ln>
                                            <a:noFill/>
                                        </a:ln>
                                    </pic:spPr>
                                </pic:pic>
                            </a:graphicData>
                        </a:graphic>
                    </wp:inline>
                </w:drawing>
            </w:p>
    </w:body>
</w:document>

Now I want to access all <w:drawing> tags and from them I wan to access <a:blip> tag and extract the value of attribute of r:embed from it.
In this case as you can see it is rId5
I am able to access the <w:drawing> tag by using xml.xpath('//w:drawing') but when I do so xml.xpath('//w:drawing').xpath('//a:blip'), it throws error :
Nokogiri::XML::XPath::SyntaxError: Undefined namespace prefix: //a:blip

What am I doing wrong, can anyone point me in the right direction?

A: I would say that this is a bug in the xml parser that you are using :
Indeed, the error seems to be that the namespace prefix a is undefined, however, it has been defined in <a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">, which is a parent of the <a:blip> element.
See here if you want to know more about xml namespaces
It seems that they are a few other questions about problems with namespace prefixes in nokogiri, for example : Undefined namespace prefix in Nokogiri and XPath

A: The error is telling you that in your XPath query, //a:blip, Nokogiri doesn't know what namespace a refers to. You need to specify the namespaces that you are targeting in your query, not just the prefix. The fact that the prefix a is defined in the document doesn't really matter, it is the actual namespace URI that is important. It is possible to use completely different prefixes in the query than those used in the document, as long as the namespace URIs match.
You may be wondering why the query //w:drawing works. You don't include the full XML, but I suspect that the w prefix is defined on the root node (something like xmlns:w="http://some.uri.here"). If you don't specify any namespaces, Nokogiri will automatically register any defined in the root node so they will be available in your query. The namespace corresponding to the a prefix isn't defined on the root, so it is unavailable, and so you get the error you see.
To specify namespaces in Nokogiri you pass a hash, mapping the prefix (as used in the query) to namespace URI, to the xpath method (or which ever query method you're using). Since you are providing your own namespace mappings, you also need to include any you use from the root node, Nokogiri doesn't include them in this case.
In your case, the code would look something like this:
namespaces = {
  'w' => 'http://some.uri', # whatever the URI is for this namespace
  'a' => 'http://schemas.openxmlformats.org/drawingml/2006/main'
}

# You can combine this to a single query.
# Also note you don't want a double slash infront of
# the `/a:blip` part, just one.
xml.xpath('//w:drawing/a:blip', namespaces)

Have a look at the Nokogiri tutorial section on namespaces for more info.


text:
Q: Play framework logging into several files I'm using play framework logger (play.logger) and I need to log different log levels into separate files. I'm new with play and this is first time I have to use logger.
I need to know what to enter in this file to make logging into more files. .
Here's my conf/logger.xml file:
<configuration>
 <conversionRule conversionWord="coloredLevel" converterClass="play.api.Logger$ColoredLevel" />

<appender name="FILE" level="INFO" class="ch.qos.logback.core.FileAppender">
 <file>${application.home}/logs/info.log</file>
 <encoder>
   <pattern>%date - [%level] - from %logger in %thread %n%message%n%xException%n</pattern>
 </encoder>
 </appender>

 <logger name="play" level="INFO" />
 <logger name="application" level="INFO" />

 <root level="ERROR">
   <appender-ref ref="STDOUT" />
   <appender-ref ref="FILE" />
 </root>

</configuration>

Thank you in advance on your answers


text:
Q: convert python string of byte data to bytes I have a Python string of bytes data. An example string looks like this:
string = "b'\xabVJ-K\xcd+Q\xb2R*.M*N.\xcaLJU\xd2QJ\xceH\xcc\xcbK\xcd\x01\x89\x16\xe4\x97\xe8\x97d&g\xa7\x16Y\x85\x06\xbb8\xeb\x02\t\xa5Z\x00'"

It is a string, it not not bytes. I wish to convert it to bytes. Normal approaches (like encode) yield this:
b'\\xabVJ-K\\xcd+Q\\xb2R*.M*N.\\xcaLJU\\xd2QJ\\xceH\\xcc\\xcbK\\xcd\\x01\\x89\\x16\\xe4\\x97\\xe8\\x97d&g\\xa7\\x16Y\\x85\\x06\\xbb8\\xeb\\x02\\t\\xa5Z\\x00'

which leads to issues (note the addition of all the extra slashes).
I've looked through 10+ potential answers to this question on SO and only one of them works, and its a solution I'd prefer not to use, for obvious reasons:
this_works = eval(string)

Is there any way to get this to work without eval? Other potential solutions I've tried, that failed:
Option 1
Option 2
Option 3

A: I assume that you have python-like string representation in variable s:
s = r"b'\xabVJ-K\xcd+Q\xb2R*.M*N.\xcaLJU\xd2QJ\xceH\xcc\xcbK\xcd\x01\x89\x16\xe4\x97\xe8\x97d&g\xa7\x16Y\x85\x06\xbb8\xeb\x02\t\xa5Z\x00'"

Yes, if you eval this then you got real python bytes object.
But you can try parse it with ast module:
import ast
s = r"b'\xabVJ-K\xcd+Q\xb2R*.M*N.\xcaLJU\xd2QJ\xceH\xcc\xcbK\xcd\x01\x89\x16\xe4\x97\xe8\x97d&g\xa7\x16Y\x85\x06\xbb8\xeb\x02\t\xa5Z\x00'"
tree = ast.parse(s)
value = tree.body[0].value.value
print(type(value), value)

This will output your bytes object:
<class 'bytes'> b'\xabVJ-K\xcd+Q\xb2R*.M*N.\xcaLJU\xd2QJ\xceH\xcc\xcbK\xcd\x01\x89\x16\xe4\x97\xe8\x97d&g\xa7\x16Y\x85\x06\xbb8\xeb\x02\t\xa5Z\x00'


text:
Q: How to style my View to wrap the contents inside Let me preamble this by saying I'm new to react-native
Here is my component:
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, { Component } from 'react';
import { Text, View, Image, TextInput } from 'react-native';

class CountryCodeInput extends Component {
  state = { text: '' }
  constructor(props) {
    super(props)
  }

  componentDidMount() {
  }

  onTextChange(text) {
    if (/^\d+$/.test(text) || text === "") {
     this.setState({ text })
    }
    // this.props.onTextChange(text)
  }

  render() {
    return (
      <View style={{flex: 1, flexDirection: "row", marginRight: 0, backgroundColor: 'red', alignSelf:'baseline', flexWrap: "wrap"}}>
      <Text style={{backgroundColor:"yellow"}}>+</Text>
        <TextInput
        onChangeText={(text)=>this.onTextChange(text)}
        maxLength={3}
        keyboardType="numeric"
        style={{backgroundColor:"grey", borderBottomColor: 'black', borderBottomWidth: 1, fontSize: 16, height: 24, width: 36, paddingVertical: 4 }}
        value={this.state.text} />
      </View>
    );
  }
}

export default CountryCodeInput

Here is what it looks like:

I need to remove all the red portion, and limit the height of the yellow section to the height of the grey section. How can I do this?
alignSelf:'baseline' and flexWrap: "wrap" dont seem to help much.

A: Remove flex from your style
<View style={{ flexDirection: "row", marginRight: 0, backgroundColor: 'red', alignSelf:'baseline', flexWrap: "wrap"}}>


text:
Q: Use aggregate values for farther calculation I have the followin query:
SELECT contracts.id,
  (SELECT sum(pos.sum_to_pay) FROM pos
    where pos.contract_id=contracts.id and pos.is_draft=0) as paid,
  (SELECT sum(acts.amount) FROM acts
    where acts.contract_id=contracts.id) as acts_sum
from contracts

it works but i want to add another result field to_pay that should be calculated like acts_sum - paid = to_pay.
I'm trying to do it like this:
 SELECT contracts.id,
      (SELECT sum(pos.sum_to_pay) FROM pos
        where pos.contract_id=contracts.id and pos.is_draft=0) as paid,
      (SELECT sum(acts.amount) FROM acts
        where acts.contract_id=contracts.id) as acts_sum,
      (acts_sum - paid) as to_pay
    from contracts

but I got the error Unknown column 'acts_sum'. How can i find to_pay value based on acts_sum and paid?

A: Do it with a subquery like this
SELECT acts_sum, paid, (acts_sum - paid) as to_pay FROM
(SELECT contracts.id,
  (SELECT sum(pos.sum_to_pay) FROM pos
    where pos.contract_id=contracts.id and pos.is_draft=0) as paid,
  (SELECT sum(acts.amount) FROM acts
    where acts.contract_id=contracts.id) as acts_sum,
from contracts ) subq

A: You could rewrite your query using joins, correlated sub queries sometimes considered as a costly solution
select c.id,
COALESCE(a.acts_sum,0),
COALESCE(p.paid,0),
COALESCE(a.acts_sum,0) - COALESCE(p.paid,0) as to_pay
from contracts c
left join (
    SELECT contract_id,sum(sum_to_pay) paid
    FROM pos
    where is_draft=0
    group by contract_id
) p on c.id = p.contract_id
left join (
    SELECT contract_id,sum(amount) acts_sum
    FROM acts
    group by contract_id
) a on c.id = a.contract_id


text:
Q: Definition of rational equivalence In the book "C. Voisin. Hodge Theory and Complex Algebraic Geometry. Volume II. Cambridge studies in advanced mathematics 76 (2002)" page 247, definition 9.4,  says:
Definition 9.4.
The group ${Z_k(X)}_{\mathrm{rat}}$ of cycles rationally equivalent to $0$ is a subgroup of $Z_k(X)$ generated by the cycles of the form
\begin{equation*}
    \tau_* \operatorname{div}(\phi), \dim(W)=k, \phi\in R(W)^*
\end{equation*} where,   $\tau:\tilde{W}\rightarrow W\subset X$ is the normalization of a closed $(k+1)$-dimensional subvariety of $X$.
In this definition, I think there is a typo, it should say $\dim(W)=k+1$ instead of $\dim(W)=k$. Am I right or I am missing something?


text:
Q: How to display query without executing it with eloquent I want to display a query without executing it using Eloquent. I want to write something like:
\DB::table('my_table')-> updateOrInsert(['a' => 'b'], ['c' => 'd']);

It's a production action so I am a bit stressed about running it directly. Is there any way to display it instead of running it?

A: If you have a query builder instance you can use toSql(). Since the updateOrInsert() method does not return an builder instance you can't prevent its execution that way. Instead you can put the query inside a DB::pretend() closure and it should return the query it would execute.
\DB::pretend(function() {
    \DB::table('my_table')->update(['a' => 'b']);
});

Should return:
[
    [
        "query" => "update `my_table` set `a` = ?",
        "bindings" => [
            "b",
        ],
        "time" => 0.01,
    ],
]

Note: the example you provided will never work because insertOrUpdate() does not exist. I believe you're looking for updateOrInsert()

A: You can see raw queries with:
$foo = DB::getQueryLog();
var_dump($foo);

It will execute the queries.


text:
Q: Include another script in my parent Perl script How can I include another Perl script in my base Perl script?
I have a primary source file test.pl and I want to include secondary sóurce file config.pl within it.
What is a standard method to achieve this in Perl?

A: (I'm guessing that the program called config.pl sets config values that you want to access in test.pl. You don't make that clear in your question.)
A simple example. If config.pl looks like this:
#!/usr/bin/perl

$some_var = 'Some value';

Then you can write test.pl to look like this:
#!/usr/bin/perl

use feature 'say';

do './config.pl';

say $some_var;

But this is a terrible idea for many reasons. Not least because it stops working when you add use strict and use warnings to either of the files (and you should aim to have use strict and use warnings in all of your Perl code).
So what's a better approach? Turn your configuration into a proper module that returns a hash (I only have a single scalar variable in my example above, but a hash gives you a way to deliver many values in a single variable). A simple approach might look like this.
A module called MyConfig.pm:
package MyConfig;

use strict;
use warnings;

use parent 'Exporter';

our @EXPORT = qw[config];

sub config {
  my %config = (
    some_var => 'Some value',
  );

  return %config;
}

1;

And a test.pl like this:
#!/usr/bin/perl

use strict;
use warnings;

use feature 'say';
use FindBin '$Bin';
use lib $Bin;

use MyConfig;

my %config = config();

say $config{some_var};

Having got that working, you can add improvements like parsing the %config hash from an external file (perhaps stored in JSON) and then allowing different configurations for different environments (development vs production, for example).
It's a little bit more work than your current approach, but it's far more flexible. And you can use strict and warnings.


text:
Q: i want to print a matrix into an txt file using a display function i want to output a matrix into a txt file using a display function ( i tried to do it without the displayDor function and still didn't work)
the error is in the last line inside the function enregistrer line 48
and its saying :
[Error] no match for 'operator<<' (operand types are 'std::ofstream {aka std::basic_ofstream}' and 'void')
the code is the following  :
01 -#include <iostream>
02 -#include<ctime>
03 -#include<cstdlib>
04 -#include<fstream>
05 -using namespace std;
06 -struct Case{
07 -    bool N,W,S,E;
08 -    };
09 -
10 -struct laby{
11 -    int p;
12 -    int q;
13 -    Case **tab;
14 -    };
15 -
16 -laby *cree_laby(int p,int q){
17 -    laby *labyr=new laby;
18 -    labyr->p=p;
19 -    labyr->q=q;
20 -    labyr->tab=new Case*[p];
21 -    for(int i=0;i<p;i++){
22 -        labyr->tab[i]=new Case[q];
23 -        for(int j=0;j<q;j++){
24 -            labyr->tab[i][j].N=false;
25 -            labyr->tab[i][j].W=false;
26 -            labyr->tab[i][j].S=false;
27 -            labyr->tab[i][j].E=false;
28 -            }
29 -        }
30 -    return labyr;
31 -    }
32 -
33 -void displayLaby(const laby &labyr){
34 -    for(int i=0;i<labyr.p;i++){
35 -        for(int j=0;j<labyr.q;j++){
36 -            cout<<'['<<labyr.tab[i][j].N<<','<<labyr.tab[i][j].E<<','<<labyr.tab[i][j].S<<','<<labyr.tab[i][j].W<<']';
37 -            }
38 -            cout<<"\n";
39 -        }
40 -    }
41 -
42 -void enregistrer(laby & labyr,char *filename){
43 -    ofstream f;
44 -    f.open(filename);
45 -    f<<labyr.p;
46 -    f<<labyr.q;
47 -    f<<endl;
48 -    f<<displayLaby(labyr);
49 -}
50 -
51 -int main(){
52 -    laby *labyr;
53 -    labyr=cree_laby(5,5);
54 -    enregistrer(*labyr,"laby.txt");
55 -    return 0;
56 -    }

i tried to use a function display and i used loops also to output the maze into a txt file but they are both not working,
i would appreciate the help,
Thank you,

A: Your displayLaby writes to std::cout, if you want it to write somewhere else (like a file) then you have to pass the stream as a parameter to the function. Like this
void displayLaby(const laby &labyr, ostream& os){
    for(int i=0;i<labyr.p;i++){
        for(int j=0;j<labyr.q;j++){
            os<<'['<<labyr.tab[i][j].N<<','<<labyr.tab[i][j].E<<','<<labyr.tab[i][j].S<<','<<labyr.tab[i][j].W<<']';
        }
        os<<"\n";
    }
}

void enregistrer(laby & labyr,char *filename){
    ofstream f;
    f.open(filename);
    f<<labyr.p;
    f<<labyr.q;
    f<<endl;
    displayLaby(labyr, f);
}

Here os is the new parameter, and writes go to that stream instead of cout. The type of the new parameter is ostream& which means it will work for any kind of output stream. Of course if you want to write to cout anyway then you just call the new function like this displayLaby(labyr, cout);.


text:
Q: Django: How to add next to manual login redirect? I have a view:
def create_something(request):
    ...

I want to redirect to login if a person isn't logged in. Normally I'd use:
@login_required
def create_something(request):
    ...

but ...
I want to add a message before the redirect.
I wanted to do it like this:
def create_something(request):
    if not request.user.is_authenticated:
        messages.info(request, 'You must be logged in to create a thing .')
        return redirect('login')
    ...

However, that doesn't include a ?next in the url to go back to the page I was going to.
So my question is:
How would you manually redirect back to the login page WITH a manually added ?next query?

A: We can look at the source code [GitHub] of the @user_passes_test decorator [Django-doc] and determine how such redirect is done.
In the source code we see:

# ⋮
path = request.get_full_path()
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(path, resolved_login_url, redirect_field_name)

We can thus mimic this behaviour with:
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.views import redirect_to_login
from django.urls import reverse

def create_something(request):
    if not request.user.is_authenticated:
        messages.info(request, 'You must be logged in to create a thing �.')
        path = request.get_full_path()
        return redirect_to_login(path, reverse('login'))
    # …
Here the .redirect_to_login(…) function [Django-doc] will thus produce a redirect where the querystring will contain a key next=… where next is associated with the path.
You should use path = request.build_absolute_uri() in case the schema or hostname.

A: Just add the below decorator to your function:
 @login_required(login_url='/console/login')

The 'console/login' is the url path you want to redirect to. Alternatively, you can add the url to your settings.py file.
 LOGIN_URL = 'url'


text:
Q: ObjectDataSource Select Question Is it possible to get to the object that an ObjectDataSource creates when calling the select function? Not the result of the select function itself but the object that is creates from the parameter specified in TypeName.
I would like to call some other functions on that same instance after Select is called.
The other solution would be to DataBind manually.

A: The ObjectCreated event will be able to give you the instance you want...
You'll have to hold a reference to that until you handle the Selected event


text:
Q: is there a way to find what names values of "..." would get if I were to use them with a given function?     other.function <- function( x, y ) {

    }

    my.function <- function( ... ) {

        the.args <- figure.it.out( other.function, ... )

    }

    my.function(   1, 2 ) ## the.args would now be: list( x=1, y=2 )
    my.function( y=1, 3 ) ## the.args would now be: list( x=3, y=1 )

Is there a way to figure out what part of ... would be applicable to a given other function, and, in list form, what names they would end up having?
It should also be able to do the right thing if other.function accepts ... (not examplified above).

A: Usually the best practice is to store ... arguments in a list and later access using the names of arguments. It is kind of similar to what you see in **kwargs in python.
For example:
f1 = function(x,y){
}

f2 = function(...){
    arguments = list(...)
    do.something = f1(x=argumetns$x, y = arguments$y)
}

Ofcourse, the one downside of this is that it isn't quite clear, with what names should the arguments be passed. One way to address that is with comprehensive documentation or else you could put in checks to ensure that arguments have been passed before executing the function.
For example, you could ensure that user has passed argument x before making the function call with something like following:
f2 = function(...){
    arguments = list(...)
    if(is.null(arguments$x) || is.null(arguments$y)){
        stop('f2 missing the value for argument x or y')
    } #this will halt the execution and alert the user of missing x or y argument

    do.something = f1(x = arguments$x, y = arguments$y)
}

I have found using is.null() as a check for missing arguments to be very useful. If the user has not supplied a particular argument, say x, then is.null(arguments$x) would return TRUE.

A: Is this what you expect :

other.function <- function(x,y) {}

my.function <- function( ..., other.function ) {
  argsin <- list(...)
  argsfn <- formalArgs(other.function)
  # Unknown arguments
  unknown <- setdiff(names(argsin),argsfn)
  if(any(unknown!="")) {stop(paste("wrong argument(s):",unknown[unknown!=""]))}
  common.args <- intersect(names(argsin),argsfn)
  other.args <- setdiff(argsfn,names(argsin))
  # Recognised arguments
  l <- argsin[common.args]
  argsin[common.args]<-NULL
  # Other arguments
  names(argsin) <- other.args
  as.list(unlist(list(l,argsin)))
}

my.function(   1, 2,other.function = other.function ) ## the.args would now be: list( x=1, y=2 )
$x
[1] 1

$y
[1] 2

my.function( y =1, 3,other.function = other.function ) ## the.args would now be: list( x=3, y=1 )

$y
[1] 1

$x
[1] 3


text:
Q: Visual Studio 2019: Linking to folder I am trying to link to a folder that is not inside the project directory. To give an example,
If my project is in C:\project and I have a folder C:\shared, how can I manage to link C:\shared into the project (and being able to edit/view the files in Solution Explorer) without making a copy of the directory and placing it into the project directory.
I need this due to the fact that many projects will use this folder and it would be ideal to have them edit/use the same files rather than copy the folder into each project individually. That way if a bug is fixed in one project, all other projects will now use the fixed files as well.
For more context, this is a C++ project using Visual Studio 2019.
What I've tried/considered.

*

*Additional include directories

*

*Problem: This does not show the files in the Solution Explorer

*Dragging/dropping the folder (or copy/pasting) as seen in another StackOverflow thread.

*

*Problem: This just crashes my visual studio completely. The folder is quite large so I assume that's related to why.

Appreciate any insight on how to proceed. It's really unfortunate that this is a pain, I would think that something like this would be common, but all the posts I've seen related to it have either gone unanswered or could not be applied to my situation.
Thanks.

A: Shared Projects are the key here.. I just found out they existed. After creating one, drop the folder/files in the same directory that has .vcxitems file. Now in the project you want to include the shared folder, right click your solution, Add -> Existing Project and select your .vcxitems file.


text:
Q: What are the odds of matching? Sorry, I know this is probably simple but for some reason I can't get my head around it. Two people each have a 25% chance of making a shot which means they also each have a 75% chance of missing. How do you calculate the total odds of them matching each other with either hits or misses?
Thanks

A: If I'm understanding the problem statement correctly, the probability they both hit is $0.25^2$, and the probability they both miss is $0.75^2$ (assuming that whether one person hits/misses is independent of whether the other person hits/misses). Then the total probability that they either both hit or both miss is $0.25^2 + 0.75^2 = 0.625$.

A: Assuming you meant that $0.25$ is a parameter in Binomial distribution, you have the following outcomes (this also assumes independence events and $n$ repetitions):
$$
P(X=0, Y=0) = \binom{n}{0}\binom{n}{0}(0.75)^{2n} \\
P(X=1, Y=1) = \binom{n}{1}\binom{n}{1}(0.25)^2(0.75)^{2n-2} \\
\ldots\\
P(X=n, Y=n) = \binom{n}{n}\binom{n}{n}(0.25)^{2n}
$$
In total, $P(S) = \sum_{k=0}^{n} P(X=k,Y=k)$.
Although I'm not sure Binomial sum of the form $\sum_{k=0}^{n} (\binom{n}{k})^2 x^k$ exists in closed form. You can find a good asymptotic approximation for large $n$.


text:
Q: Windows Server 2003: Schedule FORFILE loop in TASK SCHEDULER I am trying to create a SCHEDULED TASK that will kick off a FORFILE loop, and terminate the process after an hour (or 12 hours).  I expect there to be MILLIONS of files the the paths defined, and I want to run the task off-hours to minimize the performance impact.
The code I'm trying to run is:
forfiles /P "E:\Mutex_01" /S /M *.txt /D -5 /C "cmd /c del @path"
Looking in the logs, I don't get the sense that task is running correctly.  When I enumerate the folder, there is no change. Am I missing something? How can I become the expected result?

A: Personally I would do it differently... I would kick off the routine interactively and then schedule a script that has:
PSKILL forfiles.exe
PSKILL CMD.EXE

Schedule that script to run at a particular time with administrative credentials.
You could even do a test right now... start the forfiles routine, and schedule your kill script to run five minutes from now...


text:
Q: How to reset the identity column in C#? I need to reset my identity field parametrically in MVC.net. I am using Linq and Entity Framework.
Reason: I am inserting thousands of records in my table by importing. I am importing records again after some period of time, so my id field value increasing so much
For ex. In 100000000 so my field data type is Big int but it is not sufficient for my this value. So I need to reset my identity field.

A: Hi  I  have  searched  and  found  answer  for  my  related  question.
that  is  the  query   in  c# with  mvc3  and  entity framework
 db.ExecuteStoreCommand("DBCC CHECKIDENT('BibContents',RESEED,1);");
 db.SaveChanges();


text:
Q: getting system's double click timer interval in WPF (value from control panel) I have a FrameworkElement and I want to perform action A when the user single clicks, and action B when the user double clicks.
Due to the way events are delivered, I always get a single click event which begins action A.  After looking around, I found an interesting technique here using a timer to delay the handling of the clicks.  However, this example hardcodes the timer to 300 milliseconds, but I would prefer to use the user's "Double-click speed" setting Control Panel's Mouse Properties dialog.
What's the wpf/C# API for getting that value from the system?

A: If you don't want reference System.Windows.Forms assembly, you can try this:
    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern int GetDoubleClickTime();

A: This should work SystemInformation.DoubleClickTime

A: You can find the time here: System.Windows.Forms.SystemInformation.DoubleClickTime
You can actually see a full implementation of what you are trying to achieve here:
WPF: Button single click + double click issue

A:
I have a FrameworkElement and I want to perform action A when the user
  single clicks, and action B when the user double clicks.

If you're handling an event that provides a MouseButtonEventArgs, such as UIElement.MouseLeftButtonDown, you can access MouseButtonEventArgs.ClickCount to determine if multiple clicks have happened within the double-click time of each other. Since FrameworkElement derives from UIElement this should be possible in your case.
No need to use DllImport or WinForms, as you don't really need to know the double-click time to accomplish your main goal.
Edit add: I discovered that this only really works for the ButtonDown events (left or right). I'm not sure why they didn't implement this properly for the ButtonUp events, but it should suffice to catch both events, and keep a member variable of the ClickCount from the ButtonDown that you can check when receiving ButtonUp.


text:
Q: What's different about 'const' keyword placement in Dart? void main() {
  var list1 = const [1, 2, 3];
  const list2 = [1, 2, 3];
}

Is there any difference between list1 and list2?
What's different about 'const' keyword placement in Dart?

*

*between 'const' before the list literal and 'const' before the variable name

A: The const as keyword makes your object constant where you are not able to reassign any value to it later.

Const means that the object's entire deep state can be determined entirely at compile-time and that the object will be frozen and completely immutable.

In your example
list1 = []; // perfectly fine
list2 = []; // but this throw errors (Error: Can't assign to the const variable 'list2'.)

On the other hand, var allows you to reassign value to the variable.
However, the const after the value makes the value unmodifiable let's take a look at an example
list1.add(22); // ERROR! Cannot add to an unmodifiable list
// but you still can reassign the value
list1 = [];
// while the
list2 = []; // throw errors as I said above!

the const for the value in const keyword variable is hidden.
const list2 = const [1,2,3];
list2.add(22); // ERROR! Cannot add to an unmodifiable list

In Short: One makes the memory allocated immutable, the other one the same, and also the pointer pointing to it. in both cases, the list(object) will be immutable.
I hope this helps you understand the difference.
Read more from offical documentation on dart.dev/language-tour#final-and-const


text:
Q: R shinydashboard: capture click event on dashboard body How can I capture click events on the shinydashboard body?
Attempt is below.  It loads a dashboard and gives an alert without clicking on the body.  Then clicking on the body does nothing.  The expected behaviour is that it would alert each time I click on the body.
library(shiny)
library(shinydashboard)
library(shinyjs)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(useShinyjs())
)

server <- function(input, output) {

  shinyjs::runjs("document.body.addEventListener('click', alert('hello'));")

  }

shinyApp(ui, server)

One idea is to give the body an id and use that with shinyjs::onclick, however I'm not sure how to give the body an id.

A: Your event listener should be a function, not an expression. For example

  shinyjs::runjs("document.body.addEventListener('click', function() {alert('hello')});")

}

That way each time a click happens, that function will get called.


text:
Q: What is the $\setminus \{a\}$ in $x \in [ a - \delta, a + \delta ]\setminus \{a\}$? What does the  $\setminus \{a\}$ in
$$x \in [ a - \delta, a + \delta ]\setminus \{a\}$$
mean?

A: It just means $x$ is some number greater than (or equal to) $a- \delta$, smaller  than (or equal to) $a+\delta$, but different than $a$.
In general, if $A$ is a set, $A\setminus\{a\}$ is another set which has all the members of $A$ except for $a$.

A: To generalize from YoTengoUnLCD's answer, this is a notation for set difference. For two sets $A$ and $B$, $A \setminus B = \{e \mid e \in A \wedge e \not \in B\}$.


text:
Q: Need to select different column for a query which requires group by clause I have a Student table which contains following columns:
studentName, startYear, EndYear, classId, some more columns
This table contains startYear and EndYear for students of different class.
I want to write a query to find all the students name which took maximum years (diff b/w EndYear and startYear) to pass a class.
I want following three fields in select query
select studentName, classId,  max(EndYear- startYear) as maxYears from Students group by classId;

but as group by doesn't contains studentname hence this query fails(and it make sense too).
Then I could do as :
Putting result of following query in temp table TEMP:
select classId,  max(EndYear- startYear) from Students group by classId

and then join this temp table with student table.
select studentName, classId, EndYear- startYear from Student s join Temp t on s.classId = t.classId and (s.EndYear- s.startYear) = t.maxYears

But this doesn't look optimal to me.  I am wondering what could be other ways to do it .

A: The following script with correlated sub-query should be equivalent to the JOIN solution and even could be converted into JOIN by the SQL Server optimizer.
SELECT studentName, classId
FROM Students s
WHERE (EndYear- startYear) = (SELECT MAX(EndYear- startYear)
                              FROM Students sm
                              WHERE c.classId = sm.classId)

A: Try this query, which does a self-join to fetch the row with maximum (EndYear- startYear):
select s1.studentName, s1.classId, s1.EndYear-s1.startYear
from Student s1
inner join
(
select classId, max(EndYear- startYear)
from Students
group by classId
) s2
on s1.classId = s2.classId;

A: Try this:
SELECT  *
FROM (
    SELECT  studentName, startYear, EndYear, classId,
            DENSE_RANK() OVER(PARTITION BY classId ORDER BY endYear - startYear DESC) AS Rnk
    FROM    dbo.Student
) x
WHERE x.Rnk = 1;


text:
Q: I am unable to get my new Angular Project up and running My HTML looks this:
            <html ng-app="myApp" ng-controller="myController">
                <head>
                    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
                </head>
                <body>
                    ******{{randomValue}}*******
                </body>
            </html>

My Javascript looks like this:
            var myApp = angular.module('myApp', [
                'ui.bootstrap',
                'ngSanitize'
            ]);

            myApp.config(['$stateProvide', '$httpProvider', function config($stateProvider, $httpProvider) {

            }]);

            myApp.run(['$location', '$timeout', '$rootScope', function($location, $timeout, $rootScope) {

            }]);

            myApp.controller('myController', ['$scope', '$rootScope', function($scope, $rootScope) {

                $scope.randomValue = "Hello World!";

            }]);

I am getting an angular error in the browser console that leads me to the Angular Website


text:
Q: Sometimes Receipt Validation for In-App Purchase is taking to much time to give response Swift This is my verification validation code:
func receiptValidation(completion: @escaping(_ isPurchaseSchemeActive: Bool, _ error: Error?) -> ()) {
    let receiptFileURL = Bundle.main.appStoreReceiptURL
    guard let receiptData = try? Data(contentsOf: receiptFileURL!) else {
        //This is the First launch app VC pointer call
        completion(false, nil)
        return
    }
    let recieptString = receiptData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
    let jsonDict: [String: AnyObject] = ["receipt-data" : recieptString as AnyObject, "password" : AppSpecificSharedSecret as AnyObject]

    do {
        let requestData = try JSONSerialization.data(withJSONObject: jsonDict, options: JSONSerialization.WritingOptions.prettyPrinted)
        let storeURL = URL(string: self.verifyReceiptURL)!
        var storeRequest = URLRequest(url: storeURL)
        storeRequest.httpMethod = "POST"
        storeRequest.httpBody = requestData
        let session = URLSession(configuration: URLSessionConfiguration.default)
        let task = session.dataTask(with: storeRequest, completionHandler: { [weak self] (data, response, error) in
            do {
                if let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
                    if let latestInfoReceiptObjects = self?.getLatestInfoReceiptObjects(jsonResponse: jsonResponse) {
                        self?.getCurrentTimeFromServer(completionHandler: { currentDateFromServer in
                            let purchaseStatus = self?.isPurchaseActive(currentDateFromServer: currentDateFromServer, latestReceiptInfoArray: latestInfoReceiptObjects)
                            completion(purchaseStatus!, nil)
                        })
                    }
                }
            } catch let parseError {
                completion(false, parseError)
            }
        })
        task.resume()
    } catch let parseError {
        completion(false, parseError)
    }
}

I start calling the observer inside of didFinishLaunchingWithOptions:
IAPManager.shared.startObserving()

And then call the receiptValidation to check the subscription status of product:
IAPManager.shared.receiptValidation { isPurchaseSchemeActive, error in
    //Handle authentication based on isPurchaseSchemeActive status
}

I end calling the observer inside of applicationWillTerminate:
IAPManager.shared.stopObserving()

I am also calling the receiptValidation inside of the applicationWillEnterForeground to check the validity whenever user come from background to foreground:
IAPManager.shared.receiptValidation { isPurchaseSchemeActive, error in
    //Handle authentication based on isPurchaseSchemeActive status
}

My IAPManager in short:
class IAPManager: NSObject {
    static let shared = IAPManager()
    private override init() { super.init() }

    func startObserving() {
        SKPaymentQueue.default().add(self)
    }

    func stopObserving() {
        SKPaymentQueue.default().remove(self)
    }
}

And obviously calling receiptValidation after each successful purchase transaction and restoring product transactions before SKPaymentQueue.default().finishTransaction(transaction).
It works perfectly. But sometimes the receiptValidation stuck at JSON response for more than 10 or higher minutes. In this case, I am trying to cancel the receiptValidation call with a 1 minute timer. A pop up alert will appear saying try again and It will request the call again if user tap on "Try again" button.
My question is If I want to cancel an ongoing receiptValidation call, should I turn off IAPManager.shared.stopObserving() observer and turn on IAPManager.shared.startObserving() observer again before calling it? Or simply recall the receiptValidation request?


text:
Q: Something wrong with my grid I'm building the game of life and my grid doesn't display correctly.
If you resize the browser (shrinking it), the grid of cells looks very out of proportion.
It must be something wrong with the way I set the grid and square sizes.
I'm relatively beginner in CSS, so any help is greatly appreciated! Below is my attempt:
import React, { Component } from 'react';
import {Grid} from './Grid';
import './App.css';

class App extends Component {
  constructor(props){
    super(props);
    this.rows = 30;
    this.cols= 50;
    this.state = {generation:0, gridFull: Array(this.rows).fill(Array(this.cols).fill(0)) };
  }

  render(){
    console.log(this.state.gridFull)
  return (

     <Grid gridFull = {this.state.gridFull} rows={this.rows} cols= {this.cols}/>

    );
  }
}

export default App;

import React,{Component} from 'react';
import {Cell} from './Cell';
import './App.css';

export class Grid extends Component{

    render(){

    return(

       {this.props.gridFull.map((boardrow,i) =>
          (

            {boardrow.map((square,k) =>

                <Cell key={k}/>
            )}

)
       )}

        )
    }
}

import React, {Component} from 'react';
import './App.css';

export class Cell extends Component{
    render(){
        return(

            )
    }
}

.App {
   display: flex;
  flex-direction: row;

}

.board-row:after {
  clear: both;
  content: "";
  display: table;
}

.square {
  background: #fff;
  border: 1px solid black ;
  float: left;
  padding: 0;
}
.square:focus {
  outline: none;
}


text:
Q: Extreme directions of $S=\{x:-x_1+2x_2\le 4,x_1-3x_2\le 3,x_1,x_2\ge 0\}$
Consider the set $S=\{x:-x_1+2x_2\le 4,x_1-3x_2\le 3,x_1,x_2\ge 0\}$. Identify all
  extreme points and extreme directions of $S$. Represent the point $(4,1)^t$ as a
  convex combination of the extreme points plus a nonnegative combination of
  the extreme directions.

Recall:
Definition: $d\in \mathbb R^n$ is a extreme direction of $S$ if $d=\lambda_1d_1+\lambda_2d_2,$ then $\lambda d_1=d_2.$, where $d_1,d_2$ are directions of $S.$ and $\lambda>0,\lambda_i>0$

This is what I've done:
I draw the region and I found 3 extreme points $(0,0),(0,2),(3,0).$
And I don't know how to identify the extreme directions, I don't even see it geometrically.
How can I see it geometrically?
For instance the extreme points are "the vertex of the figure". So the extreme directions are ... ?
And finally, how do I prove it?

A: Check out the graph at https://www.desmos.com/calculator/sarf5jl1cq
Extreme directions are $(2,1)$ and $(3,1)$, which are the direction vectors emanating from the two nonzero extreme points in the boundary.


text:
Q: What is the action of writing with both hands simultaneously called? I can write with both my hands so I am ambidextrous. But it means adept and deft in using both the hands equally. So if someone was exhibiting their skill of ambidexterity by writing something with both their hands simultaneously, what would this piece of action be called? Is there a word for it?
I need the word that means simultaneously using both the hands, for writing or whatever.

A: There are clever and high-falutin' ways to convey the idea of writing with both hands simultaneously but employing the K.I.S.S. approach - Keep It Simple, Stupid! :-), why not just say that "he/she wrote with both hands simultaneously"?
To me, it is obvious that someone who is writing with both hands, simultaneously or alternatively, is ambidextrous so that word isn't really needed, is it?

A: Synamphichiry would be properly formed from Greek, meaning something like "using both hands together at the same time" (syn- expressing "together at the same time").
Amphichirography would mean "writing with both hands".

A:
I need the word that means simultaneously using both the hands, for
  writing or whatever.

Actions involving both hands simultaneously are called bimanual. Playing a piano is an example of bimanual activity. Others would be tying shoes, clapping hands, etc. As @ Third News commented above, researchers use the term bimanual simultaneous handwriting, but I wouldn't expect that to be in common parlance. The problem with seeking a single word for an obscure condition or rare phenonmenon is that even if if you find one, it is likely to be of little use since no one would understand it without the definition being provided. Still, how would you know if you don't ask.

A: I don't think a single word exists but some people afflicted by Kallman syndrome are affected by a condition called bimanual synkinesis in which the movements of one hand are mirrored by the other hand. So, analogously, I would use "bimanual writing", using bimanual as an adjective or an adverb, i.e., "He's bimanualy writing".

A: If:

*

*you are using a cell phone

*you are using the thumb of both hands

then it is called texting.

A: One type of simultaneous right- and left-hand writing is called "writing in mirror images" or, more simply, "simultaneous mirror-writing." You can see a YouTube video of a woman performing this two-handed feat here.
For a fairly long article on simultaneous and nonsimultaneous mirror-writing (mostly the latter), see Robert D. McIntosh and Sergio Della Sala, "Mirror-writing" (October 2012), posted on the British Psychological Society's The Psychologist website. The part of that article most relevant to simultaneous writing is this excerpt:

Could deliberate mirror-writing offer insight into the nature of involuntary mirror-writing in brain-damaged adults?
We have recently had the chance to address this issue with Kasimir Bordihn (KB), a German artist, who has practised various forms of mirror-writing for more than 50 years. KB is a natural left-hander, schooled to write with the right hand, who 'discovered' mirror-writing aged nine, finding that he could halve his time writing lines by writing forward with his right hand and simultaneously backward with his left. He later practised and extended this technique, writing forward or backward with either hand, including vertical as well as horizontal flips, and incorporating these into a distinctive 'mirror-art' (see cover). We have begun a case study of KB's abilities, which is providing clear support for the motor hypothesis of mirror-writing, and some less expected results.

Undoubtedly, when KB simultaneously writes the same words forward with one hand and backward with the other, he is engaged in simultaneous mirror-writing. But I'm not sure what you'd call his simultaneously writing half a line left-to-right with his right hand and writing the other half of the line right-to-left with his left hand. The article doesn't identify that skill by name.

A: Wonderful and creative question.
I remember the Rector at our Boys Home saying something similar:

Michelangelo was ambidextrous and often painted bimanually.  The least we can do is to be two-handed in prayer.  Manibus sedeas, Amen.

Bottom line is, IMHO, I believe we can use two-handed or bimanually.
PS: I just up-voted GMB's answer for originality and application of mind.  It was GMB's answer that reminded me of this.
PS2: Our guidance counselor uses the term "bihemispherical activity" to indicate usage of both sides of the brain simultaneously.  Not sure if this is a common term, though.

A: I do not have enough reputation to comment, but you can always use the adverb ambidextrously plus the verb you need. For examples, you can go here: http://www.oxforddictionaries.com/definition/english/ambidextrous?q=ambidextrously#ambidextrous__10

A: It is called writing. Writing does not imply using one hand or two hands. You can write in different ways so if you are using two or one hands it is still writing which is the act of enscribing information onto a medium. There are no rules for how the writing gets on the page.

A: Ambidextrous is the word for a person who can use both hands.
Wiki : Ambidexterity is the state of being equally adept in the use of both left and right appendages (such as the hands).
One can say, he is an expert in ambidexterity.
You can say, I am writing ambidextrously.

A: Ambitexterity.
I just needed the concept myself and this is what came up.

A: A word for writing with both hands is ambidextrous and you are only 1 percent (of people?). Basically, if someone writes equally well with both hands, you may call them ambidextrous.


text:
Q: pass data with SimpleHttpOperator to trigger cloud function 2nd gen I have the following task:
this_is_a_task = SimpleHttpOperator(
    task_id= 'task_id',
    method='POST',
    http_conn_id='conn_id',
    endpoint='/?test=foo',
    # data={"test": "foo"},
    headers={"Content-Type": "application/json"}

on the cloud functions side, I'm trying to catch the parameters with the two following ways:
# catching data
# test_data = request.get_json().get('test')
# print('test: {}'.format(test))

# catching end point
test_endpoint = request.args.get('test')
print('test: {}'.format(test))

the second option is working (request.args.get('test')) however when trying the first option request.get_json().get('test') I'm getting a 400 request error.
so if I'm not using the endpoint variable from my SimpleHttpOperator how can I catch the json object pass into the data variable?

A: I've tried to replicate your issue and based on this documentation you need to add json.dumps when you are calling a POST with json data. Then provide authentication credentials as a Google-generated ID token stored in an Authorization header.
See below sample code:
import datetime
import json

from airflow import models
from airflow.operators import bash
from airflow.providers.http.operators.http import SimpleHttpOperator

YESTERDAY = datetime.datetime.now() - datetime.timedelta(days=1)

default_args = {
    'owner': 'Composer Example',
    'depends_on_past': False,
    'email': [''],
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': datetime.timedelta(minutes=5),
    'start_date': YESTERDAY,
}

with models.DAG(
        'composer_quickstart',
        catchup=False,
        default_args=default_args,
        schedule_interval=datetime.timedelta(days=1)) as dag:

    # Print the dag_run id from the Airflow logs
    gen_auth = bash.BashOperator(
        task_id='gen_auth', bash_command='gcloud auth print-identity-token '
    )

    auth_token = "{{ task_instance.xcom_pull(task_ids='gen_auth') }}"

    this_is_a_task = SimpleHttpOperator(
        task_id='task_id',
        method='POST',
        http_conn_id='cf_conn1',
        data=json.dumps({"test": "foo"}),
        headers={"Content-Type": "application/json","Authorization": "Bearer " + auth_token}
    )

    gen_auth >> this_is_a_task

On the cloud functions side tried to use below sample code:
test_data = request.get_json().get('test')
print(test_data)

return test_data

You can also test your function using this curl command:
curl -i -X POST -H "Content-Type:application/json"  -d '{"test": "foo"}' "Authorization: bearer $(gcloud auth print-identity-token)" https://function-5-k6ssrsqwma-uc.a.run.app


text:
Q: Incorrect updating integer values in the database I' ve got an error when I attempt to update integer parameter in my database. If I changed it +1/-1 everything fine but changing it more (+5, +7, -4) save +1/-1 step only (example: change 5 to 10 and load it from DB - get 6).
Objects of drug_storage class are in a BindingList. I trace changes using ListChanged method. I use integer updown counter binded to drug_quantity parameter in two way mode; also use not mapped integer tag property of an object to store information about previous number of parameter. If counter change this parameter tag != parameter and DB updates
XAML:
<UserControl.Resources>
    <DataTemplate x:Key="ComboBoxDataTemplate">
        <StackPanel Orientation="Horizontal">
            <CheckBox IsChecked="{Binding is_selected, Mode=TwoWay}" x:Name="checkbox" Margin="3" Checked="SelectComboBoxItem" Unchecked="SelectComboBoxItem" />
            <TextBlock Text="{Binding public_drug_name}" Margin="2" />
            <lc1:IntegerUpDown x:Name="iudQuantity" Minimum="1" Increment="1" Value="{Binding drug_quantity, Mode=TwoWay}" Margin="3"
                               Visibility="{Binding IsChecked, ElementName=checkbox, Converter={StaticResource BooleanToVisibilityConverter}}" ValueChanged="SelectComboBoxItem" />
        </StackPanel>
    </DataTemplate>
</UserControl.Resources>

<ComboBox ItemsSource="{Binding InfusionDrugList}" Margin="5" ItemTemplate="{StaticResource ComboBoxDataTemplate}"
              SelectedItem="{Binding SelectedDrug, Mode=OneWayToSource}">

XAML.CS (if something in data template is clicked comboboxitem becomes selected and set value of SelectedDrug what triggers viewmodel code:
private void SelectComboBoxItem(object sender, RoutedEventArgs e)
    {
        var v = FindVisualParent<ComboBoxItem>(sender as UIElement);
        if (v != null) { v.IsSelected = true; } // some checkboxes can become selected automatically at the moment of druglist loading and v would be null
    }
    public static T FindVisualParent<T>(UIElement element) where T : UIElement
    {
        UIElement parent = element; while (parent != null)
        {
            T correctlyTyped = parent as T; if (correctlyTyped != null)
            {
                return correctlyTyped;
            }
            parent = VisualTreeHelper.GetParent(parent) as UIElement;
        }
        return null;
    }

    private void SelectComboBoxItem(object sender, RoutedPropertyChangedEventArgs<int> e)
    {
        var v = FindVisualParent<ComboBoxItem>(sender as UIElement);
        if (v != null) { v.IsSelected = true; } // some updowns can become selected automatically at the moment of druglist loading and v would be null
    }

VIEW MODEL:
In Constructor:
 SelectedDrugs = new BindingList<drug_storage>();
        SelectedDrugs.RaiseListChangedEvents = true;
        SelectedDrugs.ListChanged += ProcessSelectedDrugCommands;

Later:
 ` public BindingList<drug_storage> SelectedDrugs { get; set; }
    private drug_storage selectedDrug;
    public drug_storage SelectedDrug
    {
        get { return selectedDrug; }
        set
        {
            selectedDrug = value;
            NotifyPropertyChanged();
            AddDrugForProcessing();
        }
    }
    private void AddDrugForProcessing()
    {
        if (SelectedDrug != null && !SelectedDrugs.Contains(SelectedDrug))
        {
            SelectedDrugs.Add(SelectedDrug);
        }
    }

 private void ProcessSelectedDrugCommands(object sender, ListChangedEventArgs e)
        {
.... //code to add and remove objects to DB

if (e.ListChangedType == ListChangedType.ItemChanged)
            {
                int position = e.NewIndex;
                drug_storage drug = SelectedDrugs[position];
                if (drug.is_selected && drug.tag != drug.drug_quantity) //when user changed number in updown counter
                {
                    ChangeNumberOfDrugInDB(drug);
                }

 void ChangeNumberOfDrugInDB (drug_storage drug)
        {
            int procedure_id = SelectedInListProcedure.PMR_Id;
            int drug_id = SelectedDrug.drug_id;
            using (var db = new MainEntityModel())
            {
                var query = (from d in db.PMR_infusions_drugs
                             where d.PMR_Id == procedure_id && d.drug_id == drug_id
                             select d).Single();
                query.drug_quantity = drug.drug_quantity;
                db.SaveChanges();
                drug.tag = drug.drug_quantity;
            }
        }}

I believe every time user change integerupdown binded to drug_quantity parameter it triggers DB update and then updates tag property but it looks like after inintial 1-integer-step updating drug.tag already becomes equal to final drug_quantity value. Can it be so?
Thanks
ADDITIONALY:
EF Class:
 public partial class drug_storage
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public drug_storage()
    {
        PMR_infusions_drugs = new HashSet<PMR_infusions_drugs>();
    }

    [Key]
    public int drug_id { get; set; }

    [Required]
    [StringLength(50)]
    public string drug_name { get; set; }

    [NotMapped]
    public bool is_selected { get; set; }

    [NotMapped]
    private int quantity = 1;

    [NotMapped]
    public int drug_quantity { get { return quantity; } set { quantity = value; } }

    [NotMapped]
    public int tag = 0;

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<PMR_infusions_drugs> PMR_infusions_drugs { get; set; }
}


text:
Q: Create an arrayformula that find word I'm trying to find a formula with arrayformula that will search a specific word on many columns and report an anwser. So in my exemple below, if a row show need order, it will tell need order in the arrayformula column and if not it will show ok.

=arrayformula
Column B
Column C

need order
$ 20
need order

ok
$ 60
$100$

I've tried to used the formula below wiht arrayformula but couldn't find a way to make it work.
=IF(COUNTIF(B2:C3,"need order")>0,"need order","ok")
I'm open to all suggestion
Cheers

A: Assuming GS, try something along the lines of:
=BYROW(FILTER(B:C,B:B<>""),LAMBDA(a,IF(COUNTIF(a,"need order"),"need order","ok")))

In case of headers, try:
=BYROW(FILTER(B2:C,B2:B<>""),LAMBDA(a,IF(COUNTIF(a,"need order"),"need order","ok")))


text:
Q: html button to send email How do I send an email with specified initial values for the headers subject and message from a button in html, such as this
<form method="post" action="mailto:email.com?subject=subject&message=message">

where subject and message are values fetched from a form?

A: I couldn't ever find an answer that really satisfied the original question, so I put together a simple free service (PostMail) that allows you to make a standard HTTP POST request to send an email. When you sign up, it provides you with code that you can copy & paste into your website. In this case, you can simply use a form post:
HTML:
<form action="https://postmail.invotes.com/send"
    method="post" id="email_form">

    <input type="text" name="subject" placeholder="Subject" />
    <textarea name="text" placeholder="Message"></textarea>

    <input type="hidden" name="access_token" value="{your access token}" />

    <input type="hidden" name="success_url"
      value=".?message=Email+Successfully+Sent%21&isError=0" />
    <input type="hidden" name="error_url"
      value=".?message=Email+could+not+be+sent.&isError=1" />

    <input id="submit_form" type="submit" value="Send" />
</form>

Again, in full disclosure, I created this service because I could not find a suitable answer.

A: You can use mailto, here is the HTML code:

Replace EMAILADDRESS with your email.

A: This method doesn't seem to work in my browser, and looking around indicates that the whole subject of specifying headers to a mailto link/action is sparsely supported, but maybe this can help...
HTML:
<form id="fr1">
    <input type="text" id="tb1" />
    <input type="text" id="tb2" />
    <input type="button" id="bt1" value="click" />
</form>

JavaScript (with jQuery):
$(document).ready(function() {
    $('#bt1').click(function() {
        $('#fr1').attr('action',
                       'mailto:test@test.com?subject=' +
                       $('#tb1').val() + '&body=' + $('#tb2').val());
        $('#fr1').submit();
    });
});

Notice what I'm doing here.  The form itself has no action associated with it.  And the submit button isn't really a submit type, it's just a button type.  Using JavaScript, I'm binding to that button's click event, setting the form's action attribute, and then submitting the form.
It's working in so much as it submits the form to a mailto action (my default mail program pops up and opens a new message to the specified address), but for me (Safari, Mail.app) it's not actually specifying the Subject or Body in the resulting message.
HTML isn't really a very good medium for doing this, as I'm sure others are pointing out while I type this.  It's possible that this may work in some browsers and/or some mail clients.  However, it's really not even a safe assumption anymore that users will have a fat mail client these days.  I can't remember the last time I opened mine.  HTML's mailto is a bit of legacy functionality and, these days, it's really just as well that you perform the mail action on the server-side if possible.

A: You can not directly send an email with a HTML form. You can however send the form to your web server and then generate the email with a server side program written in e.g. PHP.
The other solution is to create a link as you did with the "mailto:". This will open the local email program from the user. And he/she can then send the pre-populated email.
When you decided how you wanted to do it you can ask another (more specific) question on this site. (Or you can search for a solution somewhere on the internet.)

A: @user544079
Even though it is very old and irrelevant now, I am replying to help people like me!
it should be like this:
<form method="post" action="mailto:$emailID?subject=$MySubject &message= $MyMessageText">

Here
$emailID,
$MySubject,
$MyMessageText are variables which you assign from a FORM or a DATABASE Table or just you can assign values in your code itself. Alternatively you can put the code like this (normally it is not used):
<form method="post" action="mailto:admin@website.com?subject=New Registration Alert &message= New Registration requires your approval">

A: You can use an anchor to attempt to open the user's default mail client, prepopulated, with mailto:, but you cannot send the actual email. *Apparently it is possible to do this with a form action as well, but browser support is varied and unreliable, so I do not suggest it.
HTML cannot send mail, you need to use a server side language like php, which is another topic. There are plently of good resources on how to do this here on SO or elsewhere on the internet.
If you are using php, I see SwiftMailer suggested quite a bit.

A: As David notes, his suggestion does not actually fulfill the OP's request, which was an email with subject and message. It doesn't work because most, maybe all, combinations of browsers plus e-mail clients do not accept the subject and body attributes of the mailto: URI when supplied as a <form>'s action.
But here's a working example:
HTML (with Bootstrap styles):

<input id="subject" type="text" placeholder="type your subject here"
    class="form-control">

<input id="message" type="text" placeholder="type your message here"
    class="form-control">

Create email

JavaScript (with jQuery):

Notes:

*

*The <form> element with associated action attribute is not used.

*The <input> element of type button is also not used.

*

* styled as a button (here using Bootstrap) replaces <input type="button">

*focusout() with updateMailString() is necessary because the  tag's href attribute does not automatically update when the input fields' values change.

*updateMailString() is also called when document is loaded in case the input fields are prepopulated.

*Also encodeURIComponent() is used to get characters such as the quotation mark (") across to Outlook.

In this approach, the mailto: URI is supplied (with subject and body attributes) in an a element's href tag. This works in all combinations of browsers and e-mail clients I have tested, which are recent (2015) versions of:

*

*Browsers: Firefox/Win&OSX, Chrome/Win&OSX, IE/Win, Safari/OSX&iOS, Opera/OSX

*E-mail clients: Outlook/Win, Mail.app/OSX&iOS, Sparrow/OSX

Bonus tip: In my use cases, I add some contextual text to the e-mail body. More often than not, I want that text to contain line breaks. %0D%0A (carriage return and linefeed) works in my tests.

A:  <form action="mailto:someone@example.com" method="post"               enctype="text/plain">
 Name:

<input type="text" name="name">

 E-mail:

<input type="text" name="mail">

Comment:

<input type="text" name="comment" size="50">

<input type="submit" value="Send">
<input type="reset" value="Reset">


text:
Q: Chromecast MetaData Having all sorts of fun trying to get the desired metadata, lockscreen and cast popup behaviour working in a music app that utilizes a custom receiver on Chromecast. Here's where I've got to..
private void _dummyRemotePlay(long id,String mUrl,String artist,String title,String iUrl) {

    // CODE THAT CHANGES BEHAVIOUR
    MediaTrack.Builder b = new MediaTrack.Builder(id,MediaTrack.TYPE_AUDIO);
    b.setSubtype(MediaTrack.SUBTYPE_METADATA);
    // END CODE THAT CHANGES BEHAVIOUR

    MediaMetadata mdata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MUSIC_TRACK);
    mdata.putString(MediaMetadata.KEY_ARTIST, artist);
    mdata.putString(MediaMetadata.KEY_TITLE, title);
    mdata.addImage(new WebImage(Uri.parse(iUrl)));

    MediaInfo mi =  new MediaInfo.Builder(mUrl)
                .setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
                .setContentType("audio/mpeg")
                .setMetadata(mdata)
                .build();

    MediaQueueItem qi = new
    MediaQueueItem.Builder(mi).setAutoplay(true).setPreloadTime(20).build();
    MediaQueueItem[] qa = new MediaQueueItem[]{qi,qi}; // Two so SKIP_NEXT works...

    _remoteMediaClient.queueLoad(qa,0,MediaStatus.REPEAT_MODE_REPEAT_OFF, null);}

Without the call to b.setSubType(MediaTrack.SUBTYPE_METADATA) the cast popup works (image, controls etc), a cast notification appears and the cast volume is adjusted by the volume keys. What doesn't work is the lockscreen metadata and controls. The artist is unknown and the controls do nothing.
With the b.setSubType call the lockscreen works fine (artist correctly displayed, controls work). However, there's no cast notification and the cast popup has no media selected (no image, no controls, just volume slider and end cast). Also the volume keys are not bound to cast volume.
Arrived at this point just playing around. Originally called b.build() to create a MediaTrack, added it to a list and called .setMediaTracks(list) on the MediaInfo.builder. Distilled it down to just the above though. The b.setSubType call on just a builder without a MediaTrack being built is enough to switch behaviour.
What I'm looking for is correct lockscreen behaviour, correct cast dialog image and control, volume keys working. I'm indifferent to a cast notification as the app has one anyway. It seems I can't achieve all of this.


text:
Q: Unable to open playwright HTML Report (using Docker) I have pulled the image using below command into my root of the project
docker pull mcr.microsoft.com/playwright:v1.24.2-focal

and then run the image using below command:
docker run -it --rm --ipc=host mcr.microsoft.com/playwright:v1.24.2-focal /bin/bash

and it takes me to the container (please check screenshot below)

when I run the command npx playwright test my all test got passed but when I tried to open test report using command: npx playwright show-report then it shows me below result:

It says:

Failed to open browser on http://127.0.0.1:9323

What can I try to resolve this?

A: Max is right, you have to add for example in your playwright.config.ts the option open: 'never'. For example:
const config: PlaywrightTestConfig = {
  // (...)
  reporter: [ ['html', { open: 'never'}], ['list'] ],
  // (...)
}

And to answer to your second question, about getting the reports on your host, you have to use a volume when executing docker run.
For example, let's say that on your host, in your current folder, you have your playwright.config.ts file, then run the following command to mount the whole directory on the container:
docker run -it --rm --ipc=host \
  --workdir=/my_tests \
  -v $PWD:/my_tests \
  mcr.microsoft.com/playwright:v1.24.2-focal bash


text:
Q: Bib entry cannot be encoded in ansinew I'm compiling the following files which are enconded in Western-1252. Using biber to compile the bib
example.tex
\documentclass[11pt, twoside, a4paper]{memoir}

\usepackage[ansinew]{inputenc}
\usepackage[spanish, es-noquoting, es-tabla]{babel}
\usepackage[spanish]{translator}
\usepackage[OT1]{fontenc}

\usepackage[firstinits=true, url=true, doi=false, style=alphabetic, sorting=nyt, maxnames=5]{biblatex}
\DefineBibliographyStrings{spanish}{
    urlseen = {Última visita},
    urlfrom = {from},
    url = {url},
}
\DeclareFieldFormat{url}{\textsc{\bibstring{url}}:\space\url{#1}}
\addbibresource{example.bib}

\begin{document}

Hola que tal \cite{Doe:2009:Online}

\end{document}

example.bib
@ONLINE{Doe:2009:Online,
author = {Doe, Ringo},
title = {This is a test entry of type {@ONLINE}},
month = jun,
year = {2009},
url = {http://www.test.org/doe/?a},
urldate = {2008},
}

If I include a ? or a % in the url I get the following error:
The entry 'Doe:2009:Online' has characters which cannot be encoded in 'ansinew'. Recoding problematic characters into macros.
Any idea why is that? the question mark exists in ansinew. How can I escape the code in the url?

Edit:
Another try using this, didn't work:
\usepackage[firstinits=true, url=true, doi=false, style=alphabetic, sorting=nyt, maxnames=5, bibencoding=utf8]{biblatex}

Edit2:
I have realized the problem is somewhere with the final pdflatex execution:
[]\OT1/cmr/m/n/10.95 MAGNET. \OT1/cmr/m/it/10.95 Pro-ject Na-me\OT1/cmr/m/n/10.95 . 2004. \OT1/cmr/m/sc/10.95 Url\OT1/cmr/m/n/10.95 : [][]$\OT1/pcr/m/n/10.95 http :$
[28]
! Missing $ inserted.
<inserted text>
$

@STRING{NAME = "ProjectShort"}
@STRING{NAME_LONG = "{ProjectLong}"}

@MISC{MAGNET:PROJECT,
 author = {{NAME}},
title = NAME_LONG,
subtitle = {{FP6-IST-1234}},
year = "2004",
url = {http://www.proect.org},
urldate = {2008},
}


text:
Q: how to do routing inside multiple instances of same component in angular 6 In my POC, I have two instances of dashboard displayed. I want the children to appear in the respective instance of the component.
But the current behaviour is, even if I click the button in the first instance, the children are getting rendered in the second instance itself.
Dashboard component.html

    dashboard works!

  <button [routerLink]="['child1']">one</button>
  <button [routerLink]="['child2']">two</button>

    <router-outlet></router-outlet>

-----------------------------------------------

app.component.html

  <app-dashboard></app-dashboard>    // instance 1

  <app-dashboard></app-dashboard>   //  instance 2

app.routing.module.ts
const routes: Routes = [
  { path: 'child1',
  component: ChildOneComponent
  },
  {
    path: 'child2',
    component: ChildTwoComponent
  }
];

child-one.component.html

  child-one works!

child-two.component.html

  child-two works!

I want to write additional code in child 1 and child 2, once the components load.
Can anyone tell me where I went wrong or which approach to take? I have already tried using auxiliary routes and assigning id to the routes. But they didn't work.
I just want to create multiple instances of the same component and enable routing inside them so that the particular component that is routed is rendered inside the respective instance.

A: Router is a global component so it doesn't bellong to one component.
if you have many instances, you need to use a function to reload one instance.
like :
Dashboard component.html

        dashboard works!

      <button (click)='routeone()'>one</button>
      <button (click)='routetwo()'>two</button>

          {{mydata}}

-----------------------------------------------

Dashboard component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  mydata;
  constructor( private router: Router) { }

  ngOnInit() {
  }

  routeone(){
    this.mydata = 'childOne'
  }
  routetwo(){
    this.mydata = 'childTwo'
  }

}


text:
Q: C# WP8 async HttpWebRequest Post with xml request message i've been reading here for quite a long time, but in this case i'm not getting any further.
I'm rather new to Windows Phone development and facing the following problem.
I'm calling a webservice were I have to post a xml request message. I've got the code working in regular c# (see code below)
private static string WebRequestPostData(string url, string postData)
{
    System.Net.WebRequest req = System.Net.WebRequest.Create(url);

    req.ContentType = "text/xml";
    req.Method = "POST";

    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
    req.ContentLength = bytes.Length;

    using (Stream os = req.GetRequestStream())
    {
        os.Write(bytes, 0, bytes.Length);
    }

    using (System.Net.WebResponse resp = req.GetResponse())
    {
        if (resp == null) return null;
            using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
        {
            return sr.ReadToEnd().Trim();
        }
    }
}

But for Windows Phone (8) development it needs to be async. After searching the web, and trying the various samples given here I came to the following code:
private async void DoCallWS()
{
    string url = "<my_url>";

        // HTTP web request
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest.ContentType = "text/xml";
    httpWebRequest.Method = "POST";

    // Write the request Asynchronously
    using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
                                                                 httpWebRequest.EndGetRequestStream, null))
    {
        string requestXml = "<my_request_xml>";

        // convert request to byte array
        byte[] requestAsBytes = Encoding.UTF8.GetBytes(requestXml);

        // Write the bytes to the stream
        await stream.WriteAsync(requestAsBytes , 0, requestAsBytes .Length);

        stream.Position = 0;
        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
        {
            //return reader.ReadToEnd();

            string result = reader.ReadToEnd();
        }
    }
}

The string result has the value of my request xml message i'm trying to sent....
I'm aware that async void methodes are not preferred but i will fix that later.
I've also tried to following the solution as described by Matthias Shapiro (http://matthiasshapiro.com/2012/12/10/window-8-win-phone-code-sharing-httpwebrequest-getresponseasync/) but that caused the code to crash
Please point me in the right direction :)
Thnx Frank

A: What you're doing is only writing to the request stream. You're missing the code which reads from the response.
The reason you're getting back your request xml is that you reset the request stream and read from that exact stream.
Your method should look as follows:
private async Task DoCallWSAsync()
{
   string url = "<my_url>";

   // HTTP web request
   var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
   httpWebRequest.ContentType = "text/xml";
   httpWebRequest.Method = "POST";

   // Write the request Asynchronously
   using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
                                                             httpWebRequest.EndGetRequestStream, null))
   {
       string requestXml = "<my_request_xml>";

       // convert request to byte array
       byte[] requestAsBytes = Encoding.UTF8.GetBytes(requestXml);

       // Write the bytes to the stream
       await stream.WriteAsync(requestAsBytes , 0, requestAsBytes .Length);
    }

    using (WebResponse responseObject = await Task<WebResponse>.Factory.FromAsync(httpWebRequest.BeginGetResponse, httpWebRequest.EndGetResponse, httpWebRequest))
    {
        var responseStream = responseObject.GetResponseStream();
        var sr = new StreamReader(responseStream);
        string received = await sr.ReadToEndAsync();

        return received;
    }
}


text:
Q: AWS IOT subscribe timeout exception I have been using the AWS IOT python sdk for developing a cloud based iot software as a part
of a larger solution.However I frequently get the subscribe and publish timeout exceptions after some time on every run. Though i don't see a pattern here i am able to receive the messages published for some time duration.
How do i fix this issue so that i do not get those exceptions?
Is there any parameter that i have to set to prevent the IOt Subscription issue?
Or is there any additional setup needed to be done on the cloud?
Thanks in advance.


text:
Q: Achieving A 1600 x 900 Resolution For (Guest OS) Ubuntu Under (Host OS) Windows 7 I am running Ubuntu 11.10 as a guest OS using VirtualBox 4.1.16 installed on Windows 7 Ultimate.
On my laptop I'd like to be able to run Ubuntu in full screen mode at 1600 x 900.  I only have options within the virtual machine to select 4:3 display settings such as 1600 x 1200, 1440 x 1050 etc.
I have guest additions installed.
At the windows command prompt, I tried typing:
VBoxManage setextradata "Virtual Ubuntu Coursera ESSAAS" "CustomVideoMode1" "1600x900x16"
This didn't work, still no 1600 x 900 res available in Ubuntu.
I tried this having read the following section of the VirtualBox help (this also says something about a 'video mode hint feature' not sure what this means):

9.7. Advanced display configuration
  9.7.1. Custom VESA resolutions Apart from the standard VESA resolutions, the VirtualBox VESA BIOS allows you to add up to 16
  custom video modes which will be reported to the guest operating
  system. When using Windows guests with the VirtualBox Guest Additions,
  a custom graphics driver will be used instead of the fallback VESA
  solution so this information does not apply.
Additional video modes can be configured for each VM using the extra
  data facility. The extra data key is called CustomVideoMode with x
  being a number from 1 to 16. Please note that modes will be read from
  1 until either the following number is not defined or 16 is reached.
  The following example adds a video mode that corresponds to the native
  display resolution of many notebook computers:
VBoxManage setextradata "VM name" "CustomVideoMode1" "1400x1050x16"
  The VESA mode IDs for custom video modes start at 0x160. In order to
  use the above defined custom video mode, the following command line
  has be supplied to Linux:
vga = 0x200 | 0x160 vga = 864 For guest operating systems with
  VirtualBox Guest Additions, a custom video mode can be set using the
  video mode hint feature.

UPDATE 02.06.12
I've just tried creating a new virtual machine using the same original disk image I had been given.  This had Guest Additions v 4.1.6 installed and provided me with the 1600 x 900 full screen display I want.  It's after I then install Guest Additions v 4.1.16 (the version included with my VirtualBox installation) that my only choices are 4:3 displays e.g. 1600 x 1200.  Seems this is the cause.

A: So, this seems to be a known defect.
The workaround is to disable 3D Acceleration for the Virtual Machine under Settings >> Display >> Uncheck "Enable 3D Acceleration" on the Video Tab.

A: Install Guest Additions + give the virtual machine 48mb video memory + fullscreen(ctrl/command+F) = it works for me.


text:
Q: Show values of measure names from previous week and make difference? My sheet has measure names divided by ops managers and managers filtered to show values only for current week. What I need is to make new column for each of the measures to show values for previous week and then make %diff. I have seen solutions by putting week in row but is it possible this way somehow?
What I tried:

*

*LOOKUP(sum([missed hours]),-1) (shows values from previous row)

*{ FIXED DATEPART('week',[metric_date]),[ops_login_name],[supervisor_login_name]:sum([missed hours])} does nothing, same values as normal

*I even tried separate calc field DATEPART('week',[metric_date])-1 that shows previous week number and then { FIXED [previous_week],[ops_login_name],[supervisor_login_name]:sum([missed hours])}

A: You can do this by filtering for the desired week in the Measure Value and not in the filter shelf. Create two boolean expressions that isolate your week.
Is this week? : datetrunc('week',{max([metric_date])}) = datetrunc('week',([metric_date]))
Is last week? : dateadd('week',-1,datetrunc('week',{max([metric_date])})) = datetrunc('week',([metric_date]))
Then create week specific measure values with sum(if [Is this week?] then [total_miss_cnt] end)
Repeat for previous week and then you can do a % diff. Make sure to remove and date filtering from the filter shelf.


text:
Q: How to increment a variable of type String.CharacterView.Index? I was trying this (at the Playground):
class SomeClass {

    private let input: String.CharacterView
    private var position: String.CharacterView.Index

    ...

    private func advance() {

        position += 1

    } // advance

} // SomeClass

...but I'm getting the following error message:

error: binary operator '+=' cannot be applied to operands of type
  'String.CharacterView.Index' and 'Int'

The reason behind me trying to increment this index it's because I would like to do something like:
input[position]

...and access a specific character at input.
At this point I already know that I can't use this binary operator over position. What would be a viable solution?
I'm using Swift 3 and Xcode Version 8.0 beta 6 (8S201h)

A: In Swift 3, "Collections move their index", compare
 A New Model for Collections and Indices on Swift evolution.
In your case
private func advance() {
    input.formIndex(&position, offsetBy: 1)
}

would advance the index position by one. Here you have to ensure
that the index is not already equal to endIndex, alternatively use
private func advance() {
    input.formIndex(&position, offsetBy: 1, limitedBy: input.endIndex)
}


text:
Q: How to evaluate MATLAB command inside SIMULINK Suppose I have variable ii entering into the SIMULINK simulation from workspace and I would like to assign a new value for it after some condition is satisfied and save the value into a workspace. The values of variable could be defined in array, however, array length is not predefined. I see the block "MATLAB Function" could be useful, but is it proper way to evaluate just one simple command like ii=ii+1?
On the picture below started with ii=0, I expected the value of ii to be increased by one until tout>2 and its value to be saved accordingly. But I only got two values of ii: 1 till time of 2 seconds and 0 from time > 2 seconds on.
simulink_scheme

A: Usually you can use simple operations avoiding use of MATLAB Function Block. In your case there are different solutions. For example this way:

I load ii variable from workspace, check the condition in Switch block, and return new variable with the same name ii to workspace.
But! Important moment here is: to load data into Simulink with From Workspace block loaded data must be in special format: timeseries, matrix or structure. So you can't load just ii=1. And the same thing about To Workspace block - it returns data to workspace in timeseries, array or structure. This mean you take values of ii for every timestep of your simulation.
You can solve this problem using Decimation parameter in To Workspace block, then you can get only last value of ii. To get only value of ii without time column use Save format: Array in To Workspace block options. This let you get just 1 value as you wish. But, now you can simulate your program only 1 time: you load ii with time column (as it necessary for From Workspace block) and save just one value. Simulink can't load now ii because now it hasn't time column!
So the solutions depends on what you want.
P.S. One more advice to you: do not use just i variable! MATLAB has predefined variable i = 0.0000 + 1.0000i - imaginary unit.

I made some workaround this problem and get this example:

Where subsystem is:

Attention: To Workspace block save result as Array (avoiding time column). How it works: create ii=0 in workspace. Start simulation. While subsystem is enabled (t<=2) it will modify ii value in this way: increase ii at every timestep by 1. I mean:
t = 0, ii = 1
t = 1, ii = 2
t = 2, ii = 3
t = 3, ii = 3 ...

at the next simulation we load last value of ii array - ii(end) and continue simulation in the same way.


text:
Q: how can I run a perl script which needs root? I need to execute a perl script located in /root/scripts/ from php using ssh from another computer or from the same computer. The thing is that I just don't know how to make php log into roots account to excecute only that file.
As user$ I can't access /root/scripts/, so I can't call it using excec or system. I have tried using ssh to log into sudo su, and when I give my password it hangs.
I leave the code here:
<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('IP');
if (!$ssh->login('user', 'password')) {
exit('Login Failed');
}else{
echo ("login suscess");
}
echo $ssh->read(']$');

echo $ssh->write("sudo su\n");

echo $ssh->read('user:');
//the code normally runs if I dont write the lines below

$ssh->write('password\n');//here I try to get ssh the root pass but php wont respond after this
echo $ssh->read('user]#');//normally this would work to show the root prompt  but I don't know what happens

?>

I hope you can help me out here.

A: Usually you would tell sudo that the webserver user can execute the script without need to authenticate with a  password. You'll have to add a line like the following in /etc/sudoers:
www-data ALL=(ALL:ALL) NOPASSWD: /root/scripts/script.pl

This would let the www-data user execute script.pl via sudo without having to enter a password.
Then execute the script from PHP using
exec('sudo /root/scripts/script.pl');

A: *

*Echo'ing out $ssh->write() calls doesn't really do much.

*sudo needs a password. Here's an example on phpseclib's site of how to handle that: http://phpseclib.sourceforge.net/ssh/examples.html#sudo


text:
Q: How automate API testing for rest API built using Django Rest framework I want to automate testing of Rest API built using DRF. This automation should run the test cases every 2 minutes and this has to run continuously not in local machine(API is deployed in AWS). If there is any test cases failure then it has to record that failure in log report. This can be any service type. I am using Postman now to run test cases since it is free plan I am using, so have limited API calls and monitors in postman don't have minute wise running.
please help!!
How can I do this?

A: Yes,
After some research and help of my mentors I found a way to automate API testing.

*

*Coding part:
I have a python script which uses requests package to call the API and then I am using some conditions to ensure the response is behaving according to the requirements.
few example test cases are response status code, response time and schema test.

*Automation: I am using AWS lambda function and AWS cloud event bridge to automate and schedule the execution of this script on required time intervals.

*Incase of any exceptions, errors we can send alerts to slack channel or Microsoft teams


text:
Q: How to bind view model to a UserControl in MVVMCROSS? I am using the excellent Mvvmcross and Ninja Coder for Mvvmcross for building a cross platform app. For my windows store app I have created a view and a view model using Ninja coder. I have also created a UserControl which will be referenced in the view. Hence I need to bind the same viewmodel to the User control also. I have been trying to set the Data context of the user control to the singleton instance of viewmodel. I have set the data context of the user control like below.
public sealed partial class SearchResultsGridViewControl : UserControl
{
    private SearchresultsViewModel _viewModel;

    public SearchResultsGridViewControl()
    {
        this.InitializeComponent();

        _viewModel = Mvx.IocConstruct<SearchresultsViewModel>();

        this.DataContext = _viewModel;
    }
}

But when I refer this User Control in my main view, it throws an error in XAML saying "Object Reference not set to an instance of an object. Cannot create an instance of SearchResultsGridViewControl".
This is my viewmodel:
    public class SearchresultsViewModel : BaseViewModel
{
    private ISearchResultsService _searchResultsService;

    public SearchresultsViewModel(ISearchResultsService searchResultsService)
    {
        _searchResultsService = searchResultsService;
        var items = _searchResultsService.DisplaySearchResults();
        SchoolDetails = new ObservableCollection<School>(items);
    }

    private ObservableCollection<School> _schoolDetails;

    public ObservableCollection<School> SchoolDetails
    {
        get { return _schoolDetails; }
        set
        {
            _schoolDetails = value;
            RaisePropertyChanged(() => SchoolDetails);
        }
    }

    public ICommand RefineCommand
    {
        get
        {
            refineCommand = refineCommand ?? new MvxCommand(FilterSearchResultsBasedOnRefine);
            return refineCommand;
        }
    }

    public void FilterSearchResultsBasedOnRefine()
    {
        SchoolDetails = new ObservableCollection<School>(_searchResultsService.FilterSchoolsBasedOnRefine(MidDayMeals, PlayGround, DigitalClassroom, DayBoarding, TransportationFacility));
    }
}

The grid view in my usercontrol is getting populated when it loads for the first time. But when RefineCommand is called to update the collection from the main view, the grid view in usercontrol is not getting updated. And I am guessing its because of that error earlier in setting the data context of the user control to view model. Please let me know what could be going wrong. I have been banging my head about it for days.

A: I've been using MVVMCross with Windows Store fairly recently.  Without looking back at my code, I'm pretty sure that the Datacontext will inherit from it's parent unless overridden.
So as long as the MvxPage that you have presented has a viewmodel, any user control that you add to it, either in XAML or in code-behind, should share the same data context.  If you are looking at doing some MVVMCross data-binding from the User Control, you should probably make sure your User Control implements IMvxStoreView, and ensure that the ViewModel property is set to the value of DataContext.
Hope that help.
Cheers,
Tristan

A: I think your first problem "Object Reference not set to an instance of an object" is a design time only issue - because you are trying to set the viewmodel using Mvx. at design time. You can workaround this issue if you want to by using design time viewmodels and possibly also by using one of the design time helpers (see https://github.com/MvvmCross/MvvmCross/blob/v3.1/CrossCore/Cirrious.CrossCore.Wpf/Platform/MvxDesignTimeHelper.cs).

I've no idea what your second problem is "The grid view in my usercontrol is getting populated when it loads for the first time. But when RefineCommand is called to update the collection from the main view, the grid view in usercontrol is not getting updated" - this sounds like an issue either in your xaml or in the results returned from FilterSearchResultsBasedOnRefine. From the current level of detail, I can't see what it is. My "gut feeling" is that the problem won't be MvvmCross specific - it'll just be a general Mvvm/data-binding issue.