text:
Q: Rename factors in a spineplot with R Is it possible to rename factor's in a spineplot? The names of my factors are to long, so they overlap.
Thanks for your advices!

A: Reading the help for spineplot, it is clear that you can pass the parameters yaxlabels and xaxlabels to control the vectors for annotation of the axes.
One useful function is abbreviate which will shorten character strings.
Combining this information with the spineplot example gives:
treatment <- factor(rep(c(1, 2), c(43, 41)), levels = c(1, 2),
    labels = c("placebo", "treated"))
improved <- factor(rep(c(1, 2, 3, 1, 2, 3), c(29, 7, 7, 13, 7, 21)),
    levels = c(1, 2, 3),
    labels = c("none", "some", "marked"))

spineplot(improved ~ treatment, yaxlabels=abbreviate(levels(improved), 2))

Not all of the plot functions in R have this type of parameter.  For a more general solution, it might be necessary to rename the factors before passing to a plot function.  You can access and modify factor names using the levels function:
levels(treatment) <- abbreviate(levels(treatment), 5)
plot(improved ~ treatment)


text:
Q: Toolbar - findViewById is null I have tried this:
Toolbar - findViewbyID returning null.
I'm getting a null pointer on "findViewById" even then.
themes.xml
<resources xmlns:android="http://schemas.android.com/apk/res/android">

<style name="Theme.Customtheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
    <item name="actionBarItemBackground">@drawable/selectable_background_customtheme</item>
    <item name="popupMenuStyle">@style/PopupMenu.Customtheme</item>
    <item name="dropDownListViewStyle">@style/DropDownListView.Customtheme</item>
    <item name="actionBarTabStyle">@style/ActionBarTabStyle.Customtheme</item>
    <item name="actionDropDownStyle">@style/DropDownNav.Customtheme</item>
    <item name="actionBarStyle">@style/ActionBar.Solid.Customtheme</item>
    <item name="actionModeBackground">@drawable/cab_background_top_customtheme</item>
    <item name="actionModeSplitBackground">@drawable/cab_background_bottom_customtheme</item>
    <item name="actionModeCloseButtonStyle">@style/ActionButton.CloseMode.Customtheme</item>
            <!-- Light.DarkActionBar specific -->
    <item name="actionBarWidgetTheme">@style/Theme.Customtheme.Widget</item>
    <item name="android:buttonStyle">@style/Theme.CustomTheme.Widget.Button</item>
    <item name="android:textViewStyle">@style/Theme.CustomeTheme.Widget.TextViewStyle</item>
    <item name="android:windowBackground">@drawable/appbackground</item>
    <item name="actionMenuTextColor">@color/orange</item>
    <item name="actionBarTabTextStyle">@style/TabStyle</item>
    <item name="windowActionBar">false</item>
</style>

<style name="TabStyle" parent="@style/Widget.AppCompat.Light.ActionBar.TabText.Inverse">
  <item name="android:textColor">@color/blue</item>
  <item name="android:textStyle">normal</item>
</style>

<style name="ActionBar.Solid.Customtheme" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
    <item name="background">@drawable/ab_solid_customtheme</item>
    <item name="backgroundStacked">@drawable/ab_stacked_solid_customtheme</item>
    <item name="backgroundSplit">@drawable/ab_bottom_solid_customtheme</item>
    <item name="progressBarStyle">@style/ProgressBar.Customtheme</item>
    <item name="titleTextStyle">@style/Theme.CustomTheme.WindowTitleTextStyle</item>
    <item name="android:icon">@drawable/movie</item>
</style>

<style name="Theme.CustomTheme.WindowTitleTextStyle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:paddingLeft">10dip</item>
    <item name="android:textColor">@color/orange</item>
</style>

<style name="ActionBar.Transparent.Customtheme" parent="@style/Widget.AppCompat.ActionBar">
    <item name="background">@drawable/ab_transparent_customtheme</item>
    <item name="progressBarStyle">@style/ProgressBar.Customtheme</item>
</style>

<style name="PopupMenu.Customtheme" parent="@style/Widget.AppCompat.PopupMenu">
    <item name="android:popupBackground">@color/white</item>
    <item name="android:actionMenuTextColor">@color/blue</item>
</style>

<style name="DropDownListView.Customtheme" parent="@style/Widget.AppCompat.ListView.DropDown">
    <item name="android:listSelector">@drawable/selectable_background_customtheme</item>
</style>

<style name="ActionBarTabStyle.Customtheme" parent="@style/Widget.AppCompat.ActionBar.TabView">
    <item name="background">@drawable/tab_indicator_ab_customtheme</item>
</style>

<style name="DropDownNav.Customtheme" parent="@style/Widget.AppCompat.Spinner.DropDown.ActionBar">
    <item name="background">@drawable/spinner_background_ab_customtheme</item>
    <item name="android:popupBackground">@drawable/menu_dropdown_panel_customtheme</item>
    <item name="android:dropDownSelector">@drawable/selectable_background_customtheme</item>
</style>

<style name="ProgressBar.Customtheme" parent="@style/Widget.AppCompat.ProgressBar.Horizontal">
    <item name="android:progressDrawable">@drawable/progress_horizontal_customtheme</item>
</style>

<style name="ActionButton.CloseMode.Customtheme" parent="@style/Widget.AppCompat.ActionButton.CloseMode">
    <item name="background">@drawable/btn_cab_done_customtheme</item>
</style>

<!-- this style is only referenced in a Light.DarkActionBar based theme -->
<style name="Theme.Customtheme.Widget" parent="@style/Theme.AppCompat">
    <item name="popupMenuStyle">@style/PopupMenu.Customtheme</item>
    <item name="dropDownListViewStyle">@style/DropDownListView.Customtheme</item>
    <item name="windowActionBar">false</item>
</style>

v14-themes.xml:
<resources>

<style name="Theme.Customtheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">

    <item name="android:actionBarItemBackground">@drawable/selectable_background_customtheme</item>
    <item name="android:popupMenuStyle">@style/PopupMenu.Customtheme</item>
    <item name="android:dropDownListViewStyle">@style/DropDownListView.Customtheme</item>
    <item name="android:actionBarTabStyle">@style/ActionBarTabStyle.Customtheme</item>
    <item name="android:actionDropDownStyle">@style/DropDownNav.Customtheme</item>
    <item name="android:actionBarStyle">@style/ActionBar.Solid.Customtheme</item>
    <item name="android:actionModeBackground">@drawable/cab_background_top_customtheme</item>
    <item name="android:actionModeSplitBackground">@drawable/cab_background_bottom_customtheme</item>
    <item name="android:actionModeCloseButtonStyle">@style/ActionButton.CloseMode.Customtheme</item>
    <!-- Light.DarkActionBar specific -->
    <item name="android:actionBarWidgetTheme">@style/Theme.Customtheme.Widget</item>
    <item name="android:buttonStyle">@style/Theme.CustomTheme.Widget.Button</item>
    <item name="android:textViewStyle">@style/Theme.CustomeTheme.Widget.TextViewStyle</item>
    <item name="android:windowBackground">@drawable/appbackground</item>
    <item name="android:actionMenuTextColor">@color/orange</item>
    <item name="@android:attr/actionBarTabTextStyle">@style/TabStyle</item>
    <item name="windowActionBar">false</item>

</style>

<style name="ActionBar.Solid.Customtheme" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
    <item name="android:background">@drawable/ab_solid_customtheme</item>
    <item name="android:backgroundStacked">@drawable/ab_stacked_solid_customtheme</item>
    <item name="android:backgroundSplit">@drawable/ab_bottom_solid_customtheme</item>
    <item name="android:progressBarStyle">@style/ProgressBar.Customtheme</item>
    <item name="android:titleTextStyle">@style/Theme.CustomTheme.WindowTitleTextStyle</item>
   <item name="android:icon">@drawable/movie</item>
</style>

<style name="ActionBar.Transparent.Customtheme" parent="@style/Widget.AppCompat.ActionBar">
    <item name="android:background">@drawable/ab_transparent_customtheme</item>
    <item name="android:progressBarStyle">@style/ProgressBar.Customtheme</item>
</style>

<style name="Theme.CustomTheme.WindowTitleTextStyle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:paddingLeft">10dip</item>
    <item name="android:textColor">@color/orange</item>
</style>

<!-- this style is only referenced in a Light.DarkActionBar based theme -->
<style name="Theme.Customtheme.Widget" parent="@style/Theme.AppCompat">
    <item name="android:popupMenuStyle">@style/PopupMenu.Customtheme</item>
    <item name="android:dropDownListViewStyle">@style/DropDownListView.Customtheme</item>
    <item name="windowActionBar">false</item>
</style>

v21-themes.xml:
<?xml version="1.0" encoding="utf-8"?>

    <item name="android:windowContentTransitions">true</item>
    <item name="android:windowAllowEnterTransitionOverlap">true</item>
    <item name="android:windowAllowReturnTransitionOverlap">true</item>
    <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
    <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
    <item name="android:windowActionModeOverlay">true</item>
    <item name="android:actionModeStyle">@style/MyTheme.ActionMode</item>
    <item name="windowActionBar">false</item>
</style>

<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="spinBars">true</item>
    <item name="color">@android:color/white</item>
</style>

<style name="MyTheme.ActionMode" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:colorPrimary">@color/blue</item>
    <item name="android:colorPrimaryDark">@color/blue</item>
    <item name="actionModeBackground">@color/blue</item>
    <item name="android:colorBackground">@color/blue</item>
</style>

styles.xml:
<?xml version="1.0" encoding="utf-8"?>

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:windowContentTransitions">true</item>
    <item name="android:windowAllowEnterTransitionOverlap">true</item>
    <item name="android:windowAllowReturnTransitionOverlap">true</item>
    <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
    <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
    <item name="android:windowActionModeOverlay">true</item>
    <item name="android:actionModeStyle">@style/MyTheme.ActionMode</item>
    <item name="windowActionBar">false</item>
</style>

<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="spinBars">true</item>
    <item name="color">@android:color/white</item>
</style>

<style name="MyTheme.ActionMode" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="actionModeBackground">@color/blue</item>
</style>

I'm not sure what's wrong!

A: In addition to disabling the default Action bar, before calling the findViewById(), the Activity's window must first be created with a call to setContentView(), not the reverse order!

A: To Enable Toolbar, you have to disable the default Action bar in your style by inheriting a parent Theme without Action Bar.
Something Like this
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/myPrimaryColor</item>
        <item name="colorPrimaryDark">@color/myPrimaryDarkColor</item>
        <item name="colorAccent">@color/myAccentColor</item>
        <item name="android:textColorPrimary">@color/myAccentColor</item>
        <item name="android:textColor">@color/myAccentColor</item>
        <item name="android:textColorSecondary">@color/myAccentColor</item>
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
        <item name="android:windowBackground">@color/myWindowBackground</item>
    </style>

