text:
Q: Sort by day, ignoring hours and minutes I have a little problem for you. I would like to sort by day, but if several with different times are sorted on the day, it separates them. How do I get it out that he only shows all day by day
My date field looks like this
Datum                         weight
2022-12-09 07:12:49.000       2150
2022-12-09 08:15:49.000       1250

My query
Select FORMAT(Datum, 'dd/MM/yyyy', 'de-DE') as Datum, SUM(weight)
FROM [Produktionsdaten].[dbo].[produktionedelstahl]
WHERE Anlage IN ('Bonak 2')
  AND YEAR(Datum)=YEAR(CURRENT_TIMESTAMP)
  AND MONTH(Datum)=MONTH(CURRENT_TIMESTAMP)
group BY (Datum)

I want the day to be summarized
Datum           weight
12-09-2022      3400

A: could you try to perform the SELECT in this way.
SELECT FORMAT(DATE(Datum), 'dd/MM/yyyy', 'de-DE') AS Datum, SUM(weight)
FROM [Produktionsdaten].[dbo].[produktionedelstahl]
WHERE Anlage IN ('Bonak 2')
AND YEAR(Datum)=YEAR(CURRENT_TIMESTAMP)
AND MONTH(Datum)=MONTH(CURRENT_TIMESTAMP)
GROUP BY DATE(Datum)

A: I think you were nearly there - just change the last line
Select FORMAT(Datum, 'dd/MM/yyyy', 'de-DE') as Datum, SUM(weight)
FROM [Produktionsdaten].[dbo].[produktionedelstahl]
WHERE Anlage IN ('Bonak 2')
  AND YEAR(Datum)=YEAR(CURRENT_TIMESTAMP)
  AND MONTH(Datum)=MONTH(CURRENT_TIMESTAMP)
group BY FORMAT(Datum, 'dd/MM/yyyy', 'de-DE')

A: You can do it by casting the DATETIME to a DATE and going from there.
SELECT CAST(Datum AS DATE) AS Datum, SUM(Weight) AS Weight
FROM [Produktionsdaten].[dbo].[produktionedelstahl]
GROUP BY CAST(Datum AS DATE)

Here is a very small sample script to demonstrate that this works:
DECLARE @Data TABLE (Datum DATETIME, Weight INT);
INSERT INTO @Data(Datum, Weight) VALUES ('2022-12-09 07:12:49.000', 2150), ('2022-12-09 08:15:49.000', 1250);

SELECT CAST(Datum AS DATE) AS Datum, SUM(Weight) AS Weight
FROM @Data
GROUP BY CAST(Datum AS DATE)

Output:

Datum
Weight

2022-12-09
3400


text:
Q: predict new data by pre-trained model in tensor-flow I trained a LSTM model in tensor-flow and I want to predict new data based on it. However, I keep getting an error I can't understand:
This is the model:
def __init__(self , snapshot_dir, save_dir ):
    self.save_dir = save_dir
    self.snapshot_dir =  snapshot_dir
    self.learning_rate = params["learning_rate"]
    self.training_steps = params["training_steps"]
    self.batch_size = params["batch_size"]
    self.display_step = params["display_step"]
    self.num_input = params["num_input"]
    self.timesteps = params["timesteps"]
    self.num_hidden = params["num_hidden"]
    self.num_classes = params["num_classes"]
    self.define_graph()

def define_graph(self):

    self.X = tf.placeholder("float", [None, self.timesteps, self.num_input], name="X")
    self.Y = tf.placeholder("float", [None, self.num_classes], name="Y")
    self.weights = {'out': tf.Variable(tf.random_normal([self.num_hidden, self.num_classes]))}
    self.biases = {'out': tf.Variable(tf.random_normal([self.num_classes]))}

def RNN(self):

    x = tf.unstack(self.X, self.timesteps, 1)
    lstm_cell = rnn.BasicLSTMCell(self.num_hidden, forget_bias=1.0, reuse=tf.get_variable_scope().reuse)
    outputs, states = rnn.static_rnn(lstm_cell, x , dtype=tf.float32)
    return tf.matmul(outputs[-1], self.weights['out']) + self.biases['out']

