text:
Q: Mathematical news sources. I'm studying my high school right now but I really like math and it would be great for me if I could find a place where I can find about what is going on in the math world nowadays. About a year ago I was subscribed to the scientific american magazine and one time they put an article in there about Terrence Tao http://adsabs.harvard.edu/abs/2012arXiv1201.6656T finding this proof to a weak version of the Goldbach conjecture.
Any good places where I can get a grasp of current mathematical research and what is being done right now? I know about papers and journals but I would like to get a wider picture without needing to be an expert in every field.

A: There's an extensive mathblog circuit. While some blogs maintain a high level of rigor, I'd say that most intermix deep math, general thoughts and ramblings, and recent events of interest.
I'd like to recommend 4:

*

*Firstly, the conglomerator mathblogging.org is a big compendium of bloggers that is somewhat differentiated based on the skill level and content.

*Secondly, I recommend Terry Tao's blog, although much of the time, Terry talks about his own research which will probably fly above most audiences.

*I also recommend Timothy Gower's blog, which tends to be almost entirely math news.

*If you'll forgive the self-plugging, I also think my blog is pretty approachable, and I try to talk about things of interest to the greater math community some times.
Also, perhaps surprisingly, many mathematicians are very active of GooglePlus. Really, I'm serious.

A: The notes in American Mathematical Monthly don't generally require PhD level expertise (though many of the articles do).  They aren't always about current events, but it could be a good place to start.

A: i offer you  see following blog

1.Mathematical Institutions and Centers
2.Electronic Newsgroups and Listservs
3.MathDB Forum
4.Sage in the news, blogs, forums and buzz sites

A: Less of a "news" kind of answer, but I very much recommend casually reading the Princeton Companion To Mathematics. It helps bring you up to speed by giving a broad overview of various topics.


text:
Q: stacked GRU model in keras I am willing to create a GRU model of 3 layers where each layer will have 32,16,8 units respectively. The model would take analog calue as input and produce analog value as output.
I have written the following code:
def getAModelGRU(neuron=(10), look_back=1, numInputs = 1, numOutputs = 1):
    model = Sequential()
    if len(neuron) > 1:
        model.add(GRU(units=neuron[0], input_shape=(look_back,numInputs)))
        for i in range(1,len(neuron)-1):
            model.add(GRU(units=neuron[i]))
        model.add(GRU(units=neuron[-1], input_shape=(look_back,numInputs)))
    else:
    model.add(GRU(units=neuron, input_shape=(look_back,numInputs)))
    model.add(Dense(numOutputs))
    model.compile(loss='mean_squared_error', optimizer='adam')
    return model

And, I will call this function as:
chkEKF = getAModelGRU(neuron=(32,16,8), look_back=1, numInputs=10, numOutputs=6)

And, I obtained the following:
Traceback (most recent call last):
  File "/home/momtaz/Dropbox/QuadCopter/quad_simHierErrorCorrectionEstimator.py", line 695, in <module>
    Single_Point2Point()
  File "/home/momtaz/Dropbox/QuadCopter/quad_simHierErrorCorrectionEstimator.py", line 74, in Single_Point2Point
    chkEKF = getAModelGRU(neuron=(32,16,8), look_back=1, numInputs=10, numOutputs=6)
  File "/home/momtaz/Dropbox/QuadCopter/rnnUtilQuad.py", line 72, in getAModelGRU
    model.add(GRU(units=neuron[i]))
  File "/home/momtaz/PycharmProjects/venv/lib/python3.6/site-packages/keras/engine/sequential.py", line 181, in add
    output_tensor = layer(self.outputs[0])
  File "/home/momtaz/PycharmProjects/venv/lib/python3.6/site-packages/keras/layers/recurrent.py", line 532, in __call__
    return super(RNN, self).__call__(inputs, **kwargs)
  File "/home/momtaz/PycharmProjects/venv/lib/python3.6/site-packages/keras/engine/base_layer.py", line 414, in __call__
    self.assert_input_compatibility(inputs)
  File "/home/momtaz/PycharmProjects/venv/lib/python3.6/site-packages/keras/engine/base_layer.py", line 311, in assert_input_compatibility
    str(K.ndim(x)))
ValueError: Input 0 is incompatible with layer gru_2: expected ndim=3, found ndim=2

I tried online but did not find any solution for 'ndim' related issue.
Please let me know which I am doing wrong here.

A: You need to ensure input_shape parameter is being defined in the first layer exclusively, and every layer to have return_sequences=True except potentially the last one (depending on your model).
The code below serves for the common case where you want to stack several layers and only the number of units in each layer changes.
model = tf.keras.Sequential()

gru_options = [dict(units = units,
                    time_major=False,
                    kernel_regularizer=0.01,
                    # ... potentially more options
                    return_sequences=True) for units in [32,16,8]]
gru_options[0]['input_shape'] = (n_timesteps, n_inputs)
gru_options[-1]['return_sequences']=False # optionally disable sequences in the last layer.
                                          # If you want to return sequences in your last
                                          # layer delete this line, however it is necessary
                                          # if you want to connect this to a dense layer
                                          # for example.
for opts in gru_options:
    model.add(tf.keras.layers.GRU(**opts))

model.add(tf.keras.Dense(6))

By the way there is a bug in your code, as no indentation is done after the else clause. Also notice that Python classes that implement the Iterable protocol (e.g. lists and tuples) can be iterated over by using for-in syntax, you don't have to do C-like iteration (it's more idiomatic or pythonic to use the aforementioned syntax).

redpajama_set_name: RedPajamaStackExchange


text:
Q: I am using hidden input type to set value and using request.getParameter() to get the value in another page but it is always returning "null" I am using hidden input type to set value and using request.getParameter()
    to get the value in another page but it is always returning "null".
    Why it is returning null value?
First Page:-
<%
try{
       Class.forName("org.postgresql.Driver");
       Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/passkey_database","postgres","4457");
       PreparedStatement ps=con.prepareStatement("select * from visitor_table");
       ResultSet rs=ps.executeQuery();
       ResultSetMetaData metaData=rs.getMetaData();
       while(rs.next()){

%>

  <input type="text" name="name" value="<%=rs.getString("visitor_name")%>">
   <%=rs.getString("visitor_name")%>

<%for(int i = 2; i<=metaData.getColumnCount();i++){ %>

  <%= rs.getString(i)%>

<%    }   %>

<%}
}catch (Exception e) {
e.printStackTrace();
}

