text:
Q: How to set decimal separator in MS Access using VBA? My software creates PAIN001.XML files directly from an Access financial database. The decimal separator must always be a dot. The numbers are formatted with:
MyText = Format(MyNumber, "#0.00")

However, the format string's dot is automatically replaced by the system decimal separator, which might be "," instead of "." !
In Excel there are easy solutions, for example:
Application.DecimalSeparator = "."
...

However, MS Access doesn't recognize this application property.
Is there a simple way to define a decimal separator within Access vba code ?
Of course, one can create a function which scans each MyText number for wrong decimal separators and replaces them with a dot, but this function would have to be called separately for each number, slowing down the code quite a lot…

A:
The decimal separator must always be a dot.

Then use Str:
MyText = Str(MyNumber)

To convert such a string to a number use Val:
MyNumber = Val(MyText)

A: I guess the problem is not solveable with the decimal separator Application.DecimalSeparator = ".", even if it was supported by the Access library. It is a rather complicated issue, for the non-US users, as we are used to have , as a decimal separator.
In general, VBA considers only . as a decimal separator. Without taking care of the application default separator, the location of the user and their settings. Thus, some interesting cases could happen:

Sub TestMe()
    Dim myText As String
    myText = "123,42"
    Debug.Print Replace(Format(myText, "#0.00"), ",", ".")
End Sub

A possible solution, that I have implemented some time ago was to use Replace() and to replace as in the gif above. It could be a bit slow indeed, but taking into account the usage of VBA and Access, extreme speed is not something the app could achieve anyway.


text:
Q: what exactly the .parentNode is? I write a simple html:
<!DOCTYPE html>

Hi

and this simple script on google chrome:
var div = document.querySelector('div');
console.log(div.parentNode.innerHTML);
console.log("%O",div);

then the console print out the innerHTML and the object.
expending the object then find out the value of parentNode is null.
I know the parentNode is one of the properties of node object, but what inside this variable?
it's a pointer? sub-object? function?
if it's a sub-object, would it be wasting memory to storage an object inside another object as the member variable?

A: JavaScript doesn't have "pointers", or "sub-objects".  Every "object" variable (or property) is invisibly treated as a reference to an object.
var a = 1;    // a contains the value "1"
var b = {};   // b contains a reference to the newly created empty object {}

In this case, the .parentNode property is merely a reference to the HTMLBodyElement object that contains the
.
More information:
These references are somewhat like C's pointers, but they are completely opaque - you cannot obtain any meaningful value of a reference.  You may however compare references using the === operator to see if two references actually refer to the same object.
Every object is reference counted - if there are no more references (i.e. there are no in-scope variables or properties pointing at it) then the object may be garbage collected.
When you pass an object to a function you are actually passing a copy of a reference.  This means that within the function you may access that object's properties, and modify that object, but you cannot modify the caller's reference to the object.

A: JavaScript has no concept of "a pointer" or "a sub-object".
The value of parentNode is the object representing the DOM node that is the parent of the object on which the property is set (if it has one, if it doesn't, then it becomes null instead).
Like all values which are objects in JS, this is handled as a reference.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rewrite urls not working with apache2 and laravel Today I started a new project on my server. In my point of view I guess I had configured everything correct. However my .htaccess seems not work correctly or it's ignored. I dont know why it's not working. The problem is that rewrite urls will show an 404.
The project based on Laravel 5.0 or more specified I will be try Larasocial. Larasocial is a social community based on Laravel 5.
I checked up my Vhosts and Htaccess file, but can't find the problem right know. Also try to restart the apache with service apache2 restart and look if rewrite module is enabled for my apache. I guess everything should be okay.
Thanks in advance for helping me!
Now this are my Vhosts and Htaccesss.
<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    ServerName integration.julian.droeger.rene-backhaus.de

    ServerAdmin contact@rene-backhaus.de
    DocumentRoot /var/www/html/robot/customers/julian.droeger/integration/public

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog /home/robot/logs/customers/error.log
    CustomLog /home/robot/logs/customers/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf

        # Das folgende erzwingt SSL
    #RewriteEngine On
    #RewriteCond %{HTTPS} off
    #RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
         <Directory /var/www/robot/customers/julian.droeger/integration/public>
          #Options Indexes FollowSymLinks
          AllowOverride All
      #Require all granted
        </Directory>
RewriteEngine on
RewriteCond %{SERVER_NAME} =rene-backhaus.de
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]
</VirtualHost>

SSL
<IfModule mod_ssl.c>
<VirtualHost *:443>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    ServerName integration.julian.droeger.rene-backhaus.de

    ServerAdmin contact@rene-backhaus.de
    DocumentRoot /var/www/html/robot/customers/julian.droeger/integration/public/

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog /home/robot/logs/customers/error.log
    CustomLog /home/robot/logs/customers/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf

        # Das folgende erzwingt SSL
    #RewriteEngine On
    #RewriteCond %{HTTPS} off
    #RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
         <Directory /var/www/robot/customers/julian.droeger/integrationi/public>
          #Options Indexes FollowSymLinks
           AllowOverride All
           #Require all granted
    </Directory>
RewriteEngine on
# Some rewrite rules in this file were disabled on your HTTPS site,
# because they have the potential to create redirection loops.
# RewriteCond %{SERVER_NAME} =rene-backhaus.de
# RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]
SSLCertificateFile /etc/letsencrypt/live/rene-backhaus.de/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/rene-backhaus.de/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>

Htaccess
</IfModule>
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

Edit
Apache error logs:
[Sun Sep 17 12:42:35.463054 2017] [core:notice] [pid 6843] AH00094: Command line: '/usr/sbin/apache2'
[Sun Sep 17 12:42:42.107113 2017] [mpm_prefork:notice] [pid 6843] AH00171: Graceful restart requested, doing restart
[Sun Sep 17 12:42:42.153704 2017] [mpm_prefork:notice] [pid 6843] AH00163: Apache/2.4.10 (Debian) OpenSSL/1.0.1t configured -- resuming normal operations
[Sun Sep 17 12:42:42.153724 2017] [core:notice] [pid 6843] AH00094: Command line: '/usr/sbin/apache2'
[Sun Sep 17 12:42:44.121750 2017] [mpm_prefork:notice] [pid 6843] AH00171: Graceful restart requested, doing restart
[Sun Sep 17 12:42:44.163280 2017] [mpm_prefork:notice] [pid 6843] AH00163: Apache/2.4.10 (Debian) OpenSSL/1.0.1t configured -- resuming normal operations
[Sun Sep 17 12:42:44.163295 2017] [core:notice] [pid 6843] AH00094: Command line: '/usr/sbin/apache2'
[Sun Sep 17 12:42:46.255223 2017] [mpm_prefork:notice] [pid 6843] AH00171: Graceful restart requested, doing restart
[Sun Sep 17 12:42:46.301081 2017] [mpm_prefork:notice] [pid 6843] AH00163: Apache/2.4.10 (Debian) OpenSSL/1.0.1t configured -- resuming normal operations
[Sun Sep 17 12:42:46.301109 2017] [core:notice] [pid 6843] AH00094: Command line: '/usr/sbin/apache2'

Vhost access logs:
79.214.162.134 - - [17/Sep/2017:12:44:02 +0200] "GET /fonts/glyphicons-halflings-regular.woff2 HTTP/1.1" 200 18377 "https://integration.thomas.walczak.rene-backhaus.de/css/libs.css" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"
79.214.162.134 - - [17/Sep/2017:12:44:18 +0200] "GET /feeds HTTP/1.1" 404 725 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"
79.214.162.134 - - [17/Sep/2017:12:44:18 +0200] "GET /favicon.ico HTTP/1.1" 404 593 "https://integration.thomas.walczak.rene-backhaus.de/feeds" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"
79.214.162.134 - - [17/Sep/2017:13:58:26 +0200] "GET / HTTP/1.1" 200 6771 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"
79.214.162.134 - - [17/Sep/2017:13:59:43 +0200] "GET / HTTP/1.1" 200 3664 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"
79.214.162.134 - - [17/Sep/2017:13:59:51 +0200] "GET /feeds HTTP/1.1" 404 725 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"
79.214.162.134 - - [17/Sep/2017:14:00:34 +0200] "GET /feeds HTTP/1.1" 404 725 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"
79.214.162.134 - - [17/Sep/2017:14:00:35 +0200] "GET /feeds HTTP/1.1" 404 587 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"
79.214.162.134 - - [17/Sep/2017:14:01:04 +0200] "GET /feeds HTTP/1.1" 404 725 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"
79.214.162.134 - - [17/Sep/2017:14:01:05 +0200] "GET /feeds HTTP/1.1" 404 587 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"

Vhost error log:
[Sat Sep 16 22:57:22.509547 2017] [:error] [pid 30198] [client 217.238.62.18:64841] script '/var/www/html/robot/customers/julian.droeger/integration/status.php' not found or unable to stat
[Sat Sep 16 22:57:23.156553 2017] [:error] [pid 30198] [client 217.238.62.18:64841] script '/var/www/html/robot/customers/julian.droeger/integration/remote.php' not found or unable to stat
[Sat Sep 16 22:57:54.927797 2017] [:error] [pid 30191] [client 217.238.62.18:64850] script '/var/www/html/robot/customers/julian.droeger/integration/status.php' not found or unable to stat
[Sat Sep 16 22:57:55.068064 2017] [:error] [pid 30191] [client 217.238.62.18:64850] script '/var/www/html/robot/customers/julian.droeger/integration/remote.php' not found or unable to stat
[Sat Sep 16 22:58:26.504328 2017] [:error] [pid 30190] [client 217.238.62.18:64852] script '/var/www/html/robot/customers/julian.droeger/integration/status.php' not found or unable to stat
[Sat Sep 16 22:58:26.614808 2017] [:error] [pid 30190] [client 217.238.62.18:64852] script '/var/www/html/robot/customers/julian.droeger/integration/remote.php' not found or unable to stat
[Sat Sep 16 22:58:58.510322 2017] [:error] [pid 30197] [client 217.238.62.18:64853] script '/var/www/html/robot/customers/julian.droeger/integration/status.php' not found or unable to stat
[Sat Sep 16 22:58:58.620842 2017] [:error] [pid 30197] [client 217.238.62.18:64853] script '/var/www/html/robot/customers/julian.droeger/integration/remote.php' not found or unable to stat
[Sat Sep 16 22:59:30.507615 2017] [:error] [pid 30191] [client 217.238.62.18:64863] script '/var/www/html/robot/customers/julian.droeger/integration/status.php' not found or unable to stat
[Sat Sep 16 22:59:30.639602 2017] [:error] [pid 30191] [client 217.238.62.18:64863] script '/var/www/html/robot/customers/julian.droeger/integration/remote.php' not found or unable to stat

A: Lesseon learned I guess ...
After this article reviewed my apache.conf. And what I see there?
Htaccess is not enabled for the /var/www direcotry! Now the solution was quite simple I had to change AllowOverride None to AllowOverride All.
It fix the problem!
But and the end I had already a question. Before this article I thourght that the Vhost configuration will be the important configuration. So that AllowOverride is on All in the Vhost file, apache will take this configuration. Why apache2 needs the AllowOverride All configuration globally? Can anyone explaine?