def run(self, X_train, y_train):

    logits = self.RNN()
    self.prediction = tf.nn.softmax(logits, name="prediction")
    loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
        logits=logits, labels=self.Y))
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate)
    train_op = optimizer.minimize(loss_op)
    correct_pred = tf.equal(tf.argmax(self.prediction, 1), tf.argmax(self.Y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
    init = tf.global_variables_initializer()
    with tf.Session() as sess:

        sess.run(init)
        saver = tf.train.Saver()
        for step in range(1, self.training_steps + 1):
            start_idx = random.randint(0, len(X_train) - self.timesteps - 1)
            batch_x = self.generate_x_batch_data(start_idx, X_train, self.batch_size)
            batch_y = self.generate_y_batch_data(start_idx, y_train, self.batch_size)

            sess.run(train_op, feed_dict={self.X: batch_x, self.Y: batch_y})
        saver.save(sess, self.save_dir, global_step=step)

And the prediction part:

    sess = tf.Session()
    saver = tf.train.import_meta_graph("{}.meta".format(self.newest_snapshot))
    saver.restore(sess, self.newest_snapshot)
    X_as_batch = self.aux.generate_x_batch_data(0,X, len(X))
    pred = tf.get_default_graph().get_operation_by_name("prediction").outputs[0]
    feed_dict = {tf.get_default_graph().get_operation_by_name('X').outputs[0]: X_as_batch}
    prediction = sess.run(pred,
                          feed_dict=feed_dict)

the shape of X_as_batch is as expected by pred (it's shape is [5126, 60, 39]  and the shape of pred is [?, 60, 39])
But I get the error

InvalidArgumentError (see above for traceback): You must feed a value
  for placeholder tensor 'X_1' with dtype float and shape [?,1024]
  [[Node: X_1 = Placeholderdtype=DT_FLOAT, shape=[?,1024],
  _device="/job:localhost/replica:0/task:0/cpu:0"]]

What might be the reason?

A: The reason you have a X_1 tensor is that you have restored a graph while your old graph still exists.  In order to avoid having two TensorFlow variables which are both called X, the new one gets an _1 appended to it.
I can't be sure because you haven't included all your code, but if you're doing all your work in one execution you might not need to restore anything.  Alternatively, you might just need to restore the checkpoint file that saver creates, using something like saver.restore(sess, './model.ckpt'), with './model.ckpt' replaced by the path to your ckpt file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: XPath find text in any text node I am trying to find a certain text in any text node in a document, so far my statement looks like this:
doc.xpath("//text() = 'Alliance Consulting'") do |node|
  ...
end

This obviously does not work, can anyone suggest a better alternative?

A: This expression //text() = 'Alliance Consulting' evals to a boolean.
In case of this test sample:
<r>
    <t>Alliance Consulting</t>
    <s>
        <p>Test string
            <f>Alliance Consulting</f>
        </p>
    </s>
    <z>
        Alliance Consulting
        <y>
            Other string
        </y>
    </z>
</r>

It will return true of course.
Expression you need should evaluate to node-set, so use:
//text()[. = 'Alliance Consulting']

E.g. expression:
count(//text()[normalize-space() = 'Alliance Consulting'])

against the above document will return 3.
To select text nodes which contain 'Alliance Consulting' in the whole string value (e.g. 'Alliance Consulting provides great services') use:
//text()[contains(.,'Alliance Consulting')]

Do note that adjacent text nodes should become one after parser gets to the document.


text:
Q: Vue: how to make component providing info about logged in user reactive to session data? I understand how to use a Vue plugin like vue-session for creating and holding a session.
But I am not sure how to deal with user data from a session, especially when it comes to reactivity.
E.g.:
I have a User component in the navigation header which displays the currently logged in user. How do I ensure that the username shown via this User component is reactive? In other words: if somewhen while using the application a login happens (to enable restricted functions), then how can the User component know?
Is $watch the right way to go? But this means polling, doesn't it?
How can I ensure that the user data stored in the session plugin is reactive?
Imagine such a component which visualises the logged in user:
<template>

        Logged in as {{user.username}}

        Not logged in.

</template>

I do not want to determine the session user in the create method because it should be reactive (reactive to logout/login).
What's the best option for that?

A: The best way is to use a computed property (like you did) that uses a getter from a Vuex store (or a mapped getter in Vuex speak). All the state stored in a Vuex store is reactive so you'll get what you're looking for.
Instead of storing the current user in the $session from vue-session, it would be stored in the Vuex store.
Vuex: https://vuex.vuejs.org/
About vue-session
I had a quick look at that plugin and its source (only ~100 lines) and there is definitely no reactivity option in there. It's essentially a convenience interface over window.localStorage. $watch only works on reactive data (e.g. a component's data object) which is not provided by this plugin.
Reactivity could be retrofitted in there with Vue.observable(object) I guess though.
A nice read on reactivity: https://stackoverflow.com/a/54492326/1030527


text:
Q: AngleSharp - Find innermost nested tables I try to get a list of all innermost tables with AngleSharp. This tables doesn't contain any tables.
With HtmlAgilityPack I've realised it this way:
    var wrapper = html.DocumentNode.SelectSingleNode(".//td[@class='wrapper']");
    var innerMostTables = wrapper.SelectNodes(".//table [not(descendant::table)]");

With AngleSharp I've tried this, but it doesn't work:
    var parser = new HtmlParser();
    var document = parser.Parse(html);

    var wrapper = document.All.Where(d => d.ClassName == "wrapper");
    var innerMostTables = wrapper.Where(w => w.Descendents()
                                     .Select(c => c.NodeName == "table").Count() == 0);

A: I could solve the problem:
    foreach (IElement ch in wrapper.Descendents()
             .Where(d => d.NodeName == "TABLE" && d.Descendents()
                 .Where(d2 => d2.NodeName == "TABLE").Count() == 0))
    {
        Console.WriteLine(ch.OuterHtml);
    }


text:
Q: Are Subversion commits atomic? Are commits performed by Subversion atomic?
What will happen if commit failed?
Are there some files committed successfully while some failed?
If so, what could i do to go back to the correct state?

A: Yes, commits are atomic — here's a citation from "The Subversion book":

A Subversion client commits (that is, communicates the changes made
  to) any number of files and directories as a single atomic
  transaction. By atomic transaction, we mean simply this: either all of
  the changes are accepted into the repository, or none of them is.
  Subversion tries to retain this atomicity in the face of program
  crashes, system crashes, network problems, and other users' actions.

A:
Are there some files committed successfully while some failed? If so,
  what could i do to go back to the correct state?

No, this cannot happen by design. Commits in Apache Subversion are atomic.


text:
Q: Loop over name list in a ShinyApps server.R While trying to create a series of InfoBoxes for a Shiny project, I've come across a loop that even though I've endlessly tried to solve, ends up in me pasting the code as many times as InfoBoxes I need, which is incredibly.
My original chunk of code is something like this
output$**name** <- renderValueBox({
  InformacionIE2 <- InformacionIE2.df[ which(InformacionIE2.df$INSTITUCIONEDUCATIVA==input$input_typen),]
  if (InformacionIE2$**name** =="Si") {
    infoBox("Planos Electricos",
            color = "green",
            icon = icon("thumbs-up", lib = "glyphicon"),
            print (InformacionIE2$**name**)
    )
  } else {
    infoBox("**name** ",
            color = "red",
            icon = icon("thumbs-down", lib = "glyphicon"),
            print (InformacionIE2$**name**)
    )
  }
})

What I need is to find a way for name1, name2, name3, ..., nameN to iterate in place of name in that exact same chunk of code without having to copy paste as namy times as names there are.
I tried to do this with a simple loop over a list, but get back an error telling me there is a syntax error near unexpected token.
How could this be solved?

A: Use lapply instead of a for loop and it should work. No clue why:
lapply(**names**, function(name) {
output[[name]] <- <- renderValueBox({
  InformacionIE2 <- InformacionIE2.df[ which(InformacionIE2.df$INSTITUCIONEDUCATIVA==input$input_typen),]
  if (InformacionIE2[[name]] =="Si") {
    infoBox("Planos Electricos",
            color = "green",
            icon = icon("thumbs-up", lib = "glyphicon"),
            print (InformacionIE2[[name]])
    )
  } else {
    infoBox(name,
            color = "red",
            icon = icon("thumbs-down", lib = "glyphicon"),
            print (InformacionIE2[[name]])
    )
  }
})
})


text:
Q: Gradient of $F(\mathbf{x}) = \|\mathbf{Ax}-\mathbf{b}\|_{2}^2$ So, I have a matrix $A\in\mathbb{R}^{M\times N}$, $M\geq N$ with rank  $N$ and $\mathbf{b}\in\mathbb{R}^M$. Unfortunately I'm a bit rusty on how to do multivariable calculus, so I would like to know how to calculate $\nabla F$ of
$$F(\mathbf{x})=\|\mathbf{Ax}-\mathbf{b}\|_{2}^2$$
I would furthermore also appreciate literature suggestions regarding sources where multivariable calculus is well explained, especially differentiation.

A: Just apply product- and chain-rule:
$$\begin{align}D_x(\langle F(x),F(x)\rangle)(v)&=
2\langle D_x F(v),F(x)\rangle\\
&=2\langle Av,Ax-b\rangle\\
&=2\langle v,A^t(Ax-b)\rangle,
\end{align}$$
hence
$$\nabla F(x)=2A^t(Ax-b).$$

A: We can always expand $F$. So, we have $F(\mathbf{x})=\|\mathbf{Ax}-\mathbf{b}\|_{2}^2 = \sum_{i=1}^N\left(\sum_{j=1}^M (A_{i,j}x_j - b_j)\right)^2$. Now $\nabla F(x)_k = \sum_{i=1}^N 2A_{i,k}\sum_{j=1}^M(A_{i,j}x_j - b_j)$.

A: Let $$F(x) = \Vert f(x) \Vert_2^2$$
where $f(x) = Ax - b$. Using the fact that $$\frac{d \Vert f(x) \Vert^2}{dx}  = 2\frac{df(x)}{dx}f(x)$$
and that
$$\frac{df(x)}{dx} = A^T$$
we get
$$\frac{d \Vert f(x) \Vert^2}{dx}  = 2A^T(Ax-b)$$
Why is $\frac{df(x)}{dx} = A^T$ ?
Since $f(x) = Ax - b$ is a vector then a derivative of a vector wrt a vector is defined as
$$\frac{df(x)}{dx} = \begin{bmatrix} \frac{df_1(x)}{dx_1} &  \frac{df_1(x)}{dx_2} & \ldots &  \frac{df_1(x)}{dx_n} \\
\vdots &  \vdots  & \ldots &  \vdots  \\ \frac{df_m(x)}{dx_1} &  \frac{df_m(x)}{dx_2} & \ldots &  \frac{df_m(x)}{dx_n} \end{bmatrix}^T$$
Since the derivative of $Ax-b$ is the same as that of $Ax$, let's consider $f(x) = Ax$, which looks like this
$$f(x) = Ax = \begin{bmatrix} \sum_{j=1}^n A_{1j}x_j \\ \sum_{j=1}^n A_{2j}x_j \\ \vdots \\ \sum_{j=1}^n A_{mj}x_j \end{bmatrix}$$
Note that it is easy to see that
$$\frac{df_i(x)}{dx_j} = A_{ij}$$
So we get $\frac{df(x)}{dx} = A^T$.
Note that some references define $$\frac{df(x)}{dx} = \begin{bmatrix} \frac{df_1(x)}{dx_1} &  \frac{df_1(x)}{dx_2} & \ldots &  \frac{df_1(x)}{dx_n} \\
\vdots &  \vdots  & \ldots &  \vdots  \\ \frac{df_m(x)}{dx_1} &  \frac{df_m(x)}{dx_2} & \ldots &  \frac{df_m(x)}{dx_n} \end{bmatrix}$$
which is laying the denominator vector as $x^T$, in that case you'll get that the derivative is $A$ and not its transpose.


text:
Q: Handle relational data in Flutter with MobX I'm new to Flutter and I'm trying to create an app for a personal project. The project is a content sharing platform where you can upload sound files or image files inside Albums that you created.
The backend is written in Django / Django Rest Framework and I have multiple CRUD (one for the albums, one for the works (sound / picture), one for the users and one for the categories. The database is a PostgreSQL.
I got everything working for making the network calls but I'm struggling to structure how to handle the relations between all these objects to avoid instantiating multiple times the same object.
I'm struggling to decide how and where to store my data and if I should separate the UI stores and the data stores....
If you need more information, tell me, I'll update this post with what's needed (models, endpoints documentation,...)
I hope someone has a good advice or want to share what he does !
Thanks !

A: well actually stackoverflow is not the best place to start ;)
What you're asking here is how to architecture your app, I'll put ressources here from where you can start:

*

*Medium flutter architecture

*The very rich Brian Egan github with the live demo for each enter link description here

*Here's a list of approaches for state management from flutter
This should be a good start !!
And if you're stuck on a very specific point of code please feel free to come and ask ;)


text:
Q: Random between two letters only **
Hi everyone, I use to swim around everyday and this is my first time to ask... I wrote this code and dont know how to random M or F for gender output.. here is my code:
**
from os import linesep
from random import Random

def generaterandomrecord(firstnamelength, lastnamelength, gender):
    rnd = Random()
    generatedline = ""

    generatedline += chr(rnd.randint(65, 90))
    for index in range(0, firstnamelength):
        randomasciinumber = rnd.randint(97, 122)
        generatedline += chr(randomasciinumber)

    generatedline += " "

    generatedline += chr(rnd.randint(65, 90))
    for index in range(0, lastnamelength):
        randomasciinumber = rnd.randint(97, 122)
        generatedline += chr(randomasciinumber)

    generatedline += ","

    for index in range(0, 10):
        generatedline += str(rnd.randint(0, 10) )

    generatedline += ","

    for index in range(0, gender):
        generatedline += chr(rnd.randint(106, 115))

    return generatedline

filepath = r"t:\test.txt"

filestream = open(filepath, "w")

rnd = Random()
for index in range(0, 300):
    firstnamelength = rnd.randint(3, 5)
    lastnamelength = rnd.randint(5,7 )
    gender = rnd.randint(106, 115)
    filestream.write(generaterandomrecord(firstnamelength, lastnamelength, gender) + linesep)

filestream.flush()

filestream.close()
print("Done processing")

thank you

A: import random
print random.choice("MF")


text:
Q: How to apply a single section across multiple columns in Business Intelligence I do a lot of reporting out of our Electronic Health Record using a Business Objects product, and one thing I run into frequently is records for which most of the columns are the same, but a few may have multiple different values.
For instance, a report I'm working on has 8 columns, mostly static information about the patient/encounter, some lab values, and a column for the consulting physician.  All the columns will have only a single value per patient/encounter, except for consulting physician which may have multiple.  I'd like to somehow set the table to show only a single row for the data that is unchanged, so they don't end up seeing the FIN, MRN, and lab values over and over.
However, as far as I've been able to tell with my fiddling around, I can only apply a section or break to a single column.  Creating multiple sections or breaks nests them.  Does anybody know of a way to treat multiple columns as sort of a composite section?
edit:  I did try pulling the consulting physician column out into its own table and then setting the room number as a section, but it still caused repeated rows of the other data for any that had multiple consultings.
Additional edit: As requested here's a mockup of approximately what I'd like to see.  This is mostly how it looks already when I tell BO to use the room number (the number in blue, top left of each row) as a section, however in the case of the third room, it would repeat the information in the first 5 columns for each consulting listed.

A: Couple of ways to do it, but putting breaks on each column is what I would do.
So, starting from "FIN" and working to "Attending", add a break on each column.  It will add a summary row for each, so it will look like:

Then select the summary rows, right-click, and Delete:


text:
Q: how to parse simple JSON file to get Country name [
{
    "value": "America (America)",
    "id": "1898"
},
{
    "value": "Afghanistan",
    "id": "546"
},
{
    "value": "India",
    "id": "119"
},
{
    "value": "London",
    "id": "1884"
},
{
    "value": "Caneda",
    "id": "32"
},
{
    "value": "Australiya",
    "id": "1891"
},

A: First create a class as model :
public class Country {
    String countryName;
    String countryValue;

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

    public String getCountryValue() {
        return countryValue;
    }

    public void setCountryValue(String countryValue) {
        this.countryValue = countryValue;
    }

}

And use like this in your code :
ArrayList<Country> mCountries = new ArrayList<Country>();
            try {
                JSONArray mJsonArray = new JSONArray(response);
                for (int i = 0; i < mJsonArray.length(); i++) {
                    JSONObject mJsonObject = mJsonArray.getJSONObject(i);
                    Country mCountry = new Country();
                    mCountry.setCountryName(mJsonObject.getString("value"));
                    mCountry.setCountryValue(mJsonObject.getString("id"));
                    mCountries.add(mCountry);
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

A: Try using below code:
ArrayList<HashMap<String, String>> mylist= new ArrayList<HashMap<String, String>>();
JSONArray json = new JSONArray(result);

for(int i=0;i<json.length();i++){
    HashMap<String, String> map = new HashMap<String, String>();
    JSONObject obj = json.getJSONObject(i);

    map.put("value", obj.getString("value"));
    map.put("id", obj.getString("id"));
    mylist.add(map);
}


text:
Q: WPF performance issue when resizing the window with lots of controls I have a WPF window that contains a fancy image with roughly 200 controls (derived from buttons), all of which use one of my 5 templates (paths, shadow effects, etc).  Agreed, it is a heavy window to draw.  I can live with that.
My problem comes from resizing the window.  Maximize/Restore take about 1-2 seconds, but manually dragging the bottom-left corner causes the system to hang for about 5-10 seconds.  In that delay, the window is black & contains partial leftovers until the final result is shown.  It looks amateurish and that, I can't live with.
Remote connection : using a remote account, I found that the window resize always takes 1-2 seconds, but doesn't draw the "intermediate" stages while I'm dragging the window borders.  The result is as snappy as I would expect.
My conclusion is this: It's the redraws during the resize that are bottlenecks.
The inevitable question is this : how can I prevent redrawing the window until the resize is finished?
Thanks in advance for any ideas...

A:
@Seb:  I'm beginning to think WPF is
  not designed for interfaces that go
  beyond 2-3 controls at a time

Visual Studio 2010 and Expression Blend should be good counterexamples. Though Visual Studio sometimes freezes the bottleneck is definitely not in the WPF rendering.

@Seb: The inevitable question is this : how
  can I prevent redrawing the window
  until the resize is finished?

Simply set the window's content visibility to Visibility.Collapsed before the resize/maximize and make it visible afterwards. Though I think you asked the wrong question. Here is the right one
How to make my controls measure/arrange extremely fast?
And to answer it you should take a look at your code. Maybe you intensively use dependency properties in the measuring/arrange algorithm? Or maybe you picked wrong panels (e.g. Grid is slower than Canvas)? Or maybe... I stop guessing here :).
By the way, it's always better to launch your app under profiler and prove the bottleneck rather than assuming the place where it might be. Check Eqatec Profiler it's free yet powerful enough. VS 2010 also offers nice profiling features, though it's far from being free. And you may want to check WPF Performance Suite.
Hope this helps.

A: Let me know how this works... I am assuming that your root visual item is stretching to horizontally and vertically to fill your window with auto height/width. Get rid of the Auto height/width. On app start up set the dimensions of the root element. There is a FrameworkElements have a size changed event. Register for this on your Application.Current.MainWindow (maybe be a typo, that was from memory). Whenever this event fires, start a timer with a small interval. If you get another resize while the timer is running, ignore it and reset the timer. Once the timer fires, you now know the new size the user desires and that they have (at least for a short period) stopped resizing the window.
Hope that helps!

A: From Ragepotato's answer and your comment about needing to see roughly what the interface would look like while resizing, as long as you don't have your objects dynamically re-locating themselves (like a Wrap Panel) - you could take a screenshot of the window contents and fill your frame with it.
Set it to stretch both height and width, and you'd get a (slightly fuzzy) idea of what a particular size would be. It wouldn't be live while resizing, but for those few seconds that probably wouldn't matter..


text:
Q: Is there a way to do Bluetooth scans in a Android Instant App? It seems that every single method or property of accessing BluetoothAdapter instance would cause crashes on Instant Apps, even with android.permission.BLUETOOTH and android.permission.BLUETOOTH_ADMIN are added to AndroidManifest.xml.
I know that I cannot find bluetooth releated permissions and operations here:
https://developer.android.com/topic/google-play-instant/getting-started/instant-enabled-app-bundle
I have also tried reflection way to trigger BluetoothAdapter.enable, but got InvocationTargetException.
Wondering if there are any other workarounds?
Thanks

A: You cannot use Bluetooth as an instant app.
The narrow list of permissible permissions shown at Supported permissions and operations give hint at the greater broad of the APIs that are restricted from being used in instant apps.

*

*ACCESS_COARSE_LOCATION

*ACCESS_FINE_LOCATION

*ACCESS_NETWORK_STATE

*BILLING – Deprecated as of Play Billing Library 1.0.

*CAMERA

*INSTANT_APP_FOREGROUND_SERVICE – Only in Android 8.0 (API level 26)
and higher.

*INTERNET

*READ_PHONE_NUMBERS – Only in Android 8.0 (API level 26) and higher.

*RECORD_AUDIO

*VIBRATE

*WAKE_LOCK

If you try to use a restricted API as an instant app, it'll typically cause an exception (SecurityException, etc..) or some denial of sort.


text:
Q: Page Viewer with Side Menu (Navigation drawer) I am using REFrostedViewController as a side menu controller, the problem is this menu will appear from any point of screen, I want it to be like the Android version, which will appear only if you start swiping from the start left of screen, if swiping from any other point, the menu will not appear.
I want this because I am having a Page viewer inside this menu.
Since I am new in IOS, I looked inside the library code and didn't find any function that define the starting point also tried to modify the message
panGestureRecognized it didn't work .
So I'd like to suggest me a help or any other library that have the option.

A: If you have follow this Library then i think you have put this code too
In ViewDidLoad

    [self.view addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognized:)]];

And

- (void)panGestureRecognized:(UIPanGestureRecognizer *)sender
{
    // Dismiss keyboard (optional)
    //
    [self.view endEditing:YES];
    [self.frostedViewController.view endEditing:YES];

    // Present the view controller
    //
    [self.frostedViewController panGestureRecognized:sender];
}

Replace Above code with below code.
Confirm UIGestureRecognizerDelegate Delegate protocol

@interface DEMONavigationController () <UIGestureRecognizerDelegate>

In ViewDidLoad

    UIScreenEdgePanGestureRecognizer *leftEdgeGesture = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(handleLeftEdgeGesture:)];
    leftEdgeGesture.edges = UIRectEdgeLeft;
    leftEdgeGesture.delegate = self;
    [self.view addGestureRecognizer:leftEdgeGesture];}

And
- (void)handleLeftEdgeGesture:(UIScreenEdgePanGestureRecognizer *)gesture {

    if(UIGestureRecognizerStateBegan == gesture.state ||
       UIGestureRecognizerStateChanged == gesture.state) {
        [self.frostedViewController presentMenuViewController];

    }else{
        // DO nothing
    }
}


text:
Q: Which method is more efficient, Using DataTemplate of ListBox in XAML or populating ListBox at runtime? I was using DataTemplate in a ListBox as XAML code earlier, I have recently modified my code and now at runtime I am populating the ListBox using foreach and other loops.
(In this way I have more control for formatting and other manipulations.)
The problem is the efficiency of the code, which has decreased. It's taking 1 to 2 seconds more time now with loops than the Item/Data template in XAML earlier.
(Less control over code, lots of Bindings and converters, increasing complexity of the code which is not easy to manipulate.)
Kindly, suggest me

*

*Which way is more efficient way? and why?

*How can I still make solution with loops more efficient? Threading?

*Any friendly tutorial for learning Async threading? for non-native English speakers?

Thanks a lot and regards!

A: The XAML parser is optimized to create the controls in the best way possible given the WPF layout system, further they allow for virtualization of the items, that means that the actual controls representing the items are only created when the item is visible.
Besides that i would always prefer a DataTemplate as it is declarative, easier to read and less code.


text:
Q: psycopg2 OperationalError         import psycopg2

def creat_tabel():
    conn=psycopg2.connect("dbname='database1' user='postgres' password='postgres123' host='localhost' port='5432' ")
    cur=conn.cursor()
    cur.execute("CREATE TABLE İF NOT EXISTS store (item TEXT , quantity INTEGER , price REAL)")
    conn.commit()
    conn.close()

creat_tabel()

This is my code and this is my error. How can I fix it? Please help.
C:\Users\sinan urgun\Desktop\python\db>script2_postgresql.py
Traceback (most recent call last):
  File "C:\Users\sinan urgun\Desktop\python\db\script2_postgresql.py", line 10, in <module>
    creat_tabel()
  File "C:\Users\sinan urgun\Desktop\python\db\script2_postgresql.py", line 4, in creat_tabel
    conn=psycopg2.connect("dbname='database1' user='postgres' password='postgres123' host='localhost' port='5432' ")
  File "C:\Users\sinan urgun\AppData\Local\Programs\Python\Python39\lib\site-packages\psycopg2\__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError

A: You have a typo in your SQL. You have written "İF", where that first character is U+0130 : LATIN CAPITAL LETTER I WITH DOT ABOVE. You want to write "IF" instead.
You can see the dot above the I in your question; you should also be able to see this in your local editor. If this is a regular problem you may want to experiment with different fonts that make the issue more obvious.


text:
Q: Index of list item clicked does not reset On a fresh page load, the code works just fine and will display the correct information, but if you navigate backwards and try again, it displays the information from the first click. First off, here is the code and I will explain what I have...
$(document).on('pageinit', '#months', function(){
    $('#listOfHolidays').on('click', 'li', function () {
        listIndex = $(this).index();
        $.mobile.changePage('#detail');
    });
});
$(document).on('pageinit', '#detail', function(){
    console.log(listIndex);
    $('#ho').text(holidayNames[listIndex]);
    $('#hi').text('The index of the list item clicked is: ' + listIndex);

});

I have 2 pages (divs with data-role="page") named #months, which is the one containing my list of items to select from, and #detail which is a page that I want to populate based on the user's choice from the list. The id for my listview is #listOfHolidays and the array which holds the values of each item in the list is called holidayNames. I then display this basic info in the detail page in divs called #hi and #ho (some of this will be changed, I am just trying to test my way out of this problem). I have a back button enabled in the header of detail also.
Like I said, when I load this fresh, the correct holiday name and index number show up in my detail page, but when I use the back button to navigate back and try again, it populates the detail page with the same info from the first click.
I would assume this is because jquery is initializing the detail page in the second $(document).on() function with 'pageinit' and since it is initialized with the first index and holiday name I choose, it just doesn't need to initialize again and draws the data from the first request when I click another list item.
That is my vague understanding of what is going on, so please correct me where I'm wrong and guide me in the right direction!
Thanks!

A: The 'pageinit' event only fires when the page is introduced to the DOM. Thus the code you have bound to replace the holiday text with the new one, only fires on the original click. The next few clicks do not cause that function to fire.
If you bind to the 'pagebeforeshow' then it will trigger everytime you change pages and you can bind the same function there and it should work correctly.
$(document).on('pagebeforeshow', '#detail', function () {
  console.log(listIndex);
  $('#ho').text(holidayNames[listIndex]);
  $('#hi').text('The index of the list item clicked is: ' + listIndex);
});

I removed some things to simplify the example.
JSFiddle example


text:
Q: Setting column classes and assigning factor levels, without using a loop I have been grappling with the following problem for a while, as I need to load in, manipulate, and produce scores from new datasets as quickly as possible. I have defined a data dictionary containing a description of each variable class (e.g. numeric, factor, character, date) and, where applicable, a list of all possible factor levels:
DD <- data.frame(Var = c("a", "b", "c", "d"),
   Class = c("Numeric", "Factor", "Factor", "Date"),
   Levels = c(NA, "B1, B2, B3", "C1, C2", NA))

Data <- data.frame(a = 5, b = "B1", c = "C2", d = "2015-05-01")

Ultimately, I intend to use model.matrix to produce a design matrix with a common set of indicator variables/ columns regardless of the actual factor levels observed in the particular dataset, so I can accurately score up the data from a model.
I need to do these tasks as quickly as possible and, hence, I am trying to find a solution that avoids using lapply/ loops. Here is (a slightly convoluted version of) my existing solution for setting the factor levels, which is currently too slow for my requirements:
lapply(1:ncol(Data[,DD$Class=="Factor"]), function(i) {
   factor( as.character( unlist( Data[,DD$Class=="Factor"][i])) ,
   levels = unlist(strsplit(as.character(DD$Levels[DD$Class=="Factor"][i]), ", ")) )
})

Any suggestions for avoiding use of a loop here, if it is even possible, or any alternative solutions would be much appreciated!
Thanks!

A: *

*First remark

It is inefficient to store the levels as a single string that needs to be parsed. I suggest using a list and storing the levels as a character vector directly.
DD <- list(a = list(class="numeric"),
           b = list(class="factor", levels = c("B1", "B2", "B3")),
           c = list(class="factor", levels = c("C1", "C2")),
           b = list(class="Date"))

*

*Second remark:

You don't need to "unfactor" your factor to add new levels.
Example:
fac <- factor(c("a", "b", "a"))
# two levels

factor(fac, letters)
# 26 levels, data has not changed

*

*Third remark

I don't see how to avoid a "loop" here, but lapply is an efficient way of performing loop, I doubt this is the performance bottleneck. With remarks 1 and 2, you can write a more efficient inner function. Ditching the data.frame for a data.table or a tbl may prove useful too.

A: You can define column classes (and hence levels for your factors) right when you create your data frame:
mylevels <- c("b1","b2","b3","c1","c2")

myData <- data.frame(a =
numeric(), b = factor(levels=mylevels), c = factor(levels=mylevels), d
= character())

This creates a blank data frame that you can fill up later.
In reply to your comment: rbind will only work if  myData has same column classes as data. Otherwise column classes will change. My point is: if data that you load is similar (has same number of columns, columns have same names, etc.) then you can set classes right when you load that data, something like:
myclasses <- c("numeric","factor","factor","date")
myData <- read.table("mydatafile.csv", sep=",", header = TRUE, colClasses = myclasses)
myLevels <- c("a1","a2","b1","b2")
myfactorlist <- c("b","c")
levels(myData[,myfactorlist]) <- myLevels

here I assume your column names are as in previous example: "a","b","c","d", where "c" and "b" are factor columns.

A: You are going to have iterate over the columns but it could be done in a bit cleaner fashion like this.  We have assumed you want to preserve the input data frame so we create a new data frame, Data2 to hold the result.  Note that we have made the columns of DD character rather than factor.  Data is from the question.
DD <- data.frame(Var = c("a", "b", "c", "d"),
   Class = c("Numeric", "Factor", "Factor", "Date"),
   Levels = c(NA, "B1, B2, B3", "C1, C2", NA), stringsAsFactors = FALSE)

Data2 <- Data

# factors
Factors <- subset(DD, Class == "Factor")
Levels <- strsplit(as.character(Factors$Levels), ", ")
Data2[Factors$Var] <- Map(factor, Data2[Factors$Var], Levels)

# dates
Dates <- subset(DD, Class == "Date")
Data2[Dates$Var] <- Map(as.Date, Data2[Dates$Var])

giving:
> str(Data2)
'data.frame':   1 obs. of  4 variables:
 $ a: num 5
 $ b: Factor w/ 3 levels "B1","B2","B3": 1
 $ c: Factor w/ 2 levels "C1","C2": 2
 $ d: Date, format: "2015-05-01"


text:
Q: Change element property based on placement of another element - jQuery I'm having trouble working out how I can target a super annoying edgecase I'm having.
How can I target the h1, that comes after the cite tag?
As cite is wrapped inside the p tag, I don't know how to traverse out to target it.
The gap between the cite (technically the p) is too large, yet on 'non-cite' paragraphs, it is fine.
TL:DR -
Check if a paragraph has a cite tag inside of it, then if it does - change the padding-top on the h1 tag to something less. If the paragraph doesn't have a cite inside, leave it untouched.
http://codepen.io/anon/pen/Jksam
HTML
<link href='http://fonts.googleapis.com/css?family=Lato:400,900' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Gentium+Book+Basic:400,400italic,700,700italic' rel='stylesheet' type='text/css'>

          "Work is the curse of the drinking classes."

          Oscar Wilde

       This is a H1

       Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.

       This is a H1

CSS
.post {
  width: 50%;
  padding-left: 25%;
  padding-top: 3rem;
}

h1 {
  color: #333332;
  font-family: 'Lato', sans-serif;
  padding-top: 1.5rem;
  padding-bottom: 1rem;
  font-weight: 900;
  font-size: 3.3rem;
}

p + h1 {
  padding-top: 4rem;
}

blockquote {
  border-left: 4px solid #ED5565;
  margin-left: -24px;
  margin-top: -1px;
}

cite {
  color: #b3b3b1;
  font-family: 'Lato', sans-serif;
  font-weight: 400;
  font-size: 0.8rem;
  position: relative;
  top: -15px;
  padding: 0;
  margin: 0;
}

cite:before {
  content: "- ";
}

blockquote > p {
  padding: 1em;
  margin: 0;
}

p {
  color: #333332;
  font-family: 'Gentium Book Basic', serif;
  font-weight: 400;
  font-size: 1.5rem;
  line-height: 1.8rem;
  padding-bottom: 1rem;
  padding-top: 1rem;
}

A: You can use .has() method or :has selector:
$('p').has('cite').next('h1').css({'padding-top': 'value'});

Assuming all next h1 siblings of the selected p should be selected:
$('p').has('cite').nextAll('h1').css({'padding-top': 'value'});

A: another way would be to start from the cite tag using then use .closest() to get to the p tag - then get the next h1 element
$('cite').closest('p').next('h1').css('padding-top','50px')


text:
Q: How to optimize Powershell script with Get-ChildItem consuming all RAM I have this script which parses all shares on a file server to gather information on share size, ACLs, and count of files and folders. The script works great on smaller file servers but on hosts with large shares it consumes all RAM and crashes the host, I can't seem to figure out how to optimize the script during the Get-ChildItem portion to not consume all RAM.
I found a few articles which mentioned to use a foreach loop and pipe out what I need. I am a Powershell beginner, I can't figure out how to get it to work like that. What can I try next?
$ScopeName     = Read-Host "Enter scope name to gather data on"
$SavePath      = Read-Host "Path to save results and log to"
$SaveCSVPath   = "$SavePath\ShareData.csv"
$TranscriptLog = "$SavePath\Transcript.log"

Write-Host
Start-Transcript -Path $TranscriptLog

$StartTime = Get-Date
$Start     = $StartTime | Select-Object -ExpandProperty DateTime

$Exclusions = {$_.Description -ne "Remote Admin" -and $_.Description -ne "Default Share" -and $_.Description -ne "Remote IPC" }
$FileShares = Get-SmbShare -ScopeName $ScopeName | Where-Object $Exclusions
$Count      = $FileShares.Count
Write-Host
Write-Host "Gathering data for $Count shares" -ForegroundColor Green
Write-Host
Write-Host "Results will be saved to $SaveCSVPath" -ForegroundColor Green
Write-Host

ForEach ($FileShare in $FileShares)
{
    $ShareName = $FileShare.Name
    $Path      = $Fileshare.Path

    Write-Host "Working on: $ShareName - $Path" -ForegroundColor Yellow

    $GetObjectInfo = Get-Childitem -Path $Path -Recurse -Force -ErrorAction SilentlyContinue

    $ObjSize = $GetObjectInfo | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue

    $ObjectSizeMB = "{0:N2}" -f ($ObjSize.Sum / 1MB)
    $ObjectSizeGB = "{0:N2}" -f ($ObjSize.Sum / 1GB)
    $ObjectSizeTB = "{0:N2}" -f ($ObjSize.Sum / 1TB)

    $NumFiles   = ($GetObjectInfo | Where-Object {-not $_.PSIsContainer}).Count
    $NumFolders = ($GetObjectInfo | Where-Object {$_.PSIsContainer}).Count

    $ACL            = Get-Acl -Path $Path
    $LastAccessTime = Get-ItemProperty $Path | Select-Object -ExpandProperty LastAccessTime
    $LastWriteTime  = Get-ItemProperty $Path | Select-Object -ExpandProperty LastWriteTime

    $Table = [PSCustomObject]@{
        'ScopeName'          = $FileShare.ScopeName
        'Sharename'          = $ShareName
        'SharePath'          = $Path
        'Owner'              = $ACL.Owner
        'Permissions'        = $ACL.AccessToString
        'LastAccess'         = $LastAccessTime
        'LastWrite'          = $LastWriteTime
        'Size (MB)'          = $ObjectSizeMB
        'Size (GB)'          = $ObjectSizeGB
        'Size (TB)'          = $ObjectSizeTB
        'Total File Count'   = $NumFiles
        'Total Folder Count' = $NumFolders
        'Total Item Count'   = $GetObjectInfo.Count
    }

    $Table | Export-CSV -Path $SaveCSVPath -Append -NoTypeInformation
}

$EndTime = Get-Date
$End     = $EndTime | Select-Object -ExpandProperty DateTime

Write-Host
Write-Host "Script start time: $Start" -ForegroundColor Green
Write-Host "Script end time: $End" -ForegroundColor Green

Write-Host
$ElapsedTime = $(($EndTime-$StartTime))
Write-Host "Elapsed time: $($ElapsedTime.Days) Days $($ElapsedTime.Hours) Hours $($ElapsedTime.Minutes) Minutes $($ElapsedTime.Seconds) Seconds $($ElapsedTime.MilliSeconds) Milliseconds" -ForegroundColor Cyan

Write-Host
Write-Host "Results saved to $SaveCSVPath" -ForegroundColor Green

Write-Host
Write-Host "Transcript saved to $TranscriptLog" -ForegroundColor Green

Write-Host
Stop-Transcript

A: To correctly use the PowerShell pipeline (and preserve memory as each item is streamed separately), use the PowerShell ForEach-Object cmdlet (unlike the ForEach statement) and avoid assigning the pipeline to a variable (as you doing with $FileShares = ...) and don't use parenthesis ((...)) arround the the pipeline:
Get-SmbShare -ScopeName $ScopeName | Where-Object $Exclusions | ForEach-Object {

And replace all $FileShare variables in your loop with the current item: $_ variable (e.g. $FileShare.Name → $_.Name).
For the Get-Childitem part you might do the same thing (stream! meaning: use the mighty PowerShell pipeline rather than piling everything up in $GetObjectInfo):
$ObjSize = Get-Childitem -Path $Path -Recurse -Force -ErrorAction SilentlyContinue |
    Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue

As an aside; you might simplify your 3 size properties to a single smarter size property, see: How to convert value to KB, MB, or GB depending on digit placeholders?
addition
"But isn't putting everything into $ObjSize just swapping one variable for another?"
No it is not, think of the PowerShell pipeline as an assembly line. In this case, at the first station you take each single file information and pass it to the next (last) station where you just sum the length property and the current (file) object disposed.
Where in your question example, you read the information of all files in once and store it into $GetObjectInfo and than go to the whole list to just use (add) the length property of the (quiet heavy) PowerShell file objects.
But why don't you try it?:
Open a new PowerShell session and run:
$Path = '.'
$GetObjectInfo = Get-Childitem -Path $Path -Recurse -Force -ErrorAction SilentlyContinue
$ObjSize = $GetObjectInfo | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue
Get-Process -ID $PID

Now, open a new session again and use the PowerShell pipeline:
$Path = '.'
$ObjSize = Get-Childitem -Path $Path -Recurse -Force -ErrorAction SilentlyContinue |
           Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue
Get-Process -ID $PID

Notice the difference in memory usage (WS(M)).

A: You are buffering the entire collection of [FileSystemInfo] on $FileShare into a variable with...
$GetObjectInfo = Get-Childitem -Path $Path -Recurse -Force -ErrorAction SilentlyContinue

So, if there's a million directories and files on that share then that's a million [FileSystemInfo] instances stored in a million-element array, none of which can be garbage collected during that iteration of the foreach loop.  You can use Group-Object to improve that a bit...
$groupsByPSIsContainer = Get-Childitem -Path $Path -Recurse -Force -ErrorAction SilentlyContinue |
    Group-Object -Property 'PSIsContainer' -AsHashTable
# $groupsByPSIsContainer is a [Hashtable] with two keys:
#     - $true gets the collection of directories
#     - $false gets the collection of files

$ObjSize = $groupsByPSIsContainer[$false] | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue

$NumFiles   = $groupsByPSIsContainer[$false].Count
$NumFolders = $groupsByPSIsContainer[$true].Count

...but that still ends up storing all of the [FileSystemInfo]s in the two branches of the [Hashtable].  Instead, I would just enumerate and count the results myself...
$ObjSize    = 0L # Stores the total file size directly; use $ObjSize instead of $ObjSize.Sum
$NumFiles   = 0
$NumFolders = 0

foreach ($fileSystemInfo in Get-Childitem -Path $Path -Recurse -Force -ErrorAction SilentlyContinue)
{
    if ($fileSystemInfo.PSIsContainer)
    {
        $NumFolders++
    }
    else
    {
        $NumFiles++
        $ObjSize += $fileSystemInfo.Length
    }
}

That stores only the current enumeration result in $fileSystemInfo and never the entire sequence.
Note that if you weren't summing the files' sizes Group-Object would work well...
$groupsByIsContainer = Get-Childitem -Path $Path -Recurse -Force -ErrorAction SilentlyContinue |
    Group-Object -Property 'PSIsContainer' -NoElement

$NumFiles   = ($groupsByIsContainer | Where-Object -Property 'Name' -EQ -Value $false).Count
$NumFolders = ($groupsByIsContainer | Where-Object -Property 'Name' -EQ -Value $true ).Count

-NoElement prevents the resulting group objects from storing the grouped elements; we just care about the count of members in each grouping but not the members themselves.  If we passed -AsHashTable then we'd lose the convenient Count property, hence why the two groups have to be accessed in this awkward way.


text:
Q: Using "pub serve", how do I serve a root resource? I am using "pub serve" to serve my Dart web app.  Pub is running at http://localhost:8080/.
I can access my app at http://localhost:8080/index.html which loads the index.html file in the web directory in my project.
I would like to be able to load the same index.html directly from http://locahost:8080/.  How do I do accomplish this task?

A: This is probably what you are looking for:
"pub serve" should support index.html and directory listing


text:
Q: In Visual Studio, is it possible to add an add-in assembly as a reference to another assembly in the solution? I am using Visual Studio 2010.  I have multiple C# projects in my solution.  One of the projects is an Excel Add-In.  I want to be able to write unit tests on some of the code that I have in the Excel Add-In project.  To do this, I have created another project in the solution.  I want this test project to be able to reference the Add-In project. However, the Add-In project does not show up on the Projects tab of the Add Reference dialog.  The only way that I have been able to do anything is by adding the Add-In dll file as a reference in the test project.  This is not ideal, because a new dll would have to be generated whenever changes are made in the Add-In project.  Is this a limitation of Excel Add-In projects?  Or do I need to set the Excel Add-In project up in a particular way to make it visible to the test project?

A: Why dont you just create the test classes under a different namespace in the excel addin?
ExcelAddin.Tests

If you are not familiar with namespaces then take a look here: http://msdn.microsoft.com/en-us/library/z2kcy19k(VS.80).aspx


text:
Q: Troubles: JavaFX Webview + Windows8.1 + 1920x1080 = unusable small fonts unfortunately i have some problems with my new notebook and javafx development.
Whenever i use a webview to display content in my program i'm getting really small and nearly unreadable fonts - now i'm not sure what exactly the problem is:

*

*Is it the new Win8.1 environment which is extremly bad for javaFX (+webView) development, or

*Is it the new notebook with 1920x1080 resolution on an 13" display which is way to much for a small screen, or

*Is it only a matter of configuration and i've overseen some basics :-)

i would really appreciate every possible suggestion
thanks :)
p.s.: I'm using JDK7 and NetBean 7.4 - i also tried JDK8 but that didn't change anything?!

A: Apply the WebView fontScaleProperty to scale the text displayed in the WebView.
If you think it's an issue (e.g. the fontScaleProperty should default to some better value for your particular configuration), you might want to also take a screenshot (maybe even a digital photo of the laptop screen), and log an issue in the JavaFX issue tracker.


text:
Q: useEffect not updating unless I refresh I have a custom Hook:
import React, { useState, useEffect } from 'react';
import firebase from "../../firebase";

export default function useCurrentUserDetails() {
    const uid = firebase.auth().currentUser?.uid;
    const [data, setData] = useState(null);

    useEffect(() => {
        if (!uid) {
            setData(null);
            return;
        }

        const unsubscribe = firebase.firestore().collection("users").doc(uid).onSnapshot((snapshot) => {
            if (snapshot.exists) {
                setData(snapshot.data());
            } else {
                setData(null);
            }
        })

        return unsubscribe;
    }, [uid]);

    const updateCurrentUserData = (newData) => firebase.firestore().collection("users").doc(uid).set(newData);

    return [data, updateCurrentUserData];
}

When im using this is should just get the user from firebase and I should be able to use the data. Im using it like this:
function HomeScreen({navigation}) {

    const [currentUserDetails, setCurrentUserDetails] = useCurrentUserDetails();
    const [username, setUsername] = useState("")

    useEffect(() => {
        setUsername(currentUserDetails?.name);
    }, [currentUserDetails]);

    return (
        <Screen style={styles.screen}>
            <View>
                <Text>Hello</Text>
                <Text style={styles.nameText}>{username}</Text>
            </View>
        </Screen>
    )
}

When the screen firsts loads, the username doesn't show, but lets says i change to:
<Text style={styles.nameText}>{name}</Text>

and refresh the app, the name shows. And now if i change it back to username:
<Text style={styles.nameText}>{username}</Text>

it works.
It just doesn't show when I open up the screen, I need to refresh the variable for it to work.

A: Your useEffect is using the value of currentUserDetails, but you are not passing it as a dependencie to the hook:
 useEffect(() => {
        setUsername(currentUserDetails?.name);
    }, [currentUserDetails]);

A: if you trying to update state when component did mount try this:
useEffect(() => {
        if (!uid) {
            setData(null);
            return;
        }[])


text: Q: Connecting Teiid with Elastic Search I am trying to connect Teiid with Elastic Search. I downloaded wildfly and teiid.jboss.org/downloads/.I don't know what to do next .The documentation is confusing please help me.


text:
Q: if $f \in L^1,$ is there a Riemann integrable $g$ s.t. $f=g$ almost everywhere? I'm currently studying the basic properties of $L^p$ spaces, and the following question popped to my mind.
If $f \in L^1(\mathbb{R}),$ does it hold that there exists a Riemann integrable function $g$ such that $f=g$ almost everywhere? I can't immediately come up with neither a proof nor a counterexample.

A: The following example comes from Carothers. Let $G$ be an open subset of $[0,1]$ containing the rationals in $[0,1]$ such that the outer measure of $G$, $\lambda^*(G)$, satisfies $\lambda^*(G)<1/2$. If $f=1_G$, then $f$ is not Riemann integrable, and also cannot be equal a.e. to ANY Riemann integrable function. See if you can show this! A key result in doing so is that for a bounded function $f$, $f$ is Riemann integrable if and only if $f$ is continuous at almost every point.


text:
Q: Hand cursor not showing on links when Safari is inactive As the title says, every browser can show the hand cursor on links even when the window is inactive, but that's unfortunately not working on Safari v5.1.7 on Windows, last version installed today.
Does anyone know if that's a Safari bug? Has anyone an idea of how to solve or if it's possible to solve?

A: Yeah, that was a bug in safari.


text:
Q: Encode and assemble multiple features in PySpark I have a Python class that I'm using to load and process some data in Spark. Among various things I need to do, I'm generating a list of dummy variables derived from various columns in a Spark dataframe. My problem is that I'm not sure how to properly define a User Defined Function to accomplish what I need.
I do currently have a method that, when mapped over the underlying dataframe RDD, solves half the problem (remember that this is a method in a larger data_processor class):
def build_feature_arr(self,table):
    # this dict has keys for all the columns for which I need dummy coding
    categories = {'gender':['1','2'], ..}

    # there are actually two differnt dataframes that I need to do this for, this just specifies which I'm looking at, and grabs the relevant features from a config file
    if table == 'users':
        iter_over = self.config.dyadic_features_to_include
    elif table == 'activty':
        iter_over = self.config.user_features_to_include

    def _build_feature_arr(row):
        result = []
        row = row.asDict()
        for col in iter_over:
            column_value = str(row[col]).lower()
            cats = categories[col]
            result += [1 if column_value and cat==column_value else 0 for cat in cats]
        return result
    return _build_feature_arr

Essentially what this does is, for the specified dataframe, takes the categorical variable values for the specified columns, and returns a list of the values of these new dummy variables. That means the following code:
data = data_processor(init_args)
result = data.user_data.rdd.map(self.build_feature_arr('users'))

returns something like:
In [39]: result.take(10)
Out[39]:
[[1, 0, 0, 0, 1, 0],
 [1, 0, 0, 1, 0, 0],
 [1, 0, 0, 0, 0, 0],
 [1, 0, 1, 0, 0, 0],
 [1, 0, 0, 1, 0, 0],
 [1, 0, 0, 1, 0, 0],
 [0, 1, 1, 0, 0, 0],
 [1, 0, 1, 1, 0, 0],
 [1, 0, 0, 1, 0, 0],
 [1, 0, 0, 0, 0, 1]]

This is exactly what I want in terms of generating the list of dummy variables I want, but here's my question: How can I either (a) make a UDF with similar functionality that I can use in a Spark SQL query (or some other way, I suppose), or (b) take the RDD resulting from the map described above and add it as a new column to the user_data dataframe?
Either way, what I need to do is generate a new dataframe containing the columns from user_data, along with a new column (let's call it feature_array) containing the output of the function above (or something functionally equivalent).

A: Spark >= 2.3, >= 3.0
Since Spark 2.3 OneHotEncoder is deprecated in favor of OneHotEncoderEstimator. If you use a recent release please modify encoder code
from pyspark.ml.feature import OneHotEncoderEstimator

encoder = OneHotEncoderEstimator(
    inputCols=["gender_numeric"],
    outputCols=["gender_vector"]
)

In Spark 3.0 this variant has been renamed to OneHotEncoder:
from pyspark.ml.feature import OneHotEncoder

encoder = OneHotEncoder(
    inputCols=["gender_numeric"],
    outputCols=["gender_vector"]
)

Additionally StringIndexer has been extended to support multiple input columns:
StringIndexer(inputCols=["gender"], outputCols=["gender_numeric"])

Spark < 2.3
Well, you can write an UDF but why would you? There are already quite a few tools designed to handle this category of tasks:
from pyspark.sql import Row
from pyspark.ml.linalg import DenseVector

row = Row("gender", "foo", "bar")

df = sc.parallelize([
  row("0", 3.0, DenseVector([0, 2.1, 1.0])),
  row("1", 1.0, DenseVector([0, 1.1, 1.0])),
  row("1", -1.0, DenseVector([0, 3.4, 0.0])),
  row("0", -3.0, DenseVector([0, 4.1, 0.0]))
]).toDF()

First of all StringIndexer.
from pyspark.ml.feature import StringIndexer

indexer = StringIndexer(inputCol="gender", outputCol="gender_numeric").fit(df)
indexed_df = indexer.transform(df)
indexed_df.drop("bar").show()

## +------+----+--------------+
## |gender| foo|gender_numeric|
## +------+----+--------------+
## |     0| 3.0|           0.0|
## |     1| 1.0|           1.0|
## |     1|-1.0|           1.0|
## |     0|-3.0|           0.0|
## +------+----+--------------+

Next OneHotEncoder:
from pyspark.ml.feature import OneHotEncoder

encoder = OneHotEncoder(inputCol="gender_numeric", outputCol="gender_vector")
encoded_df = encoder.transform(indexed_df)
encoded_df.drop("bar").show()

## +------+----+--------------+-------------+
## |gender| foo|gender_numeric|gender_vector|
## +------+----+--------------+-------------+
## |     0| 3.0|           0.0|(1,[0],[1.0])|
## |     1| 1.0|           1.0|    (1,[],[])|
## |     1|-1.0|           1.0|    (1,[],[])|
## |     0|-3.0|           0.0|(1,[0],[1.0])|
## +------+----+--------------+-------------+

VectorAssembler:
from pyspark.ml.feature import VectorAssembler

assembler = VectorAssembler(
    inputCols=["gender_vector", "bar", "foo"], outputCol="features")

encoded_df_with_indexed_bar = (vector_indexer
    .fit(encoded_df)
    .transform(encoded_df))

final_df = assembler.transform(encoded_df)

If bar contained categorical variables you could use VectorIndexer to set required metadata:
from pyspark.ml.feature import VectorIndexer

vector_indexer = VectorIndexer(inputCol="bar", outputCol="bar_indexed")

but it is not the case here.
Finally you can wrap all of that using pipelines:
from pyspark.ml import Pipeline
pipeline = Pipeline(stages=[indexer, encoder, vector_indexer, assembler])
model = pipeline.fit(df)
transformed = model.transform(df)

Arguably it is much robust and clean approach than writing everything from scratch. There are some caveats especially when you need consistent encoding between different datasets. You can read more in the official  documentation for StringIndexer and VectorIndexer.
Another way to get a comparable output is RFormula which:

RFormula produces a vector column of features and a double or string column of label. Like when formulas are used in R for linear regression, string input columns will be one-hot encoded, and numeric columns will be cast to doubles. If the label column is of type string, it will be first transformed to double with StringIndexer. If the label column does not exist in the DataFrame, the output label column will be created from the specified response variable in the formula.

from pyspark.ml.feature import RFormula

rf = RFormula(formula="~ gender +  bar + foo - 1")
final_df_rf = rf.fit(df).transform(df)

As you can see it is much more concise, but harder to compose doesn't allow much customization. Nevertheless the result for a simple pipeline like this one will be identical:
final_df_rf.select("features").show(4, False)

## +----------------------+
## |features              |
## +----------------------+
## |[1.0,0.0,2.1,1.0,3.0] |
## |[0.0,0.0,1.1,1.0,1.0] |
## |(5,[2,4],[3.4,-1.0])  |
## |[1.0,0.0,4.1,0.0,-3.0]|
## +----------------------+

final_df.select("features").show(4, False)

## +----------------------+
## |features              |
## +----------------------+
## |[1.0,0.0,2.1,1.0,3.0] |
## |[0.0,0.0,1.1,1.0,1.0] |
## |(5,[2,4],[3.4,-1.0])  |
## |[1.0,0.0,4.1,0.0,-3.0]|
## +----------------------+

Regarding your questions:

make a UDF with similar functionality that I can use in a Spark SQL query (or some other way, I suppose)

It is just an UDF like any other. Make sure you use supported types and beyond that everything should work just fine.

take the RDD resulting from the map described above and add it as a new column to the user_data dataframe?

from pyspark.ml.linalg import VectorUDT
from pyspark.sql.types import StructType, StructField

schema = StructType([StructField("features", VectorUDT(), True)])
row = Row("features")
result.map(lambda x: row(DenseVector(x))).toDF(schema)

Note:
For Spark 1.x replace pyspark.ml.linalg with pyspark.mllib.linalg.


text:
Q: Sum of $\sum_{n=1}^{\infty}\frac{n}{2^n}$. I was trying to find the sum of $\sum_{n=1}^{\infty}\frac{n}{2^n}$.
I tried like this $S = \sum_{n=1}^{\infty}\frac{n}{2^n} = \sum_{n=1}^{\infty}(\frac{n+1}{2^n} - \frac{1}{2^n}) = 2\sum_{n=2}^{\infty}\frac{n}{2^n} - 1$
So,$S = 2(S - \frac{1}{2}) - 1$
Implying $S =2$.
EDIT:
Also from many posts in the comment below I found a method of looking at the sum $\sum x^n$ and differentiating and plugging for $x$.
Is there any other method of looking at the problem and calculating the sum apart from the above method,may be it would be interesting to see different approaches to the same problem which may be used to visualize other problems based on summation of series?

A: Multiply with $(2-1)$:
$$ (2-1)\sum_{n=1}^\infty n2^{-n}=\sum_{n=1}^\infty(n2^{1-n}-n2^{-n})=\sum_{n=0}^\infty (n+1)2^{-n}-\sum_{n=1}^\infty n2^{-n}=\sum_{n=0}^\infty2 ^{-n}$$

A: Summing $x^n$ gives $\frac{1}{1-x}-1$, so summing $nx^{n-1}$ gives $\frac{1}{(1-x)^2}$. Set $x=1/2$.

A: Hint: Use the geometric series
$$\frac{1}{1-u}=\sum_{n=0}^{\infty}u^n.$$
This series is uniformly convergent for $|u|\leq 1$, hence we can differentiate it with respect to $u$, in which $|u|\leq 1$.
$$-\frac{1}{(1-u)^2}=\sum_{n=1}^{\infty}n^{} u^{n-1} \implies -\frac{u}{(1-u)^2}=\sum_{n=1}^{\infty}n^{} u^{n} .$$
Relate this sum to your sum, in which $u=1/2$. Note, that your series is starting at $n=2$ and this series is starting at $n=1$.


text:
Q: Have PDF appear in HTML rather than loading with Adobe or into separate window I have a java web application that in theory, when working correctly, will display a PDF in the browser window next to some input text boxes so that an employee could index the document and store it away.
JSP URL: localhost:1234/Application
What is currently happening is this:
->User tells JSP to tell servlet to go into filesystem and grab a batch of PDFs
-->JSP displays which batch(folder) was grabbed, and the files contained inside the folder to the screen
EXAMPLE:
Folder1:
-document1 (button)
-document2 (button)
-document3 (button)
--->Person clicks on button that appears next to document name on the JSP and the servlet serves up the PDF data in a byte array as follows:
File file = new File(Dir + "\\" + batchName + "\\" + fileName);
byte[] by = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(by);
fis.close();

response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment; filename=TheDocument." + "pdf");
response.getOutputStream().write(by);
response.getOutputStream().flush();
response.getOutputStream().close();

The PDF then opens in a SEPARATE WINDOW than what the application is running on, and the PDF file is downloaded to the machine into the downloads folder
What happens after this does not matter in the scope of this question.
What I WANT to happen is this:

*

*User tells JSP to tell servlet to go into filesystem and grab a batch of PDFs

*JSP displays which batch(folder) was grabbed, and the files contained inside the folder to the screen

*Person clicks on button next to document name in the JSP and the servlet serves up the PDF document and loads it into the html page so that the person can view it in real time on the same window and do their indexing.

Changing the header to inline does not give me the desired effect as it loads the PDF in the same browser window, but only by clicking back can I get back to my JSP.  It essentially loads up a whole new HTML/JSP window. The browser actually points right to my servlet in this case:
localhost:1234/Application/Servlet
Below is what I want the application to look like:

I've looked into several jquery plugins such as PDFObject, Colorbox and many others.  I do not seem to get the desired effect that I want.

A: You could use pdf.js to render the pdf, with a Flash fallback for browser that aren't supported by pdf.js.
The helloworld example renders a pdf in a <canvas> element.

A: Whether a PDF opens in a separate application or in the browser is a setting in the browser, in Adobe, and in Windows Explorer (assuming Windows).  You have no control over it, short of displaying your PDF in a Flash app, and then the user might not have Flash.

A: Not sure if this is what you are looking for but typically you can put a PDF in an iframe and have it opened up that way. The PDF just needs to be published on your server.
This answer may help you:
How to open a PDF file in an <iframe>?


text:
Q: GDAL loads in Python, but not IPython (Linux) I am trying my hardest to utilize the work of the good folks at the GeoDa center, but I cannot seem to get all of the components to load.  GDAL, in particular, has been giving me some difficulty.  The biggest issue arises because I am operating within the IPython Notebook.  If you are unfamiliar with the Notebook, to say it's worth a look is the understatement of the century.
In any event, after some difficulty and some assistance, I was able to install the GDAL module.  It was even importable at the Python prompt:
Python 2.7.5 |Anaconda 1.6.1 (64-bit)| (default, Jun 28 2013, 22:10:09)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gdal
>>>

However, after my difficulties in the Notebook, I went back to the IPython prompt to discover the following difficulty:
Python 2.7.5 |Anaconda 1.6.1 (64-bit)| (default, Jun 28 2013, 22:10:09)
Type "copyright", "credits" or "license" for more information.

IPython 1.0.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import gdal
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-27bf4694dd2b> in <module>()
----> 1 import gdal

/home/choct155/analysis/Anaconda/lib/python2.7/site-packages/gdal.py in <module>()
      1 # import osgeo.gdal as a convenience
----> 2 from osgeo.gdal import deprecation_warn
      3 deprecation_warn('gdal')
      4
      5 from osgeo.gdal import *

/home/choct155/analysis/Anaconda/lib/python2.7/site-packages/osgeo/__init__.py in <module>()
     19                 fp.close()
     20             return _mod
---> 21     _gdal = swig_import_helper()
     22     del swig_import_helper
     23 else:

/home/choct155/analysis/Anaconda/lib/python2.7/site-packages/osgeo/__init__.py in swig_import_helper()
     15         if fp is not None:
     16             try:
---> 17                 _mod = imp.load_module('_gdal', fp, pathname, description)
     18             finally:
     19                 fp.close()

ImportError: /usr/lib/libgdal.so.1: undefined symbol: sqlite3_column_table_name

Has anyone else encountered this issue?
I know that sqlite3 is an installed module already, so if I can't see it being a dependency issue.  That being said, I am not sure where to start beyond poking around the osgeo source.
I am using Ubuntu 13.04.
I first discovered this problem when having trouble with the R package, rgdal from within Notebook (but curiously not from within RStudio).  Upon discovering deficiencies on the Python side as well, I thought it might be useful to talk to a more spatially-focused crowd.

With respect to the first comment (SQLite), how would I verify that one was using a different version from the other?
I checked the paths in os.environment, and they are the same.
With respect to the latter, sys.executable was identical (and I initiated both from the same working directory):
>>> import sys, os
>>> sys.executable
'/home/choct155/analysis/Anaconda/bin/python'

In [2]: import sys, os

In [3]: sys.executable
Out[3]: '/home/choct155/analysis/Anaconda/bin/python'

However, I did find differences in os.environ:
print set(python_environ.items())-set(ipython_environ.items())

print set(ipython_environ.items())-set(python_environ.items())
*****************************
set([('OLDPWD', '/home/choct155/analysis/fwtools/FWTools-linux-x86_64-3.0.6'), ('WINDOWID', '54529262'), ('_', '/home/choct155/analysis/Anaconda/bin/python'), ('C_INCLUDE_PATH', '/usr/include/gdal'), ('CPLUS_INCLUDE_PATH', '/usr/include/gdal')])
set([('WINDOWID', '54526233'), ('_', '/home/choct155/analysis/Anaconda/bin/ipython'), ('OLDPWD', '/tmp/pip-build-root/GDAL')])

To my eye, the environmental variables that I set in .bashrc (the include paths) are the elephant in the room.  In fact, without these set, I couldn't get GDAL to install at all.  What I am not clear on is why they would apply only to Python when IPython is using the same Python executable as the back end.
Sidenote: To those that are working with these tools, in general it's probably a good idea to check out minrk's github page and GeospatialPython.org.

Admittedly, I have very little theory behind this attempted fix, but I tried to harmonize the two environments by explicitly adding the missing environmental variables with a startup script in the default_profile for IPython.  This, probably predictably, did not work.  I am guessing that these variables are utilized only during installation.  Since I already installed gdal...
!sudo pip install gdal
*********************
Requirement already satisfied (use --upgrade to upgrade): gdal in /home/choct155/analysis/Anaconda/lib/python2.7/site-packages
Cleaning up...

… I am still not sure how to remedy this.  Further, I am still unclear on how and why my Python and IPython platforms would be looking at different versions of SQLite when they have the same PATH.

A: So it turned out to be a SQLite version conflict (hat tip GP.com).  It seems as though IPython loaded a version of SQLite upon initializing the session, and GDAL requires another version.  The solution was to interrupt the IPython default importation (thank you IPython help chat).  This was done by creating a new script titled sqlite3.py, and populating it with raise ImportError.  The script was placed in the first directory in the IPython sys.path.
Caveat:  SQLite is used under the hood in IPython for various actions, and thus a version switch may cause some issues.  At the current time, this is the cost of doing business for using these (awesome) tools together.


text:
Q: once something has been .remove() - can it be bought back? Or can original source be refreshed? jQuery I'm having a bit an issue, just wondering if this is possible?
Lets say I have this...

ONE

TWO

THREE

FOUR

The I use this to remove all but one particular div...
$('#box div[data-group!=3]').remove();

Now is there anyway to bring back the orginal child elements of the div#box - after they have been removed?
I made a fiddle... http://jsfiddle.net/motocomdigital/N8vUy/4/

Any suggestions would be great thanks.

A: You can't restore removed nodes except of re-creating them from scratch and inserting back into parent node.
Depending to your purpose maybe it's an option to just hide node and show it when you'll need.
$('#box div[data-group!="3"]').hide(); // hide node
$('#box div[data-group!="3"]').show(); // show node

A: The remove method will not only take the elements out of the DOM, it will also unbind events and remove jQuery data for the elements, so even if you keep a reference to the elements, it doesn't just work to reinsert them in the DOM.
Use the detach method instead when you want to keep the elements:
var el = $('div[data-group!=3]');
el.detach();

$('#box').append(el);

Demo: http://jsfiddle.net/Guffa/N8vUy/10/

A: $('a#button').on('click', function (){
$('div [data-group!="3"]').remove();

});

place 1 space after the div tag thats why all div tag have disappear after you click
the link.
and for your first question
you cant bring it back.
try to use .hide() and .show()
or try toy use .toggle()


text:
Q: Render and redirect_to in rails I just answered a question on a quiz and the question is as follows:
Which of the following is an invalid statement regarding render and redirect_to?

*

*render doesn't send a new request but redirect_to does

*redirect_to doesn't send a new request but render does

*render will not cause the current action to stop executing

*redirect_to will not cause the current action to stop executing

I selected the Option 1 as my answer but it came out to be wrong. I checked online and found this link where it's clearly stated that redirect_to sends a new request to browser:

There is an important difference between render and redirect_to: render will tell Rails what view it should use (with the same parameters you may have already sent) but redirect_to sends a new request to the browser.

A: Option two will be the right answer as in question clearly written: Which of the following is an invalid statement
As you understood and know redirect_to send a new request but in option it says that doesn't send so it becomes invalid statement and your answer should be
redirect_to doesn't send a new request but render does

Note:
Kindly read question properly and understand it first before give the answer..

A: I guess you missed the invalid word in the question, the correct answer would be Option 4
redirect_to will not cause the current action to stop executing

Option 1 render doesn't send a new request but redirect_to does is valid, since redirect_to sends a get request to an action of type get, but render just renders the view, it has nothing to do with the other action


text:
Q: ¿Por qué obtengo 0. como resultado en esta red neuronal con Python? Estoy intentando hacer una red neuronal bastante simple la cual diferencie entre perros y gatos, pero a la hora de pasarle cualquier imagen el valor que siempre me devuelve es [0.]. Este es el código:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 11 17:22:20 2022

@author: mariomiranda
"""

#Parte 1 de redes neuronales convolucionales

#Importamos las librerías y paquetes

import keras
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense

classifier = Sequential()

#Convolución

classifier.add(Convolution2D(filters = 32,kernel_size = (3, 3), input_shape = (64, 64, 3),
                             activation = "relu"))
print(classifier)

#Paso 2: Max pulling. Aprende rotaciones y escalado de imágenes

classifier.add(MaxPooling2D(pool_size=(2,2)))

print(classifier)

# Una segunda capa de convolucón y max pooling
classifier.add(Convolution2D(filters = 32,kernel_size = (3, 3), input_shape = (64, 64, 3),
                             activation = "relu"))
print(classifier.add)

classifier.add(MaxPooling2D(pool_size=(2,2)))

print(classifier)

# Añadimos una tercera capa de convolución

classifier.add(Convolution2D(filters = 32,kernel_size = (3, 3), input_shape = (64, 64, 3),
                             activation = "relu"))
print(classifier)

classifier.add(MaxPooling2D(pool_size=(2,2)))

print(classifier.add)

# Añadimos una cuarta capa de convolución
classifier.add(Convolution2D(filters = 32,kernel_size = (3, 3), input_shape = (64, 64, 3),
                             activation = "relu"))

classifier.add(MaxPooling2D(pool_size=(2,2)))

#Paso 3: Flattening o aplanado de lso datos. Construimos un vector para reducir el tamaño
# tiene que ser un vector unidimensional ya que así es la primera capa de la red neuronal

classifier.add(Flatten())

print(classifier)

#Paso 4: Full Conexion
#128 nodos en la capa oculta

classifier.add(Dense(units = 128, activation = "relu"))

print(classifier)
classifier.add(Dense(units = 1, activation = "sigmoid")) # Función de activación

print(classifier)
#Compilar la red neuronal de convolución

classifier.compile(optimizer="adam", loss = "binary_crossentropy",
                   metrics = ["accuracy"])
print(classifier)

#Parte 5: Importamos las imágenes para entrenar

from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)
print(train_datagen)

test_datagen = ImageDataGenerator(rescale=1./255)
print(test_datagen)

training_dataset = train_datagen.flow_from_directory('/Users/mariomiranda/Desktop/IA Python/dataset/training_set',
                                                    target_size=(64, 64),
                                                    batch_size=32,
                                                    class_mode='binary')
print(training_dataset)

testing_dataset = test_datagen.flow_from_directory('/Users/mariomiranda/Desktop/IA Python/dataset/test_set',
                                                target_size=(64, 64),
                                                batch_size=32,
                                                class_mode='binary')
print(testing_dataset)

classifier.fit_generator(training_dataset,
                        steps_per_epoch=len(training_dataset),
                        epochs=50,
                        validation_data=testing_dataset,
                        validation_steps=len(testing_dataset))

print(classifier.fit_generator)

# Importamos librerías necesarias

from tensorflow.keras.applications.resnet50 import preprocess_input
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import load_img
import numpy as np

# Pasamos una imagen por la red neuronal

img_path = "/Users/mariomiranda/Desktop/Foto Sena/perro1.jpg"

print(img_path)

img = image.load_img(img_path, target_size=(64, 64))

# Para que la imagen sea procesada correctamnete, cambiamos el formato de la
# imagen. La ponemos en formato de batches porque es lo que espera la CNN

img_array = image.img_to_array(img)

img_batch = np.expand_dims(img_array, axis=0)

# Escalamos los pixeles de la imagen entre 0 y 1

img_preprocessed = preprocess_input(img_batch)

print(img_preprocessed)

# Prediccion

prediction = classifier.predict(img_preprocessed)

print(prediction)

if prediction > 0.5:

    solution = 'perro'

else:

    solution = 'gato'

print("La foto es de un",solution)

Lo que he hecho con la imagen ha sido procesarla para que sea posible pasarla por la red neuronal y tenga el tamaño correcto así como todas sus catacterísticas. No se si habré cometido algún error a la hora de crear la red neuronal pero he tenido que añadir alguna capa más de convolución para que la red pudiera llegar al 85% de precisión en test.A ver si alguno de vosotros puede echarme un cable, gracias de antemano.


text:
Q: Call function destroyed callback in last call I have function, which create popup similar as alert, confirm or prompt. Problem occurs when is called new popup (any type), then is destroyed callback in first call (prompt value)
PoppyPopup.prompt('Type your name', 'User control', {}, function(value) {
    PoppyPopup.alert('Welcome ' + value); //<-- value is id of second popup
});

PoppyPopup.alert('Hi, this is a PopUp!', 'With title!');

DEMO: https://jsfiddle.net/yojz8sb3/
Edit: When is call one time, it's OK, I really dont know where is problem.

A: Well, the short answer is because PoppyPopup isn't designed to handle having more than one popup open at a time.
popupType is shared between all popups so when you open the alert popup it sets popupType to ALERT and so when the prompt popup's accept callback is called it's handled as if it's an ALERT type popup.

One (fairly hacky) solution is to remove var popupType = null; and instead pass popupType to the Popup constructor as a 4th argument. Then you can change
PoppyPopup.accept(basePopup.id, options);

to
PoppyPopup.accept(basePopup.id, options, popupType);

in Popup function.
And change
accept: function(popupId, options) {

to
accept: function(popupId, options, popupType) {

that way the popup type is associated with the popup instance instead of being shared among all popups.
Here is a working example: https://jsfiddle.net/0xpz7f9L/

However my answer above doesn't fix the issue that clicking the accept button appears to close a random popup (obviously not ideal). I'd recommend rewriting the whole thing to simplify it and make it easier to read/understand. Also this sort of thing traditionally uses promises instead of callbacks.
Here is how I would rewrite it:

const PoppyPopup = (function() {
  let nextPopupId = 0;

  return {
    alert: function(message, title, options) {
      const realOptions = buildOptionsFrom(options);
      const popupElem = buildPopupElem(title, message, realOptions, false, false);

      const promise = new Promise(resolve => {
        popupElem.querySelector('.accept').onclick = resolve;
      });
      promise.finally(() => close(popupElem, realOptions.removeWhenClosed));
      document.querySelector('body').appendChild(popupElem);

      return promise;
    },

    confirm: function(message, title, options) {
      const realOptions = buildOptionsFrom(options);
      const popupElem = buildPopupElem(title, message, realOptions, false, true);

      const promise = new Promise((resolve, reject) => {
        popupElem.querySelector('.accept').onclick = resolve;
        popupElem.querySelector('.cancel').onclick = reject;
      });
      promise.finally(() => close(popupElem, realOptions.removeWhenClosed));
      document.querySelector('body').appendChild(popupElem);

      return promise;
    },

    prompt: function(message, title, options) {
      const realOptions = buildOptionsFrom(options);
      const popupElem = buildPopupElem(title, message, realOptions, true, true);

      const promise = new Promise((resolve, reject) => {
        popupElem.querySelector('.accept').onclick = () => resolve(popupElem.querySelector('input').value);
        popupElem.querySelector('.cancel').onclick = reject;
      });
      promise.finally(() => close(popupElem, realOptions.removeWhenClosed));
      document.querySelector('body').appendChild(popupElem);

      return promise;
    }
  };

  function close(popupElem, removeWhenClosed) {
    popupElem.classList.remove('show');

    popupElem.addEventListener('transitionend', function(e) {
      if (e.propertyName === 'opacity' && removeWhenClosed) {
        popupElem.parentNode.removeChild(popupElem);
      }
    });
  }

  function buildOptionsFrom(options) {
    return Object.assign({
      showBackground: true,
      removeWhenClosed: true,
      width: '400px'
    }, options || {});
  }

  function buildPopupElem(title, message, options, provideInput, provideCancel) {
    const basePopupDiv = document.createElement("DIV");
    basePopupDiv.className = "poppy-popup show";
    basePopupDiv.id = nextPopupId++;

    if (options.showBackground) {
      const backgroundDiv = document.createElement("DIV");
      backgroundDiv.className = "poppy-popup-background";
      basePopupDiv.appendChild(backgroundDiv);
    }

    const containerDiv = document.createElement("DIV");
    containerDiv.className = "poppy-popup-container";
    containerDiv.style.width = options.width;
    containerDiv.style.height = options.height;

    if (title) {
      const headerTitleDiv = document.createElement("DIV");
      headerTitleDiv.className = "poppy-popup-title-text";
      headerTitleDiv.innerHTML = title;

      const headerDiv = document.createElement("DIV");
      headerDiv.className = "poppy-popup-header";
      headerDiv.appendChild(headerTitleDiv);

      containerDiv.appendChild(headerDiv);
    }

    const contentDiv = document.createElement("DIV");
    contentDiv.className = "poppy-popup-content";
    contentDiv.innerHTML = message;

    if (provideInput) {
      const input = document.createElement("INPUT");
      input.type = "text";
      contentDiv.appendChild(input);
    }

    const acceptLink = document.createElement("A");
    acceptLink.className = 'accept';
    acceptLink.href = "#";
    acceptLink.innerHTML = "done OK";

    const acceptSpan = document.createElement("SPAN");
    acceptSpan.className = "poppy-popup-accept";
    acceptSpan.appendChild(acceptLink);

    const buttonsDiv = document.createElement("DIV");
    buttonsDiv.className = "poppy-popup-buttons";
    buttonsDiv.appendChild(acceptSpan);

    if (provideCancel) {
      const cancelLink = document.createElement("A");
      cancelLink.className = "cancel";
      cancelLink.href = "#";
      cancelLink.innerHTML = "close Cancel";

      const cancelSpan = document.createElement("SPAN");
      cancelSpan.className = "poppy-popup-cancel";
      cancelSpan.appendChild(cancelLink);

      buttonsDiv.appendChild(cancelSpan);
    }

    containerDiv.appendChild(contentDiv);
    containerDiv.appendChild(buttonsDiv);

    basePopupDiv.appendChild(containerDiv);

    return basePopupDiv;
  } //end of buildPopupElem()
})();

PoppyPopup.prompt('Type your name', 'User control').then(value => {
  PoppyPopup.alert('Welcome ' + value).then(() => {
    PoppyPopup.confirm('And just for completeness, confirm?')
      .then(() => alert('accepted'), () => alert('rejected'));
  });
});

PoppyPopup.alert('Hi, this is a PopUp!', 'With title!');
*, *:before, *:after {
  box-sizing: border-box; }

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  font-family: 'Roboto', sans-serif;
  font-size: 16px;
  background-color: #eeeeee; }

.poppy-popup {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  width: 100vw;
  height: 100vh;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-pack: center;
      justify-content: center;
  -ms-flex-align: center;
      align-items: center;
  font-size: 16px;
  opacity: 0;
  transition: opacity .3s; }
  .poppy-popup.show {
    opacity: 1; }
  .poppy-popup > .poppy-popup-background {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1010;
    background-color: rgba(0, 0, 0, 0.5);
    width: 100%;
    height: 100%; }
  .poppy-popup > .poppy-popup-container {
    max-width: 90%;
    max-height: 90%;
    width: 100%;
    position: relative;
    z-index: 1020;
    border-radius: 3px;
    box-shadow: 0 0 10px 1px rgba(0, 0, 0, 0.3); }
    .poppy-popup > .poppy-popup-container > .poppy-popup-header {
      background-color: #FFFFFF;
      color: #222222;
      height: 50px;
      width: 100%;
      position: relative;
      border-top-left-radius: 3px;
      border-top-right-radius: 3px; }
      .poppy-popup > .poppy-popup-container > .poppy-popup-header > .poppy-popup-title-text {
        width: 100%;
        max-height: 50px;
        font-size: 1.5em;
        text-align: center;
        line-height: 50px;
        text-overflow: ellipsis;
        font-weight: bold;
        overflow: hidden;
        white-space: nowrap; }
    .poppy-popup > .poppy-popup-container > .poppy-popup-content {
      background-color: #FFFFFF;
      width: 100%;
      padding: 10px 20px;
      border-left: 1px solid #DDDDDD;
      border-right: 1px solid #DDDDDD;
      overflow: auto; }
      .poppy-popup > .poppy-popup-container > .poppy-popup-content > input[type="text"] {
        background-color: transparent;
        border-width: 0;
        border-bottom: 2px solid #CCCCCC;
        outline: none;
        font-size: 1.3em;
        width: 100%;
        margin-top: 20px;
        padding: 5px;
        box-shadow: none;
        transition: border-bottom .2s; }
        .poppy-popup > .poppy-popup-container > .poppy-popup-content > input[type="text"]:focus {
          border-bottom: 2px solid #2088AD; }
    .poppy-popup > .poppy-popup-container > .poppy-popup-buttons {
      width: 100%;
      height: 50px;
      padding: 0 10px;
      background-color: #FFFFFF;
      border-bottom-left-radius: 3px;
      border-bottom-right-radius: 3px;
      overflow: hidden; }
      .poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-accept, .poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-cancel {
        width: 120px;
        display: block;
        float: right;
        color: #2088AD; }
        .poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-accept > a, .poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-cancel > a {
          display: block;
          color: inherit;
          text-decoration: none;
          text-align: center;
          padding: 10px 0;
          border-radius: 3px;
          transition: background-color .2s, box-shadow .1s; }
          .poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-accept > a:active, .poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-cancel > a:active {
            box-shadow: inset 0 0 5px 1px rgba(0, 0, 0, 0.3); }
          .poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-accept > a > i, .poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-cancel > a > i {
            vertical-align: middle;
            margin-top: -3px; }
      .poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-accept {
        right: 0;
        color: #2088AD; }
        .poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-accept > a:hover {
          background-color: rgba(0, 0, 0, 0.1); }
      .poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-cancel {
        left: 0;
        color: #2088AD; }
        .poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-cancel > a:hover {
          background-color: rgba(0, 0, 0, 0.1); }

Note: The css is unchanged.


text:
Q: How can I print include path in cygwin? I am new to cygwin & I want to print the list of include paths cygwin will search for header files.
Is there a cygwin bash shell command to print the include path list?
if so, what it is ?
if there is n't any, how can I know the include path list cygwin will search for?

A: echo $PATH (echo ${PATH}) would be one possibility. To show all environment variables type env.
Normally, include paths are defined by the Make-Environment, either in the makefile, along with the compiler call or within the cmake environment. This is better than to put it in the PATH environment because if someone compiles something different, the "old" include definition in the PATH environment variable maybe in the way (which is not, if you specify it for every project, e.g. in the Makefile or threw the cmake environment).
If someone still wants to define it in the PATH variable, it can be done on the command prompt (if your cygwin(64) resides on "cygdrive/c":
export PATH=/cygdrive/c/cygwin64/usr/include:$PATH


text:
Q: What is happening with this CUDA code that returns this unexpected output? Having finally gotten Dynamic Parallelism up and running, I'm trying to now implement my model with it.  It took me a while to figure out that some strange output resulted from needing to use cudaDeviceSynchronize() to make the parent kernel wait for the child kernel to finish.
It seems there is something wrong with the device function I defined as arrAdd.  Here's a table of outputs before and after each child kernel in the k2 parent kernel.
Initially    : k1   = { -1   0   0   0   0 }
Post arrInit : temp = { .25 .25 .25 .25 .25}
Post arrMult : temp = {-.25  0   0   0   0 }
post arrAdd  : temp = { -8   0   0   0   0 }
Expected     : temp = {-.50  0   0   0   0 }

__global__ void k2(double* concs, int* maxlength, double* k1s, double* k2s, double * temp, double* tempsum)
{
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    double a21 = .25;

    arrInit<<< 1, *maxlength >>>(temp, a21);                //temp = a21
    cudaDeviceSynchronize();
    arrMult<<< 1, *maxlength >>>(k1s, temp, temp);          //temp = a21*k1
    cudaDeviceSynchronize();
    arrAdd<<< 1, *maxlength >>>(temp, temp, temp);          //temp = 2*a21*k1
    cudaDeviceSynchronize();
}

__global__ void arrAdd(double* a, double* b, double* c)
{
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    c[idx]=a[idx]+b[idx];
}
__global__ void arrMult(double* a, double* b, double* c)
{
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    c[idx]=a[idx]*b[idx];
}
__global__ void arrInit(double* a, double b)
{
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    a[idx]=b;
}

A: You probably don't need to synchronize with the parent kernel. Child kernels execute in the order specified by parent kernel and the end of parent kernel is an implicit synchronization point with the last child kernel.
When you use dynamic parallelism, be careful about these items:

*

*The deepest you can go is 24 (CC=3.5).

*The number of dynamic kernels pending for launch at the same time is limited ( default 2048 at CC=3.5) but can be increased.

*Keep parent kernel busy after child kernel call otherwise with a good chance you waste resources.
I guess your strange wrong results originate from the second factor mentioned above. When you hit the limit, some of dynamic kernels simply don't run and if you don't check for errors, you won't notice because error creation mechanism is per thread.
You can increase this limit by cudaDeviceSetLimit() having cudaLimitDevRuntimePendingLaunchCount as the limit. But the more you specify, the more you consume global memory space. Have a look at section C.4.3.1.3 of the documentation here.


text:
Q: Tail on scala iterator I want to check that every line in a file, apart from the first header line, contains the string "14022015". I wanted to do this the Scala way and I came up with something clever (I thought) usingfoldLeft:
assert(Source.fromFile(new File(s"$outputDir${File.separator}priv.txt"))
  .getLines().foldLeft(true)((bool, line) => (bool && line.contains("14022015"))))

Until I found out about the header line, which needs to be excluded from the test. tail will not work as getLines returns an Iterator and not a List. Is there something else I can do (Scala wise)?

A: Simply:
val res: Boolean = myFile.getLines.drop(1).forall(_.contains("14022015"))

A: iterator.drop(1) will help you achieve exactly what you need
UPD: A side note, consider using a recursive solution instead of fold in this case - fold will always scan the entire iterator, and based on your code it looks like you may want it to short-circuit, just like standard a && b && c is not going to evaluate expressions down the list as soon as it encounters a false


text:
Q: React js unit testing with enzyme Hi guys i am new to react can anyone help me to write unit test for the below code .. i want to test if link is redirecting properly..
Here is my code ..
import React { Component } from 'react';
import {Link} from 'react-router';
import './App.css';

class Home extends Component {
  render() {
    return (
      <Link to='/college/masters/cs' className="student">

Branch

      </Link>
    );
  }
}

My test
import React from 'react';
import { mount, shallow } from 'enzyme';
import {expect} from 'chai';
import 'ignore-styles';
import Home from '../src/Home';

describe('<Home/>', function () {
  it('should have a Link', function () {
    const wrapper = shallow(<Home/>);

    expect(wrapper.find('Link')).to.have.length(1);
  });
});

Please help me to write test if link is redirecting properly..
Thank you

A: Well, try this out. It should work.
You merely need to check whether you are passing the valid to property with a relevant value to the Link component. That's it. You don't need to check whether it takes you to the given url, since it is the functionality of the Link component and they should have tests to verify that. If you need that then what you are writing is not a unit test, it is called an e2e. You may need selenium or so in doing that.
expect(wrapper.find('Link').props().to).to.eql('/college/masters/cs')