After that you can find the Toolbar from your Resource ID.

redpajama_set_name: RedPajamaStackExchange


text:
Q: OrmLite Update() vs Save() When using OrmLite to add an entry into the database there seems to be two ways of doing it:
dbConn.Insert(customer);

and
dbConn.Save(customer);

When using Insert() the AutoIncrement ID field does not get updated, but when using Save() it does.
If you use:
dbConn.LastInsertId();

It will return the correct ID if Save() is used but the wrong ID if Insert() is used.
Why do these two methods exist?  Using Insert() will add an entry to the database with the correct ID, it is just not reflected in the POCO model.  It seems strange that there are no exceptions thrown and no indication of a problem, when you can end up using the wrong ID and get hard to track bugs if you are not aware of this.

A: It's already mentioned in the documentations:

Save and SaveAll will Insert if no record with Id exists, otherwise it Updates. Both take multiple items, optimized to perform a single read to check for existing records and are executed within a sinlge transaction.

For Insert operation, it's pretty straighforward, there's nothing special in that functions.
So, Use Insert when you know there's no duplicated key in your records, otherwise use save method.
If you want to retrieve the LastInsertId, with Insert method, you need to specify the [AutoIncrement] on your POCO.

UPDATE: When you set your IDbConnectionFactory using Singelton With Lazy< T > implementation, it seems the LastInsertId will not working. so just use lock or static implementation.


text:
Q: I need to run a progress bar using a time in a DLL C# It seems I need to use a timer in a separate thread, since a time is not working if i use a normal time.  So i did the following, however while it stops at the Invoke statement the progress bar does not change value!
public partial class LoadingForm : Form
{
    System.Threading.Timer t;

    public LoadingForm()
    {
        InitializeComponent();
    }

    private void LoadingForm_Load(object sender, EventArgs e)
    {
        progressBar.Value = 0;
        progressBar.Minimum = 0;
        progressBar.Maximum = 100;

        t = new System.Threading.Timer(TimerCallback, null, 0, 500);
    }

    private void TimerCallback(object e)
    {
        //time is here
        progressBar.Invoke(new Action(() => progressBar.Value++));
    }

    private void timerTick()
    {
        //this is what i need to do !!!!
        if (progressBar.Value == progressBar.Maximum) { progressBar.Value = 0; }
        progressBar.Value++;
    }
}

(if it works ideally I would want to be able to call timerTick() in the Invoke statement)


text:
Q: R: NA on mean for a numerical variable I am trying to determine some values based on cellular carrier. I have a main data frame that contains data from all carriers, and I have created 3 individual data frames from the main data frame by provider:
verizondf <- maindata[maindata$network == "Verizon",]
attdf <- maindata[maindata$network=="ATT",]
tmobiledf <- maindata[maindata$network=="TMobile",]

I want to get the average for one of the variables, "download", which is a numerical value.
On the verizondf data frame, it works fine:
> mean(verizondf$download)
[1] 462004.4

For the other 2, I get NA:
> mean(attdf$download)
[1] NA

I wondered if the data type had changed at some point, but I checked and it is still numeric:
> str(attdf$download)
 num [1:5516] 321585 50722 400085 287968 138301 ...

What could be causing this issue?

A: Others have pointed this out with their comments, I can give a "fuller" explanation here.
When you look at the help manual pages using ?mean you will get the description, including this info:

Usage
mean(x, ...)
## Default S3 method:
     mean(x, trim = 0, na.rm = FALSE, ...)

Looking under the "Arguments" section, you will see this:

na.rm
     a logical value indicating whether NA values should be stripped before the >    computation proceeds.

This tells you that the default for mean is to not strip out NA's, which will lead to a mean of NA if your data contains NA's.
If you want a numeric mean computed when you have NA values (and this is ok, given the fact you have NA's...something that is not always true!!!) you would use mean with the argument na.rm = TRUE.


text:
Q: Отрезать путь к файлу Всем привет,перейдем сразу к делу.
У нас есть строка:
String text = new String("C:\\home\\work.txt");

На выходе мне нужно сделать work
Как отрезать txt,я знаю:
text = text.substring(0 , text.indexOf(".txt"));
System.out.println(text);

На выходе получим C:\home\work
А как получить просто work,кстати название файла будет меняться,и директория тоже,может это вообще надо делать с помощью регулярок
Начало :
 String text = new String("C:\\home\\work.txt");
 Pattern pattern = Pattern.compile("C:\\s*");//Его нужно закончить!!))
 Matcher matcher = pattern.matcher(text);
 System.out.println(matcher);

Короче помогайте)
A: Предлагаю просто распарсить text и достать оттуда нужный тебе work.
Парсится как-то так:
String text = new String("C:\\home\\work.txt");
String[] pars = text.split("\\");
String work = pars[2]; // Что-то типа такого

И уже из этого массива можешь достать свой work
A: Велосипедисты, блин.
import org.apache.commons.io.FilenameUtils;
String path = "C:\\home\\work.txt";
String fileName = FilenameUtils.getBaseName(path);

A: String text = new String("C:\\home\\work.txt");
String[] pars = text.split("\\\\");
System.out.println(pars[pars.length-1]);//тут получили work.txt
String[] work = pars[pars.length-1].split("\\.");
System.out.println(work[0]);//а тут получили просто work

Это максимально подробно :)
Код не отобразился полностью, нужно добавить ещё слеши и тогда всё заработает, теперь должен работать!


text:
Q: Different ways of Creating Toast Notification in Windows store App I am able to create the toast in two ways (XML and Notification toolkit). What is the difference in a toast that is created and which is efficient?

A: They are equivalent. The toolkit provides wrapper functions that generate the XML. This is easier and less error prone, but ultimately both send the same XML toast data.


text:
Q: python: unpacking an array of dictionaries in a matrix I am relatively new to python, and a piece of existing code has created an object akin to per below. This is part of a legacy piece of code. i can unfortunately not change it. The code creates many objects that look like the following format:
[[{'a': 2,'b': 3}],[{'a': 1,'c': 3}],[{'c': 2,'d': 4}]]

I am trying to create transform this object into a matrix or numpy arrays. In this specific example - it would have three rows (1,2,3) and 4 columns (a,b,c,d), with the dictionary values inserted in the cells. (I have inserted how this matrix would look as a dinky toy example. However - i am not looking to recreate the table from scratch, but i am looking for code that translate the object per above in a matrix format).
I am struggling to find a fast and easy way to do this. Any tips or advice much appreciated.
   a  b  c  d
1  2  3  0  0
2  1  0  3  0
3  0  2  0  4

A: Simpy use:
import pandas as pd
df = pd.DataFrame.from_items([('1', [2, 3, 0,0]), ('2', [1, 0, 3,0]),('3', [0, 2, 0,4])], orient='index', columns=['a', 'b', 'c','d'])

arr = df.values

You can then reference it like a normal numpy array:
print(arr[0,:])

A: I suspect you are focusing on the fast and easy, when you need to address the how first.  This isn't the normal input format for np.array or `pandas.  So let's focus on that.
It's a list of lists; suggesting a 2d array.  But each sublist contains one dictionary, not a list of values.
In [633]: dd=[[{'a': 2,'b': 3}],[{'a': 1,'c': 3}],[{'c': 2,'d': 4}]]
In [634]: dd[0]
Out[634]: [{'b': 3, 'a': 2}]

So let's define a function that converts a dictionary into a list of numbers.  We can address the question of where a,b,c,d labels come from, and whether you need to collect them from dd or not, later.
In [635]: dd[0][0]
Out[635]: {'b': 3, 'a': 2}
In [636]: def mk_row(adict):
    return [adict.get(k,0) for k in ['a','b','c','d']]
   .....:
In [637]: mk_row(dd[0][0])
Out[637]: [2, 3, 0, 0]

So now we just need to apply the function to each sublist
In [638]: [mk_row(d[0]) for d in dd]
Out[638]: [[2, 3, 0, 0], [1, 0, 3, 0], [0, 0, 2, 4]]

This is the kind of list that @Colin fed to pandas.  It can also be given to np.array:
In [639]: np.array([mk_row(d[0]) for d in dd])
Out[639]:
array([[2, 3, 0, 0],
       [1, 0, 3, 0],
       [0, 0, 2, 4]])


text:
Q: I'm receiving duplicate messages in my clustered node.js/socket.io/redis pub/sub application I'm using Node.js, Socket.io with Redisstore, Cluster from the Socket.io guys, and Redis.
I've have a pub/sub application that works well on just one Node.js node. But, when it comes under heavy load is maxes out just one core of the server since Node.js isn't written for multi-core machines.
As you can see below, I'm now using the Cluster module from Learnboost, the same people who make Socket.io.
But, when I fire up 4 worker processes, each browser client that comes in and subscribes gets 4 copies of each message that is published in Redis.  If there are are three worker processes, there are three copies.
I'm guessing I need to move the redis pub/sub functionality to the cluster.js file somehow.
Cluster.js
var cluster = require('./node_modules/cluster');

cluster('./app')
  .set('workers', 4)
  .use(cluster.logger('logs'))
  .use(cluster.stats())
  .use(cluster.pidfiles('pids'))
  .use(cluster.cli())
  .use(cluster.repl(8888))
  .listen(8000);

App.js
redis = require('redis'),
sys = require('sys');

var rc = redis.createClient();

var path = require('path')
  , connect = require('connect')
  , app = connect.createServer(connect.static(path.join(__dirname, '../')));

// require the new redis store
var sio = require('socket.io')
  , RedisStore = sio.RedisStore
  , io = sio.listen(app);

io.set('store', new RedisStore);io.sockets.on('connection', function(socket) {
    sys.log('ShowControl -- Socket connected: ' + socket.id);

    socket.on('channel', function(ch) {
        socket.join(ch)
        sys.log('ShowControl -- ' + socket.id + ' joined channel: ' + ch);
    });

    socket.on('disconnect', function() {
        console.log('ShowControll -- Socket disconnected: ' + socket.id);
    });
});

rc.psubscribe('showcontrol_*');

rc.on('pmessage', function(pat, ch, msg) {
    io.sockets.in(ch).emit('show_event', msg);
    sys.log('ShowControl -- Publish sent to channel: ' + ch);
});

// cluster compatiblity
if (!module.parent) {
  app.listen(process.argv[2] || 8081);
  console.log('Listening on ', app.address());
} else {
  module.exports = app;
}

client.html
<script src="http://localhost:8000/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script>
    var socket = io.connect('localhost:8000');
    socket.emit('channel', 'showcontrol_106');
    socket.on('show_event', function (msg) {
        console.log(msg);
        $("body").append('<br/>' + msg);
    });
</script>