text:
Q: Восстановление m файла Нечаянно сохранила новый m- файл под тем же именем, что и старый. Есть ли возможность восстановить старый файл.

A: Теоретически есть возможность искать удалённые файлы на диске, но неизвестно, удаляется ли файл, или же просто открывается на запись и записывается поверх. Во втором случае ничего восстановить не удастся.
Если программа, в которой выполнялось редактирование, ещё открыта, можно попытаться нажимать в ней отмена до тех пор, пока не вернёшься к оригинальному состоянию файла. После этого сохранить файл и начать нажимать повторить, чтобы вернуться к актуальному состоянию. Ну и вместо второй части можно просто предварительно сделать копию текущего файла.
Думаю, матлаб достаточно адекватная программа, чтобы не ограничивать историю изменений и можно было откатиться к исходному файлу.


text:
Q: javascript to select dropdownlist automatically based on another dropdown I am having 2 dropdown lists on my page if i select an item the same selected item should be displayed in another drop down list. Can any one give me a javascript for this i need Javascript not Jquery

A: You can attach an onchange event on your dropdown.
Then whenever your selected Index changes, it will fire and call the supplied update method.
For example:
HTML
<asp:DropDownList id="FirstDropdown" onChange="javascript:update();" ...>

JavaScript
<script type="text/javascript">
function update ( ) {
   document.getElementById('<%= SecondDropdown.ClientID %>').value =
   document.getElementById('<%= FirstDropdown.ClientID %>' ).value;
}

A: here is a very simple implementation of what you are describing:
given the html:
<select id="select1">
  <option value="foo">foo</option>
  <option value="bar">bar</option>
</select>
<select id="select2">
  <option value="foo">foo</option>
  <option value="bar">bar</option>
</select>

and this javascript:
document.getElementById('select1').onchange = function(e) {
  var index = this.selectedIndex;
  document.getElementById('select2').options[index].selected = true;
}

you can achieve what you want.  note the indexes should be exactly the same in both select boxes (as in the options should be in the same order)

A: Try this
<asp:DropDownList ID="ddl1" runat="server">
            <asp:ListItem Value="1"></asp:ListItem>
            <asp:ListItem Value="2"></asp:ListItem>
            <asp:ListItem>3</asp:ListItem>
            <asp:ListItem Value="4"></asp:ListItem>
        </asp:DropDownList>
        <asp:DropDownList ID="DropDownList1" runat="server">
            <asp:ListItem>1</asp:ListItem>
            <asp:ListItem>2</asp:ListItem>
            <asp:ListItem>3</asp:ListItem>
            <asp:ListItem>4</asp:ListItem>
            <asp:ListItem></asp:ListItem>
        </asp:DropDownList>

  <script type="text/javascript">
function MyApp(sender){
    var lbMatch = false;
    var loDDL2 = document.getElementById('DropDownList1');
    for(var i=0; i< loDDL2.length-1; i++){
        lbMatch = sender.value==loDDL2.options[i].value;
        lsSelected = lbMatch ? "<=SELECTED" : "";
        if(lbMatch)
            loDDL2.selectedIndex = sender.selectedIndex;
    }
}
        </script>

In page load event add this
  ddl1.Attributes.Add("OnChange", "MyApp(this)");


text:
Q: How do gzip don't find two same part? I wrote such code
#include "zlib.h"
unsigned char dst[1<<26];
unsigned char src[1<<24];
int main() {
    unsigned long dstlen = 1<<26;
    srand (12345);
    for (int i=0; i<1<<23; i++) src[i] = src[i | 1<<23] = rand();
    compress(dst,&dstlen,src,1<<24);
    printf ("%d/%d = %f\n", dstlen, 1<<24, dstlen / double(1<<24));
}

which tries to compress two same 223 bytes part connected together. However, the result is
16782342/16777216 = 1.000306

How is data with such rule not compressed?

A: The maximum distance for matching strings in zlib is 32,768 bytes back.


text:
Q: Adding iframe (google map) to jquery with php This code works, but I want to work with PHP, so I can control in wordpress settings.
<script type="text/javascript">
        jQuery('document').ready(function(){
            setTimeout(function(){
                var meps = '<iframe style="border: 0;" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2209.031679248075!2d22.554804516065!3d56.381033750830454!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x46ef7f4796620a77%3A0xb28151d9fd19376d!2sDariaus%20ir%20Gir%C4%97no%20g.%2C%20Lai%C5%BEuva%2089475!5e0!3m2!1sen!2slt!4v1629095714907!5m2!1sen!2slt" width="600" height="450" allowfullscreen="allowfullscreen"></iframe>';
                jQuery("#mapas").append(meps);
            }, 8000);
        });
    </script>

And this code doesn't work, no clue what is the problem.
<?php $map = get_field('map','options') ?>
<script type="text/javascript">
    jQuery('document').ready(function(){
        setTimeout(function(){
            var meps = '<?php echo $map ?>';
            jQuery("#mapas").append(meps);
        }, 8000);
    });
</script>

The $map contains the iframe and prints out the map, but won't "stick" with jquery, why?

A: Try adding the same code in your active theme's footer.php file after the wp_footer() function.
If that works then that means jquery is not loaded when you are executing this code.


text:
Q: What is Not If and what does it have to do with strings I have been reading about how to figure out if a string is empty or has value within Python and discovered Not If i done some reading and found out that Not will return true if a condition does not equal what the programmer expects it to this is used in a if statement like this if not how does this work with strings?
#!/usr/bin/python
Data = ""
if not Data:
    print 'Hello'
else:
    print 'Goodbye'

I expect the output to be Hello and wish to know how this works

A: not object is essentially a shorthand for bool(object) == False. It's generally used to negate the truth value of object.
However, the truth value of object depends on object's type:

*

*If object is a boolean, then True evaluates to True and False evaluates to False.

*If object is an number (integer or floating-point), then 0 evaluates to False and any other value evaluates to True

*If object is a string, then the empty string "" evaluates to False and any other value evaluates to True (this is your case at the moment)

*If object is a collection (e.g. list or dict), then an empty collection ([] or {}) evaluates to False, and any other value evaluates to True.

*If object is None, it evaluates to False. Barring the above cases, if object is not None, it will usually evaluate to True.

These are generally grouped into two categories of truthy and falsey values - a truthy value is anything that evaluates to True, whereas a falsey value is anything that evaluates to False.
Python programmers use if not object: as a shorthand to cover multiple of these at once. In general, if you're not sure, you should check more specifically. In your case:
data = ""
if data == "":
    print("Hello")
else:
    print("Goodbye")

or if you wanted to make sure that, say, data didn't end with the character p, you could do this:
data = "orange"
if not data.endswith(p):
    print("data does not end with p")
else:
    print("data ends with p")


text:
Q: How to externally change a state variable belonging to a React Native default class so that it re-renders In my app, I have defined a default class A in module xyz.js that renders a page on my navigation stack. Depending on one of class A's state variables, the views that are rendered differ. For example, if the app is placed in an "edit mode", then an editing view is rendered in addition to the other standard views rendered when the app is not in the "edit mode". I can't figure out how to change that state variable and cause the instantiation of class A to re-render.
Here is what I have:
Module abc.js:
import XYZ from './xyz';
import {Edit} from './xyz';
import { pencilEditButton } from './Images';

const App = createStackNavigator(
{
    Home: {
        screen: My App,

        navigationOptions: ({ navigation }) => ({
            title: 'myApp',

            headerRight: (
            <View>
                <TouchableHighlight
                    onPress={() => EditMix()}
                    underlayColor="gray">
                    <View>
                        <Image source={pencilEditButton} style={styles.navigationButtonImage} />
                    </View>
                </TouchableHighlight>
            </View>
            ),
        }),
    },
}
);

export default createAppContainer(App);

Module xyz.js:
export default class XYZ extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        editMode: false,
    };
  };

render() {
  return (
        <View style={styles.container}>
           { this.state.editMode === true ?
             <TouchableHighlight
                    onPress={this._onXPressed}
                    underlayColor="white">
                <View style={[styles.flowRight, styles.controlButton]}>
                    <Text style={styles.buttonText}>{'Edit Mode'}</Text>
                </View>
            </TouchableHighlight>
             :

             <TouchableHighlight
                    onPress={this._onYPressed}
                    underlayColor="white">
                <View style={[styles.flowRight, styles.controlButton]}>
                    <Text style={styles.buttonText}>{'Non Edit Mode'}</Text>
                </View>
            </TouchableHighlight>
           }
        </View>
     );
   }
 }

export  function Edit() {
   editMode = true;
   alert('User wants to edit!');
}

So as you can see, there is a named function called "Edit()" at the bottom of module xyz.js. This function is called from module abc.js when the edit button is pressed. When the edit button is pressed, the alert view is displayed, but the XYZ function is not re-rendered. How do I correctly update the state variable "editMode" inside the instantiated XYZ class and how do I cause it to re-render?


text:
Q: How to use std::allocator_traits::construct to create struct object from function parameters? I have a struct defined as:
struct Foo
{
    double x;
    double y;
};

I have a function which takes this struct as a parameter:
void doSomethingWithFoo(Foo foo);

I'd also like to use this function by passing the struct members directly:
void doSomethingWithFoo(double x, double y);

Is there a way using std::allocator_traits::construct or any other way to be able to that without explicitly defining the second function?

A: You can just do this directly: doSomethingWithFoo({ 1, 2 });. The compiler knows that doSomethingWithFoo takes a Foo type, so it looks for a conversion from what you give it (int, int) to Foo. As a simple "plain old data" (POD) type, then the constructor from the initializer list is implicit, and it just works.
struct Foo
{
    double x;
    double y;
};

void doSomethingWithFoo(Foo foo)
{
    std::cout << foo.x << ", " << foo.y << std::endl;
}

int main()
{
    doSomethingWithFoo({ 1, 2 });

    return 0;
}

Prints:
1, 2

A: Considering that Foo is a simple POD-type, you can create an instance of it as Foo{x, y}.
Then you could just make an overload that calls the first version of the function:
inline void doSomethingWithFoo(double x, double y)
{
    doSomethingWithFoo(Foo{x, y});
}


text:
Q: My button-style doesn't show my background image on MouseOver I have create a style for a button like this
    <Style TargetType="{x:Type Button}" x:Key="BoutonRessources">
       <Setter Property="Width" Value="18" />
       <Setter Property="Margin" Value="-1,0,-2,0" />
       <Setter Property="ToolTip" Value="Clear" />
       <Setter Property="VerticalAlignment" Value="Center" />
       <Setter Property="BorderThickness" Value="0" />
       <Setter Property="HorizontalAlignment" Value="Center" />
       <Setter Property="Background" Value="Transparent" />
       <Setter Property="HorizontalContentAlignment" Value="Center" />
       <Style.Triggers>
           <Trigger Property="IsMouseOver" Value="True">
               <Setter Property="Background">
                   <Setter.Value>
                       <ImageBrush ImageSource="BoutonToolbarSelected.png"/>
                   </Setter.Value>
               </Setter>
               <Setter Property="Height"  Value="22"/>
               <Setter Property="Width"  Value="32"/>
           </Trigger>
       </Style.Triggers>
   </Style>