Second Page:-
 <%

   String name=request.getParameter("name");
    out.println(name);
   try{
       Class.forName("org.postgresql.Driver");
        Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/passkey_database","postgres","4457");
            PreparedStatement ps=con.prepareStatement("select * from visitor_table where visitor_name=?");
            ps.setString(1,name);
            ResultSet rs=ps.executeQuery();
            while(rs.next()){

  %>

A: You can do this task by just a simple trick
update this line
<%
        String visitor_name = rs.getString("visitor_name");
        String link = "permissionform.jsp?name=" + visitor_name;
    %>
    <input type="text" name="name" value="<%=visitor_name%>">
    <a href="<%=link%>"><%= visitor_name%>

by this code you really dont need the <input> tag if you use this code because link is already parsed.
by this name value forworded will not be null if visitor_name is not null
Hope it helps your problem.:)

A: You can use Session , Cookie or Context  objects to get variable in other page,or use form tag with action another page if you have <input type="submit"/>  tag
try this code

     <form action="permissionForm.jsp">
      <input type="text" name="name"
       value="<%=rs.getString("visitor_name")%>">
     <input type="submit" value="<%=rs.getString("visitor_name")%>"/>
    </form>


text:
Q: "535 5.7.8 Error: authentication failed: authentication failure" with postfix and dovecot sasl authentication I'm testing remote smtp login on a server and keep getting 535 5.7.8 Error: authentication failed: authentication failure errors in the syslog and mail.log. Postfix is configured to use system user names and passwords.
I generated a user name and password with perl -MMIME::Base64 -e 'print encode_base64("username");' and perl -MMIME::Base64 -e 'print encode_base64("password");'
I am logging into the server with openssl s_client -starttls smtp -connect email.example.com:587 and using the auth login to input the user name and password.
I've turned on dovecot debugging but not seeing much in logs other than the authentication failure message.
Postfix main.cf:
# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
#smtpd_sasl_type = dovecot
#smtpd_sasl_auth_enable = yes
myhostname = email.example.org
mydomain = example.com
myorigin = example.com
home_mailbox = Maildir/
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
mydestination = $myhostname, email.example.com, ip-172-30-0-39.ec2.internal, localhost.ec2.internal, localhost, $mydomain, localhost.$mydomain
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all

dovecot:
auth_debug = yes
auth_debug_passwords = yes
auth_mechanisms = plain login
auth_verbose = yes
mail_location = maildir:~/Maildir
mail_privileged_group = mail
namespace inbox {
  inbox = yes
  location =
  mailbox Drafts {
    special_use = \Drafts
  }
  mailbox Junk {
    special_use = \Junk
  }
  mailbox Sent {
    special_use = \Sent
  }
  mailbox "Sent Messages" {
    special_use = \Sent
  }
  mailbox Trash {
    special_use = \Trash
  }
  prefix =
}
passdb {
  driver = pam
}
protocols = " imap"
service auth {
  unix_listener /var/spool/postfix/private/auth {
    group = postfix
    mode = 0666
    user = postfix
  }
  unix_listener auth-userdb {
    mode = 0666
  }
}
service imap-login {
  inet_listener imap {
    port = 143
  }
  inet_listener imaps {
    port = 993
    ssl = yes
  }
}
ssl_cert = </etc/dovecot/private/dovecot.pem
ssl_client_ca_dir = /etc/ssl/certs
ssl_dh = # hidden, use -P to show it
ssl_key = # hidden, use -P to show it
userdb {
  driver = passwd
}

service auth {
  # auth_socket_path points to this userdb socket by default. It's typically
  # used by dovecot-lda, doveadm, possibly imap process, etc. Users that have
  # full permissions to this socket are able to get a list of all usernames and
  # get the results of everyone's userdb lookups.
  #
  # The default 0666 mode allows anyone to connect to the socket, but the
  # userdb lookups will succeed only if the userdb returns an "uid" field that
  # matches the caller process's UID. Also if caller's uid or gid matches the
  # socket's uid or gid the lookup succeeds. Anything else causes a failure.
  #
  # To give the caller full permissions to lookup all users, set the mode to
  # something else than 0666 and Dovecot lets the kernel enforce the
  # permissions (e.g. 0777 allows everyone full permissions).
  unix_listener auth-userdb {
    mode = 0666
    #user =
    #group =
  }

  # Postfix smtp-auth
  unix_listener /var/spool/postfix/private/auth {
    mode = 0666
    user = postfix
    group = postfix
  }

  # Auth process is run as this user.
  #user = $default_internal_user
}

service auth-worker {
  # Auth worker process is run as root by default, so that it can access
  # /etc/shadow. If this isn't necessary, the user should be changed to
  # $default_internal_user.
  #user = root
}

service dict {
  # If dict proxy is used, mail processes should have access to its socket.
  # For example: mode=0660, group=vmail and global mail_access_groups=vmail
  unix_listener dict {
    #mode = 0600
    #user =
    #group =
  }
}

A: OK, I was able to get authentication working by adding the following lines to the postfix main.cf config file:
 smtpd_sasl_path = private/auth
 smtpd_sasl_type = dovecot
 smtpd_sasl_auth_enable = yes


text:
Q: PHP Elastic Search - fetching all documents before executing search (to save time/performance) I am currently using the following query in a php function hitCount($keyword)
  'query' => [
    'bool' => [
      'must' => [
        [
          'range' => [
            'date' => [
              'gte' => 'now-4w/d',
              'lt'  => 'now/d'
            ],
          ]
        ],
        [
          'match' => [
            'content' => $keyword
          ]
        ]
      ]
    ]
  ]

It allows me to go through a list of keywords and execute the query for each keyword - i basically want to know "how many times has a keyword been included in the last 4 weeks" - and it works perfectly fine for a handful of keywords. But as you can imagine as soon as I want to execute this function for a long array of keywords (100+) it starts to take a long time because it needs to fetch all documents first before it can look for my matching keyword.
now my question:
how can i make this query faster? can I first fetch all documents of the past 4 weeks ( the range date query) and THEN execute the match-keyword query?
Something like that:
$documentsToSearchIn = $client->get($prefetchParams);
$finalResponse = $client->search($matchParams, $documentsToSearchIn);


text:
Q: PL/SQL errors during dynamic sql execution I have a PL/SQL Procedure that prints out a correct sql but once I call EXECUTE, I get an error that sql is not properly ended.
here is my procedure
procedure my_proc(p_first VARCHAR2, p_second NUMBER, p_third NUMBER DEFAULT NULL, p_fouth NUMBER DEFAULT NULL)
IS
str varchar2(3200);
v1 VARCHAR2(20);
v2 VARCHAR2(20);
v3 VARCHAR2(20);
str2 varchar2(1000);

begin

str2:='SELECT t2.c1,t2.c2,t2.c3 FROM ';

if p_third=3 then
        str:= 't1,t2,t3 where t1.c1=t2.c1 and t2.c1=t3.c1 and t1.c1=p_first ;' ;
elsif p_third=2 then
        str:=' t1,t2,t4 where t1.c1=t2.c1 and t2.c1=t4.c1 and t2.c1=p_second ;' ;
else
        str:='t2 where t2.c1=p_second ;';
end if;

str2:=str2 || str;

dbms_output.put_line(str2);
EXECUTE IMMEDIATE  str2 into v1,v2,v3;

--dbms_output.put_line(v1||','||v2||','||v3);

end;

When I comment out EXECUTE statement, I get
SELECT t2.c1,t2.c2,t2.c3 FROM t1,t2,t4 where t1.c1=t2.c1 and t2.c1=t4.c1 and t2.c1=p_second;

which looks fine, so I am not sure why execution gives me `SQL command not properly ended.
I tried removing semicolon at the end of the sql but then I get ORA-00904: "p_second": invalid identifier
.
What am I doing wrong?

A: The error you are getting is because the dynamic statement should not have a semicolon at the end. That is a client statement separator, not part of the statement itself, and execute immediate only accepts a single statement. (Whether you get "ORA-00933: SQL command not properly ended" or "ORA-00911: invalid character" depends on your Oracle version).
So the first fix is to change your code to remove those:
if p_third=3 then
        str:= 't1,t2,t3 where t1.c1=t2.c1 and t2.c1=t3.c1 and t1.c1=p_first' ;
elsif p_third=2 then
        str:=' t1,t2,t4 where t1.c1=t2.c1 and t2.c1=t4.c1 and t2.c1=p_second' ;
else
        str:='t2 where t2.c1=p_second';
end if;

But when those statements are executed they are in a separate SQL context that has no visibility or knowledge of the PL/SQL variables and procedure arguments. It will try, and fail, to interpret p_first or p_second as column names, and they are unlikely to exist (and even if they do it won't do what you expect).
You can concatenate in the arguments directly, as @are suggested (but still without the semicolons):
        str:= 't1,t2,t3 where t1.c1=t2.c1 and t2.c1=t3.c1 and t1.c1=''' || p_first || '''';
        str:=' t1,t2,t4 where t1.c1=t2.c1 and t2.c1=t4.c1 and t2.c1=' || p_second;
        str:='t2 where t2.c1=' || p_second;

etc., which gets slightly more complicated with other data types as you need to handle dates properly and so on.
But it would be better to use bind variables; which means have separate execute immediate calls so you can supply the relevant bind value for each generated query. Something like:
begin

  str := 'SELECT t2.c1,t2.c2,t2.c3 FROM ';

  if p_third=3 then
    str := str || 't1,t2,t3 where t1.c1=t2.c1 and t2.c1=t3.c1 and t1.c1=:p_first';
    dbms_output.put_line(str);
    execute immediate str into v1, v2, v3 using p_first;
  elsif p_third=2 then
    str := str || ' t1,t2,t4 where t1.c1=t2.c1 and t2.c1=t4.c1 and t2.c1=:p_second';
    dbms_output.put_line(str);
    execute immediate str into v1, v2, v3 using p_second;
  else
    str := str || 't2 where t2.c1=:p_second';
    dbms_output.put_line(str);
    execute immediate str into v1, v2, v3 using p_second;
  end if;

  --dbms_output.put_line(v1||','||v2||','||v3);

end;

A: you cannot pass parameters this way
't1,t2,t3 where t1.c1=t2.c1 and t2.c1=t3.c1 and t1.c1=p_first ;'

change to
't1,t2,t3 where t1.c1=t2.c1 and t2.c1=t3.c1 and t1.c1='''||p_first ||''';'

A: Apart from Alex's answer I would recommend ANSI join syntax:
begin

  str := 'SELECT t2.c1,t2.c2,t2.c3 FROM ';

  if p_third=3 then
    str := str || 't1 JOIN t2 ON t1.c1=t2.c1 JOIN t3 ON t2.c1=t3.c1 WHERE t1.c1=:p_first';
    dbms_output.put_line(str);
    execute immediate str into v1, v2, v3 using p_first;
  elsif p_third=2 then
    str := str || ' t1 JOIN t2 ON t1.c1=t2.c1 JOIN t4 ON t2.c1=t4.c1 where t2.c1=:p_second';
    dbms_output.put_line(str);
    execute immediate str into v1, v2, v3 using p_second;
  else
    str := str || 't2 where t2.c1=:p_second';
    dbms_output.put_line(str);
    execute immediate str into v1, v2, v3 using p_second;
  end if;

  --dbms_output.put_line(v1||','||v2||','||v3);

end;


text:
Q: How to correctly pass JSON from php to Javascript with Dates? I am tinkering with the Jquery Weekly Calendar Plugin (Which you can look at the full demo here: skedyul.herokuapp.com)
Now, I'm trying to put some events dynamically using PHP but I'm fairly new to the concept of JSON.
This is my example php array to be encoded to JSON:
<?php
        $events = array(
            array(
            "id" => 1,
            "start" => date("D M j Y H:i:s "),
            "end" =>  date("D M j Y H:i:s ",strtotime("+30 minutes")),
            "title" => "College Algebra"
            ),
            array(
            "id" => 2,
            "start" => date("D M j Y H:i:s ",strtotime("+30 minutes +1 day")),
            "end" =>  date("D M j Y H:i:s ",strtotime("+45 minutes +1 day")),
            "title" => "Calculus"
            )
        );
?>

And here is the working Javascript code with some sample data:
<script type="text/javascript">

        function getEventData() {
          var year = new Date().getFullYear();
          var month = new Date().getMonth();
          var day = new Date().getDate();
          console.log(new Date(year, month, day, 12));
          return {
             events : [
                {
                   "id":1,
                   "start": new Date(year, month, day, 12),
                   "end": new Date(year, month, day, 13, 30),
                   "title":"College Algebra",
                },
                {
                   "id":2,
                   "start": new Date(year, month, day, 14),
                   "end": new Date(year, month, day, 14, 45),
                   "title":"Statistics and Probability"
                }
             ]
          };
       }

And here, I changed the above Javascript into this (putting the json encoded php associative array)
<script type="text/javascript">

            function getEventData() {
              var year = new Date().getFullYear();
              var month = new Date().getMonth();
              var day = new Date().getDate();
              console.log(new Date(year, month, day, 12));
              return {
                 events : <?php echo json_encode($events)?>
              };
           }
</script>

It's seems to work an doesn't spews out errors but the problem is about the Date.
It's not showing properly at the calendar..
How do I correctly pass JSON from PHP with dates?
Thank you :)

A: Please consider: date.js from http://code.google.com/p/datejs
You can use Date.parse() or Date.parseExact()
In your case, you use Date.parseExact(dateString, "d MMM d yyyy HH:mm:ss")
In your page, include the date.js.
<script src="http://yoursite/path/to/date.js"></script>

Then try the following...
var dateobj = Date.parseExact(dateString, "d MMM d yyyy HH:mm:ss")
alert(dateobj.toString());

Please read http://code.google.com/p/datejs/wiki/FormatSpecifiers for date formatting


text:
Q: Backup mounted drive of an image in Time Machine As a mac user, I'm fairly new but I now find myself using disk images a lot (dmgs and sparseimages/bundles) to organise my files. Mostly encrypted images to hold my private stuff and other images that hold work files and "mission critical" files.
Now that I've got a new drive, I was trying to set up Time Machine. And I noticed that while it does indeed backup the image file itself (since these are stored on my home dir and it's not excluded), it doesn't backup the mount point itself (ie, /Volumes/MyImageDrive).
Is there no way to treat files in "Virtual drives" like any other files on HDD? Can I not use the Time machine cool/easy restore thing with files store on these drives?
Obviously, I can always restore the whole image. But I imagine trying to restore a few instances of a 30GB image just because I'm not quite sure where the change happened is going to be quite a pain.
Thanks

A: Time Machine doesn't back up the contents of mounted drives for a few reasons.  For example:

*

*Mounted images can be very transient.  If /Volumes/MyVolume exists on Monday but disappears on Tuesday, should it consider those files no longer existing and therefore remove from future backups?  What if MyVolume comes back on Wednesday?  Now it has to make a whole new copy of the contents again because it can't be sure the files are same ones it saw on Wednesday.

*What if yesterday it's mounted as /Volumes/MyVolume but today it's mounted as /Volumes/OurVolume.  Does Time Machine have to make a whole duplicate copy?

*Backing up the contents of an image in addition to the image itself would waste space on your backup volume.  You'd essentially be storing two copies of every file.
However, you can view past backups manually without taking the time to restore them.  Browse to your Time Machine volume.  For example, mine looks like this:
/Volumes/TimeMachine/Backups.backupdb/Hypatia/
    2009-11-27-163215/
    2009-12-11-075355/
    ....
    2010-06-22-004524/
        Hypatia/
            Applications/
            Developer/
            Library/
            System/
            Users/

Rather than using the fancy Time Machine interface, if you are looking for a specific version of an image (or bundle) file, I suggest looking through those dated folders and mounting the backup copies of your image file directly.  You can open the folder that contains the dated folders then use the window's Spotlight search to find every copy of the image you're looking for (i.e., search for "NameOfImage.sparsebundle").
This way, you save the step of copying it back to your system drive and overwriting whatever is there.  It's a little more tedious than using Time Machine's goofy interface, but it gets the job done.


text:
Q: Convert Material UI app to mobile and make it responsive I was building a web app with React and Material UI and I have difficulty with mobile size. So I have several questions:

*

*How to make margins responsive for example:  marginLeft: theme.spacing(20), this is how I set up margin for logo  example on desktop:
example mobile:

A: I once had a similar problem in a project I was doing. I solved with react-device-detect. With this package you can set margin and layout in general based on device running your app.
import {
  BrowserView,
  MobileView,
  isBrowser,
  isMobile
} from "react-device-detect";

Then you can both generate two views
<BrowserView>
    <h1> This is rendered only in browser </h1>
</BrowserView>
<MobileView>
    <h1> This is rendered only on mobile </h1>
</MobileView>

Or use isMobile for conditional rendering.

A: You could use CSS Media Queries:

CSS media queries are the idiomatic approach to make your UI
responsive. The theme provides four styles helpers to do so:

*

*theme.breakpoints.up(key)

*theme.breakpoints.down(key)

*theme.breakpoints.only(key)

*theme.breakpoints.between(start, end)

Default breakpoints:

Each breakpoint (a key) matches with a fixed screen width (a value):

*

*xs, extra-small: 0px

*sm, small: 600px

*md, medium: 960px

*lg, large: 1280px

*xl, extra-large: 1920px

These breakpoint values are used to determine breakpoint ranges. A
range starts from the breakpoint value inclusive, to the next
breakpoint value exclusive:
value         |0px     600px    960px    1280px   1920px
key           |xs      sm       md       lg       xl
screen width  |--------|--------|--------|--------|-------->
range         |   xs   |   sm   |   md   |   lg   |   xl

These values can be customized.

Example:
const useStyles = makeStyles(theme => ({
  myLogo: {
    // Match [md, ∞)
    //       [960px, ∞)
    [theme.breakpoints.up('md')]: {
      ...,
      marginLeft: theme.spacing(20),
      ...
    },
    // Match [0, sm + 1)
    //       [0, md)
    //       [0, 960px[
    [theme.breakpoints.down('sm')]: {
      ...,
      // no margin
    },
  }
}));


text:
Q: Why won't my server and client I coded in Java work? My server keeps getting this error when I run the client:
Exception in thread "main" java.io.EOFException
    at java.io.DataInputStream.readInt(Unknown Source)
    at java.io.ObjectInputStream$BlockDataInputStream.readInt(Unknown Source)
    at java.io.ObjectInputStream.readInt(Unknown Source)
    at MyServer.main(MyServer.java:10)

Here is the server code:
import java.net.*;
import java.io.*;

public class MyServer{
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(40);
        Socket clientSocket = serverSocket.accept();
        ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
        System.out.println(in.readInt());
        serverSocket.close();
        System.exit(0);
    }
}

And here is the client code:
import java.io.*;
import java.net.*;

public class MyClient {
    public static void main(String[] args) throws IOException {

        Socket socket = new Socket("localhost", 40);
        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
        out.writeInt(5);
        socket.close();
        System.exit(0);
    }
}

A: You should flush your ObjectOutputStream before closing the Socket.

A: Try adding
out.flush();

just before
socket.close();


text:
Q: How to switch  text after click with unique id I'm working with BootstrapVue. I have a b-button in my template where I want to switch its text after clicking on it.
I'm passing my generated unique item.id to my script, but this is not working out in the case that every b-button text will be changed and not only the one I'm clicking. What is the problem in here?
You should be able to copy, paste the code and it should work out.
Please notice that it's just a replica of my code shortened on needed code, so the code should not be changed this much.
My template:

  {{btnText}}

Add Input

My script:
data() {
  return {
    collapsed: [true],
    id: null,
    inputs: [{id: 0}],
    btnText: "It's false",
  }
},

methods: {
  changeText(item) {
    this.collapsed[item.id] = !this.collapsed[item.id]

    if(this.collapsed[item.id] === true) {
      this.btnText = "It's true"
    }
    else if(this.collapsed[item.id] === false) {
      this.btnText = "It's false"
    }
  },

  addInput() {
    this.inputs.push({
      id: this.id += 1,
    })
    this.collapsed.push(true);

  }
}

A: *

*Instead of having separate arrays to store the different fields, move them into the inputs[] object array, so that each item in the v-for has its own id, collapsed, and btnText.

*Then update changeText() to refer to the fields within the item argument.

*Also update the template to use the item.btnText field.

<template>

   3⃣
      {{ item.btnText }}

    Add Input

</template>

demo

A: You can maintain an object for btnText like
data() {
  return {
    collapsed: [false],
    id: null,
    inputs: [{id: 0}],
    btnText: {0: "It's false"} //Change added
  }
},

methods: {
  changeText(item) {
    this.collapsed[item.id] = !this.collapsed[item.id]

    if(this.collapsed[item.id] === true) {
      this.btnText[item.id] = "It's true"; //Change added
    }
    else if(this.collapsed[item.id] === false) {
      this.btnText[item.id] = "It's false"; //Change added
    }
  },

  addInput() {
    this.inputs.push({
      id: this.inputs.length, // Change added
    })
    this.btnText[this.inputs.length] = 'It's false';  //Change added
    this.collapsed.push(true);

  }
}

and your template should be like

  {{btnText[item.id]}}

Add Input


text:
Q: Configuration System Failed to Initialize I'm writing a small program in C# visual Studio 2010, using 2.0 .Net framework.  I'm trying to read values from an App.config file.  My config file looks like this...
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
      <section name="MyApp.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <applicationSettings>
    <add key="Path" value ="C:\Program Files\MyApp\bin\" />
    <add key="UserName" value="UserName" />
    <add key="Pword" value="Password" />
  </applicationSettings>
</configuration>

Then in my code at:
path = ConfigurationManager.AppSettings["Path"];

I get a runtime error "Configuration System Failed to Initialize".
From what I've read the configSection has to be first in the file, but I've done this and still get the error.

A: Put <configSections> before <appSettings> and it should work
<configuration>
<configSections>
...
</configSections>
<appSettings>
...
</appSettings>
</configurations>

A: I've worked it out, the tag applicationSettings should be called appSettings.  And I can then get rid of the sectionGroup tags leaving just this.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
  </configSections>
  <appSettings>
    <add key="Path" value="C:\Program Files\MyApp\bin\" />
    <add key="UserName" value="username" />
    <add key="Pword" value="password" />
  </appSettings>
</configuration>

A: I could be way off on this one, you should escape your backslashes.
I.e. C:\Program Files\MyApp\bin\ becomes C:\\Program Files\\MyApp\\bin\\

A: Might be The Configuration file has been corrupted and is unreadable.Delete the Existing .Config File and Create A new With Same Name and Settings .
by using same practice I have resolve same problem many time .
         <add key="Path" value ="C:\\Program Files\\MyApp\bin\\" />

If you want to use Multiple path in your Code then Use Combine Path

A: Please, check below image...
You need to add your key into  tag.

A: I do know this is a very late addition but just thought if it would help someone else why not.
When it comes to using "applicationSettings" note that you cannot as of today you cannot mix the "settings" of "applicationSettings" and "add" of "appSettings" in other words you cant have
<setting name="Name You choose" serializeAs="String">
        <value>True</value>
      </setting>

and
<add key="Name You choose" value="1000" />

in the same App.config file.


text:
Q: Hover button and fill from left to right with round shape I have a button with a hover effect that fills the background from left to right:
Current HTML
Mehr erfahren

Current CSS
body {
  background-color: #f6f6f6;
}

a {
  text-decoration: none;
  color: black;
}

a:hover {
  text-decoration: none;
}

.button {
  font-size: 20px;
  color: black;
  background-color: white;
  padding: 20px;
  border-radius: 50px;
  display: inline-block;
  background-image: radial-gradient(circle at left, black 50%, black 50%);
  background-size: 0 100%;
  background-repeat: no-repeat;
  transition: 0.4s;
}

.button:hover {
  color: white;
  background-size: 100% 100% !important;
}

.button::before {
  content: "";
  display: inline-block;
  width: 15px;
  height: 15px;
  -moz-border-radius: 7.5px;
  -webkit-border-radius: 7.5px;
  border-radius: 7.5px;
  background-color: white;
  border: 1px solid black;
  margin-right: 15px;
}

Find it also here on codepen
Goal is that the right side of the fill color has rounded corners like here:

Any ideas? Thanks in advance

A: As mentioned in this other SO question, there is no way to add border-radius directly to the background-image. If you are open to another option to get your desired result using a pseudo background element and adding a  around your text for z-index adjustment, then you can reference my example below.

body {
  background-color: #f6f6f6;
}

a {
  text-decoration: none;
  color: black;
}

a:hover,
a:focus {
  text-decoration: none;
}

.button {
  font-size: 20px;
  color: black;
  background-color: white;
  padding: 20px;
  border-radius: 50px;
  display: inline-block;
  transition: 0.4s;
}

.button:hover,
.button:focus {
  color: white;
}

/* New CSS */

.button {
  position: relative;
  overflow: hidden;
  -webkit-mask-image: -webkit-radial-gradient(white, black);
}

.button:hover::after,
.button:focus::after {
  transform: translateX(0);
}

.button::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  background: #000;
  width: 100%;
  height: 100%;
  border-radius: 50px;
  transform: translateX(-100%);
  z-index: 0;
  transition: 0.4s;
}

.button span {
  position: relative;
  z-index: 1;
}

.button span::before {
  content: "";
  display: inline-block;
  width: 15px;
  height: 15px;
  -moz-border-radius: 7.5px;
  -webkit-border-radius: 7.5px;
  border-radius: 7.5px;
  background-color: white;
  border: 1px solid black;
  margin-right: 15px;
}
Mehr erfahren


text:
Q: The Stack Exchange Active User Base I have this question related to the Stack Exchange active user base.
According to this webpage, currently, there are around 661,293 Stack Overflow users who have at least 200 points as their reputation.
Similarly, according to this webpage, currently, there are around 32,858 Super User users who have at least 200 points as their reputation.
I am not interested in their reputation points, but rather in the number of active users. Supposedly, the users who have at least 200 reputation points have been doing something at least meaningful on these websites.
The numbers seem to be surprisingly low. As in the industry, one finds themselves at least reading these webpages, if not writing something on them or providing feedback to their content (that is, reacting to it in any way).
Does this mean that the current worldwide active information technology and telecommunications professional user base is only around a few hundred thousand users?
This idea might sound to be a little bit exaggerated, but look at the number of users that a software application such as Symantec's Norton Life Lock has: only something above one million installs.
Is it possible that the whole World Wide Web could actually be sustained by only a few hundred thousand users working on it around the world?

A:
I am not interested in their reputation points, but rather in the number of active users. (...) The numbers seem to be surprisingly low

I can't quantify it but among my colleagues many have SO accounts and many others don't. Most decide not to actively participate but certainly all end up on SO if they're googling something. Traffic is probably the better indicator of how many programmers are out there.

A: Wrong base assumption.
Stack Overflow (and Super User) users are not sustaining the whole world-wide-web.

*

*Programmers can solve bugs and problems all on their own without asking on Stack Overflow.

*Programmers can ask their co-workers and friends for help, instead of asking on Stack Overflow.

*There are other sites besides Stack Overflow with possible solutions to common bugs.

So this whole discussion is moot. Amount of active or inactive users in Stack Overflow has very little effect, if any, on the world.


text:
Q: Fridge Combinatorics (is it really that trivial?) In my Fridge I have 2013 Meals of different types. Of each type there aren't more than 183 in quantaty.
Proof that I can eat 11 different meals each day for the next 183 days.
My solution is this:
In my Fridge I have the types a,b,c,d,e,f,g,h,i,j,k and maybe more.
At start I eat the meals a,b,c,d,e,f,g,h,i,j,k once every day. When one of the versions is gone, one of the remainding ones becomes the empty one. Therefore the other different types belong to one of the 11 types as well.
2013/11=183 --> Therefore I can eat 11 different types of meals everyday for the next 183 days.
I'm sure it can't really be this easy and I did a mistake somewhere

A: HINT: $$\frac{2013}{11} = 183$$

A: Imagine laying out the $2013$ meals in a rectangular array of $11$ rows and $183$ columns. Put the $n_1$ meals of type $1$ in the first $n_1$ positions in the array, reading from left to right and top to bottom. When you've laid out all of the type $1$ meals, continue with the type $2$ meals, then the type $3$ meals, and so on. If, for instance, $n_1=170$ and $n_2=150$, the type $1$ meals will occupy the first $170$ positions in the first row, and the type $2$ meals will occupy the last $13$ positions in the first row and the first $137$ positions in the second row. The idea is that each column should contain the meals for one day, so we'd like to show that no column can contain two meals of the same type.
Suppose that column $k$ contains two meals of type $\ell$. Then the type $\ell$ meals occupy at least the last $183-(k-1)=184-k$ positions of one row and the first $k$ positions of the next row, for a total of $184$ positions — which is impossible, since there are only at most $183$ meals of type $\ell$.

A: Since 2013/183=11, you have at least 11 different types of food. If there's exactly 183 of every type, then you can eat a meal of each of these 11 types 183 times. The problem is what happens when you don't have exactly 183 of each type.


text:
Q: When assigning a struct to a variable, is the instance copied or referenced? Will this program return true or false?
Will the x value of the struct carry over to a from b?
struct Vector(x, y)
{
    public int x, y;
    public Vector(x, y)
    {
        this.x = x;
        this.y = y;
    }
}

class Main()
{
    Vector a = new Vector(1, 2);
    Vector b = a;
    b.x = 3;
    if (a.x == 3) return true;
    else return false;
}

A: It's not going to carry over, they are the same thing. a and b are pointing to the same object. Whatever changes in one, you can access by the other's reference. So the answer is true.

A: A structure is essentially equivalent semantically to a bunch of independent variables stuck together with duct tape.  Thus, if one declares
public struct Foo {public int X,Y};

Foo f1,f2;
...
f1 = f2;

the declaration of f1 and f2 is roughly equivalent to:
int f1_X,f1_Y, f2_X,f2_y;

and the assignment of f2 to f1 is equivalent to
f1_X = f2_X;
f1_Y = f2_Y;

Further, defining and calling a method:
void Bar(Foo it) {...}
Bar(f1);

is essentially equivalent to:
void Bar(int it_X, int it_Y) {...}
Bar(f1_X,f1_Y);

The only aspects of structures which makes Foo f really different from int f_X,f_Y; are the facts that all of the fields of a structure behave as a unit when a ref is passed (e.g. void Boz(ref Foo it); will receive one ref which identifies both variables, rather than one for each), and an array of a struct type likewise uses one reference for everything, so var bar = new Foo[12] would declare one array that holds twelve pairs of integers, whereas var bar_X = new int[12], bar_Y = new int[12]; would declare a pair of arrays holding twelve integers each.
Although structures can declare helper methods, and one can restrict the ability of outside code to access the struct except via such methods, it is most helpful to think of a struct as simply being a bunch of independent variables stuck together with duct tape.  If that's what one wants, an public-field struct is a perfect fit.  If one wants a type which behaves as something else, one should probably use something else.  The idea that "mutable structs are evil" stems in part from the fact that compilers sometimes do evil things with methods that modify this, and in part from the idea that types should be something more than bunches of variables stuck together with duct tape.  It is certainly true that in most types should behave as something other than amalgamations of variables, and such types should be implemented as something other than public-field structures.  That does not mean, however, that in those cases where one does need an amalgamation of independent variables, one should try to use an immutable class to awkwardly emulate such behavior, or a so-called "immutable" struct which tries to emulate the awkward behavior of an immutable class, as opposed to using an exposed-field struct which would, without awkwardness, inherently behave exactly as required.


text:
Q: Cuda hello_world.cu compiles but wrongly prints "Hello Hello" I have found the following hello world program for CUDA:
#include <stdio.h>

#define cudaCheckErrors(msg) \
    do { \
        cudaError_t __err = cudaGetLastError(); \
        if (__err != cudaSuccess) { \
            fprintf(stderr, "Fatal error: %s (%s at %s:%d)\n", \
                msg, cudaGetErrorString(__err), \
                __FILE__, __LINE__); \
            fprintf(stderr, "*** FAILED - ABORTING\n"); \
            exit(1); \
        } \
    } while (0)

const int N = 16;
const int blocksize = 16;

__global__
void hello(char *a, int *b)
{
  a[threadIdx.x] += b[threadIdx.x];
}

int main()
{
  char a[N] = "Hello \0\0\0\0\0\0";
  int b[N] = {15, 10, 6, 0, -11, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

  char *ad;
  int *bd;
  const int csize = N*sizeof(char);
  const int isize = N*sizeof(int);

  printf("%s", a);

  cudaMalloc( (void**)&ad, csize );
  cudaMalloc( (void**)&bd, isize );
  cudaCheckErrors("cudaMalloc fail");
  cudaMemcpy( ad, a, csize, cudaMemcpyHostToDevice );
  cudaMemcpy( bd, b, isize, cudaMemcpyHostToDevice );
  cudaCheckErrors("cudaMemcpy H2D fail");

  dim3 dimBlock( blocksize, 1 );
  dim3 dimGrid( 1, 1 );
  hello<<<dimGrid, dimBlock>>>(ad, bd);
  cudaCheckErrors("Kernel fail");
  cudaMemcpy( a, ad, csize, cudaMemcpyDeviceToHost );
  cudaCheckErrors("cudaMemcpy D2H/Kernel fail");
  cudaFree( ad );
  cudaFree( bd );

  printf("%s\n", a);
  return EXIT_SUCCESS;
}

I compile it successfully with nvcc hello_world.cu -o hello, but when I run cuda-memcheck ./hello , I get:
========= CUDA-MEMCHECK
Fatal error: cudaMalloc fail (unknown error at hello_world.cu:39)
*** FAILED - ABORTING
Hello ========= ERROR SUMMARY: 0 errors

I'm a CUDA newbie, my questions are:
1) what's going on under the hood?
2) how can I fix it?

I'm running Ubuntu 13.04, x86_64, Cuda 5.5, without root access.
the upper output of nvidia-smi is:
+------------------------------------------------------+
| NVIDIA-SMI 337.19     Driver Version: 337.19         |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX TIT...  Off  | 0000:05:00.0     N/A |                  N/A |
| 26%   37C  N/A     N/A /  N/A |     53MiB /  6143MiB |     N/A      Default |
+-------------------------------+----------------------+----------------------+

When I run deviceQuery, I get:
../../bin/x86_64/linux/release/deviceQuery Starting...

 CUDA Device Query (Runtime API) version (CUDART static linking)

cudaGetDeviceCount returned 30
-> unknown error
Result = FAIL

And when I run deviceQueryDrv, I get:
../../bin/x86_64/linux/release/deviceQueryDrv Starting...

CUDA Device Query (Driver API) statically linked version
cuInit(0) returned 999
-> CUDA_ERROR_UNKNOWN
Result = FAIL

When I run:
#include <cublas_v2.h>
#include <cstdio>
int main()
{
  int res;
  cublasHandle_t handle;
  res = cublasCreate(&handle);
  switch(res) {
  case CUBLAS_STATUS_SUCCESS:
    printf("the initialization succeeded\n");
    break;
  case CUBLAS_STATUS_NOT_INITIALIZED:
    printf("the CUDA Runtime initialization failed\n");
    break;
  case CUBLAS_STATUS_ALLOC_FAILED:
    printf("the resources could not be allocated\n");
    break;
  }
  return 0;
}

I get the CUDA Runtime initialization failed.

A: I have had a problem exactly like yours just now. Running a sample was returning an "Unknown Error" and printing "Hello Hello ", and cublasCreate was returning CUBLAS_STATUS_NOT_INITIALIZED.
I found the answer here: http://docs.nvidia.com/cuda/cuda-getting-started-guide-for-linux/index.html#post-installation-actions

If a CUDA-capable device and the CUDA Driver are installed but deviceQuery reports that no CUDA-capable devices are present, this likely means that the /dev/nvidia* files are missing or have the wrong permissions.

Indeed, my /dev/nvidia* files were owned by root.
I just ran
chown user.user /dev/nvidia*

(where user is my local user) and all the errors disappeared.
EDIT: later I had a similar issue on another machine, and this solution did not work, because one of the devices in /dev/nvidia was missing. What did work is just executing a sample code once as a sudo. After that one extra device appeared in /dev/nvidia*, and sample code started working without sudo.


text:
Q: How do I display an image on an html 5 video element if and only if the video element is only outputting audio? I have a video element that is either displaying both video and audio or just audio through a stream.  I need to display a temporary image if it is only outputting audio.  Does the "poster" attribute for a video element work?  Or does that only display before the video has started playing?
Is there anyway to detect if a video element is only outputting audio?

A: Couple of suggestions:

*

*Use getVideoTracks() to check if the stream has video.

*Check the videoHeight of the video: if it's zero, there's no video.


text:
Q: Netty: Difference between using sync() and addListener() In a server handler, I have the following method:
private void writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) throws Exception {
    Promise<String> promise = client.run(); // client.run() will return a promise
    // the promise contains the result string I need for http response.
    promise.sync();
    // this method sends http response back, promise.getNow() is the content for the response.
    writeResponse(currentObj, ctx, promise.getNow());

}

This method is to send a response after getting some data from a client (client in the code). And when I test this using browser, I did get the response content.
However, when I change it to become:
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) throws Exception {
    Promise<String> promise = client.run();
    promise.addListener(new FutureListener<String>() {
        @Override
        public void operationComplete(Future<String> future) throws Exception {
            if (future.isSuccess()) {
                writeResponse(currentObj, ctx, future.getNow()); // (1)
            } else {
                writeResponse(currentObj, ctx, "FAILED");
            }
        }
    });
}

it didn't work anymore. From my understanding, it think the second one should also work because I've confirmed that the code did enter (1) block (the if (future.isSuccess()) block). But I didn't get any response in the browser. Can anyone explain it a little bit or point me to some references? I've found the comparison between await() and addListener in the document but it gives me the feeling that the two are similar to each other in function.
Thanks!
[update] I found this is because of this overload method:
private void writeResponse(HttpObject currentObj, ChannelHandlerContext ctx, String content) {
    FullHttpResponse response = new DefaultFullHttpResponse(
            HTTP_1_1, currentObj.decoderResult().isSuccess()? OK : BAD_REQUEST,
            Unpooled.copiedBuffer(content, CharsetUtil.UTF_8));

    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (HttpUtil.isKeepAlive(request)) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }
    ctx.write(response);
}

I shouldn't use ctx.write(response), but use ctx.writeAndFlush(response).
At first I use ctx.write(response) because I have the readComplete method to do flush for me.
public void channelReadComplete(ChannelHandlerContext ctx) {
    ctx.flush();
}

But it seems that when using addListener instead of sync, the channelReadComplete cannot do the flush. Any idea why?

A: The problem is that you just call write(...) in your ChannelFutureListener and not writeAndFlush(...). Because of this your written data will never be flushed to the socket.
The channelReadComplete(...) may be triggered before the ChannelFutureListener is executed and so you end up in this situation.
So to make it short use writeAndFlush(...) in the listener.


text:
Q: Detect UIImagePicker live view touches without "grabbing" them I am writing an app that allows the user to take pictures, using an UIImagePickerController.
I have customized the UIImagePicker with my own button bar and a few other button/options (views) added over the imagePicker view. Heres the relevant code:
self.photoPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
self.photoPicker.allowsEditing = NO;
self.photoPicker.showsCameraControls = NO;

[self.photoPicker.view addSubview:topButtonView];
[self.photoPicker.view addSubview:topButtonView2];

Everything is working as expected except for one problem. I began by targeting this app for iOS 4 and above, and one of the features I needed to have is the tap-to-focus functionality that comes embedded in the UIImagePickerController. Here is the problem. On iOS 4, when the user taps the live view, gets (presented automatically by the picker controller) a visual indicator (a square shape) showing the point were the camera is focusing and adjusting exposure. On iOS 5 and 6 that visual indicator is gone. The functionality  (tap-to-foucus) is still there, but no more square showing the user the place where the focus point is set.
I have searched and read several similar questions (but not quite), and the answers usually point to adding a transparent subview over the  UIImagePicker live view and capture the touch event. And that is easy enough, but the problem is, after I capture the users touch, I have found no way of relaying that touch to the UIImagePicker liveView.
I tried to create a custom view class to add over de imagepicker view but haven't been able to make it work. Here is the custom class code:
@interface touchGrabberViewController : UIViewController
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

{
CGPoint tapPoint;
__unsafe_unretained IBOutlet UIImageView *tapFocusIndicator;
NSTimer *indicatorDismisser;

}

@property (unsafe_unretained, nonatomic) UIImagePickerController *photoPicker;

@end

@implementation touchGrabberViewController

@synthesize photoPicker;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    tapFocusIndicator.hidden = YES;
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    return photoPicker.view;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = touches.anyObject;

   tapPoint = [touch locationInView:self.view];
    [self showTapFocusIndicator];

    [super touchesBegan:touches withEvent:event];
}

- (void)showTapFocusIndicator
{

    if (!indicatorDismisser)
    {
        tapFocusIndicator.center = tapPoint;

        tapFocusIndicator.hidden = NO;

        indicatorDismisser = [NSTimer scheduledTimerWithTimeInterval:0.5
                                                           target:self
                                                         selector:@selector(hideTapFocusIndicatorWithTimer:)
                                                         userInfo:nil
                                                          repeats:NO];
    }

}

- (void)hideTapFocusIndicatorWithTimer:(NSTimer *)timer
{
    tapFocusIndicator.alpha = 1.0;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelay:0.5];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(resetTapFocusIndicator)];
    tapFocusIndicator.alpha = 0.0;

    [UIView commitAnimations];

    [indicatorDismisser invalidate];
    indicatorDismisser = nil;
}

- (void)resetTapFocusIndicator
{
    tapFocusIndicator.hidden = YES;
    tapFocusIndicator.alpha = 1.0;
}

With this class I get a very similar visual indicator showing up were the user taps, but the user touches never get relayed back to the live view, so the focus functionality is lost.
Recently I decided to drop iOS 4, and just target versions 5 and 6, but I miss that visual indicator. As a camera apps user the indicator is really useful.
I have beeen experimenting alternatives with (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event, but no luck.
Anyone has any idea on how to achieve this, or what am I doing wrong?
Thank you.


text:
Q: Need help with extending my Perl module I am trying to extend my company specific BaseClass (Acme::BaseClass) but whenever I:
package Manager;
use strict;
use warnings;
use base qw(Acme::BaseClass)
sub new { ...

it gives me the error:
Base class package "Acme::BaseClass" is empty.

But in my script I can use the package fine:
use Acme::BaseClass;
my $bc = BaseClass->new("myname");
$bc->prnt(); # prints "myname"
exit;

This is my first time trying to inherit in Perl so maybe I am missing something basic?
NOTES:

*

*I have tried using "parent" and it also does not work

*I tried to use the old school :
BEGIN {
   require Acme::BaseClass;
   push @ISA, qw(Acme::BaseClass);
}
I am unsure how to do these correctly either. Hopefully it is something simple I am missing. If nobody can answer it I will add more details.

A: Judging from your code sample, it sounds like Acme/BaseClass.pm has something like this in it
package BaseClass;

....

1;

and it needs
package Acme::BaseClass;

....

1;

A: Possibly the child class cannot find the BaseClass module but your test script can. Check @INC is setup correctly so that both can find your module.


text:
Q: How to interpret scatter plots generated by linear regression and nonlinear regression? When I do my regression work, I find there are some problem which I can not interpret. I use Catboost regression  which is a kind of improved version of gradient boosting on decision trees and Lasso regression which is a version of Linear Regression with L1 regularization. I use 10-fold cross-validation to get each fold prediction and plot the scatter map. The map is as follows

However, two problems are in Lasso Map, one is that it appears negative prediction, beacuse it is linearity, the appeared negative prediction is normal. others is that it appears truncated prediction data (red line). why does Lasso appear truncated prediction data compared to CatBoost regression?
I do not understand it. Can you help me?


text:
Q: Spring config @RefreshScope Can I use @RefreshScope (along with @Value on a property) only in Cloud config server or can I use without config server as well? I'm trying to use it without config server. I am trying to fetch @Value property by changing value in a .property file and trying to request again, will I get updated value? Is that possible?

A: No, you should use it along with Config server otherwise you won't be able to read the update properties on fly. Follow this article and have a look into this if you face any issue loading updated properties dynamically.

In theory, you could refresh the application context, but I wouldn't
  recommend this. Spring Cloud has provided an annotation to mark a bean
  as refreshable. By adding spring actuator, we can refresh those beans
  on the fly.


text:
Q: Javascript not working if off from browser setting
Possible Duplicate:
How to detect if JavaScript is disabled?

if i am disable my javascript from browser settings, its stopped working, do i know the best way to recommend the user to enable its broswer javascript if by default it has off ? Any help ? or how can my code will detect of the javascript is off from browser or not :/
Any help ?

A: Use <noscript> tag. And add some info in this tag. This display when user has enabled javascript.

A: <noscript>
This page requires JavaScript, please turn it on.
</noscript>

A: If you for some reason don't want to use the <noscript> tag, or if you want to do the reverse (show some content only if JavaScript is enabled), you can make an element hidden by default (set display:none; through CSS). Then you have a small JavaScript add an additional-class to the element, say js-enabled. You can then you have a CSS-rule:
.js-enabled {
   display: block;
}

When your JavaScript applies the class, the element will become visible. If the user doesn't have JavaScript enabled, the class will not be added and the element will stay hidden.


text:
Q: Best way to implement background comunication with server using Firemonkey? I working on application that has to communicate with a server every few minutes, while the app is off, to check if there are new messages for it. If new message is awaylable, a notification must be shown.
For now stick to this workflow: A application starts a background service. A service on start connects to server to check for messages, then sets AlarmManager to activate the same service after few minutes and then service stops itself. And so on.
Have managed to implement something like this, but not sure if this is the best way to go.

A: You can implement firebase notification using firebase cloud messaging services. Firebase will send the notification to an application when any message received from app user. So, that will not be required to call continues background services for the check for new messages.
Please check below link for more information :
https://firebase.google.com/docs/cloud-messaging/


text:
Q: Array including multiple view types in Swift/SwiftUI I want to create a view where people can choose their preferred background image, these include a rectangle with a foreground colour or an image. So far I've got this to work by creating this
Struct:
struct BackgroundImage : Identifiable{
var background : AnyView
let id = UUID()
}

I am adding them to an array like so
ViewModel:
class VM : ObservableObject{
    @Published var imageViews : Array<BackgroundImage> = Array<BackgroundImage>()

    init(){
        imageViews.append(BackgroundImage(background: AnyView(Rectangle().foregroundColor(Color.green))))
        imageViews.append(BackgroundImage(background: AnyView(Rectangle().foregroundColor(Color.yellow))))
        imageViews.append(BackgroundImage(background: AnyView(Image("Testimage"))))
    }

which allows me to loop through an array of BackgroundImages like so
View:
LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())]) {
    ForEach(VM.imageViews, id: \.self.id) { view in
        ZStack{
            view.background
            //.resizable()
            //.aspectRatio(contentMode: .fill)
            .frame(width: g.size.width/2.25, height: g.size.height/8)
        .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
        }
    }
}

However I am unable to add
 .resizable()
 .aspectRatio(contentMode: .fill)

for the images as AnyView doesn't allow this.
Is there a better way of achieving this? Should I just have two separate arrays for Shapes/Images instead? Or is there an alternate View struct that would be better suited this?
Thanks!

A: As @DávidPásztor mentioned in the comments, it is a bad design to store Views in your ViewModel.
Really you just need to store a color and an image name.  Let the view building code construct the actual views.
Here is a possible implementation.
struct BackgroundItem: Identifiable {
    private let uicolor: UIColor?
    private let imageName: String?
    let id = UUID()

    var isImage: Bool { imageName != nil }
    var color: UIColor { uicolor ?? .white }
    var name: String { imageName ?? "" }

    init(name: String? = nil, color: UIColor? = nil) {
        imageName = name
        uicolor = color
    }
}

class VM : ObservableObject{
    @Published var imageItems: [BackgroundItem] = []

    init() {
        imageItems = [.init(color: .green),
                      .init(color: .blue),
                      .init(name: "TestImage")]
    }
}

struct ContentView: View {
    @ObservedObject var vm = VM()

    var body: some View {
        GeometryReader { g in
            LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())]) {
                ForEach(vm.imageItems) { item in
                    ZStack{
                        if item.isImage {
                            Image(item.name)
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                        } else {
                            Color(item.color)
                        }
                    }
                    .frame(width: g.size.width/2.25, height: g.size.height/8)
                    .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)
                }
            }
        }
    }
}

Note: I thought of using an enum to store the distinction between imageName and color, but it was simplest to just use optionals and store the one I needed.  With the interface that is being exposed to the view building code, you could easily change the implementation to however you'd like to store the information.


text:
Q: Not able to create Live CD I downloaded 12.04.1 on a Windows 7 machine. I burnt a DVD from the ISO image using Windows Disc Image Burner. I had 'verify disc' on.  The disc was created successfully with no errors. I was not able to use this disc for installing Ubuntu on another Windows 7 machine. I do not get the Welcome Screen on booting.
I find that on the disc I burnt, I do not find bin, disc tree, programs directories and cdromupgrade, start.*, ubuntu* files. I found the boot directory and WUBI executable file.  I tried downloading several times with the same result.  I had similar problem earlier with 11.04.
Can you please let me where the problem is?

A: First make sure that Booting from CD Drive is enable from BIOS. This will prevent Booting of CD at startup.In some Case you need to give First priority to CD Drive.


text:
Q: Very long restore time on my App I'm not sure what can be done about this. My app is an iPad app and I use about 300MB of ram. There are about 250MB of textures loaded for the game at any given time.
Here is the problem. When I sleep my iPad, if I sleep it for a few minutes and return to my game, it becomes playable again in seconds. If I leave my iPad sleeping after having played my game or while my game is still running for about 1 day then I go back, my game takes about 3.5 minutes to restore. It's not a bug, I've looked through the debugger many times and everything works as expected. iOS must be restoring the heap from somewhere which takes about 10 times longer than loading the game in from scratch.
My current solution is to forget about restoring and I intentionally crash my app so it restarts itself after it has been away which gets me to the same state about 10 times faster. But I don't like this solution.
Has anyone else experienced such issues? Are there api's I should be calling or something to lower the restore times after several hours of iPad sleeping?  Is this issue documented anywhere?

A:
My current solution is to forget about restoring and I intentionally
crash my app so it restarts itself after it has been away which gets
me to the same state about 10 times faster. But I don't like this
solution.

This is a guaranteed way to make sure that your app doesn't get approved for distribution on the App Store.  There's two solutions to this problem:
1) Redesign your game. There's various techniques to this, including:
Breaking down levels into smaller pieces, so each stage requires less assets to load.
Shrinking textures and assets. E.g., use 256x256 textures instead of 512x512.  One 512x512 texture takes up the space of four 256x256 textures.  Would you rather load four of your textures in a scene in a few seconds, or 1?
Compress your textures.  Compressed textures are smaller and quicker to load than their uncompressed bretheren.
Your application won't even run on an original iPad Mini, because of it's RAM - it has 512MB, and you're currently trying to use 300MB at any given time.
2) Disable your app from staying in the background.
Every time your app loses focus (besides lock screen being toggled), it'll force itself to be reloaded from scratch... much like you're already doing now with a forced crash. See:

If you never want your app to enter the background set the
UIApplicationExitsOnSuspend key in your application's Info.plist file
to YES

How to exit app while enter background
Those are my suggestions, though in all honesty I'd do the first one if at all possible.  It's more work, but you'd be able to make a more courteous iOS application when it comes to memory management plus you'd be able to target more devices.


text:
Q: How to downgrade php7 to php5.6 in mac high sierra Have a zend file which is perfectly go over php5.x but when it move with mac high sierra where getting error , I found that there is php 7 so want to downgrade 7 to 5.6

A: 1) On the Terminal:
curl -s http://php-osx.liip.ch/install.sh | bash -s 5.6

2) Then, open the file /etc/apache2/httpd.conf with read/write permissions and change the following lines:
Change the line:
LoadModule php7_module libexec/apache2/libphp7.so
To that:
#LoadModule php7_module libexec/apache2/libphp7.so
LoadModule php5_module /usr/local/php5/libphp5.so
<IfModule mod_php5.c>
    AddType application/x-httpd-php .php
    AddType application/x-httpd-php-source .phps
    <IfModule mod_dir.c>
        DirectoryIndex index.html index.php
    </IfModule>
</IfModule>

3) Pay attention because when you upgraded your macOS Sierra to macOS Sierra High, in apache2 folder, the previous file http.conf still in there but with another name. You can see and compare both for a correct configuration of your PHP 5.6.
Usually, the line DocumentRoot, <Directory "/some_local/"> and LoadModule were changed by the macOS upgrade, just compare what you had and change that according to you'd like the Apache/PHP behaves.
4) Restart your apache:
On the Terminal again, type it:
sudo /usr/sbin/apachectl restart

A: For those who are desperately tired and couldn't stop biting your nails to find a solution in order to install php5.6 on MAC likes me. Please have a look at this awesome article. Which allows me to see the light at the end of the tunnel.
There's no need to thank me in case you solve the problem, go there and give it to him. He deserves it.
I hope this may help.

A: you should definitely try homebrew (https://brew.sh) and it's awesome PHP packages like:

*

*php@5.6,

*php@7.0,

*php@7.1,

*php (which is latests version, currently 7.2).

I am using it for years and it is awesome.
Here is good tutorial:
https://medium.com/@romaninsh/install-php-7-2-xdebug-on-macos-high-sierra-with-homebrew-july-2018-d7968fe7e8b8
Have fun!


text:
Q: Property does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{ children?: ReactNode; }> ...' I'm trying to use React with TypeScript and Material-UI's components. Unfortunately, I'm getting the errors like this:

Property 'openToYearSelection' does not exist on type
  'IntrinsicAttributes & IntrinsicClassAttributes &
  Readonly<{ children?: ReactNode; }> ...'.

import * as React from 'react';
import DatePicker from 'material-ui/DatePicker';

interface IState {
  birthday: any,
}

export default class SampleForm extends React.Component<IProps, IState> {
  constructor(props: any) {
    super(props);

    const { record = {} } = this.props;

    this.state = {
      birthday: record.birthday || null,
    };
  }

  public birthdayPicker() {
    const { birthday } = this.state;

    return (
      <DatePicker
        defaultDate={birthday}
        hintText="Birthday"
        openToYearSelection={true}
      />
    );
  }

  public render() {
    return (
      <form style={styles.root}>
        {this.header()}
        {this.firstName()}
        {this.lastName()}
        {this.birthdayPicker()}
        {this.phoneNumber()}
        {this.actionButtons()}
      </form>
    )
  }
}

What's the right way to use Material-UI with TypeScript and React?

A: I've resolved this problem by adding missing properties to namespaces in
node_modules/@types/material-ui/index.d.ts file. It worked for me. I don't think that it's a good solution and I'm wondering if there're some better approaches.
namespace DatePicker {
    export interface DatePickerProps {
        defaultDate?: Date;
        disableYearSelection?: boolean;
        ..

A: If it's a third party library you can add this above the line that is erroring out and it'll ignore the error and let you build:
// @ts-expect-error


text:
Q: What does "dying weeks" imply?
The Obama administration had identified a more direct solution. In its dying weeks it filed a case at the WTO, suing China for its aluminium subsidies.

(The Economist)
Could this(dying weeks) mean the period when his administration had only few days left in office? Since "dying" in this case could also mean "ending"?

A: This is a metaphor, likening the administration to a person near the end of life.  It's a period when the end of its time is obviously approaching and it is less effective than before.
Your understanding is correct, and "ending" could have been used instead.  "Dying weeks" makes it clearer that this is a last-chance attempt at action, and there wouldn't be time to try again.


text:
Q: How to make $A$ and $A^T$'s location of columns that have pivots different? So $A$ is some $m \times n$ matrix. Now we have $A^T$. We know that both $A$ and $A^T$ have same rank.
How do we then show that the location of columns that have pivots for $A$ and $A^T$ (columns that do not have pivots) may be different?
(By being different, I mean: $A$ may have columns with pivots in the first, third column, while $A^T$ may have columns with pivots in te first and fourth column.)
Addition: What about the case when $A$ is $3 \times 3$ matrix?

A: $A = [0 \; 1 \; 0]$ and $A^T = \begin{bmatrix} 0 \\ 1 \\ 0 \end{bmatrix} \sim \begin{bmatrix} 1 \\ 0 \\ 0 \end{bmatrix}$.
$A$'s one and only pivot is in column 2. $A^T$'s one and only pivot is in its one and only column - column 1.


text:
Q: Can i setup a VM in ESXI with bridging two of it's ethernet adapters? I need to setup a virtual machine running windows server 2012 r2 (with 2 ethernet adapters) and install a firewall software to work in bridge mode ... Is it possible to do this in VMware ESXi using promiscuous option?

A: I believe what you are asking is that you want to setup a firewall on a Windows 2012r2 server. Yes, you can set it up on ESXi. You just need to have the two network adapters on two different network subnets or vlans.
The traffic traversing one network to the other would be ruled by the firewall.
Promiscuous is not needed for a firewall. It is needed if you are doing network sniffing or some type of intrusion detection system like snort.
https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1002934


text:
Q: kubelogin convert-kubeconfig need to be invoked after every az aks get-credentials I'm having the problem described here: https://aptakube.com/blog/how-to-use-azure-kubelogin
If I follow the article and use kubelogin convert-kubeconfig -l azurecli it works again indeed.
The problem is that every time I refresh my credentials using az aks get-credentialsz I need to repeat kubelogin convert-kubeconfig -l azurecli otherwise it won't work.
Is there a way to make this change permanent ?


text:
Q: pytorch "log_softmax_lastdim_kernel_impl" not implemented for 'torch.LongTensor' I am trying to use my own dataset to classify text according to https://github.com/bentrevett/pytorch-sentiment-analysis/blob/master/5%20-%20Multi-class%20Sentiment%20Analysis.ipynb. My dataset is a csv of sentences and a class associated with it. there are 6 different classes:
sent                      class
'the fox is brown'        animal
'the house is big'        object
'one water is drinkable'  water
...

When running:
N_EPOCHS = 5

best_valid_loss = float('inf')

for epoch in range(N_EPOCHS):

    start_time = time.time()
    print(start_time)
    train_loss, train_acc = train(model, train_iterator, optimizer, criterion)
    print(train_loss.type())
    print(train_acc.type())
    valid_loss, valid_acc = evaluate(model, valid_iterator, criterion)

    end_time = time.time()

    epoch_mins, epoch_secs = epoch_time(start_time, end_time)

    if valid_loss < best_valid_loss:
        best_valid_loss = valid_loss
        torch.save(model.state_dict(), 'tut5-model.pt')

    print(f'Epoch: {epoch+1:02} | Epoch Time: {epoch_mins}m {epoch_secs}s')
    print(f'\tTrain Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.2f}%')
    print(f'\t Val. Loss: {valid_loss:.3f} |  Val. Acc: {valid_acc*100:.2f}%')

, I receive the following error
RuntimeError: "log_softmax_lastdim_kernel_impl" not implemented for 'torch.LongTensor'

pointing to:
<ipython-input-38-9c6cff70d2aa> in train(model, iterator, optimizer, criterion)
     14         print('pred'+ predictions.type())
     15         #batch.label = batch.label.type(torch.LongTensor)
---> 16         loss = criterion(predictions.long(), batch.label)**

The solution posted here https://github.com/pytorch/pytorch/issues/14224 suggests I need to use long/int.
I had to add .long() at line ** in order to fix this earlier error:
RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target'
The specific lines of code are:
  def train(model, iterator, optimizer, criterion):
    epoch_loss = 0
    epoch_acc = 0

    model.train()

    for batch in iterator:

        optimizer.zero_grad()

        predictions = model(batch.text)
        print('pred'+ predictions.type())
        #batch.label = batch.label.type(torch.LongTensor)
        loss = criterion(predictions.long(), batch.label)**

        acc = categorical_accuracy(predictions, batch.label)

        loss.backward()

        optimizer.step()

        epoch_loss += loss.item()
        epoch_acc += acc.item()

    return epoch_loss / len(iterator), epoch_acc / len(iterator)

Note, the ** was originally loss = criterion(predictions, batch.label)
Any other suggestions to fix this issue?

A: criterion is defined as torch.nn.CrossEntropyLoss() in your notebook. As mentioned in documentation of CrossEntropyLoss, it expects probability values returned by model for each of the 'K' classes and corresponding value for ground-truth label as input. Now, probability values are float tensors, while ground-truth label should be a long tensor representing a class (class can not be a float, e.g. 2.3 can not represent a class). hence:
loss = criterion(predictions, batch.label.long())

should work.

A: if using gpu, instead of defining the long type under loss criterion, you should probably define it before using cuda. I face the same error. resolved it with below:
 # move data to GPU, if available
    if train_on_gpu:
        inp = inp.cuda()
        target = target.long()
        target=target.cuda()
    h = tuple([each.data for each in hidden])
    # perform backpropagation and optimization

    #zero accumulated gradient
    rnn.zero_grad()

    #getting out_put from model
    output,h = rnn(inp,h)
    #calculating loss and performing back_propagation

    loss = criterion(output.squeeze(), target)


text:
Q: WPF Binding к элементам, находящимся в ресурсах Всем доброго времени суток!
Имеется следующий код:
XAML:
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        xmlns:col="clr-namespace:System.Collections;assembly=mscorlib"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="525">
    <Window.Resources>
        <col:ArrayList x:Key="dataGridDef">
            <DataGrid Name="DG1" ItemsSource="{Binding Path=List1}" AutoGenerateColumns="False"
                      Tag="{Binding Path=GridNames[0]}">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Grid1Name1" Binding="{Binding Path=Name1}"/>
                </DataGrid.Columns>
            </DataGrid>
            <DataGrid Name="DG2" ItemsSource="{Binding Path=List2}"  AutoGenerateColumns="False"
                      Tag="{Binding Path=GridNames[1]}">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Grid2Name1" Binding="{Binding Path=Name1}"/>
                </DataGrid.Columns>
            </DataGrid>
        </col:ArrayList>
    </Window.Resources>
    <StackPanel>
        <ListBox x:Name="lb" ItemsSource="{StaticResource dataGridDef}" DisplayMemberPath="Tag"
                 SelectedValue="{Binding Path=SelectedGrid}"/>
        <ContentControl Content="{Binding ElementName=lb, Path=SelectedItem}"/>
        <TextBlock Height="100" Text="{Binding Path=Str.Header}"/>
        <TextBlock Text="{Binding Path=SelectedGrid.Tag}"/>
    </StackPanel>
</Window>

C#:
   public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new Content();
        }
    }

    public class Content
    {
        public ObservableCollection<Asd> List1 { get; set; }
        public ObservableCollection<Asd> List2 { get; set; }
        public DataGrid SelectedGrid { get; set; }

        private string[] _gridName;
        public string[] GridNames { get { return _gridName; } }

        public Content()
        {
            List1 = new ObservableCollection<Asd>();
            List2 = new ObservableCollection<Asd>();
            List1.Add(new Asd { Name1 = "1" });
            List1.Add(new Asd { Name1 = "2" });
            List2.Add(new Asd { Name1 = "a" });
            List2.Add(new Asd { Name1 = "b" });
            _gridName = new string[] { "G1", "G2" };
        }
    }
    public class Asd: INotifyPropertyChanged
    {
        private string _name1;
        public string Name1
        {
            get { return _name1; }
            set
            {
                if (value == _name1) return;
                _name1 = value;
                OnPropertyChanged(nameof(Name1));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        internal void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

Задача состоит в следующем:
Имеется ListBox в котором выбирается DataGrid, отображаемое имя привязано к свойству DataGrid Tag, выбранный DataGrid отображается ниже, с которым дальше и происходит работа.
Имена DataGrid, а точнее его свойство Tag привязаны к массиву из класса Content.
Но! В ListBox не отображаются имена, до тех пор пока в нем ничего не выбрано, как только элемент выбран, отображается только его имя:

Соответственно, как только выбирается второй элемент, отображается имя второго элемента, имя первого отображаться перестает.
Как сделать так, что бы имена элементов в ListBox отображались всегда?

A: Решение:
<Window x:Class="WpfApp1.MainWindow"
        <!--Ссылки-->
        Title="MainWindow" Height="450" Width="525" x:Name="MyWindow">
    <Window.Resources>
        <col:ArrayList x:Key="dataGridDef">
            <DataGrid Name="DG1" ItemsSource="{Binding Path=List1}" AutoGenerateColumns="False"
                      Tag="{Binding Path=DataContext.GridNames[0], Source={x:Reference MyWindow}}">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Grid1Name1" Binding="{Binding Path=Name1}"/>
                </DataGrid.Columns>
            </DataGrid>
            <DataGrid Name="DG2" ItemsSource="{Binding Path=List2}"  AutoGenerateColumns="False"
                      Tag="{Binding Path=DataContext.GridNames[1], Source={x:Reference MyWindow}}">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Grid2Name1" Binding="{Binding Path=Name1}"/>
                </DataGrid.Columns>
            </DataGrid>
        </col:ArrayList>
    </Window.Resources>

*

*Присваиваем окну имя: x:Name="MyWindow"

*Задаем Source для Tag: Source={x:Reference MyWindow}
https://stackoverflow.com/questions/48679600/wpf-binding-to-elements-in-resources


text:
Q: How measure Hilt/Dagger build time on my android project? Using google Hilt or Dagger for Android Projects can bring some increase on the build time.
But I would love to have some data of how much exactly the build takes with Hilt and without Hilt.
I have a multi-module project without hilt and one branch with hilt.
How to measure for sure the build/compilation time and be sure of how much Hilt take.?
I'm expecting something like:
Build without Hilt = 2m
Build with Hilt = 3m (Hilt took 45s)

Maybe I will see a decrease, not sure, but this is what I want to analyse.
All builds should be from zero without cache.
The goal is to improve compilation time for the devs in the day to day basis
Thanks!


text:
Q: Deserialize XML with repeating elements This is C# in VS2012 and building against .NET 4.5
I'm new to XML serialization/deserialization and trying to figure this out.  I have XML
<?xml version="1.0"?>
<AvailabilityResponse>
  <ApiKey>LZ6c@3O9#tq*BAyX4KGYBsCgZ*HpUDtrB*XI*WGLw</ApiKey>
  <ResellerId>101</ResellerId>
  <SupplierId>1004</SupplierId>
  <ForeignReference>1234567890</ForeignReference>
  <Timestamp>2015-08-06T05:20:49.000Z</Timestamp>
  <RequestStatus>
      <Status>SUCCESS</Status>
  </RequestStatus>
  <TTAsku>dcnt</TTAsku>
  <TourAvailability>
      <TourDate>2015-08-31</TourDate>
      <TourOptions>
          <DepartureTime>07:30 PM</DepartureTime>
      </TourOptions>
      <AvailabilityStatus>
          <Status>AVAILABLE</Status>
      </AvailabilityStatus>
  </TourAvailability>
  <TourAvailability>
      <TourDate>2015-08-31</TourDate>
      <TourOptions>
          <DepartureTime>08:30 PM</DepartureTime>
      </TourOptions>
      <AvailabilityStatus>
          <Status>AVAILABLE</Status>
      </AvailabilityStatus>
  </TourAvailability>
</AvailabilityResponse>

and I'm trying to deserialize into this class structure:
[Serializable]
public class AvailabilityResponse
{
    public string ApiKey { get; set; }
    public string ResellerId { get; set; }
    public string SupplierId { get; set; }
    public string ForeignReference { get; set; }
    public DateTime Timestamp { get; set; }
    public RequestStatus RequestStatus { get; set; }
    public string TTAsku { get; set; }
    public TourAvailability[] TourAvailability { get; set; }
}

[Serializable]
public class RequestStatus
{
    public string Status { get; set; }
}

[Serializable]
public class TourAvailability
{
    public DateTime TourDate { get; set; }
    public TourOptions TourOptions { get; set; }
    public AvailabilityStatus AvailabilityStatus { get; set; }
}
[Serializable]
public class AvailabilityStatus
{
    public string Status { get; set; }
    public string UnavailabilityReason { get; set; }
}

And I'm doing so with:
public static AvailabilityResponse DeserializeAvailabilityResponse(Stream replyStream)
{
    XmlSerializer xmlSr = null;
    XmlReader inreader = null;

    if (replyStream != null)
    {
        XmlTextReader xmlreader = new XmlTextReader(replyStream);
        XmlDocument respXml = new XmlDocument();
        respXml.Load(xmlreader);
        xmlreader.Close();

        xmlSr = DeserializeXmlDoc(respXml, out inreader, typeof(AvailabilityResponse));
    }

    if (xmlSr != null && inreader != null)
    {
        AvailabilityResponse inventory = (AvailabilityResponse)xmlSr.Deserialize(inreader);
        return inventory;
    }
    return null;
}

The problem is that when I examine the returned inventory item, the TourAvailability looks like this:

where I expected it to be like RequestStatus, for example, with the [+] allowing me to open it and see each element.  Even if I misrepresented it I would expect there to be at least one TourAvailability, not zero.
I'm probably missing several things here but any help you can give is greatly appreciated.  I have a bunch more of this kind of thing to deal with because our company is slightly changing direction.

A: Just use [XmlElement("TourAvailability")] attribute, Then you'll see the array's elemets.
public class AvailabilityResponse
{
    public string ApiKey { get; set; }
    public string ResellerId { get; set; }
    public string SupplierId { get; set; }
    public string ForeignReference { get; set; }
    public DateTime Timestamp { get; set; }
    public RequestStatus RequestStatus { get; set; }
    public string TTAsku { get; set; }
    [XmlElement("TourAvailability")]
    public TourAvailability[] TourAvailability { get; set; }
}

BTW: You don't need those [Serializable] attributes
PS: Your deserialization code can be simplified as:
using (var f = File.OpenRead(filename))
{
    XmlSerializer ser = new XmlSerializer(typeof(AvailabilityResponse));
    var resp = (AvailabilityResponse)ser.Deserialize();
}

A: Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Globalization;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            Stream stream = File.Open(FILENAME, FileMode.Open);
            AvailabilityResponse availabilityResponse = DeserializeAvailabilityResponse(stream);
        }
        public static AvailabilityResponse DeserializeAvailabilityResponse(Stream replyStream)
        {
            AvailabilityResponse availabilityResponse = null;
            XmlReader inreader = null;

            if (replyStream != null)
            {
                XmlSerializer xs = new XmlSerializer(typeof(AvailabilityResponse));
                inreader = new XmlTextReader(replyStream);
                availabilityResponse = (AvailabilityResponse)xs.Deserialize(inreader);
                return availabilityResponse;
            }
            else
            {
                return null;
            }
        }

    }
    [XmlRoot("AvailabilityResponse")]
    public class AvailabilityResponse
    {
        [XmlElement("ApiKey")]
        public string ApiKey { get; set; }
        [XmlElement("ResellerId")]
        public int ResellerId { get; set; }
        [XmlElement("SupplierId")]
        public int SupplierId { get; set; }
        [XmlElement("ForeignReference")]
        public string ForeignReference { get; set; }
        [XmlElement("Timestamp")]
        public DateTime Timestamp { get; set; }
        [XmlElement("RequestStatus")]
        public RequestStatus RequestStatus { get; set; }
        [XmlElement("TTAsku")]
        public string TTAsku { get; set; }
        [XmlElement("TourAvailability")]
        public List<TourAvailability> TourAvailability { get; set; }
    }

    [XmlRoot("RequestStatus")]
    public class RequestStatus
    {
        [XmlElement("Status")]
        public string Status { get; set; }
    }

    [XmlRoot("TourAvailability")]
    public class TourAvailability
    {
        [XmlElement("TourDate")]
        public DateTime TourDate { get; set; }
        [XmlElement("TourOptions")]
        public TourOptions TourOptions { get; set; }
        [XmlElement("AvailabilityStatus")]
        public AvailabilityStatus AvailabilityStatus { get; set; }
    }
    [XmlRoot("TourOptions")]
    public class TourOptions
    {
        public DateTime dTime { get; set; }

        [XmlElement("DepartureTime")]
        public string DepartureTime
        {
            get
            {
                return this.dTime.ToString("hh:mm tt");
            }
            set
            {
                this.dTime = DateTime.ParseExact(value, "hh:mm tt", CultureInfo.InvariantCulture);
            }
        }

    }

    [XmlRoot("AvailabilityStatus")]
    public class AvailabilityStatus
    {
        [XmlElement("Status")]
        public string Status { get; set; }
        [XmlElement("UnavailabilityReason")]
        public string UnavailabilityReason { get; set; }
    }
}


text:
Q: Store Static files on S3 _AND_ locally at the same time? I've successfully used django-storages to store all my static and media files in Django on Amazon S3 - however I also want to store them on the server as well at the same time.
So, when I run collectstatic I want it to both sync the /static folder and the s3.domain.tld/static folder.
My settings looks like this:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'cupcard/static')]
STATICFILES_LOCATION = 'static'
STATIC_URL = "http://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)
STATICFILES_STORAGE = 'lindshop.utils.custom_storages.CachedS3BotoStorage'

My current Static Storage looks like this:
class CachedS3BotoStorage(S3BotoStorage):
    location = settings.STATICFILES_LOCATION

    def __init__(self, *args, **kwargs):
        super(CachedS3BotoStorage, self).__init__(*args, **kwargs)
        self.local_storage = get_storage_class(
            "compressor.storage.CompressorFileStorage")()

    def save(self, name, content):
        non_gzipped_file_content = content.file
        name = super(CachedS3BotoStorage, self).save(name, content)
        content.file = non_gzipped_file_content
        self.local_storage._save(name, content)
        return name

When I run python manage.py collectstatic it only syncs with the S3. It does not add the files to the local /static folder.


text:
Q: Relative URL containing just the querystring I have some links in a page which only need to change the querystring portion of the current URL.
E.g. the current page is:
http://demo.com/bigreport?page=13
and I want to link to
http://demo.com/bigreport?page=14
Can I use Next as a relative link for this?
I was surprised to find it works in Chrome. I've never seen it documented or mentioned anywhere, so I'm keen to know if anyone uses this, and if there is wider browser support.

A: Further research reveals that Next is a valid relative URL.
It's documented as part of WHATWG's URL spec
http://url.spec.whatwg.org/#relative-state
The new URL will inherit the base URL's scheme, host, port and path.
Tested to work on:

*

*Chrome

*IE 7

A: Next works because browsers interpret that as a relative URL. Similar to how linking images on your site might work  Relative urls work this way (link is relative to the current page), you don't need to use the full absolute URL.
Browsers have been supporting this for long long time. People might not be aware of it because browser automatically handles it.


text:
Q: How do I get the caption text of the jQuery to align with the image? I'm having a problem with carousel. I would like to make the caption the same width as the image but just now it is set to the same width as the inner item class.
I get the following effect:

Is there a way to set the caption so it is centred (and aligned with the image)?
My markup is:

Caption

Caption text here

Caption text here

  ‹
  ›

A: If I understand your question correctly
Why you don't use text-align:center;  for the caption and change the width to the image's width
.carousel-caption
{
    text-align:center;
    width:800px;
    /*If you are having aligning problems and the position is absolute or relative use left:some_number px or margin if not absolute */

}

I hope this can help :)


text:
Q: How might I return a reversed adaptor wrapping a container? I have a class which has-a deque which it uses as a stack (could be a vector, just happened to choose deque).
At any rate, I wish to allow consumers to iterate over the contents of the stack (something that std::stack cannot do). I am currently using push_back() to push items onto the stack, and hence if one iterates over the contents in forward ordering, one goes from bottom to the top of the stack.
I would prefer to expose things in reverse order, so that iterating over the stack using for (auto e: thestack) works in top-down fashion.
I found C++11 reverse range-based for-loop which shows a couple of solutions for reversing the iteration ordering for the new for-loop syntax (as well as range-based algorithms).
What is unclear to me is how to provide a simple mechanic for giving my users access to this automatically reversed deque.
e.g. without any real effort, I can simply allow const& access to the underlying deque:
  const std::deque<T> & GetStack() const { return m_stack; }

and consumers could be responsible for the reversing:
  for (auto e : reverse(m_toolstack.GetStack()))

Here, I am attempting to use the following solution for reverse:
template<class Fwd>
struct reverser_generic
{
    Fwd &fwd;
    reverser_generic(Fwd& fwd_): fwd(fwd_) {}
    typedef std::reverse_iterator<typename Fwd::iterator> reverse_iterator;
    reverse_iterator begin() { return reverse_iterator(std::end(fwd)); }
    reverse_iterator end() { return reverse_iterator(std::begin(fwd)); }
};

template<class Fwd>
struct reverser_special
{
    Fwd &fwd;
    reverser_special(Fwd& fwd) : fwd(fwd) { }
    auto begin() -> decltype(fwd.rbegin()) { return fwd.rbegin(); }
    auto end() -> decltype(fwd.rend()) { return fwd.rend(); }
};

template<class Fwd>
auto reverse_impl(Fwd& fwd, long) -> decltype(reverser_generic<Fwd>(fwd))
{
    return reverser_generic<Fwd>(fwd);
}

template<class Fwd>
auto reverse_impl(Fwd& fwd, int) -> decltype(fwd.rbegin(), reverser_special<Fwd>(fwd))
{
    return reverser_special<Fwd>(fwd);
}

template<class Fwd>
auto reverse(Fwd&& fwd) -> decltype(reverse_impl(fwd,int(0)))
{
    static_assert(!(std::is_rvalue_reference<Fwd&&>::value), "Cannot pass an rvalue reference to reverse()");
    return reverse_impl(fwd,int(0));
}

The above all compiles and runs correctly using VS2012 (thanks to Jive Dadson et. al. for that solution).
However, in my stack facade, I really want to simply always return the reverse of the underlying container, but I am unclear on how to do so in a sensible fashion:
auto GetContents() const -> decltype(reverse(m_stack)) { return reverse(m_stack); }

The above errors, indicating that m_stack is unknown.  this->m_stack is equally unknown.
How might I go about returning the "whatever it is that is the reverse of my member m_stack"?
Note, once that is answered, I also need "How do I return the const & of whatever is the decltype of reverse(m_stack)?

A: Is the declaration of GetContents before the declaration of m_stack?
Names in a late-specified return type must obey the same rules as names in the rest of the function signature, i.e. they cannot refer to class members that haven't been declared yet:
struct X
{
    auto f() -> decltype(m_x) { return m_x; }  // ERROR
    int m_x;
    auto g() -> decltype(m_x) { return m_x; }  // OK
};

To make it work, either use std::declval to refer to the type (which means you must update the signature of GetContents if you change the type of m_stack from std::deque to std::vector) or ensure m_stack has been declared before you refer to it.