A: I've been battling with cluster and socket.io. Every time I use cluster function (I use the built in Nodejs cluster though) I get alot of performance problems and issues with socket.io.
While trying to research this, I've been digging around the bug reports and similar on the socket.io git and anyone using clusters or external load balancers to their servers seems to have problems with socket.io.
It seems to produce the problem "client not handshaken client should reconnect" which you will see if you increase the verbose logging. This appear alot whenever socket.io runs in a cluster so I think it reverts back to this. I.E the client gets connected to randomized instance in the socket.io cluster every time it does a new connection (it does several http/socket/flash connections when authorizing and more all the time later when polling for new data).
For now I've reverted back to only using 1 socket.io process at a time, this might be a bug but could also be a shortcoming of how socket.io is built.
Added: My way of solving this in the future will be to assign a unique port to each socket.io instance inside the cluster and then cache port selection on client side.

A: Turns out this isn't a problem with Node.js/Socket.io, I was just going about it the completely wrong way.
Not only was I publishing into the Redis server from outside the Node/Socket stack, I was still directly subscribed to the Redis channel.  On both ends of the pub/sub situation I was bypassing the "Socket.io cluster with Redis Store on the back end" goodness.
So, I created a little app (with Node.js/Socket.io/Express) that took messages from my Rails app and 'announced' them into a Socket.io room using the socket.io-announce module.  Now, by using Socket.io routing magic, each node worker would only get and send messages to browsers connected to them directly.  In other words, no more duplicate messages since both the pub and sub happened within the Node.js/Socket.io stack.
After I get my code cleaned up I'll put an example up on a github somewhere.


text:
Q: Tabular envionment in ConTeXt guys is there any way to setup a tabular environment in ConteXt. What i need is the equivalent of \AtBeginEnvironment{tabular} (latex command) but in ConTeXt. The goal is to use opentype features like tabular, proportional numbers only in tables.
More info here: tabular numbers in tables, proportional in text

A: Here is a complete example showing how to having old style numbers in the running text and proportional numbers in tables:
\definefontfeature[default][default][onum=yes]
\definefontfeature[lnum][onum=no, lnum=yes]

\setupbodyfont[modern]

\starttext
12345

\startTABLE[style=\addff{lnum}]
  \NC 12345 \NC 67890 \NC \NR
\stopTABLE

\stoptext


text:
Q: Rspec + Capybara : How to click on alert box I have gone through the post of capybara + click on alert box but nothing seems to be work. Following is my scenario:
Scenario: When I click update button An alert box appears which contains "OK" and "Cancel" button. Click on "Ok" then new form appears.

*

*I am writing request specs i.e. using rspec and capybara. Main problem is to click on the alert box: Following is my code:
 context "update" do
   before(:all) do
     Capybara.current_driver = :selenium
   end
   after(:all) do
     Capybara.use_default_driver
   end

   it "update user to trainer" do
     click_button('Search')
     sleep 3
     page.evaluate_script('data-confirm = function() { return true; }')
     page.click('OK')
     click_button('Upgrade')
   end
 end

But executing script gives me following error:

Failure/Error: page.evaluate_script('data-confirm = function() { return true; }') Selenium::WebDriver::Error::UnexpectedJavascriptError: invalid assignment left-hand side # ./spec/requests/user_upgrades_spec.rb:30

*For the second example i.e.

page.driver.browser.switch_to.alert.accept

My code :
 context "update" do
   before(:all) do
     Capybara.current_driver = :selenium
   end
   after(:all) do
     Capybara.use_default_driver
   end
   it "update user to trainer" do
     click_button('Search')
     sleep 3
     click_button('Upgrade')
     page.driver.browser.switch_to.alert.accept
   end
 end

I get error:

Failure/Error: page.driver.browser.switch_to.alert.accept Selenium::WebDriver::Error::UnhandledError:

Please let me know how to proceed further

A: I know this is old but this now works in poltergeist too:
page.accept_alert

A: You can click on an alert box like this:
page.driver.browser.switch_to.alert.accept

A: Updated answer here, since the options above seem to have all been deprecated.
Capybara::Session#accept_alert seems to be the best way to accomplish this now, where the action that will trigger the alert should be passed in a block.
http://www.rubydoc.info/github/jnicklas/capybara/Capybara/Session:accept_alert
e.g.:
page.accept_alert 'Alert text here' do
    click_button('Search')
end

A: page.accept_alert

worked for me using Selenium. Other drivers will probably have their own syntax.
As Jillian Foley mentioned, it seems that other answers have been deprecated.

A: For WebKit:
page.accept_confirm { click_button "Upgrade" }

For Selenium:
page.driver.browser.switch_to.alert.accept

A: Try this line if you want to click on the ok button of the alert box:
page.evaluate_script('window.confirm = function() { return true; }')

Don't forget to mark your test with the javascript flag
it "update user to trainer", js: true do
    ...
end

and enable Capybara.javascript_driver with :webkit or :selenium in your spec_helper file


text:
Q: Let $U\subset\mathbb{C}$ an open set and $f$ a holomorphic function in $U-\{z_0\}, z_0\in U$. I want to prove that $\int_{\partial R}f(z)dz=0$, where $R$ is any rectangle in $U$.
I tried to use Goursat's Theorem, but I can't conclude cause $f$ is not holomorphic in $z_0$. We have as hypotheses

*

*f is holomorphic in $U-\{z_0\}$

*$\lim_{z\to z_0}(z-z_0)f(z)=0$
Any hint?

A: Note that $f$ is bounded in $U$ by the second condition. Say $|f| < M. $Split the rectangle R into many rectangles whose $R_0, R_1, R_2 \dots$ etc. Let $R_0$ be the rectangle containing $z_0$. While splitting $R$ we can choose to make $R_0$ as small as possible.
Note that $\int_R f = \sum_i \int_{R_i} f$. However the integrals all vanish except for $i>0$ as $f$ is holomorphic in $R_1, R_2$ etc. Also, $\left |\int_{R_0}f \right|$ can be bounded by arbitrarily small $\epsilon$ through the ML inequality. So, we can see that $\int_R f = 0$


text:
Q: Spring JdbcTemplate deleting with query() method in Oracle I'm using JdbcTemplate from Spring to query the Oracle DB and return the results. However, if I run the query() method with a DELETE statement, it replies with an "ORA-00900: invalid SQL statement" error, but the entries are deleted nevertheless.
Is this a Spring bug or an Oracle bug, and how can I fix it? query() should not be able to modify.

A: You need to use the JdbcTemplate.update method. It is meant for execution a single DML operator(insert/update/delete)


text:
Q: How do you find the limit of $\lim_{x \to 0} \frac{1-e^{6x}}{1-e^{3x}}$ I would like to know how to calculate the limit for:
$$\lim_{x \to 0} \frac{1-e^{6x}}{1-e^{3x}}$$
I tried by factoring by $$\frac{1-e^{3x}}{1-e^{3x}}$$
I'm not sure if this is correct.
Am I doing something wrong?

A: $$1-e^{6x}=(1-e^{3x})(1+e^{3x})$$
so:
$$\lim_{x\to 0}\frac{1-e^{6x}}{1-e^{3x}}= \lim_{x\to0} (1+e^{3x})=2$$

A: $$\lim_{x \to 0}{\frac{1-e^{6x}}{1-e^{3x}}}=\lim_{x \to 0}{\frac{(1-e^{3x})(1+e^{3x})}{1-e^{3x}}}=1+1=2$$

A: Use L'Hôpital's rule
$$\frac{d(1-e^{6x})}{dx}=-6e^{6x}$$
$$\frac{d(1-e^{3x})}{dx} = -3e^{3x}$$
$$\lim_{x\to 0}\frac{-6e^{6x}}{3e^{3x}} = 2$$

A: Hint: $$1-e^{6x}=\left(1-e^{3x}\right)\left(1+e^{3x}\right)$$