My button appear on my screen but when the mouse is over the button, it don't show my "BoutonToolbarSelected.png". Do you know why ?
Here is how i call my button :
<Button Style="{StaticResource BoutonRessources}" >
    <Image Source= "xRtDiva_XWPF_TBR_PREMIER.PNG_IMAGES.png" Height="18"/>
</Button>

Thanks a lot :)

A: Because you set <Image Source= "xRtDiva_XWPF_TBR_PREMIER.PNG_IMAGES.png" Height="18"/> as Content of your button, the background will hide behind it.
You could change your trigger to:
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background">
                                <Setter.Value>
                                    <ImageBrush ImageSource="BoutonToolbarSelected.png"/>
                                </Setter.Value>
                            </Setter>
                            <Setter Property="Height"  Value="22"/>
                            <Setter Property="Width"  Value="32"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="False">
                            <Setter Property="Background">
                                <Setter.Value>
                                    <ImageBrush ImageSource="xRtDiva_XWPF_TBR_PREMIER.PNG_IMAGES.png"/>
                                </Setter.Value>
                            </Setter>
                            <Setter Property="Height"  Value="18"/>
                        </Trigger>
                    </Style.Triggers>


text:
Q: mediant and weighted mean, fraction Suppose there are several fractions ${\dfrac{a_1}{b_1}}$,…,${\dfrac{a_n}{b_n}}$ and $a_i$ < $b_i$ for 1≤i≤n
all a > 0 and b>0
Mediant of the above fractions
M=(a1+...an)/(b1+⋯+bn)
and the weighted mean of the fractions wrt numerator value
A=${w{\scriptscriptstyle 1}\dfrac{a{\scriptscriptstyle 1}}{b{\scriptscriptstyle 1}}}$ + ${w{\scriptscriptstyle 2}\dfrac{a{\scriptscriptstyle 2}}{b{\scriptscriptstyle 2}}}$ + ... n times
$w_i$ = $\dfrac{a_i}{\sum_{i=1}^{n}a_{i}}$
Is it always true that A≥M?
Probably yes, whats the proof. please help

A: Suppose the inequality is true for $n$ fractions. Then we need to prove that
$$
\sum_1^{n+1}w_i\frac{a_i}{b_i}\ge\frac{\sum_1^{n+1}a_i}{\sum_1^{n+1}b_i}
$$
This is equivalent to
$$
(\sum_1^{n}w_j)\sum_1^{n}\frac{w_i}{\sum_1^{n}w_j}\frac{a_i}{b_i}+w_{n+1}\frac{a_{n+1}}{b_{n+1}}\ge\frac{\sum_1^{n}a_i+a_{n+1}}{\sum_1^{n}b_i+b_{n+1}}.
$$
Using the inductive hypothesis,
$$
(\sum_1^{n}w_j)\sum_1^{n}\frac{w_i}{\sum_1^{n}w_j}\frac{a_i}{b_i}+w_{n+1}\frac{a_{n+1}}{b_{n+1}}\ge (\sum_1^{n}w_j)\frac{\sum_1^n a_i}{\sum_1^n b_i}+w_{n+1}\frac{a_{n+1}}{b_{n+1}}
$$
(observe that the weights are the right ones, corresponding to the first $n$ fractions). Using the fact that we know the inequality is true for two fractions,
$$
(\sum_1^{n}w_j)\frac{\sum_1^n a_i}{\sum_1^n b_i}+w_{n+1}\frac{a_{n+1}}{b_{n+1}}\ge \frac{\sum_1^{n}a_i+a_{n+1}}{\sum_1^{n}b_i+b_{n+1}}=\frac{\sum_1^{n+1}a_i}{\sum_1^{n+1}b_i},
$$
as desired (in the last formula, the weights are again the right ones).


text:
Q: What is the efficient Json format to send table column update data I have to create a service that can create a json data to update changes to a table. The format I initially thought was:
"tables" : [{
    "tableName" : JSONString,
    "row" : [{
        "rowId" : JSONString,
        "columnItems" : [{
            "columnName"    : JSONString
            "columnValue"      : JSONString
        }]
    }]
}]

But there will be millions of rows so the json will be too big. So I have to make sure that I use this data efficiently.
So, I thought I can use a structure like this:
"tables" : [{
    "tableName" : JSONString,
    "row" : [{
        "rowId" : JSONString,
        "columnItems" : [{
            "columnValue"      : JSONString
        }]
    }]
}]

With above template I removed the columnName. but I can't use it as not all columns will be updated. I need to carry the columnName some how.
Wondering if there is a better template to convey this data.


text:
Q: What to use to upload different file formats(audio,video) in Rails application? Does carrier wave support file format like .doc ,.pdf and other paper file formats?If not what is out there to use?
what could i use to enable user to upload audio and video in ruby on rails application?
Thank you in advance

A: Yes, you can upload files of any kind using CarrierWave. For some formats it has built in features that let you post process the uploaded files, for some formats it doesn't. But you can use it with files of any kind. See here for more information.