A: A fancy way to do it (that is indeed fancy in this case but it's the only way to get out alive from a lot of other cases):
$$1 - e^{3x} \sim -3x$$
$$1 - e^{6x} \sim -6x$$
since you can substitute, you get
$$\frac{-6x}{-3x} = 2$$


text:
Q: Limits of Expectations I've been fighting with this homework problem for a while now, and I can't quite see the light.  The problem is as follows,

Assume random variable $X \ge 0$, but do NOT assume that $\mathbb{E}\left[\frac1{X}\right] < \infty$.  Show that $$\lim_{y \to 0^+}\left(y \, \mathbb{E}\left[\frac{1}{X} ; X > y\right]\right) = 0$$

After some thinking, I've found that I can bound
$$
\mathbb{E}[1/X;X>y] =
\int_y^{\infty}\frac1{x}\mathrm dP(x) \le
\int_y^{\infty}\frac1{y}\mathrm dP(x)
$$
since $\frac1{y} = \sup\limits_{x \in (y, \infty)} \frac1{x}$ resulting in
$$
\lim_{y \to 0^+} y \mathbb{E}[1/X; X>y] \le
\lim_{y \to 0^+} y \int_y^{\infty}\frac1{y}\mathrm dP(x) = P[X>0]\le1
$$
Of course, $1 \not= 0$.  I'm not really sure how to proceed...
EDIT: $\mathbb{E}[1/X;X>y]$ is defined to be $\int_y^{\infty} \frac{1}{x}\mathrm dP(x)$.  This is the notation used in Durret's Probability: Theory and Examples.  It is NOT a conditional expectation, but rather a specifier of what set is being integrated over.
EDIT: Changed $\lim_{y \rightarrow 0^-}$ to $\lim_{y \rightarrow 0^+}$; this was a typo.

A: Hint(s) For every positive $y$, let $Z_y=(y/X)\mathbf{1}(y/X<1)$. You want to prove that $E(Z_y)\to0$ when $y\to0^+$.
It happens that $0\le Z_y<1$ with full probability, for every positive $y$, and that $Z_y\to0$ when $y\to0^+$ with full probability. (Of course you should check this.)
Now, your goal is to find a condition on a given family of nonnegative random variables $(T_y)$ that ensures that $$\lim\limits_{y\to0^+}E(T_y)=E\left(\lim\limits_{y\to0^+}T_y\right)$$ and to check that your family $(Z_y)$ fulfills this condition.
There should not exist so many conditions of this ilk in your textbook...

A: Hint: For any $k > 1$, $\int_y^\infty \frac{y}{x} \ dP(x) \le \int_y^{ky}\  dP(x) + \int_{ky}^\infty \frac{1}{k} \ dP(x) \le \ldots$


text:
Q: How to convert list of TextSpans to a single text? For example I have a list of TextSpan:
List<TextSpan> listTextSpan = [TextSpan(text: "Hello"), TextSpan(text: "World")];
then:
AutoSizeText.rich(
 TextSpan(
  children: listTextSpan,
)),

So I want to make the list of TextSpan as a single text, That I'll be able to return
AutoSizeText.rich(
 TextSpan(
  text: singleText,
)),

A: You can use the fold method in order to combine every item on a list into a single value, the shape of the fold method looks like this:
var result = list.fold(initial, (previous, current) => result);

So in your case, if you just want to get a string of the text of every TextSpan, you would do it like this:
String singleText = listTextSpan.fold(
  '',
  (prev, curr) => '$prev ${curr.text!}');

the initial value is an empty string and you take the previous value, which is the current string, and add to it a space and the text of the current TextSpan, also note that this will throw an error if one of your text spans does not have a text property, in order to avoid this, you must replace curr.text! to curr.text ?? 'whatever you want'
If you still have issues understanding how the fold method works, you can check the documentation


text:
Q: Sequentiality in a beamer: left and right part in a column and after again left I would like to divide the beamer in two parts. In the left part, I would like to have text. In the right, an image.
I would like that when I show the beamer appears a part of the text of the left and the image, and after (using pause), the rest of the text of the left part.
I am using this code, but it does not work. It appears first the first part of the text, after the second part, and last the image. I would like to have the following order: the first part of the text of the left and the image, and later the second part.
This is the code I trying to do:
\documentclass{beamer}

\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\begin{document}
    \begin{frame}{My Frame}
   \begin{columns}
% Column 1
\begin{column}{0.55\textwidth}
\begin{itemize}

\item First part of the text
\end{itemize}
    \pause
    \begin{itemize}
          \item Second part of the text

    \end{itemize}

\end{column}
% Column 2
\begin{column}{0.55\textwidth}
    \begin{figure}
    \centering
    \caption{Title}
        \includegraphics[width=0.8\textwidth]{Figure.PNG}
    \end{figure}
\end{column}
\end{columns}
    \end{frame}

\end{document}

Please, if you do not understand my problem, do not hesitate asking.

A: \pause is a very crude command. You'll get more flexibility if you use explicit beamer overlays stating on which slides your elements should be visible, e.g. <3-> will mean that this item is shown from the 3rd slide on until the end of the frame:
\documentclass{beamer}

\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\begin{document}

\begin{frame}
  \frametitle{My Frame}

  \begin{columns}

    % Column 1
    \begin{column}{0.55\textwidth}
      \begin{itemize}
        \item<1-> First part of the text
        \item<3-> Second part of the text
      \end{itemize}
    \end{column}

    % Column 2
    \begin{column}{0.55\textwidth}
      \begin{figure}
        \begin{uncoverenv}<2->
          \caption{Title}
          \includegraphics[width=0.8\textwidth]{example-image}
        \end{uncoverenv}
      \end{figure}
    \end{column}

  \end{columns}

\end{frame}

\end{document}


text:
Q: How can I store least used table files to a slower drive? Is it possible to separate the least used and most frequently used data files on to separate disks when using InnoDB?

A: What you are asking is not really an automatic feature in MySQL 5.6, I could be wrong.
Notwithstanding, you can set it up manually.
Given the following information

*

*Your datadir is /var/lib/mysql

*You data is in the Database mydb

*You have this InnoDB table

Table Description
CREATE TABLE mytable
(
   if int not null autop_increment,
   ...
   primary key (id)
) ENGINE=InnoDB;

*

*You have a data folder to hold the least often used tables called /data/least

*Make sure /data/least is owned by mysql  by running chown -R mysql:mysql /data/least
Here is what you must do manually
USE mydb
CREATE TABLE mytable_least
(
   if int not null autop_increment,
   ...
   primary key (id)
) ENGINE=InnoDB DATA DIRECTORY='/data/least';
INSERT INTO mytable_least SELECT * FROM mytable;
ALTER TABLE mytable RENAME mytable_trash;
ALTER TABLE mytable_least RENAME mytable;

How was mydb.mytable manifested before the change ?

*

*The .frm file is /var/lib/mysql/mydb/mytable.frm

*The .ibd file is /var/lib/mysql/mydb/mytable.ibd
How is mydb.mytable now manifested ?

*

*The .frm file is /var/lib/mysql/mydb/mytable.frm

*The .ibd file is /data/least/mytable.ibd
You should test this out with a blank InnoDB table and make sure.
Give it a Try !!!

A: Yes, you can separate tables into individual files and spread those files across different disks.  One example of documentation in MySQL (in this case for 5.7) is:
https://dev.mysql.com/doc/refman/5.7/en/innodb-multiple-tablespaces.html
A partial quote says: "This mode is controlled by the innodb_file_per_table configuration option, and is the default in MySQL 5.6.6 and higher."
Spreading the load can be useful for many applications.  (Using slower disks is really only for economic reasons of course.)


text:
Q: Graphical understanding of the convolution of discrete distributions. I am studying convolution and trying to get a visual sense of the process. From the wikipedia page I understand what 2 continuous gaussian or 2 uniform distributions will produced when convolved, but I'm having a hard time determine what discrete distributions will look like when convolved. What does the convolution of various discrete distributions look like graphically? Specifically, I'm trying to understand what the histograms of 2 discrete normal and uniform distributions would look like when convolve. Thanks in advance for the help.

A: It will change almost nothing. You will get the same picture that you got for the continuous case. The idea is the same (shift, multiply,+sum). In the discrete case you have summation instead of integrals. The area under a curve is in the discrete case just the summation of the multiplication of some numbers. Simply same story.

A: Perhaps you should see some animation to better understand convolution:
See the continuous first:
http://www-rohan.sdsu.edu/~jiracek/DAGSAW/4.2.html
Then see the discrete:
http://www-rohan.sdsu.edu/~jiracek/DAGSAW/4.3.html
In both you have to click on "play" to let the video play by itself.
and below:
https://www.youtube.com/watch?v=yyTu0SXeW1M


text:
Q: Express API with JWT returns "Unauthorized: Invalid Algorithm error" I've written a simple React app, following the instructions of a slightly out of date tutorial that is meant to display a list of contacts in the sidebar with individual contact data displayed in an index component but only if you have been authenticated by logging into an Auth0 component and have a JSON Web Token kept in local storage. I have confirmed that I am logged in and have the token. Everything up to this point is working fine.
The problem begins when I click on a contact in the sidebar to view that contact's data, which comes down from a pretty basic API set up with Express. I've been using Postman to troubleshoot since the only error I get from app is "401: Unauthorized"
When I hit my endpoint, suppling an Authorization header with "Bearer [JWT_VALUE_HERE]" Postman responds with "UnauthorizedError: invalid algorithm"
The full output
UnauthorizedError: invalid algorithm
                at /Users/Arkham/Documents/Web/eldrac/react-auth-server/node_modules/express-jwt/lib/index.js:102:22
                at /Users/Arkham/Documents/Web/eldrac/react-auth-server/node_modules/jsonwebtoken/verify.js:27:18
                at _combinedTickCallback (internal/process/next_tick.js:95:7)
                at process._tickCallback (internal/process/next_tick.js:161:9)

I've done a bit of googling and tweaked my Auth0 client settings, specifically the Algorithm settings but no matter what I set it to (my options are RS256 and HS256), it doesn't seem to make a difference. I'm dying to get past this.
I use Superagent to make my request
getContact: (url) => {
    return new Promise((resolve, reject) => {
      request
        .get(url)
        .set('Authorization', 'Bearer ' + AuthStore.getJwt())
        .end((err, response) => {
          if (err) reject(err);
          resolve(JSON.parse(response.text));
        })
    });
  }

Which seems to be working. I have confirmed that the url is correct and that AuthStore.getJwt() are supplying the correct parameters.

A: Your question does not provide much information necessary to diagnose the issue - First of all, you should be sending a JWT Access token to the API, not your Id Token.
Upfront questions:

*

*Do you have an API defined in the Auth0 Dashboard?

*When you authenticate, are you using an audience parameter?  It is
likely that the Access Token is using RS256. Remember for an access
token and Resource API, it is the API that controls the algorithm,
not the Client.

*What algorithm is your API using to verify the token?

*Presumably, the url in your code snippet is something like
http://localhost:3001/myendpoint?
Take your token, and paste it at https://jwt.io to see what the algorithm used is. Compare that with what is being used to verify the token.
Shall update my answer here as you give more information - please use comments section for this answer.


text:
Q: JPA join tables through query I have strange problem. I want to create database like this:
One student can has a lot of subjects. Student has one evaluation for one subject. So I have
class student with ID, Name, Surname and A_I id, like:
@Id
@GeneratedValue
long id_student;

In subject class I have:
    @Id
    @GeneratedValue
    long id_subject;
    String name;
double graduate

I have third class, named StudentWithGraduate:
@Id
@GeneratedValue
long id;
double evaluation;
@OneToOne
Student student;
@OneToOne
Subject subject;

I think I could do it better, but I don't know how. But it isn't a main problem. This, what I write up is working, but I want to do some joins in query like:
Vector<Object[]>  v = (Vector<Object[]>) em.createQuery(
"select p.name, o.graduate from Student s
left join StudentWithGraduate o on s.id_student=o.student
left join Subject p on p.id_subject=o.subject where
s.surname='"+name+"'").getResultList();

And it throw an error:
Exception Description: Object comparisons can only be used with OneToOneMappings.  Other mapping comparisons must be done through query keys or direct attribute level comparisons.
How can I change this DB scheme or change that query?
Sorry for my english.
PS. When I was doing research I found @joinTables, but I don't know how to use it..

A: You need a short introduction in JPQL, but I will try to quickly explain some missing parts:
In a JPQL query you do not write which are the JOIN conditions (i.e the ON expresions), and instead you navigate through your Entity Graph, beginning with an entity (below I begin with the StudentWithGraduate entity):
SELECT p.name, o.graduate FROM StudentWithGraduate o
    LEFT JOIN o.student s
    LEFT JOIN o.subject p
    WHERE s.surname=:name

The ":name" is called a named parameter, which helps you agains SQL injections. In order to set a value for it, you write the following:
Query query = em.createQuery(aboveQuery);
query.setParameter("name", parameterValue);
//....the rest of parameters + getResultList();


text:
Q: Does Apple allow custom versions of its own system fonts? I would like to modify a couple fonts already available on iOS -- for instance, Helvetica Neue -- to use a different line height, and then include these modified fonts in my application bundle. Nevermind why -- let's just say I need to use them in a UITextView, so modifying the appearance with CSS is impossible.
Would Apple reject an app for bundling a modified version of one of these fonts? Would it violate copyright in some way, or perhaps an Apple guideline for developers?
This is not a programming question per se, so I hope no one is offended that I have asked it here -- I did not know of a better place in the StackExchange universe.

A: It would be a copyright violation.


text:
Q: Why does Laravel Paginator not work properly on front-end? I'm working with a Laravel system, and i'm using the Paginator. This functionality works perfectly, but in front-end, happens a conflit that i don't know how to fix it. When i resize to mobile phone mode (toggle device toolbar), the pagination exceed the table that i create. Like the image below.

I tried centering this pagination together in the table. I put a simple example of my code in bootply, but I only have a button to simulate the pagination. In Laravel, I use this code to create pagination.

                {{ $prospect->appends($data)->links() }}

Can anyone help me fix this? Possibly adjusting the pagination with table and use the bootstrap 4 turning into responsive mode? What causes this problem?

A: You can use onEachSide() to limit the rendering.
$prosect->appends($data)->onEachSide(3)->links();


text:
Q: Big Data Performance Anyone know which occupies less memory and less CPU?
Option 1: binary save several images in data: base64 within several html tags.
Option 2: binary save several images in data: base64 in a javascript array.
Not if the javascript engine will consume more memory or not the same html tag in the subject of the DOM and everything.
I would use HTML5 Storage but is still very new, the normal versions of firefox and chrome does not support them as I know, only the last.
Anyone know?


text:
Q: Android studio automatically open's documentation view I don't know if it is bug or kind of setting, but it is very annoying while typing value i.e.   android:layout_gravity="", it opens hints with dropdown, and after a while the documentation view gets opened and hides the dropdown with hints.

I checked that no button is suspended or anything like that. I use Ubuntu 14.04.

A: Note that this functionality has been moved recently. It's now in:

Android Studio -> Preferences -> Editor -> General -> Other.

Uncheck "quick documentation on mouse move".

A: Studio 3.4.2, somehow had setting checked, uncheck it.
File -> Settings -> Editor -> General -> Code Completion.

Cheers

A:
This the only correct answer as far i know because i sorted out this way only. Just click on Help>find Action>auto(in the search box)> and uncheck the checkbox in the image shown

A: For Android Studio 4.x ~ Arctic Fox | 2020.3.1
Preferences > Editor > Code Editing > Quick Documentation > Show quick documentation on mouse move: unchecked

A: Follow the simple steps to remove open Documentation by cursor move :

Android Studio -> File -> Setting -> Editor -> General

Right side of the screen go to Others :

*

*Uncheck checkBox show quick documentation of mouse move & Apply.

A: Preferences > Editor > General > CodeCompletion > uncheck Auto popup feature

A: Strange, because I've not changed anything with AS from months and there was no such behavior before. There's solution:

A: I found out that I don't want to disable the documentation.
Instead, I set the window to be 'Opened as Popup',

This displays the documentation aside to the cursor and autocloses it automatically.

Surely I've set it before as a 'Tool Window' to see the full content and then I forgot to set it back.


text:
Q: Import Data from Text File into Excel 2019 When attempting to convert from TXT to excel like below inside Excel then I can't get correctly output.  I have tried it with different delimiter. but no luck.
I want to put the text in separate columns in Excel
Input :

Desired Output :

I am getting a preview like below.

thanks,

A: I suggest you use the import wizard in Excel, located under the Get & Transform Data section on the Data tab:

From there you have a wizard with preview capabilities that will show you a preliminary output based on your selections:

After pressing Load you'll have your data successfully imported:

I hope it helps :)


text:
Q: Training a simple model in Tensorflow GPU slower than CPU I have set up a simple linear regression problem in Tensorflow, and have created simple conda environments using Tensorflow CPU and GPU both in 1.13.1 (using CUDA 10.0 in the backend on an NVIDIA Quadro P600).
However, it looks like the GPU environment always takes longer time than the CPU environment. The code I'm running is below.
import time
import warnings
import numpy as np
import scipy

import tensorflow as tf
import tensorflow_probability as tfp

from tensorflow_probability import edward2 as ed
from tensorflow.python.ops import control_flow_ops
from tensorflow_probability import distributions as tfd

# Handy snippet to reset the global graph and global session.
def reset_g():
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        tf.reset_default_graph()
        try:
            sess.close()
        except:
            pass

N = 35000
inttest = np.ones(N).reshape(N, 1)
stddev_raw = 0.09

true_int = 1.
true_b1 = 0.15
true_b2 = 0.7

np.random.seed(69)

X1 = (np.atleast_2d(np.linspace(
    0., 2., num=N)).T).astype(np.float64)
X2 = (np.atleast_2d(np.linspace(
    2., 1., num=N)).T).astype(np.float64)
Ytest = true_int + (true_b1*X1) + (true_b2*X2) + \
    np.random.normal(size=N, scale=stddev_raw).reshape(N, 1)

Ytest = Ytest.reshape(N, )
X1 = X1.reshape(N, )
X2 = X2.reshape(N, )

reset_g()

# Create data and param
model_X1 = tf.placeholder(dtype=tf.float64, shape=[N, ])
model_X2 = tf.placeholder(dtype=tf.float64, shape=[N, ])
model_Y = tf.placeholder(dtype=tf.float64, shape=[N, ])

alpha = tf.get_variable(shape=[1], name='alpha', dtype=tf.float64)
# these two params need shape of one if using trainable distro
beta1 = tf.get_variable(shape=[1], name='beta1', dtype=tf.float64)
beta2 = tf.get_variable(shape=[1], name='beta2', dtype=tf.float64)

# Yhat
tf_pred = (tf.multiply(model_X1, beta1) + tf.multiply(model_X2, beta2) + alpha)

# # Make difference of squares
# resid = tf.square(model_Y - tf_pred)
# loss = tf.reduce_sum(resid)

# # Make a Likelihood function based on simple stuff
stddev = tf.square(tf.get_variable(shape=[1],
                                    name='stddev', dtype=tf.float64))
covar = tfd.Normal(loc=model_Y, scale=stddev)
loss = -1.0*tf.reduce_sum(covar.log_prob(tf_pred))

# Trainer
lr=0.005
N_ITER = 20000

opt = tf.train.AdamOptimizer(lr, beta1=0.95, beta2=0.95)
train = opt.minimize(loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    start = time.time()
    for step in range(N_ITER):
        out_l, out_b1, out_b2, out_a, laws = sess.run([train, beta1, beta2, alpha, loss],
                                                  feed_dict={model_X1: X1,
                                                             model_X2: X2,
                                                             model_Y: Ytest})

        if step % 500 == 0:
            print('Step: {s}, loss = {l}, alpha = {a:.3f}, beta1 = {b1:.3f}, beta2 = {b2:.3f}'.format(
                s=step, l=laws, a=out_a[0], b1=out_b1[0], b2=out_b2[0]))
    print(f"True: alpha = {true_int}, beta1 = {true_b1}, beta2 = {true_b2}")
    end = time.time()
    print(end-start)

Here are some outputs printed if they're any indicative of what's happening:
For the CPU run:
Colocations handled automatically by placer.
2019-04-18 09:00:56.329669: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2019-04-18 09:00:56.351151: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2904000000 Hz
2019-04-18 09:00:56.351672: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x558fefe604c0 executing computations on platform Host. Devices:
2019-04-18 09:00:56.351698: I tensorflow/compiler/xla/service/service.cc:158]   StreamExecutor device (0): <undefined>, <undefined>

For the GPU run:
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
W0418 09:03:21.674947 139956864096064 deprecation.py:506] From /home/sadatnfs/.conda/envs/tf_gpu/lib/python3.6/site-packages/tensorflow/python/training/slot_creator.py:187: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
2019-04-18 09:03:21.712913: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2019-04-18 09:03:21.717598: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcuda.so.1
2019-04-18 09:03:21.951277: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1009] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2019-04-18 09:03:21.952212: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x55e583bc4480 executing computations on platform CUDA. Devices:
2019-04-18 09:03:21.952225: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): Quadro P600, Compute Capability 6.1
2019-04-18 09:03:21.971218: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2904000000 Hz
2019-04-18 09:03:21.971816: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x55e58577f290 executing computations on platform Host. Devices:
2019-04-18 09:03:21.971842: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): <undefined>, <undefined>
2019-04-18 09:03:21.972102: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1551] Found device 0 with properties:
name: Quadro P600 major: 6 minor: 1 memoryClockRate(GHz): 1.5565
pciBusID: 0000:01:00.0
totalMemory: 1.95GiB freeMemory: 1.91GiB
2019-04-18 09:03:21.972147: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1674] Adding visible gpu devices: 0
2019-04-18 09:03:21.972248: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcudart.so.10.0
2019-04-18 09:03:21.973094: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1082] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-04-18 09:03:21.973105: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1088]      0
2019-04-18 09:03:21.973110: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1101] 0:   N
2019-04-18 09:03:21.973279: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1222] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 1735 MB memory) -> physical GPU (device: 0, name: Quadro P600, pci bus id: 0000:01:00.0, compute capability: 6.1)

I am about to post another question about implementing CUBLAS in R as well because that was giving me slow speed times compared to Intel MKL, but I'm hoping that maybe there's a clear cut reason why even something as well built as TF (compared to hacky R and CUBLAS patching) is being slow with GPU.

EDIT: Following Vlad's suggestion, I wrote up the following script to try and throw some large sized objects and training it, but I think I might not be setting it up correctly because the CPU one in this case even as the size of the matrices are increasing. Any suggestions perhaps?
import time
import warnings
import numpy as np
import scipy

import tensorflow as tf
import tensorflow_probability as tfp

from tensorflow_probability import edward2 as ed
from tensorflow.python.ops import control_flow_ops
from tensorflow_probability import distributions as tfd

np.random.seed(69)

# Handy snippet to reset the global graph and global session.
def reset_g():
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        tf.reset_default_graph()
        try:
            sess.close()
        except:
            pass

# Loop over the different number of feature columns
for x_feat in [30, 50, 100, 1000, 10000]:

    y_feat=10;
    # Simulate data
    N = 5000
    inttest = np.ones(N).reshape(N, 1)
    stddev_raw = np.random.uniform(0.01, 0.25, size=y_feat)

    true_int = np.linspace(0.1 ,1., num=y_feat)
    xcols = x_feat
    true_bw = np.random.randn(xcols, y_feat)
    true_X = np.random.randn(N, xcols)
    true_errorcov = np.eye(y_feat)
    np.fill_diagonal(true_errorcov, stddev_raw)

    true_Y = true_int + np.matmul(true_X, true_bw) + \
        np.random.multivariate_normal(mean=np.array([0 for i in range(y_feat)]),
                                      cov=true_errorcov,
                                      size=N)

    ## Our model is:
    ## Y = a + b*X + error where, for N=5000 observations:
    ## Y : 10 outputs;
    ## X : 30,50,100,1000,10000 features
    ## a, b = bias and weights
    ## error: just... error

    # Number of iterations
    N_ITER = 1001

    # Training rate
    lr=0.005

    with tf.device('gpu'):

        # Create data and weights
        model_X = tf.placeholder(dtype=tf.float64, shape=[N, xcols])
        model_Y = tf.placeholder(dtype=tf.float64, shape=[N, y_feat])

        alpha = tf.get_variable(shape=[y_feat], name='alpha', dtype=tf.float64)
        # these two params need shape of one if using trainable distro
        betas = tf.get_variable(shape=[xcols, y_feat], name='beta1', dtype=tf.float64)

        # Yhat
        tf_pred = alpha + tf.matmul(model_X, betas)

        # Make difference of squares (loss fn) [CONVERGES TO TRUTH]
        resid = tf.square(model_Y - tf_pred)
        loss = tf.reduce_sum(resid)

        # Trainer
        opt = tf.train.AdamOptimizer(lr, beta1=0.95, beta2=0.95)
        train = opt.minimize(loss)

    sess = tf.Session()
    sess.run(tf.global_variables_initializer())

    start = time.time()
    for step in range(N_ITER):
        out_l, laws = sess.run([train, loss], feed_dict={model_X: true_X, model_Y: true_Y})

        if step % 500 == 0:
            print('Step: {s}, loss = {l}'.format(
                s=step, l=laws))
    end = time.time()
    print("y_feat: {n}, x_feat: {x2}, Time elapsed: {te}".format(n = y_feat, x2 = x_feat, te = end-start))

    reset_g()