text:
Q: Is there an easier way to do this problem without using so many if statements? and how? We were given a problem that asks to use the letters QDN(Quarter, Dime, Nickel) to create a finite state machine that only accepts if they add to 40 cents. I have the basics down for using an IF statement concept. I was wondering if there is an easier way to do this that takes less time?
I've tried making tons of if cases but there are a lot of steps to using that method.
public class FSA2_rpf4961 {

public static void main(String[] args) {
    //The program will read in a sequence of strings and test them against a
    //FSM. Your strings may not contain blank spaces
    System.out.println("Enter string to test or q to terminate");
    Scanner in = new Scanner (System.in);
    String testString = in.next();

    while (!testString.equals("q"))
    {
        String testOutput = applyFSA2(testString);
        System.out.println("For the test string "+testString+
                                ", the FSM output is "+testOutput);
        System.out.println("Enter next string to test or q to terminate:");
        testString = in.next();

    }
    in.close();

}
public static String applyFSA(String s) {
   String currentOut = "0";                // initial output in s0
   String currentState = "s0";             // initial state

   int i = 0;

   while (i<s.length())
   {
            //quarter first
           if (currentState.equals("s0") && s.charAt(i) == 'q')
           {
                    currentState = "s1";
                    currentOut += 25;  // collect output on move to s1
           }
           else if (currentState.equals("s1") && s.charAt(i)  == 'd') {
            currentState = "s2";
            currentOut += 10;
           }
           else if (currentState.equals("s2") && s.charAt(i)  == 'n') {
            currentState = "s3";
            currentOut += 5;
           }
           else if (currentState.equals("s1") && s.charAt(i)  == 'n') {
            currentState = "s4";
            currentOut += 5;
           }
           else if (currentState.equals("s4") && s.charAt(i)  == 'd') {
            currentState = "s3";
            currentOut += 10;
           }

           //dime first
           else if (currentState.equals("s0") && s.charAt(i) == 'd')
           {
                    currentState = "s5";
                    currentOut += 10;   // d
            }

We need it to only accept if it adds to 40 cents. This is very confusing for me to grasp.

A: I'm going to be talking generally here, because your current code is weird to the point of almost-certain brokenness. I don't quite get what your "output" is supposed to be.
A FSM is a definition of a set of states and how input causes state transitions. It looks like you started out roughly doing that, but currentOut is broken.
If your goal was to get a sum, you're defeating the entire point of the exercise. It doesn't matter what the sum is. What matters is what state you're in at the end -- particularly whether you're in an "accept" state, which in this case is the state where the string equates to exactly 40 cents.
As for how to implement a FSM without kajillions of ifs, you can often store states in an array, and have your state name be a state number instead. At that point, you can theoretically get rid of all your ifs. (In the real world, though, you'd probably still want one to ignore or reject chars other than (q|d|n).)
Consider something like this (pseudocode):
    // Each array in `graph` represents a state.
    // Each entry is the state number (ie: index into `graph`) to go to
    // when you're in that state and see the corresponding char.
    //
    // BTW, the state graph makes a lot more sense when you consider nickels first.
    // A nickel takes you to the "next" state, and dimes and quarters act like
    // 2 and 5 nickels, respectively. When you do that, a pattern shows up.
    graph = [
      //  n  d  q
      //-----------
        [ 1, 2, 5 ], // s0
        [ 2, 3, 6 ], // s1
        [ 3, 4, 7 ], // s2
        [ 4, 5, 8 ], // s3
        [ 5, 6, 9 ], // s4
        [ 6, 7, 9 ], // s5
        [ 7, 8, 9 ], // s6
        [ 8, 9, 9 ], // s7
        [ 9, 9, 9 ], // s8
        [ 9, 9, 9 ]  // s9 (fail state)
    ]
    start = 0
    accept = 8
    fail = 9

    // at this point, walking the graph is trivial.
    state = start
    for each char c in s:
        index = "ndq".indexOf(c) // n->0, d->1, q->2, others -> -1
        state = graph[state][index]

    // Once the loop's done:
    //   if state == accept, you have exactly 40c.
    //   if state == fail, you have >40c. A FSM won't tell you how much,
    //      because FSMs can't count.
    // any other state represents a known amount that's less than 40c.


text:
Q: How to link C++ source files with Code::Blocks I'm doing something wrong, I know. I can't quite figure out how to
link two .cpp files together through a header file. The calling
method can't see the other source.
I'm using Code::Blocks as an IDE with MinGW.
Any help would be greatly appreciated. It would be even more
appreciated if you could show the fixed source, link in the reply to a
pastebin page with it.
/***********************************main.cpp***********************************/
#include <iostream>

using namespace std;

#include "test.h"

int main()
{
    printTest();            //can't see printTest, defined in test.cpp
    return 0;
};

/***********************************test.h***********************************/
#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED

void printTest();

#endif // TEST_H_INCLUDED

/***********************************test.cpp***********************************/
#include "test.h"

void printTest()
{
    cout << "Hello world!" << endl;
};

A: You might find this code blocks wiki helpful. It looks like Code blocks uses a managed build system so if you add the file to the project properly then it should know to compile it and link in the object file that results.
And just to be more explicit about some other comments, when you use "using namespace std;" the namespace is only brought into scope for the file where the using statement is located. That is why others are telling you to explicitly specify the std:: namespace. You could also bring all of the std namespace into scope in the test.cpp file. Many people consider this a bad habit to get into. It's generally better to bring into scope just what you need via
using std::cout;
using std::endl;

Finally, remember that std::endl adds a new line AND flushes the buffer, it's not a good replacement for a new line character in all cases.

A: In test.cpp replace cout << "Hello world!" << endl;
 by std::cout << "Hello world!" << std::endl;

A: sanket answer's seems incomplete to me.
You need to add #include <iostream> in your test.cpp so that the compiler knows what "cout" is.
As sanket stated, you should use std::cout and std::endl in test.cpp.


text:
Q: Unable to create/write values to Registry subkey despite Admin privileges C# In my console application, I want to create a DWORD value and set it's value to 2 to my registry sub key in Local machine. Please note, I own Administrator privileges to my machine.
Here's my code below which is getting executed successfully but I am unable to see any value getting set in Registry.
            string keyPathI = @"SOFTWARE\Microsoft\Terminal Server Client";
            string keyPathII = @"SOFTWARE\WOW6432Node\Microsoft\Terminal Server Client";

            RegistryKey keyOne = Registry.LocalMachine.OpenSubKey(keyPathI, true);
            RegistryKey keyTwo = Registry.LocalMachine.OpenSubKey(keyPathII, true);

            if (keyOne != null)
            {
                keyOne.SetValue("RemoteDesktop_SuppressWhenMinimized", 2, RegistryValueKind.DWord);

                keyOne.Close();
            }

            if (keyTwo != null)
            {
                keyTwo.SetValue("RemoteDesktop_SuppressWhenMinimized", 2, RegistryValueKind.DWord);
                keyTwo.Close();
            }

Here's my app.manifest
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>

What else I should do to write the values to Registry subkey ?
P.S : Though there are many similar articles on web, I have referred all of them but none of them could help me out.

A: This works for me (VS 2015, 32-bit app on Windows 64) (test on 64-bit hive)=>
using (RegistryKey rkLocalMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
{
    using (RegistryKey rk = rkLocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Terminal Server Client", true))
    {
        rk.SetValue("RemoteDesktop_SuppressWhenMinimized", 2, RegistryValueKind.DWord);
    }
}


text:
Q: Google Wave CLI client and googlewave.com I'm trying to use the CLI client for Google Wave that Google have created with my @googlewave.com account.  I can't seem to get it to connect -- does anyone know if this is actually possible, or if it will only connect to locally hosted wave servers?

A: Have you configured the client with the included script?
...and are you aware the Google Wave has been decommissioned since August?


text:
Q: Update / Concatenation In SQL Management Studio I'm using SQL Management Studio and I've added a new column where I want to concatenate (numerical) values from three other columns into the new column. I used Alter to add the new column and was now trying to use Update Set to finish it, but I can't figure it out. I was also trying to use concatenate functions but it wasn't working and I wasn't sure if Management Studio has a concatenate function. Any suggestions?

A: This sounds like a casting issue.
UPDATE TABLE SET NewColumn = CAST(OLDCOLUMN1 AS Varchar) + CAST(OLDCOLUMN2 AS VARCHAR) + CAST(OLDCOLUMN3 AS VARCHAR)

Have you tried casting your values that you are concatinating?
If so, provide us with some code you have ;)


text:
Q: Why am I getting the "Conversion failed" error in SQL Server 2012 even though my parameter type is varchar? Pretty much all stated in the title. I have a stored procedure with some input parameters that I execute and save as an object. Here is the declaration of the input parameters:
@As_Document_NAME VARCHAR(50) = NULL,
@As_Company_NAME VARCHAR(50) = NULL,
@As_Category_NAME VARCHAR(50) = NULL,
@As_Project_NAME VARCHAR(30) = NULL,
@As_Employee_Last_NAME VARCHAR(30) = NULL,
@As_Employee_First_NAME VARCHAR(30) = NULL,
@Ai_Employee_Ssn_NUMB INT = 0,
@As_Tag_TEXT VARCHAR(2000) = NULL,
@Ad_Start_DATE DATE = NULL,
@Ad_End_DATE DATE = NULL

However, when I try to execute the stored procedure like this:
EXEC EDOC_RETRIEVE_S2 '','','','','','',0,'pls,I,cant','',''

I get the error

Conversion failed when converting the varchar value 'pls,I,cant' to data type int.

What can I do to fix this? I checked and my parameters in the execution statement and the parameter declaration are all in the exact same order.


text:
Q: Will IE9 support WebGL and/or WebSockets? Will IE9 support WebGL and/or WebSockets?

A: As of a few months ago, the IE9 team hadn't made a decision about supporting WebSockets, and they didn't seem to see the point to WebGL.

A: WebGL seems not to be include in IE's strategy because of DirectX.
Anyway google already worked on that with the ANGLE project.
http://code.google.com/p/angleproject/

A: The IE team added a WebSocket implementation at HTML5 Labs which is their testing ground for new implementations. Chances are high that WebSockets will make it in IE9

A: Most answers to the question "When will browser X support HTML5 feature Y?" are answered by When Can I Use. In addition to list past, current and future support each item also generally has links to relevant news.

*

*WebSockets

*WebGL
Update:
Microsoft has been actively participating in the IETF HyBi working group (WebSockets protocol) and also participating in W3C work on the WebSockets API. The IE 10 preview release has WebSocket support built-in so it looks very likely that we will soon see a official release version of IE with WebSockets.
WebGL in IE still looks pretty uncertain. Microsoft claims fundamental security issues with the design of WebGL, but I suspect it has more to do with the fact that Microsoft has a vested interest in promoting their own DirectX framework rather than OpenGL (which is what WebGL is based on).

A: You can look at the current release notes for the platform demo - there is no mention of either WebSockets or WebGL.

A: There are many discussions of the security issues of WebGL. I first heard of it on one of Steve Gibson's podcasts. Since it gives much lower level access to both the operating system and the hardware any flaw can be exploited much more severely. A quick Google search found this article with descriptions and video of some of the flaws: http://www.contextis.com/research/blog/webgl2/

A: Microsoft seems quite reluctant to implement WebGL in IE, since OpenGL is a competitor to DirectX. So I think it's unlikely we'll see WebGL in IE in the near future.
I've started an Open Source project called JebGL that can serve as a fallback for IE users. It's a Java applet that when finished will serve as a plugin replacement for a WebGL canvas. It's still in the early stages of development, but you can check out the demos at http://jebgl.googlecode.com

A: Right now, the Microsoft IE team is struggling to get HTML 5 and SVG (2D graphics) into Internet Explorer 9.  Other web browser makers have been shipping with those standards built in for years.
Apple Safari, Google Chrome, and Mozilla Firefox all run fine on Windows.  Takes one mouse click to launch a different browser.  Takes a year or two to see what Microsoft might do.
IE progress has consistently been glacially slow this whole decade.
No, IE does not have WebGL support now and betas from other browser makers already run it.  IE9 will not catch up with contemporary web standards like WebGL, just ones that have been out for several years or more.
IE9 is not a cross platform web browser either.  It will only run on certain specific versions of Microsoft Windows.  Just run one of the standard web browsers and you can see what WebGL can do.  Their current betas are running some impressive WebGL demos now.

A: As a fallback until Microsoft adds WebGL support, the Google Chrome Frame beta currently supports WebGL.

A: RE: WebSockets: No. The target was websocket support in IE10. Tests show that it only has partial support.


text:
Q: How to get a list of all refs a git push would push? We're trying to implement a git workflow where there exists a pre-receive hook on the remote repo to validate that all pushed refs have commit messages that contain certain required information. In order to provide some convenience to developers, we'd also like a local git command developers can run to see what all refs would be pushed by a push command so they can verify before pushing whether or not their push would pass the hook, and also create a new git command that calls filter-branch or something else to rewrite all the commit messages to fill in any missing information.
So, is it possible to get a list of everything that would be pushed by a push command? git push --dry-run --verbose only gives a very cursory summary:
For example,
> git push --dry-run --verbose origin head:test/me

Pushing to git@git.mycompany.com:myproject.git
To git@git.mycompany.com:myproject.git
 * [new branch]      head -> test/me

A: git log @{u}..

This will list all the commits that are not yet pushed to the remote. If you want the diff of each commit then add a -p after log
git log -p @{u}..

Yes, the two dots at the end are necessary. :)

A: You can use git push --porcelain.


text:
Q: Design considerations for OAuth2 secured APIs I'll give a scenario as a premise for my question:

*

*CRM client app

*Customers API

*IDP protecting the API

*Customers api required scope : "customers"

*CRM client app OAuth2 client has "customers" scope access granted

*CRM client app requests tokens with scope "customers" and uses the API with the tokens

At some point, developers decide it is time to refactor invoicing out of customers API into a new Invoices API which now requires the scope "invoices". For the Customers API to return expected results to the CRM client app, it will now have to call on Invoices API and get that part of information out to the calling app. So passing on the token won't work because of the new scope requirement.
What is the best approach for the Customers API to keep returning the expected results to the CRM app without breaking change of requiring the CRM client app to add new scopes?
One approach would be for Customers API to authenticate as client credentials trusted subsystem but how will then Invoices API know about the initiating user? The idea here is to separate the functionality without breaking it for existing client applications.

A: Using a multi-hop or act-as granting system could help you. If I understood correctly your scenario is: Client -> API1 -> API2
If you  want each layer to have his own scope (you do according to your description) then act-as tokens will help you.
A very good summary of this is available in IdentityServer samples issue #182. You'll find an example of that scenario in their Git repository.


text:
Q: How many unordered partitions of $[n]$ are there, and how to enumerate? In this context, a partition of $[n]$ is an assignment of each $1\le i\le n$ to a class, but in which the class names don't matter (can be given in any order). For example:

*

*$[1]$ has one partition, $\{\{1\}\}$.

*$[2]$ has two partitions: $\{\{1,2\}\}, \{\{1\},\{2\}\}$.

*$[3]$ has five partitions: $$\{\{1,2,3\}\}, \{\{1\},\{2,3\}\}, \{\{2\},\{1,3\}\}, \{\{3\},\{1,2\}\}, \{\{1\},\{2\},\{3\}\}.$$

*$[4]$ has 15 partitions: $$\{\{1,2,3,4\}\},$$
$$\{\{1\},\{2,3,4\}\}, \{\{2\},\{1,3,4\}\}, \{\{3\},\{1,2,4\}\}, \{\{4\},\{2,3,4\}\},\\
\{\{1,2\},\{3,4\}\},\{\{1,3\},\{2,4\}\},\{\{1,4\},\{2,3\}\},$$
$$\{\{1\},\{2\},\{3,4\}\},\{\{1\},\{3\},\{2,4\}\},\{\{1\},\{4\},\{2,3\}\},\\
\{\{2\},\{3\},\{1,4\}\},\{\{2\},\{4\},\{1,3\}\},\{\{3\},\{4\},\{1,2\}\},$$
$$\{\{1\},\{2\},\{3\},\{4\}\}.$$

What is an efficient way to enumerate these partitions, and how many are there for general $n$? (I searched OEIS but the four terms here is not enough and I don't have a good algorithm to calculate more terms.)
Edit: To make this question not entirely trivial, is there a way to generate the $k$-th partition of $n$ using the recurrence relation for Bell numbers?

A: These are the Bell numbers, OEIS A000110. The Bell triangle is a fairly efficient way to generate them, and there's a great deal more information at the Wikipedia and OEIS links. I've not really thought about efficient schemes for enumerating the partitions.

A: This is an attempt at translating the Bell triangle method for computing Bell numbers into an enumeration of the set partitions.
The Bell triangle looks like this:
\begin{matrix}1&&&&\\
1&2&&&\\
2&3&5&&\\
5&7&10&15&\\
15&20&27&37&52\\
\end{matrix}
If $A_{n,k}$ for $1\le k\le n$ denotes the element of the triangle, then these satisfy the recurrence $A_{n,k}=A_{n,k-1}+A_{n-1,k-1}$ and $A_{n,1}=A_{n-1,n-1}$, and the Bell numbers can be read off the diagonal as $B_n=A_{n,n}$.
The combinatorial interpretation of the off-diagonal elements of the table are that $A_{n-1,k-1}$ counts the number of partitions of $[n]$ such that $\{k\}$ is the largest singleton in the partition.
To tie this in with the Bell numbers, if we take $B_n=A_{n,n}=A_{n+1,1}$ then we have three combinatorial interpretations:

*

*$B_n$ is the partitions of $[n]$

*$A_{n,n}$ is the partitions of $[n+1]$ containing $\{n+1\}$ as a partition element

*$A_{n+1,1}$ is the partitions of $[n+2]$ containing $\{2\}$ as a partition element, and with no other singletons except possibly $\{1\}$

For the first two, there is the obvious map from a partition $P$ of $[n]$ to $P\cup\{\{n+1\}\}$, which is a partition of $[n+1]$ containing $\{n+1\}$; conversely we can remove $\{n+1\}$ from any partition of $[n+1]$ containing $\{n+1\}$ to get a partition of $[n]$.
For the third property, first remove $\{2\}$ from the partition and move $1$ to the end to get a partition of $[n+1]$ with no singletons except possibly $\{n+1\}$. To get a partition of $[n]$ from this, with any arrangement of singletons, we use all of the sets except the one containing $n+1$ as-is, and add singletons for all the elements of $[n]$ in the same group as $n+1$.
The reverse map takes merges all the singletons and $n+1$ to a single set, and keeps the rest as is. This ensures that no element of $[n]$ is in a singleton in the result. Thus this describes a bijection.
Now, we need a conbinatorial interpretation of the equation $A_{n,k}=A_{n,k-1}+A_{n-1,k-1}$. This involves a bijection of two collections:

*

*The partitions of $[n+1]$ such that $\{k+1\}$ is the largest singleton

*The disjoint union of:

*

*The partitions of $[n+1]$ such that $\{k\}$ is the largest singleton

*The partitions of $[n]$ such that $\{k\}$ is the largest singleton

Given a partition of $[n+1]$ with $\{k+1\}$ as the largest singleton, we split this into two pieces according to whether $\{1\}$ is a singleton or not. If it is a singleton, then by removing $1$ and decreasing all the other numbers by one, we get a partition of $[n]$ with $\{k\}$ as the largest singleton. Otherwise, only $2\dots k+1$ can be singletons, so we can map $1\mapsto k+1$, and $i+1\mapsto i$ for each $1\le i\le k$, and the result is a partition of $[n+1]$ such that all the singletons are in $1\dots k$.
These bijections directly map to a method for efficiently calculating the $i$-th partition of $[n]$, by applying the bijections recursively in parallel with the Bell triangle method.

An alternative formula with a natural combinatorial description is the formula $$B_{n+1}=\sum_{k=0}^n{n\choose k}B_k.$$ Any partition of $[n+1]$ has a unique set containing $n+1$, which can be written in the form $[n+1]\setminus S$ for some $S\subseteq [n]$. We can first choose $|S|=k$, and there are ${n\choose k}$ possibilities for $S$ of this size; then we choose recursively one of the $B_k$ partitions of $S$, and append $[n+1]\setminus S$ to each partition.
Turning this into an efficient mechanism for finding the $i$-th partition of $[n]$ then relies on a method for getting the $i$-th subset of $[n]$ of size $k$; this problem is most commonly dealt with using a combinatorial number system.

A: The  following algorithm  is not  an optimal  contender as  this  is a
difficult problem. We use backtracking to examine potential admissible
assignments  from  among  all   permutations  in  alignment  with  the
partitions.  No details right now  due to time constraints. Written in
Perl to  be self-contained with  a free interpreter. The  algorithm is
practical to about $n=11$ (tested up to $n=12$ on a fast machine).

Remark,   somewhat   later.   The   algorithm  here   is   perfectly
straightforward  and works  by expressing  the  problem as  a kind  of
constraint satisfaction task. We  define a canonical representation of
the  set partitions  in question  by  ordering the  sets according  to
increasing size, same for their elements and sets of the same size are
ordered   according   to   their   first   element,   which   is   the
smallest. Writing this as a  table clearly yields a permutation of the
$n$ elements. The algorithm places  elements in the permutation one by
one, starting with the first element on the left. An element is placed
at a position only if it  does not violate the ordering constraints on
sets of the same size (elements in increasing order, first elements in
increasing  order). This is  backtracking. We  have found  a partition
when all  $n$ elements have been  placed. As for  the asymptotics, the
values  from the generating  function $\exp(\exp(z)-1)$  indicate that
the      value      for       $n=16$      is      a      $34$      bit
number. Wikipedia
has more on the growth rate of these numbers.

#! /usr/bin/perl -w
#

my %pcache = ();

sub part {
    my ($n, $k) = @_;
    my $key = "$n-$k";

    return $pcache{$key}
    if exists $pcache{$key};

    if($k == 1){
        $pcache{$key} = [[$n]];
        return $pcache{$key};
    }

    my @res = ();

    if($n > 1 and $k > 1){
        foreach $term (@{ part($n-1, $k-1) }){
            my @contrib = (1);
            push @contrib, @$term;

            push @res, \@contrib;
        }
    }

    if($n - $k >= $k){
        foreach $term (@{ part($n-$k, $k) }){
            my @contrib =
                map {$_ + 1} @$term;

            push @res, \@contrib;
        }
    }

    $pcache{$key} = \@res;
    return \@res;
}

sub allparts {
    my ($n) = @_;

    my @res;

    for(my $k=$n; $k>0; $k--){
        push @res, @{ part($n, $k) };
    }

    return \@res;
}

sub recurse {
    my ($n, $sofar, $src, $part, $tref, $cref) = @_;
    my $done = scalar(@$sofar);

    if($done == $n){
        my @sets;
        my @sol = @$sofar[0 .. ($n-1)];

        for(my $pos=0; $pos < scalar(@$part); $pos++){
            my @data = splice @sol, 0, $part->[$pos];

            push @sets, '{' . join(', ', @data) . '}';
        }

        print '{', join(', ', @sets), '}';
        print "\n\n";

        $$tref++;
        return;
    }

    for(my $nxt = 0; $nxt < scalar(@$src); $nxt++){
        my $elem = splice @$src, $nxt, 1;
        my $admit = 1;

        push @$sofar, $elem;

        foreach my $condx (@$cref){
            if($condx->[0] <= $done && $condx->[1] <= $done){
                if($sofar->[$condx->[0]] >=
                   $sofar->[$condx->[1]]){
                    $admit = 0;
                    last;
                }
            }
        }

        recurse($n, $sofar, $src, $part, $tref, $cref)
            if $admit;

        pop @$sofar;
        splice @$src, $nxt, 0, $elem;
    }

    1;
}

 MAIN: {
     my $n = int(shift || 5);

     my $total = 0;

     foreach my $part (@{ allparts($n) }){
         my @groups = ([$part->[0]]);

         for(my $pos = 1; $pos < scalar(@$part); $pos++){
             if($part->[$pos] == $groups[-1]->[0]){
                 push @{ $groups[-1] }, $part->[$pos];
             }
             else{
                 push @groups, [$part->[$pos]];
             };
         };

         my ($baseidx, @conds) = (0);

         foreach my $group (@groups){
             my $grplen = scalar(@$group);
             my $grptype = $group->[0];
             my $grptotal = $grplen * $grptype;

             for(my $pos = 0; $pos < $grptotal;
                 $pos += $grptype){
                 for($inpos = 1; $inpos < $grptype;
                     $inpos++){
                     push @conds,
                     [$baseidx+$pos+$inpos-1,
                      $baseidx+$pos+$inpos];
                 }
             }

             for(my $pos = $grptype; $pos < $grptotal;
                 $pos += $grptype){
                 push @conds,
                 [$baseidx+$pos-$grptype,
                  $baseidx+$pos];
             }

             $baseidx += $grptotal;
         };

         my @source = (1 .. $n);
         recurse($n, [], \@source, $part, \$total, \@conds);
     }

     print STDERR "$total\n";

     1;
}

The output from this script looks like this.

{{1}, {2}, {3}, {4}}

{{1}, {2}, {3, 4}}

{{1}, {3}, {2, 4}}

{{1}, {4}, {2, 3}}

{{2}, {3}, {1, 4}}

{{2}, {4}, {1, 3}}

{{3}, {4}, {1, 2}}

{{1}, {2, 3, 4}}

{{2}, {1, 3, 4}}

{{3}, {1, 2, 4}}

{{4}, {1, 2, 3}}

{{1, 2}, {3, 4}}

{{1, 3}, {2, 4}}

{{1, 4}, {2, 3}}

{{1, 2, 3, 4}}

15

Addendum, Aug  22 2016.  A tremendous improvement  by a  factor of
almost ten  can be obtained  by ensuring during backtracking  that the
remaining  values that  have not  been  placed in  the permutation  do
indeed contain an increasing subsequence of length at least the number
of  values required  to complete  the particular  set  currently being
assembled.  This  makes it  possible  to  process  all $27644437$  set
partitions  of $n=13$  elements in  fifteen minutes  on the  machine I
used.  Of  course these  data may  be archived in  a file  for instant
re-use later. This is the Perl code.

#! /usr/bin/perl -w
#

my %pcache = ();

sub part {
    my ($n, $k) = @_;
    my $key = "$n-$k";

    return $pcache{$key}
    if exists $pcache{$key};

    if($k == 1){
        $pcache{$key} = [[$n]];
        return $pcache{$key};
    }

    my @res = ();

    if($n > 1 and $k > 1){
        foreach $term (@{ part($n-1, $k-1) }){
            my @contrib = (1);
            push @contrib, @$term;

            push @res, \@contrib;
        }
    }

    if($n-$k >= $k){
        foreach $term (@{ part($n-$k, $k) }){
            my @contrib =
                map {$_ + 1} @$term;

            push @res, \@contrib;
        }
    }

    $pcache{$key} = \@res;
    return \@res;
}

sub allparts {
    my ($n) = @_;

    my @res;

    for(my $k=$n; $k>0; $k--){
        push @res, @{ part($n, $k) };
    }

    return \@res;
}

sub recurse {
    my ($n, $sofar, $src, $part, $tref,
        $cref, $rlref) = @_;
    my $done = scalar(@$sofar);

    if($done == $n){
        my @sets;
        my @sol = @$sofar[0 .. ($n-1)];

        for(my $pos=0; $pos < scalar(@$part); $pos++){
            my @data = splice @sol, 0, $part->[$pos];

            push @sets, '{' . join(', ', @data) . '}';
        }

        print '{', join(', ', @sets), '}';
        print "\n\n";

        $$tref++;
        return;
    }

    for(my $nxt = 0;
        $nxt <= scalar(@$src) - $rlref->[$done];
        $nxt++){
        my $elem = splice @$src, $nxt, 1;
        my $admit = 1;

        push @$sofar, $elem;

        foreach my $condx (@{ $cref->[$done] }){
            if($sofar->[$condx] >= $elem){
                $admit = 0;
                last;
            }
        }

        recurse($n, $sofar, $src, $part, $tref,
                $cref, $rlref)
            if $admit;

        pop @$sofar;
        splice @$src, $nxt, 0, $elem;
    }

    1;
}

 MAIN: {
     my $n = int(shift || 5);

     my $total = 0;

     foreach my $part (@{ allparts($n) }){
         my @groups = ([$part->[0]]);

         for(my $pos = 1; $pos < scalar(@$part); $pos++){
             if($part->[$pos] == $groups[-1]->[0]){
                 push @{ $groups[-1] }, $part->[$pos];
             }
             else{
                 push @groups, [$part->[$pos]];
             };
         };

         my ($baseidx, @conds) = (0);
         @conds = map { [] } (1..$n);

         foreach my $group (@groups){
             my $grplen = scalar(@$group);
             my $grptype = $group->[0];
             my $grptotal = $grplen * $grptype;

             for(my $pos = 0; $pos < $grptotal;
                 $pos += $grptype){
                 for($inpos = 1; $inpos < $grptype;
                     $inpos++){
                     push @{ $conds[$baseidx+$pos+$inpos] },
                     $baseidx+$pos+$inpos-1;
                 }
             }

             for(my $pos = $grptype; $pos < $grptotal;
                 $pos += $grptype){
                 push @{ $conds[$baseidx+$pos] },
                 $baseidx+$pos-$grptype;
             }

             $baseidx += $grptotal;
         };

         my @runlens;

         foreach my $comp (@$part){
             for(my $pos = 0; $pos < $comp; $pos++){
                 push @runlens, $comp-$pos;
             }
         }

         my @source = (1 .. $n);
         recurse($n, [], \@source, $part, \$total,
                 \@conds, \@runlens);
     }

     print STDERR "$total\n";

     1;
}

Addendum  II, Aug  22  2016. Actually  there  is no  need for  the
complicated  machinery from  above.   The enumeration  problem can  be
solved easily using  a basic recursion. We build  the set partiton one
element at a time, adding the new element to each set in the partition
that  has  been formed  already  or making  it  into  a new  singleton
set.  (This leaves  the  indexing problem  open  -- map  index to  set
partition). The new code makes it possible to go up to $n=14$ in  half
an hour.

#! /usr/bin/perl -w
#

sub found {
    my ($n, $sofar, $mx, $tref) = @_;

    if($n == $mx){
        my (@sets, @sorted);

        @sorted =
            sort {scalar(@$a) <=> scalar(@$b)}
            @$sofar;

        foreach my $part (@sorted){
            push @sets, '{' . join(', ', @$part) . '}';
        }

        print '{', join(', ', @sets), '}';
        print "\n\n";

        $$tref++;
        return;
    }

    for(my $pos = 0; $pos < scalar(@$sofar); $pos++){
        push @{ $sofar->[$pos] }, $n + 1;
        found($n+1, $sofar, $mx, $tref);
        pop @{ $sofar->[$pos] };
    }

    push @$sofar, [$n + 1];
    found($n+1, $sofar, $mx, $tref);
    pop @$sofar;

    1;
}

MAIN : {
    my $n = int(shift || 5);

    my $total = 0;
    found(1, [[1]], $n, \$total);

    print STDERR "$total\n\n";
}

A: To generate the partitions recursively, suppose you have all partitions of $[n-1]$. Given such a partition, you can add $n $ either as a singleton or to any part of the partition.
Note every partition of $[n] $, when removing $n $, gives a partition of $[n-1] $.  This means that every partition of $[n] $ is generated exactly once, so it is efficient in that sense.
I don't know if there is a good encoding that will let you produce the $k$th partition of $[n] $ directly.


text:
Q: What workarounds exist for the `complete` property in FireFox? I am attempting to use jQuery to determine if an image has properly loaded.
The following works just fine (and returns true or false as of the state of the image) but only seems to work in IE, in FireFox, it seems to always return true - even if the state is actually incomplete:
    var image = $("img#myImage");
    alert(image[0].complete);

What is the Firefox equivalent for image.complete in JavaScript or jQuery?

A: You could also try checking one of the dimensions of the img element in addition to complete:
function isImageLoaded() {
    var theImage = $('#myImage');

    if (!theImage.get(0).complete) {
        return false;
    }
    else if (theImage.height() === 0) {
        return false;
    }

    return true;
}

An unloaded img or an img with an invalid src attribute should have .height() and .width() equal to 0 in Firefox.  In Chrome and Opera neither method appears to work properly.  In those browsers theImage.height() always returned a positive value in my testing.

A: Jquery makes it really simple.
You can just use the .load() function to bind an event for the time when image is completely loaded.
    $("img").load(function() {
        // Yeay, it was loaded, and works in all browsers!
    });

A: You can use load() but beware of Internet Explorer: It won't fire the event, if the image is cached
if($img[0].readyState === 4){ // image is cached in IE
    alert("Image loaded!");
}else{
    $img.load(function(){ // for other browsers and IE, if not cached
        alert("Image loaded!");
    });
}

A: Yes, I was just working on an AJAX page that dynamically loaded images.  I also wanted to detect if images were loaded so I could transition them in with a jQuery effect.
img = $('myImageID')
img[0].src = 'http://new.url.for.image/';
alert(img[0].complete);                    // seems to always return true
                                           // in Firefox, perhaps because
                                           // the original src had been loaded

So instead I had to do this...
img = $('myImageID')
newImg = $('<img>')                // create a completely new IMG element
          .attr('src', 'http://new.url.for.image/')
          .attr('id', img[0].id);
img.replaceWith(newImg);
img = newImg;
alert(img[0].complete);

(Note: I haven't tested this exact code, it's a simplified version of what I was trying to do, but hopefully communicates the idea.)
Simon.

A: myimage=new Image();
myimage.src="whatever";
if(myimage.height>0 && myimage.complete){alert("my image has loaded");}

// might be overly simple but works for me in all browsers i think.

A: I dont know if firefox has another prop, method that does it but, you can use this workaround:
$(document).ready(function(){
$("img").each(
//for each image declared in html
function(index)
{
    document.images[index].complete= false;
    document.images[index].onload = function(){ this.complete= true};
});

});

A: In my case, I use the method
document.images['XXX'].addEventListener('load', dealJob(), false);

and in function dealJob, I use document.images['XXX'].complete to check the image, but it always returns true.
When I change to use the method
document.images['XXX'].onload = function() {dealJob();}

and in function dealJob, the result of document.images['XXX'].complete is correct.
Maybe it can help you.


text:
Q: Storing https data in angularJS I'm making a web app and learning AngularJS at the same time but am having trouble storing data that will be needed throughout the entire app. In one of my controllers, I have a POST call that returns a JSON object containing data that I need in separate parts of my app and I don't know how to store the entire JSON object so that I can access it later on. How can I store the JSON object so that I can access it later in a different controller? Should I even bother doing this or should I just make another POST request later on to get the data I need at that time (is it expensive to make POST/GET requests)?

A: You certainly don't want to keep making POST request for the same data (assuming it hasn't changed).
You could store it on $rootScope, pass the $rootScope to whatever controller needs access to the data and access via:
 var whatever = $rootScope.yourObject;

Example:
  //Assuming a controller makes the POSt request (not in app.run etc)
 function yourController($rootScope, $http) {

       $http.post("desired/url", { params: "foo-bar"}).then(function(response){
            //Check for errorz etc.
            $rootScope.yourObject = response.data; //Assign to rootscope
       });

 }

 function someOtherController($rootScope){
      //Fetch the item from $rootScope, assuming the POST request was
      // already made.
      var valueFromPreviousRequest = $rootScope.yourObject;
 }

A: The optimal approach would be to use custom service layer for data fetching and avoid $http in controller. In this case it's very easy to add caching mechanism.
For example, simple service:
app.factory('stats', function($q, $http) {

    // Hold cache in local variable
    var cache = null;

    return {
        load: function() {
            return cache ? $q.when(cache) : $http.get(statsUrl).then(function(response) {
                cache = response.data;
                return data;
            });
        }
    };
});

Then you could use this service like this in controller:
app.controller('someController', function(stats) {
    stats.load().then(function(data) {
        console.log(data);
    });
});

Note, how service load method returns promise object in both cases: when cache is already available and when no data has been loaded yet (first call).


text:
Q: Run a Virtual Machine inside a Rackspace Cloud Server? Is it possible to run some semblance of a Virtual Machine (perhaps not something as comprehensive as VMWare / VirtualBox, but something like User-Space Linux) inside of a Rackspace Cloud Virtual Server?
I have a bunch of Rackspace Cloud Servers created to experiment with various things and I'm just wondering if I can save some money by consolidating them all into a single bigger virtual server.

A: To be honest, I cannot see why this would not work, even with VMWare and the like. Just because it is in the cloud, it is still a real server, and people here have asked about running VM's within VM's with positive answers.
The only thing I would say is make sure you have enough RAM for each simultaneous VM you plan to run, and you will probably have to use NAT'ed network cards unless you are able to buy multiple IP addresses.
Can you run a machine emulator (Bochs) inside a virtual machine?

A: As long as your linux kernel supports it, you could run OpenVZ containers.  They are lightweight OS virtualized containers.  You can give them their own IP addresses and limit their memory and cpu.


text:
Q: Dropdown jquery method post form not working I have a problem, I added a dropdown ddslick on a page only that the post method does not work.
This is a test page: see you.
<?php
$values=$_POST['list'];
if($_SERVER['REQUEST_METHOD']=='POST')
{
   if(isset($_POST['submit']))
   {
       $i="";$s="";
       echo $i;
       echo $options[$value];
       echo $values;
       echo $s;
   }
}
?>

This is a page to test the drop down

<form method='post'>
<select id="demo-htmlselect-basic"name="list">
  <option value="0">Select</option>
  <option value="1">Part 1</option>
  <option value="2">Part 2</option>
  <option value="3">Part 3</option>
</select>

<input type="submit"name="submit"id="submit"value="Submit"/>
</form>

Waiting for your help.
Thanks.

A: You missed write the ";" at the last of one echo.

echo $s;

if(isset($_POST['submit']))
{
   $i="";$s="";
   echo $i;
   echo $options[$value];
   echo $values;
   echo $s;
}

A: You are missing name="list" in your jquery.ddslicksd.min.js file, Please modify your code
http://healtend.it/uploads/jquery.ddslicksd.min.js
add
name="list" to <input class="dd-selected-value" type="hidden" /> line.
And for php + HTML code like below:
PHP:
if(isset($_POST['submit'])){
        $values = $_POST['list'];
        $i="";
        $s="";
        echo $i;
        echo $values;
        echo $s;

    }

HTML:

This is a page to test the drop down

            <form method='POST' action="" id="dropdown">
                <select id="demo-htmlselect-basic" name="list">
                    <option value="0">Select</option>
                    <option value="1">Part 1</option>
                    <option value="2">Part 2</option>
                    <option value="3">Part 3</option>
                </select>

                <input type="submit"name="submit" id="submit"value="Submit"/>
            </form>


text:
Q: Permission issue of generated folders in magento2 Whenever we are doing the static content deploy in magento2 instance in ubuntu environment.the generated folders create with following permission
0770 and so that when we are browsing via URL the page is not loading, I have tried in many ways of work for it , what magento2 freak guys doing for this kind of scenario rather giving the manual permission to the folder when it is created, the Following class is responsible for the creating the folders with permission.
This is default driver interface class
Magento\Framework\Filesystem\DriverInterface

 const WRITEABLE_DIRECTORY_MODE = 0770;

This below class is used for the file generator
Magento\Framework\Code\Generator\Io

This function is used for creating the directory
private function _makeDirectory($directory)

If you have any suggestions or idea post it now.

A: We changed the way Magento sets file system permissions in 2.0.6. What version are you using?
We now do not set permissions on static files or anything else. For more information, see this.


text:
Q: How to mock AWS Amplify library in Angular? I am getting an error that seems to come from AWS Amplify when I run the suite of tests with Karma.
AuthEffects
    login
      √ should not dispatch any action
      √ should call setItem on LocalStorageService
Chrome 78.0.3904 (Windows 10.0.0) ERROR
  An error was thrown in afterAll
  Uncaught TypeError: Cannot read property 'clientMetadata' of undefined thrown

From that I suppose that this error is thrown from the last test that was launched: AuthEffects
In my AuthEffects, I had to do that to make AWS amplify working
import { Auth } from 'aws-amplify';
//...

const promise = Auth.signIn(username, password);

I don't understand how I can mock this API access to the Cognito.
Usually, I provide a Mock service to the constructor by dependendies injection to avoid real connection to the API. Here it's directly imported in the component.
Spec file:
describe('login', () => {
    it('should not dispatch any action', () => {
      const actions = new Actions(EMPTY);
      const effect = new AuthEffects(
      //...
      );
      const metadata = getEffectsMetadata(effect);

      expect(metadata.login).toEqual({ dispatch: false });
    });

    it('should call setItem on LocalStorageService', () => {
      const loginAction = new ActionAuthLogin('test', 'Test1234!');
      const source = cold('a', { a: loginAction });
      const actions = new Actions(source);
      const effect = new AuthEffects(
      //...
      );

      effect.login.subscribe(() => {
        expect(localStorageService.setItem).toHaveBeenCalledWith(AUTH_KEY, {
          isAuthenticated: true
        });
      });
    });

    afterAll(() => {
      TestBed.resetTestingModule();
    });
  });

Is there a way to override this import from the spec file ?

A: You can make it like this:
// service with Auth
import { Injectable } from '@angular/core';
import Auth, { CognitoUser } from '@aws-amplify/auth';
...

private getProfile(): void {
   return from(Auth.currentUserInfo());
}

// service.spec.ts
it('should set user and user profile', async () => {
   const userProfile = { profile: 'userProfile' } as any;

   Auth.currentUserInfo = jasmine.createSpy().and.callFake(() => Promise.resolve(userProfile));

   const resp = await service.getProfile.toPromise();
   expect(resp).toEqual(userProfile)

 });

A: I manage to get rid of the error.
You need to import Auth in the test file and the types that will be needed in the following solution.
import { Auth } from 'aws-amplify';
import { ClientMetaData, SignInOpts } from '@aws-amplify/auth/src/types/Auth';

Now, redefining the signIn method of the Auth will solve the problem:
describe('AuthEffects', () => {
//...
Auth.signIn = (
    usernameOrSignInOpts: string | SignInOpts,
    pw?: string,
    clientMetadata: ClientMetaData = this._config.clientMetadata
  ) => of({}).toPromise();
//...

You need to follow the signature of the method to override it.
public signIn(
        usernameOrSignInOpts: string | SignInOpts,
        pw?: string,
        clientMetadata: ClientMetaData = this._config.clientMetadata
    ): Promise<CognitoUser | any>

I don't know if it's the best (cleaner) solution to perform it, but I manage to get rid of the error and control the behavior of the Auth instance.

A: Rather than import it directly into your service or Effects class, import it into your Module and inject it. Assuming you have an AuthService service class handling AWS Amplify's Auth.
In your corresponding module:
import Auth, { AuthClass } from '@aws-amplify/auth';
...
providers: [
    AuthService,
    { provide: AuthClass, useValue: Auth }
  ]

In your component or service, simply inject it like any other dependency:
constructor(
    private auth: AuthClass
    ) {
       auth.signIn('abc', 'def')
    }

And finally, in your spec file you mock it and use a Spy:
describe('AuthService', () => {
  let service: AuthService;
  let authSpy: jasmine.SpyObj<AuthClass>
  let authSpyObj = {
    signIn: () => new Promise<any>(() => true),
    signOut: () => new Promise<any>(() => true),
    signUp: () => new Promise<any>(() => true),
    confirmSignUp: () => new Promise<any>(() => true),
    resendSignUp: () => new Promise<any>(() => true),
  }

  beforeEach(() => {
    const spyAuth = jasmine.createSpyObj('auth', authSpyObj);

    TestBed.configureTestingModule({
      providers: [
        AuthService,
        { provide: AuthClass, useValue: spyAuth },
      ]
    })

    service = TestBed.inject(AuthService)
    authSpy = TestBed.inject(AuthClass) as jasmine.SpyObj<AuthClass>
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should have called signIn', () => {
    service.signIn('a@b.c', '12345678')
    expect(authSpy.signIn).toHaveBeenCalled()
  })
});

This test file doesn't do much right now except confirm that your service/component is calling the expect Auth functions, but this should get you off the ground. Enjoy.


text:
Q: Coc: Change setting from key or script Is there a way to change a Coc settings from script? Extension options are normally stored in the coc-settings.json file. If you want to toggle a specific setting it is slow to open the file, edit and save. Preferable I would like to be able to map a key to an extension setting.

A: You can use coc#config
https://github.com/neoclide/coc.nvim/blob/101175f47c15ff11eb599c617ef895f578f758b8/doc/coc.txt
or g:coc_user_config .
https://github.com/neoclide/coc.nvim/blob/101175f47c15ff11eb599c617ef895f578f758b8/doc/coc.txt#L890

A: You can change the configurations by coc#config, for example:
call coc#config('signature', {'preferShownAbove': v:false})


text:
Q: Convert byte[] to Base64 string in Javascript I use to render data using EntityDataSource, and I use to store customer image as byte in database, the problem is how can I convert that byte to base64 on .aspx page itself to use it as image src, is there any way to do this in javascript.

A: Why do you need to convert a byte[] to base64 string? This won't allow you showing the image on the page. You could write a generic handler (.ashx) that will query the database, fetch the image bytes and write them to the response stream. Then you simply instruct your image src property to this generic handler.


text:
Q: Only load link from  when mouse is hovering over I use the following bit of code for a template I append in my index.html. The issue is that I have thousands of 's that gets appended in a loop. And I have a feeling that when I append all of this it loads the http://en.wikipedia.org for all the 's before actually hovering over the link. This is obviously not a usable solution as it takes hours, if not days, to load up the page. I had to kill the site when I tried.  Is there a way to set  so it ONLY loads the page when hovering over it?
template += " ";
template += "";
template += entry['id'];
template += "";
template += "

";
template += "	";

A: You could omit the 's src attribute, then capture, via JavaScript, the mouseover event, and set the src when the event fires.


text:
Q: Populating a dropdown list with a stored procedure (showing usernames) then showing the users full name instead of username - slow I have a drop down -
<asp:DropDownList ID="OriginatorDropDown" DataTextField="User"
DataValueField="User" runat="server" CssClass="form-control">
      <asp:ListItem Selected="True" Text="" Value="" />  </asp:DropDownList>

And I am populating it on the page load. However it is awfully slow..
i only have about 30 people in the list, it shouldnt be this slow. Any
ideas please?
   protected void Page_Load(object sender, EventArgs e)
     {
         if (!IsPostBack)
         {
             GetUsers();
         }

     }

     private void GetUsers()
     {
         OriginatorDropDown.Items.Clear();
         OriginatorDropDown.DataSource = GetUserData();
         OriginatorDropDown.DataBind();

         foreach (ListItem ltItem in OriginatorDropDown.Items)
         {
             if (ltItem.Text != String.Empty)
             {
                 using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
                 {
                     UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName
,ltItem.Text);
                     if (up != null)
                     {
                         ltItem.Text = up.DisplayName;
                     }

                 }
             }
         }
     }

     public DataSet GetUserData()
     {

         using (SqlConnection myConnection = new SqlConnection(ElectronicPayments))
         {
             //Get status descriptions
             using (SqlCommand cmd = new SqlCommand("GetAllUsers", myConnection))
             {
                 cmd.CommandType = CommandType.StoredProcedure;

                 SqlDataAdapter da = new SqlDataAdapter(cmd);
                 DataSet user = new DataSet();

                 myConnection.Open();
                 da.Fill(user);

                 return user;
             }
         }
     }

A: It is possible your context creation at each iteration may takes time. Could you try this :
    private void GetUsers()
     {
         OriginatorDropDown.Items.Clear();
         OriginatorDropDown.DataSource = GetUserData();
         OriginatorDropDown.DataBind();

using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
         foreach (ListItem ltItem in OriginatorDropDown.Items)
         {
             if (ltItem.Text != String.Empty)
             {

                     UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName
,ltItem.Text);
                     if (up != null)
                     {
                         ltItem.Text = up.DisplayName;
                     }

             }
         }
     }


text:
Q: Prove Euler characteristic is a homotopy invariant without using homology theory I was flipping through May's Concise Course in Algebraic Topology and found the following question on page 82.

*

*Think about proving from what we have done so far that $\chi(X)$ depends only on the homotopy type of $X$, not on its decomposition as a finite
  CW complex.

Here, "what we have done so far" includes a fair amount of homotopy theory, but no homology theory. The only proof I know of the homotopy invariance of $\chi$ is the one in Hatcher using homology groups, so I am intrigued by this question.
Recall that for a finite CW complex $X$, we define the Euler characteristic as
$$\chi(X)=\sum (-1)^n c_n,$$
where $c_n$ is the number of $n$-cells in $X$.

A: We will prove this by induction: suppose, we know that if $X$ consists of $\,<n$ cells then for all other finite $CW$-complexes $X'$ such that $X\approx X'$ we have $\chi(X)=\chi(X')$.
Let $Y$ and $Y'$ be two finite $CW$-complexes, $Y$ consists of $n$ cells, and $f:Y\to Y'$ is homotopy equivalence. Consider one higher-dimensional cell of $Y$: let $Y=Z\cup_\alpha D^k$, where $Z$ consists of $n-1$ cells, $D^k$ is just a cell and $\alpha:\partial D^k\to Z$ is attaching map. We see that $\chi(Z)=\chi(Y)-(-1^k)$.
Then consider the space $CZ\cup_{f|_Z}Y'$, here $CZ$ is a cone. $f$ supposed to be cellular map, so $CZ\cup_{f|_Z}Y'$ is a $CW$ complex; it contains all cells of $Y'$, all cells of $Z$ times $I$, and the vertex of the cone, thus $\chi(CZ\cup_{f|_Z}Y')=\chi(Y')-\chi(Z)+1$. But we know that this space has homotopy type of $S^k$, so by inductive hypothesis $\chi(CZ\cup_{f|_Z}Y')=1+(-1^k)$, and $\chi(Y)=\chi(Y')$ as desired.
EDIT: for the induction we also need the statement be truth in case $X\approx pt$ and $X\approx S^m$. If $X\approx S^m$, we may glue an $m+1$-disc and obtain contractible space.
Now suppose $X\approx pt$, $m$ is maximal dimension of cells of $X$ and $X$ has $p$ $\,m$-cells. The space $sk_{m-1}(X)$ is $(m-2)$-connected, so it is homotopy equivalent to the bouquet of $q$ $\,(n-1)$-spheres. Gluing $m$-cells determines a homomorphism $\phi:\mathbb Z^p\to\mathbb Z^q$, and equalities $\mathrm{coim\,}\phi=\pi_{m-1}(X)$ and $\ker\phi\subseteq\pi_m(X)$ give us $p=q$. Then we may remove $p$ $\,m$-cells, $p$ $\,(m-1)$-cells, and repeat. (this reasoning sounds more like homological argument)


text:
Q: Is it possible to reclaim the memory used by an initrd? I'm developing a boot process for an embedded device. Currently I'm using an initrd (uncompressed it's 4 megs) to be able to setup my real root partition before continuing to boot (I have to select a partition based on some information, and overlay another using unionfs).
However, I'm concerned that the memory that was used for the initrd filesystem is permanently reserved for that use, even though it's only necessary for less than a few seconds of boot time. The device only has 256 megs of RAM, and 4 megs of this seems significant.

*

*Is there a way to reclaim this memory?

*If I were to use initramfs instead of initrd, would this buy me anything?

*Is there another option?

A: Memory used by initrd/initramfs is freed after it is done with ie. when real root fs is mounted. So normally you should have to worry about this. Your question reveals that you're not using the initrd/initramfs as your run-time root fs, so the memory used for it is freed automatically.
For more details, see initrd part of kernel documentation under the heading of "Changing the root device".


text:
Q: How to print react-chartjs-2 bar chart in browser using functional component? Here is an example of Bar Chart. I want to print this bar chart in browser, for that i tried react-to-print but it is throwing error like react-to-print only works with class components.
import React from "react";
import { Bar } from "react-chartjs-2";

// dataset for bar chart
const data = {
  // goes onto X-axis
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [
    {

      label: "My First dataset",
      fill: false,
      // background color
      backgroundColor: "rgba(75,192,192,0.4)",
      // border color
      borderColor: "rgba(75,192,192,1)",
      // goes onto y-axis
      data: [65, 59, 80, 81, 56, 55, 40]
    }
  ]
};

const options={
  //options for bar chart
};

export const BarDemo = () => {
  return (

Bar Example

      <Bar data={data} />

  );
};

A: I tried so many things to overcome this problem while working on one of my project.
Finally came up with solution,maybe it helps someone.
Firstly I created Bar chart using functional components as you can see above given example.
So, Here goes the final code for asked question.
Thanks me anytime :)
import React,{useRef} from "react";
// import class component
import BarComponent from './BarComponent';

const data = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [
    {
      label: "My First dataset",
      fill: false,
      backgroundColor: "rgba(75,192,192,0.4)",
      borderColor: "rgba(75,192,192,1)",
      data: [65, 59, 80, 81, 56, 55, 40]
    }
  ]
};

const options={
  //options for bar chart
};

export const BarDemo = () => {

  const componentRef = useRef();

  return (

Bar Example

      //instead of using Bar directly,we will create a class component.
      <BarComponent ref={componentRef} data={data} options={options}/>

  );
};

// here goes the class Component somethings like this.
import React from 'react';
import {Bar} from 'react-chartjs-2';

class BarComponent extends React.PureComponent {

  componentRef = React.createRef();

  render() {
    return (

            <Bar ref={this.componentRef} id="Bar" data={this.props.data} options={this.props.options}/>

    );
  }
};
export default BarComponent;

// we can pass the ref of BarComponent as props to the print functional component something like this

import React from 'react';
import { useReactToPrint } from "react-to-print";

export const Print = ({componentRef}) =>{

    // it will print the bar chart
    const handlePrint = useReactToPrint({
       content: () => componentRef.current
    });

    return(
      <button onClick={handlePrint}> Print </button>
    );
};


text:
Q: How to make the padding in scrollbar? CSS I've tried everything, searched the whole stack overflow and google.
Can someone help me to make this particular type of scrollbar?
When I use the border-right/top/bottom to make the spaces around it, it breaks the border-radius and gets ugly. As a reference, it's the same scrollbar used in Googledocs, a slim, rounded and doesn't touch the margins of the page: https://docs.new/
Here's the image: rounded, slim and not touching
So far I got:

::-webkit-scrollbar {
  background: #262338;
  width: 6px;
}

::-webkit-scrollbar-thumb {
  padding: 0 4px;
  background: #6E7191;
  border-radius: 6px;
  height: 48px;
}

A: ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
    border-radius: 34px;
}

/* Track */
::-webkit-scrollbar-track {
    background: #f1f1f1;
}

/* Handle */
::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 8px;
    transition: all 0.4s;
    -moz-transition: all 0.4s;
    -webkit-transition: all 0.4s;
}

/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
    background: #555;
    border-radius: 16px;
}

This would get you the main design of the scrollbar you are looking. This is what I used on my website. Hope this is the design you want!

A: Scrollbar Padding
I think you'll have to use a container to accomplish the not touching part of your requirements.
Chrome vs Firefox
Be aware that the support to adjust the scrollbar is very limited in firefox compared to chrome browsers. The result of it will not show up in this snippet, nor on websites like jsfiddle. Rounded corners are impossible to achieve in firefox without using your own implementation or a third party library like thisone for example.
Example

body {
  background-color: #14142B;
}

/* FIREFOX */

html {
  scrollbar-width: thin;
  scrollbar-color: #6E7191 #262338;
}

/* CHROME */

::-webkit-scrollbar {
  width: 12px;
  border-radius: 34px;
}

::-webkit-scrollbar-track {
  background: #262338;
  border-radius: 8px;
}

::-webkit-scrollbar-thumb {
  background: #6E7191;
  border-radius: 8px;
  transition: all 0.4s;
  -moz-transition: all 0.4s;
  -webkit-transition: all 0.4s;
}

::-webkit-scrollbar-thumb:hover {
  background: #7E81A1;
}

.container {
  margin: 1.5rem .5rem;
  overflow-y: scroll;
  max-height: calc(100vh - 3rem);
}

.content {
  height: 25rem;
}

hr {
  border: 0;
  border-top: 2px solid #201F36;
}

.filler {
  height: 3rem;
}


text:
Q: Class variable have different values for different instances I read somewhere that "if python can't find instance variable it will try to return value of the class variable having the same name"
eg
class Sample:
    pi = 10

Now
x1 = Sample()
x2 = Sample()

x1.pi         # returns 10
x2.pi         # returns 10

x1.pi = 20    # change the value of class variable
x1.pi         # return 20 (OK)
x2.pi         # still returns 10 :(
Sample.pi     # returns 10 :(

What is happening??

A: As soon as you assign to a name on an instance, it gains an instance attribute that shadows the class attribute.
The only way you can assign to the class attribute is to assign to an attribute of the class, not an attribute of the instance, e.g. if you have an instance, you need to do:
x1.__class__.pi = 20
# If you're on Py3, or on Py2 and x1 is an instance of a new-style class,
# using type(x1) is slightly "nicer" than manually accessing dunder special
# variables, but unfortunately, it doesn't work on old-style class instances
# For new-style class instances though, the following is equivalent:
type(x1).pi = 20

if you want all instances of the same type as x1 to show the change. This gets the class itself from __class__ (or via type function), then assigns to it.
If you accidentally created an instance attribute and want to expose the class attribute again, you can do:
del x1.pi

which will succeed if an instance attribute named pi exists, and raise AttributeError if it does not (it will not delete the class attribute if it exists, you'd need to do del x1.__class__.pi/del type(x1).pi to do that).


text:
Q: how to detect if a URL points to a SWF Is there a way (preferrably using JavaScript) to determine whether a URL is to a SWF or a JPG?
The obvious answer is to sniff the filename for ".jpg" or ".swf" but I'm dealing with banners that are dynamically decided by the server and usually have a lot of parameters and generally don't include an extension.
so i'm wondering if I could load the file first and then read it somehow to determine whether it's SWF or JPG, and then place it, because the JavaScript code I'd need to display a JPG vs a SWF is very different.
Thanks!

A: I would extend Sijin's answer by saying:
An HTTP HEAD request to the url can be used to examine the resource's mime-type.  You
won't need to download the rest of the file that way.

A: You could use javascript to detect if it is a image by creating a dynamic img-tag.
function isImage(url, callback) {
    var img = document.createElement('img');
    img.onload = function() {
        callback(url);
    }
    img.src = url;
}

And then calling it with:
isImage('http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/bald-eagle-head.jpg', function(url) { alert(url + ' is a image'); });

Update
This version will always execute the callback with a boolean value.
        function isImage(url) {
        var img = document.createElement('img');
        img.onload = function() {
            isImageCallback(url, true);
        }
        img.onerror = function() {
            isImageCallback(url, false);
        }
        img.src = url;
    }

    function isImageCallback(url, result) {
        if (result)
            alert(url + ' is an image');
        else
            alert(url + ' is not an image');
    }

Put your logic in the isImageCallback function.

A: Completely untested, basicly just an idea:
function isImage(url)
{
    var http = getHTTPObject();
    http.onreadystatechange = function ()
    {
        if (http.readyState == 4)
        {
            var contentType = http.getResponseHeader("Content Type");
            if (contentType == "image/gif" || contentType == "image/jpeg")
                return true;
            else
                return false;
        }
    }

    http.open("HEAD",url,true);
    http.send(null);
}

function getHTTPObject()
{
    if (window.XMLHttpRequest)
    {
        return new XMLHttpRequest();
    }
    else
    {
        if (window.ActiveXObject)
        {
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return false;
}

A: I am not sure the of the exact setup you have, but can you use the HTTP response and check the mime-type to determine image vs flash?

A: If the URL doesn't have an extension then there is no way to tell without requesting the file from the server.