A: Select your Device using tf.device()
with tf.device('/cpu:0'):
    #enter code here of tf data

On a typical system, there are multiple computing devices. In TensorFlow, the supported device types are CPU and GPU. They are represented as strings. For example:
"/cpu:0": The CPU of your machine.
"/device:GPU:0": The GPU of your machine, if you have one.
"/device:GPU:1": The second GPU of your machine, etc.

GPU:
with tf.device('/device:GPU:0'):
  #code here: tf data and model

Reference: Link

A: As I said in a comment, the overhead of invoking GPU kernels, and copying data to and from GPU, is very high.  For operations on models with very little parameters it is not worth of using GPU since frequency of CPU cores is much higher. If you compare matrix multiplication (this is what DL mostly does), you will see that for large matrices GPU outperforms CPU significantly.
Take a look at this plot. X-axis are the sizes of two square matrices and y-axis is time took to multiply those matrices on GPU and on CPU. As you can see at the beginning, for small matrices the blue line is higher, meaning that it was faster on CPU. But as we increase the size of the matrices the benefit from using GPU increases significantly.

The code to reproduce:
import tensorflow as tf
import time
cpu_times = []
sizes = [1, 10, 100, 500, 1000, 2000, 3000, 4000, 5000, 8000, 10000]
for size in sizes:
    tf.reset_default_graph()
    start = time.time()
    with tf.device('cpu:0'):
        v1 = tf.Variable(tf.random_normal((size, size)))
        v2 = tf.Variable(tf.random_normal((size, size)))
        op = tf.matmul(v1, v2)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        sess.run(op)
    cpu_times.append(time.time() - start)
    print('cpu time took: {0:.4f}'.format(time.time() - start))

import tensorflow as tf
import time

gpu_times = []
for size in sizes:
    tf.reset_default_graph()
    start = time.time()
    with tf.device('gpu:0'):
        v1 = tf.Variable(tf.random_normal((size, size)))
        v2 = tf.Variable(tf.random_normal((size, size)))
        op = tf.matmul(v1, v2)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        sess.run(op)
    gpu_times.append(time.time() - start)
    print('gpu time took: {0:.4f}'.format(time.time() - start))

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(sizes, gpu_times, label='GPU')
ax.plot(sizes, cpu_times, label='CPU')
plt.xlabel('MATRIX SIZE')
plt.ylabel('TIME (sec)')
plt.legend()
plt.show()

A: to reproduce answer from first comment for tensorflow 2.0+
tf.compat.v1.disable_eager_execution()
cpu_times = []
sizes = [1, 10, 100, 500, 1000, 2000, 3000, 4000, 5000, 8000, 10000]
for size in sizes:
    ops.reset_default_graph()
    start = time.time()
    with tf.device('cpu:0'):
        v1 = tf.Variable(tf.random.normal((size, size)))
        v2 = tf.Variable(tf.random.normal((size, size)))
        op = tf.matmul(v1, v2)

    with tf.compat.v1.Session() as sess:
        sess.run(tf.compat.v1.global_variables_initializer())
        sess.run(op)
    cpu_times.append(time.time() - start)
    print('cpu time took: {0:.4f}'.format(time.time() - start))

import tensorflow as tf
import time

gpu_times = []
for size in sizes:
    ops.reset_default_graph()
    start = time.time()
    with tf.device('gpu:0'):
        v1 = tf.Variable(tf.random.normal((size, size)))
        v2 = tf.Variable(tf.random.normal((size, size)))
        op = tf.matmul(v1, v2)

    with tf.compat.v1.Session() as sess:
        sess.run(tf.compat.v1.global_variables_initializer())
        sess.run(op)
    gpu_times.append(time.time() - start)
    print('gpu time took: {0:.4f}'.format(time.time() - start))

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(sizes, gpu_times, label='GPU')
ax.plot(sizes, cpu_times, label='CPU')
plt.xlabel('MATRIX SIZE')
plt.ylabel('TIME (sec)')
plt.legend()
plt.show()

A: Your model is very small, so the overhead of transferring data to GPU and back to CPU outweights the speed up.

A: The code below will produce the exact same thing what you saw with the acccepted answer but this code is fully tested for version 2.10 of tensorflow (also the above code by @Art does not work in later version of tensorflow 2.x)
import tensorflow as tf
import time
import matplotlib.pyplot as plt

#something of an extra or the below code will produce an error as "Tensor.graph is undefined when eager execution is enabled."
#this code is needed to not let tensorflow produce error for the cpu part of code or the gpu part.
#the reason for this error is because Session does not work with either eager execution or tf.function, and you should not invoke it directly.

tf.compat.v1.disable_eager_execution()

cpu_times = []
sizes = [1, 10, 100, 500, 1000, 2000, 3000, 4000, 5000, 8000, 10000]
for size in sizes:
    tf.compat.v1.reset_default_graph()
    start = time.time()
    with tf.device('cpu:0'):
        v1 = tf.Variable(tf.random.normal((size, size)))
        v2 = tf.Variable(tf.random.normal((size, size)))
        op = tf.matmul(v1, v2)

    with tf.compat.v1.Session() as sess:
        sess.run(tf.compat.v1.global_variables_initializer())
        sess.run(op)
    cpu_times.append(time.time() - start)
    print('cpu time took: {0:.4f}'.format(time.time() - start))

gpu_times = []
for size in sizes:
    tf.compat.v1.reset_default_graph()
    start = time.time()
    with tf.device('gpu:0'):
        v1 = tf.Variable(tf.random.normal((size, size)))
        v2 = tf.Variable(tf.random.normal((size, size)))
        op = tf.matmul(v1, v2)

    with tf.compat.v1.Session() as sess:
        sess.run(tf.compat.v1.global_variables_initializer())
        sess.run(op)
    gpu_times.append(time.time() - start)
    print('gpu time took: {0:.4f}'.format(time.time() - start))

fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(sizes, gpu_times, label='GPU')
ax.plot(sizes, cpu_times, label='CPU')
plt.xlabel('MATRIX SIZE')
plt.ylabel('TIME (sec)')
plt.legend()
plt.show()


text:
Q: Shared base for both ToolStripMenuItem and Control? ToolStripMenuItem and the base type Control both contain the property Enabled.
I need to pass both types to a function such as EnableItems(multipleItems);, but I am not able to find a common base that contain the Enabled property.
Label or LinkLabel inherit from Control (which are typically the types I want to switch from "not enabled" to "enabled").
Is there any way to do this with out of the box features in c#?

A: Use dynamic type. It allows you to make the compiler trust you. It can give runtime exeptions if you misuse it, but if you are careful there is no problem.
    public static  void Enable(List<object> ctrs, bool enable)
    {
        foreach (var ctr in ctrs)
        {
            dynamic a=ctr;
            a.Enabled = enable;
        }
    }

Pass it a llist with whatever you want to enable or disble. If it have no enable property it will crash at runtime, so be carefull

A: If you didn't want to use a dynamic type then both Control and ToolStripMenuItem inherit from the base class System.ComponentModel.Component.  So you could use this as your list type:
public void EnableItems(IList<Component> cpnts)
{
    foreach (Component cpnt in cpnts)
    {
        ToolStripItem tsItem = cpnt as ToolStripItem;
        if (tsItem != null) { tsItem.Enabled = true; break; }

        Control ctrl = cpnt as Control;
        if (ctrl != null) { ctrl.Enabled = true; break; }
    }
}

You can now choose if you want the foreach loop to crash at run time (by adding an exception throw for an unexpected type) or you can choose to ignore the unexpected types.


text:
Q: Syntax of regex incoherent I'm trying to do a regex:
 static regex(version: string) {
    const match = /^([0-9])*\.([0-9])*\.([0-9])*-([0-9])*-(toto)$/.exec(version);
    return parseInt(match[1]) + "." + parseInt(match[2]) + "." + parseInt(match[3]) + "-" + parseInt(match[4]);
}

When version is:

*

*1.0.0-7-toto, it return me 1.0.0-7 so it's good

But when is:

*

*1.0.0-17-toto,  it return me 1.0.0-7 and not 1.0.0-17

Where is my problem ?
Thanks

A: As already pointed out in the comments your repeats should be in the capture groups.
Please try:
 static regex(version: string) {
    const match = /^([0-9]*)\.([0-9]*)\.([0-9]*)-([0-9]*)-(toto)$/.exec(version);
    return parseInt(match[1]) + "." + parseInt(match[2]) + "." + parseInt(match[3]) + "-" + parseInt(match[4]);
}

A: What's the point of parsing the \d+ into numbers, just to immediately convert them back to strings? You don't even change the radix. Same for the entire pattern. You take it apart, just to immediately put it the same way back together.
And if your string doesn't match the pattern your function will throw when trying to access the groups.
Here a simpler version, imo.

function regex(version) {
  const match = /^\d+\.\d+\.\d+-\d+(?=-toto$)/.exec(version);
  return match && match[0];
}

console.log(regex("1.0.0-7-toto"));
console.log(regex("1.0.0-17-toto"));
console.log(regex("1.0.0-17-abba"));


text:
Q: How to find URL domain using JavaScript I was working on how to find a URL's domain, and thanks to my previous question, I came to this answer:
var domain = (location.host)
        var arr=domain.split(".")
        extension=arr[arr.length-1]

        if(extension=="cnn")
            alert("true");

However, I have 2 problems:

*

*It works fine untill you come across to a site with extension co.uk.

*Is there a way to count . from the start and not from the end?

For example, for the website www.cnn.com, it'd start counting from the www, and not from the com.

A: Okay, here's the edit to make you understand how it works.
Say, your website is "www.cnn.co.uk". If you understand array, this line would return you the array of 4 elements delimited by '.'
var arr=domain.split(".")

i.e. [www, cnn, co, uk];
Now it's really upto you what element you want out of this array. If you know the element name, and you want to retrieve cnn, you can do
`extension = arr[1];`

You can also iterate over an array to get each element.

extension = arr[0];
it will return you www.

A: Use this function:
function GetDomainName() {
    if (location.host.split('.')[0] == 'www') {
        return location.host.split('.')[1];
    } else {
        return location.host.split('.')[0];
    }
}

Call it like this:
var domainName=GetDomainName();

But remember, this will not work in subdomains like
programmers.stackexchange.com

Demo: http://jsfiddle.net/j7VP6/


text:
Q: Swap two blocks of text programatically I have an XML file made up of multiple blocks that are very similar. Here are two:
    <Grid Name="EMFieldMany" GridType="Uniform">
        <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
        <Attribute AttributeType="Scalar" Name="Er" Center="Node">
            <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/field/Er-0
            </DataItem>
        </Attribute>
        <Geometry GeometryType="VXVYVZ">
            <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/r
            </DataItem>
            <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/theta
            </DataItem>
            <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/z
            </DataItem>
        </Geometry>
    </Grid>
    <Grid Name="EMFieldMany" GridType="Uniform">
        <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
        <Attribute AttributeType="Scalar" Name="Er" Center="Node">
            <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/field/Er-1
            </DataItem>
        </Attribute>
        <Geometry GeometryType="VXVYVZ">
            <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/r
            </DataItem>
            <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/theta
            </DataItem>
            <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/z
            </DataItem>
        </Geometry>
    </Grid>

Typically I have hundreds of similar <Grid> objects in a single file. Now, I want to programatically swap the positions of the <DataItem Name="r"> and <DataItem Name="z"> blocks in each <Grid> object such that the <DataItem>s are in the order z, theta, r. Also, for each Dimensions=" x y z " statement, each Dimensions attribute that contains three values, I want the attribute to be rewritten as Dimensions=" z y x ".
I don't really mind the programming language being used to do this. I'm on a Linux workstation with bash, python, perl... all the standard stuff.
EDIT: This answer uses sed to match blocks of text, but I'm not sure how to manipulate the selected block afterwards. This other answer swaps single lines up and down, but I'm not sure how to generalize to blocks of text, and to make it swap blocks.

A: This can be easily done with ed:
g/<DataItem Name="r"/-ka\
/<DataItem Name="z"/\
-kb\
.,/\/DataItem/m'a\
+1,/\/DataItem/m'b

A: As you mention sed, I suggest this perl solution however it's better parsing xml with xml parser.
#!/usr/bin/perl

# changing input line separator
$/="</Grid>";

while ( $_=<> ) {
    s@(\s*<DataItem Name="r".*?</DataItem>)(\s*<DataItem Name="theta".*?</DataItem>)(\s*<DataItem Name="z".*?</DataItem>)@$3$2$1@s;
    s@<DataItem Dimensions="\K(\d+) (\d+) (\d+) @$3 $2 $1 @;
    print;
}

Or the one-liner equivalent
perl -pe 'BEGIN{$/="</Grid>"}s@(\s*<DataItem Name="r".*?</DataItem>)(\s*<DataItem Name="theta".*?</DataItem>)(\s*<DataItem Name="z".*?</DataItem>)@$3$2$1@s;s@<DataItem Dimensions="\K(\d+) (\d+) (\d+) @$3 $2 $1 @;' <input.txt

A: You can do that with replace, if you have your XML as a string :
#Swapping ( '\"' the slash escape the " to make it the string caracter)
XML_str = XML_str.replace("\"r","SomethingThatNeverAppearInTheXML")
XML_str = XML_str.replace("\"z","\r")
XML_str = XML_str.replace("SomethingThatNeverAppearInTheXML","\"z")
#Replacing
XML_str = XML_str.replace("x y z","z y x")

input
XML_str = """
    <Grid Name="EMFieldMany" GridType="Uniform">
        <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
        <Attribute AttributeType="Scalar" Name="Er" Center="Node">
            <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/field/Er-0
            </DataItem>
        </Attribute>
        <Geometry GeometryType="VXVYVZ">
            <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/r
            </DataItem>
            <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/theta
            </DataItem>
            <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/z
            </DataItem>
        </Geometry>
    </Grid>
    <Grid Name="EMFieldMany" GridType="Uniform">
        <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
        <Attribute AttributeType="Scalar" Name="Er" Center="Node">
            <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/field/Er-1
            </DataItem>
        </Attribute>
        <Geometry GeometryType="VXVYVZ">
            <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/r
            </DataItem>
            <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/theta
            </DataItem>
            <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/z
            </DataItem>
        </Geometry>
    </Grid>
"""

output
<Grid Name="EMFieldMany" GridType="Uniform">
    <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
    <Attribute AttributeType="Scalar" Name="Er" Center="Node">
        <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/field/Er-0
        </DataItem>
    </Attribute>
    <Geometry GeometryType="VXVYVZ">
        <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/r
        </DataItem>
        <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/theta
        </DataItem>
        <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/z
        </DataItem>
    </Geometry>
</Grid>
<Grid Name="EMFieldMany" GridType="Uniform">
    <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
    <Attribute AttributeType="Scalar" Name="Er" Center="Node">
        <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/field/Er-1
        </DataItem>
    </Attribute>
    <Geometry GeometryType="VXVYVZ">
        <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/r
        </DataItem>
        <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/theta
        </DataItem>
        <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/z
        </DataItem>
    </Geometry>
</Grid>


text:
Q: set class variable in other function than constructor This is probably a very basic question, but I did not find anything on the internet.
I am writing a matlab class, which has various class properties. I am setting all of them (some with input arguments, some default).
I change one class variable in another class method.
This does not work (the variable gets deleted when out of the function scope).
What is the best way to solve this?
Put everything in the constructor?
classdef MyClass
properties
    matrix1
    matrix2
    matrix3
end
methods
    function obj = MyClass()
    obj.matrix1 = zeros(2)
    obj.matrix2 = ones(3)
    end

    function obj = func(obj)
    obj.matrix2 = 3*ones(3)
    end
    function obj = func2(obj)
    obj.matrix3 = obj.matrix2 %this does not work. matrix2 has its original value, not 3*ones(3)
    end
end
end

I call it like
object = MyClass()
   object.func()
   object.func2()

A: MATLAB supports both value-type and reference-type classes.
The way you have defined your class, it is inherently a value type, which means that each function call uses a copy of your object, and does not refer to the calling object's data.
To make a class behave as a reference type, that would then modify the object's data as you require, inherit your class from handle.
Do:
classdef MyClass < handle
    % Everything else same here...
end


text:
Q: How to get multiple notifications in Android In one activity I have three DatePickerDialog where the user can put three date for a reminder purpose. The app must notify each date and if the user enters two or three equal date they must be notified in sequence . My problem is that only the last date entered is notified. I use a random number for the notification_id. How do I fix? Thanks
Here the code:
ScheduleClient.java
public class ScheduleClient {

    private ScheduleService mBoundService;
    private Context mContext;
    private boolean mIsBound;

    public ScheduleClient(Context context) {
        mContext = context;
    }

    public void doBindService() {
        // Establish a connection with our service
        mContext.bindService(new Intent(mContext, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder  service) {
            // This is called when the connection with our service has been established,
            // giving us the service object we can use to interact with our service.
            mBoundService = ((ScheduleService.ServiceBinder) service).getService();
        }

        public void onServiceDisconnected(ComponentName className) {
            mBoundService = null;
        }
    };

    public void setAlarmForNotification(Calendar c){
        mBoundService.setAlarm(c);
    }

    public void doUnbindService() {
        if (mIsBound) {
            // Detach our existing connection.
            mContext.unbindService(mConnection);
            mIsBound = false;
        }
    }
}

ScheduleService.java
public class ScheduleService extends Service {

    public class ServiceBinder extends Binder {
        ScheduleService getService() {
            return ScheduleService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("ScheduleService", "Received start id " + startId + ": " + intent);

         stopped, so return sticky.
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private final IBinder mBinder = new ServiceBinder();

    public void setAlarm(Calendar c) {
        // This starts a new thread to set the alarm
        // You want to push off your tasks onto a new thread to free up the UI to carry on responding
        new AlarmTask(this, c).run();
    }
}

AlarmTask.java
public class AlarmTask implements Runnable {

    private final Calendar date;
    private final AlarmManager am;
    private final Context context;

    public AlarmTask(Context context, Calendar date) {
        this.context = context;
        this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        this.date = date;
    }

    @Override
    public void run() {
        // Request to start are service when the alarm date is upon us
        // We don't start an activity as we just want to pop up a notification into the system bar not a full activity
        Intent intent = new Intent(context, NotifyService.class);
        intent.putExtra(NotifyService.INTENT_NOTIFY, true);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

        // Sets an alarm - note this alarm will be lost if the phone is turned off and on again
        am.set(AlarmManager.RTC, date.getTimeInMillis(), pendingIntent);
    }
}

NotifyService.java
public class NotifyService extends Service {

    public class ServiceBinder extends Binder {
        NotifyService getService() {
            return NotifyService.this;
        }
    }

    Random random = new Random();
    int randomID = random.nextInt(9999 - 1000) + 1000;
    public static final String INTENT_NOTIFY = "com.try.myapp.INTENT_NOTIFY";
    private NotificationManager mNM;

    @Override
    public void onCreate() {
        Log.i("NotifyService", "onCreate()");
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);

        // If this service was started by out AlarmTask intent then we want to show our notification
        if(intent.getBooleanExtra(INTENT_NOTIFY, false))
            showNotification(randomID);

        // We don't care if this service is stopped as we have already delivered our notification
        return START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private final IBinder mBinder = new ServiceBinder();

    private void showNotification(int notificationID) {
        // This is the 'title' of the notification
        CharSequence title = "Notification!";
        // This is the icon to use on the notification
        int icon = R.drawable.ic_dialog_alert;
        // This is the scrolling text of the notification
        CharSequence text = "Sub text notification.";
        // What time to show on the notification
        long time = System.currentTimeMillis();

        Notification notification = new Notification(icon, text, time);

        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, notificationID, new Intent(this, SecondActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, title, text, contentIntent);

        // Clear the notification when it is pressed
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.defaults |= Notification.DEFAULT_LIGHTS;
        notification.defaults |= Notification.DEFAULT_VIBRATE;

        // Send the notification to the system.
        mNM.notify(notificationID, notification);

        // Stop the service when we are finished
        stopSelf();
    }
}

InsertDateActivity.java
public class InsertCarActivity extends AppCompatActivity {

....

toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            int id = item.getItemId();
            if (id == R.id.saveButton) {
                firstDate = fDate.getText().toString().trim();
                secondDate = sDate.getText().toString().trim();
                thirdDate = tDate.getText().toString().trim();

                String[] arrFirstDate = firstDate.split("-");

                int day = Integer.parseInt(arrFirstDate[0]);
                int month = Integer.parseInt(arrFirstDate[1]);
                month -= 1;
                int year = Integer.parseInt(arrFirstDate[2]);

                Calendar c = Calendar.getInstance();
                c.set(year, month, day);
                c.set(Calendar.HOUR_OF_DAY, 0);
                c.set(Calendar.MINUTE, 0);
                c.set(Calendar.SECOND, 0);

                scheduleClient.setAlarmForNotification(c);

                String[] arrSecondDate = secondDate.split("-");

                int day1 = Integer.parseInt(arrSecondDate[0]);
                int month1 = Integer.parseInt(arrSecondDate[1]);
                month1 -= 1;
                int year1 = Integer.parseInt(arrSecondDate[2]);

                Calendar c1 = Calendar.getInstance();
                c1.set(year1, month1, day1);
                c1.set(Calendar.HOUR_OF_DAY, 0);
                c1.set(Calendar.MINUTE, 0);
                c1.set(Calendar.SECOND, 0);

                scheduleClient.setAlarmForNotification(c1);

                String[] arrThirdDate = thirdDate.split("-");

                int day2 = Integer.parseInt(arrThirdDate[0]);
                int month2 = Integer.parseInt(arrThirdDate[1]);
                month2 -= 1;
                int year2 = Integer.parseInt(arrThirdDate[2]);

                Calendar c2 = Calendar.getInstance();
                c2.set(year2, month2, day2);
                c2.set(Calendar.HOUR_OF_DAY, 0);
                c2.set(Calendar.MINUTE, 0);
                c2.set(Calendar.SECOND, 0);

                scheduleClient.setAlarmForNotification(c2);

                return true;
                }
            return false;

         }

....

}

A: When you create your PendingIntent here:
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

you probably want to pass a different requestCode (the first 0 you're passing) every time or the PendingIntent will be the same as the last one you created and the following:
am.set(AlarmManager.RTC, date.getTimeInMillis(), pendingIntent);

will set a new alarm for the same PendingIntent as before, so only the last alarm you set will actually ever trigger.
From the official docs

If you truly need multiple distinct PendingIntent objects active at the same time (such as to use as two notifications that are both shown at the same time), then you will need to ensure there is something that is different about them to associate them with different PendingIntents. This may be any of the Intent attributes considered by Intent.filterEquals, or different request code integers supplied to getActivity(Context, int, Intent, int), getActivities(Context, int, Intent[], int), getBroadcast(Context, int, Intent, int), or getService(Context, int, Intent, int).


text:
Q: Running inference on InceptionV3 network twice bring totally different results When i calculate inception score, i got NaN most of the time.
Trying to investigate why it happen i found that running the network twice on the same images can lead for some of the images to totally different results (difference greater than 0.9 while the maximum difference can be 1), the images which got high difference changed from run to run.
My GPU is 2080ti, i use Ubuntu with tensorflow=1.13.1.
i try to change drivers, tensorflow version, run form docker, the same problem happen all the time.
I have another server at the university which has the same GPU (2080ti), and when i try to run there the problem disappear.
Thanks for the help.
my script
# Code derived from tensorflow/tensorflow/models/image/imagenet/classify_image.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os.path
import tarfile

import numpy as np
from six.moves import urllib
import tensorflow as tf
import sys
import warnings
from scipy import linalg

MODEL_DIR = '/tmp/imagenet'
DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
softmax = None
pool3 = None

# Call this function with list of images. Each of elements should be a
# numpy array with values ranging from 0 to 255.
def get_features(images):
   assert ((images.shape[3]) == 3)
   assert (np.max(images) > 10)
   assert (np.min(images) >= 0.0)
   images = images.astype(np.float32)
   bs = 100
   sess = tf.get_default_session()
   preds = []
   for inp in np.array_split(images, round(images.shape[0] / bs)):
       sys.stdout.write(".")
       sys.stdout.flush()
       pred = sess.run(softmax, {'InputTensor:0': inp})
       preds.append(pred)
   preds = np.concatenate(preds, 0)
   return preds

# This function is called automatically.
def _init_inception():
   global softmax
   global pool3
   if not os.path.exists(MODEL_DIR):
       os.makedirs(MODEL_DIR)
   filename = DATA_URL.split('/')[-1]
   filepath = os.path.join(MODEL_DIR, filename)
   if not os.path.exists(filepath):
       def _progress(count, block_size, total_size):
           sys.stdout.write('\r>> Downloading %s %.1f%%' % (
               filename, float(count * block_size) / float(total_size) * 100.0))
           sys.stdout.flush()

       filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)
       print()
       statinfo = os.stat(filepath)
       print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')
   tarfile.open(filepath, 'r:gz').extractall(MODEL_DIR)
   with tf.gfile.GFile(os.path.join(
           MODEL_DIR, 'classify_image_graph_def.pb'), 'rb') as f:
       graph_def = tf.GraphDef()
       graph_def.ParseFromString(f.read())
       # Import model with a modification in the input tensor to accept arbitrary
       # batch size.
       input_tensor = tf.placeholder(tf.float32, shape=[None, None, None, 3],
                                     name='InputTensor')
       _ = tf.import_graph_def(graph_def, name='inception_v3',
                               input_map={'ExpandDims:0': input_tensor})
   # Works with an arbitrary minibatch size.
   pool3 = tf.get_default_graph().get_tensor_by_name('inception_v3/pool_3:0')
   ops = pool3.graph.get_operations()
   for op_idx, op in enumerate(ops):
       if 'inception_v3' in op.name:
           for o in op.outputs:
               shape = o.get_shape()
               shape = [s.value for s in shape]
               new_shape = []
               for j, s in enumerate(shape):
                   if s == 1 and j == 0:
                       new_shape.append(None)
                   else:
                       new_shape.append(s)
               o.set_shape(tf.TensorShape(new_shape))
   w = tf.get_default_graph().get_operation_by_name("inception_v3/softmax/logits/MatMul").inputs[1]
   logits = tf.matmul(tf.squeeze(pool3, [1, 2]), w)
   softmax = tf.nn.softmax(logits)

_init_inception()
if __name__ =='__main__':
   (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
   with tf.Session() as sess:
       preds1 = get_features(x_train)
       preds2 = get_features(x_train)
       print(abs(preds1-preds2).max())


text:
Q: Using Replace only once I'm using the Wordpress Avada Theme and I'm trying to translate the social media privacy labels/contents using jQuery. So far it works fine but one thing does not.
Here is the HTML:

function translate() {
  jQuery(".fusion-privacy-label").text(function() {
    return jQuery(this).html().replace("For privacy reasons Google Maps needs your permission to be loaded. For more details, please see our ", "Here is some example translation text. For more Details, please visit");
  });
}
setTimeout(translate, 1000);

  For privacy reasons Google Maps needs your permission to be loaded. For more details, please see our
  Privacy.

That works so far but it also deletes the Privacy HTML link. I don't want to translate this HTML link. If I try to add Privacy within my translation, it shows as text and not as a HTML Link element.
What I want is just the Translation of the first text part, not the a-tag element or the text within the a-tag.
What did I wrong?

A: Try following. Use jQuery.html instead of jQuery.text

function translate(){
  jQuery(".fusion-privacy-label").html(function () {
    return jQuery(this).html().replace("For privacy reasons Google Maps needs your permission to be loaded. For more details, please see our ", "Here is some example translation text. For more Details, please visit");
});
}
setTimeout(translate, 1000);

For privacy reasons Google Maps needs your permission to be loaded. For more details, please see our
Privacy.

A: I would use .html instead of .text as you have html in your div:

function translate() {
  jQuery(".fusion-privacy-label").html(function(index, oldHtml) { // as you use the function, just use the arguments of the function instead of $(this).html()
    return oldHtml.replace("For privacy reasons Google Maps needs your permission to be loaded. For more details, please see our", "Here is some example translation text. For more Details, please visit"); // watch the spaces here - there is no space after our in your actual html
  });
}
setTimeout(translate, 1000);

  For privacy reasons Google Maps needs your permission to be loaded. For more details, please see our
  Privacy.

A: Try this below code,

             For privacy reasons Google Maps needs your permission to be loaded. For more details, please see our
             Privacy.

                   (or)


text:
Q: How do I get the continuation mapping from the URL in a Spring application? I have this spring application where I want to get the values from a URL, for example:
The url send to the spring application is www.example.com/app/account/register. How do I get the /register part after /account when my code looks like this.
For this example I used /register but this can be /login, /something as well.
@RestController
@RequestMapping("/app")
public class MainController {

    @RequestMapping(value = "/account")
    public boolean AccountServer(@RequestHeader HttpHeaders httpHeaders, @RequestBody Map<String, String> payLoad){
        return true;
    }
}

A: You can use the @PathVariable annotation to get the value.
@RestController
@RequestMapping("/app")
public class MainController {

    @RequestMapping(value = "/account/{operation}")
    public boolean AccountServer(@RequestHeader HttpHeaders httpHeaders,
                                 @RequestBody Map<String, String> payLoad,
                                 @PathVariable("operation") String operation){

        return true;
    }
}

A: Use UriComponentsBuilder as a parameter, it will be injected by Spring and initialized with current URI. You can then convert to UriComponents UriComponents to query the path.
@RestController
@RequestMapping("/app")
public class MainController {

    @RequestMapping(value = "/account")
    public boolean AccountServer(UriComponentsBuilder builder, @RequestHeader HttpHeaders httpHeaders, @RequestBody Map<String, String> payLoad){
        List<String> pathSegments = builder.build().getPathSegments();
        ...
        return true;
    }
}


text:
Q: Android softkeyboard hiddin other elements? my app screen first picture
when i fist open soft keyboard picture in the middle
and then I close the keyboard and open again and the keyboard is hiding elements. picture on the right.
how to fix this? I want my keyboard always to open like the first time
http://postimg.org/image/ufw3v45in/
thanks for the time. Sorry if a am breaking some rule.

A: you can define windowSoftInputMode in manifest file for different mode for activity like :-
<activity
                android:windowSoftInputMode="adjustResize">

A: try this:
in the manifest add this tag to activity.for more details
http://developer.android.com/guide/topics/manifest/activity-element.html#wsoft
<activity
 android:windowSoftInputMode="adjustPan" >