text:
Q: QTabWidget: set a widget as the background widget when there is no tabs I want to set a widget as the background widget of a tab widget when there is no tab opened. I wish it will work in this way:

*

*Initially there is no tab in the tab widget, I want to add a widget as the background of the tab widget, the background widget will show some hint text as the placeholder.

*When the user opens any tab, the background will be hidden automatially, and the background widget won't handle any user events(clicks, double-clicked, keyboard events).

*When all tabs are closed, the background shows again.

Any ideas? Thanks.

A: [Moved from comments]
From the requirements you outline it sounds as if you don't really need a separate widget.  Something like the following should suffice...
#include <QApplication>
#include <QLabel>
#include <QPainter>
#include <QTabWidget>

namespace {
  class tab_widget: public QTabWidget {
    using super = QTabWidget;
  public:
    explicit tab_widget (QWidget *parent = nullptr)
      : super(parent)
      {}
  protected:
    virtual void paintEvent (QPaintEvent *event) override
      {
        super::paintEvent(event);
        if (!count()) {
          QPainter painter(this);
          painter.drawText(rect(), Qt::AlignCenter, "Some informative text goes here...");
        }
      }
  };
}

int
main (int argc, char **argv)
{
  QApplication app(argc, argv);
  tab_widget w;
  for (int i = 0; i < 5; ++i) {
    auto text = QString("Tab %1").arg(i);
    w.addTab(new QLabel(text), text);
  }
  w.show();
  return app.exec();
}


text:
Q: Hide Title column links in the print out In a custom list view, we are using Title(Linked to item with edit menu) or the the Title (linked to item) columns. However when the list is printed it shows the underlying links/urls in addition to the column text. To prevent this we are using the plain Title column, but this is not the permanent solution. We would like to use one of the the hyperlinked Title columns, but don't want to see the urls/links for the text. Is there a CSS solution for this?

A: Media print CSS does the trick.
@media print {
  a[href]:after {
    content: none !important;
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove null from list string c# Seems it was answered a few times already but it's not working for me...
I have a list  called combox. I want to remove null items.
I wrote:
   List<String> comboxTable = new List<string>();
    comboxTable = comboxTable.RemoveAll(item => item == null);

but I'm getting:

Error 14  Cannot implicitly convert type 'int' to
  'System.Collections.Generic.List'

I tried this one:
comboxTable = comboxTable.RemoveAll(string.IsNullOrWhiteSpace);

Same error.
Where is the 'int'?
What am I doing wrong?
(Combox is getting its string value someplace else in the code and has Nulls here and there. I want to delete them)

A: RemoveAll() modifies the instance itself and returns the number of elements removed

A: Using Linq:
List<String> comboxTable = new List<string>();
comboxTable = comboxTable.Where(m => !string.IsNullOrEmpty(m)).ToList();

A: Check the documentation. RemoveAll() returns an integer and your code tries to cast it to an object of type System.Collections.Generic.List
Change your code to this:
comboxTable.RemoveAll(string.IsNullOrWhiteSpace);

and it will work. The null items will be removed. RemoveAll operates on the instance itself it does not return a new one

A: You can also do something like below code
            comboxTable.RemoveAll(var => String.IsNullOrEmpty(var));


text:
Q: Is there a Gecko equivalent to -webkit-mask or a fancy way of degrading for Gecko browsers? I'm looking for a solid answer on whether or not there is an equivalent to -webkit-mask in Gecko browsers/Firefox?
If not, is there any way of degrading -webkit-mask in CSS to a straight background-image deal or should I just give up and use Javascript?
Thanks a lot!

A: If you're targeting firefox, it has great SVG support, so you can now use SVG masks instead of CSS. Here is Mozillas documentation on how to do a mask in SVG Webkit masks aren't standards track - so I have a personal doubt that you'll ever see them cross-browser.

A: After struggling with this for many hours, I was finally able to apply a complex SVG path as a mask for a div element on my site, and it works in Firefox. Here's what I did:
First, for Webkit browsers, the solution was ideal, and I simply had to make a flattened png file with the same size (or really the same shape, could be different scale) as the div I want to mask, and with the area I want to be visible in black, and the parts I want clipped out transparent. Then, I added the following line to the CSS for the div element I want to mask:
-webkit-mask-box-image: url(path/to/mask.png);

That was easy! Now let's get to the fun part of getting this working in Firefox. For this method to work, the vector shape must be the exact same size as the area you want to mask. So my mask is a relatively complex vector path designed in Fireworks, and I need to get it converted to an SVG path, and thankfully, I have Illustrator available. Otherwise, use your favorite SVG editor to convert your shape path to SVG. If you're also using Fireworks to draw your vector shapes, you can right-click on the vector shape you want to use, go to 'Edit' -> 'Copy Path Outlines', and then you can paste it into a sufficiently large document in Illustrator, or whatever SVG editor you're using.
Next, you need to export it to an SVG file. In Illustrator, I used the 'Export for Web' function, selected SVG format, version 1.0, and exported it to an SVG file. The position and document size don't really matter, as we're just after the path description, and we'll discard the rest.
So, now open that SVG file you just made with a text editor, such as Text Edit or Notepad. You'll see some XHTML-formatted content, and one element in particular is something like:
<path fill-rule="evenodd" clip-rule="evenodd" d="M0,43v0.5V44v0.5v1V46v0.5v1V48v0..."/>

The d="..." portion will probably be many lines long for a complex shape. This is the only portion of this SVG file that we care about.
Next, we must embed an SVG mask describing this path into our site HTML. First, let's add the following elements to our HTML:
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
    <defs>
        <mask id="maskid" maskUnits="userSpaceOnUse">
            <path fill="white" d=""/>
        </mask>
    </defs>
</svg>

Now, we simply copy the contents of the d="" property of the path element from the SVG file we saved earlier (i.e. M0,43v0...) and paste into the same d="" property of the path element in the embedded SVG's mask element. Then, we can add the following entry to the CSS for the element we want to mask:
mask: url("#maskid");

That's it. The path should now be applied as a mask to the element you specified.

A: Here is the trick , you need to convert all points generated in your svg file to ratio that is equal the point path divided by mask dimension .
For easier explaination , i have made a quick tool to help designers convert their svg into a mask that is compatible with firefox , you can see a live demo on my website ( http://www.prollygeek.com ) , for example the facebook logo , and twitter logo are just masks , and here is the tool that you can use to convert your svg to a mask:
http://prollygeek.com/svg-mask/
for example:
<mask id="fb"  maskUnits="objectBoundingBox" maskContentUnits="objectBoundingBox">
<path d="M236.626,120.827v27.295h-14.851c-4.416,0-7.225,1.204-8.63,3.612c-1.003,1.604-1.405,4.415-1.405,8.229v12.442h25.287l-3.01,27.494H211.74v79.273h-32.712v-79.273h-16.055v-27.494h16.055v-16.457c0-16.858,5.82-27.695,17.259-32.311
c5.619-2.208,10.436-2.811,15.453-2.811H236.626z"/>

will be turned to:
<mask id="fb"  maskUnits="objectBoundingBox" maskContentUnits="objectBoundingBox">
<path d="M0.59,0.3v0.0675h-0.035c-0.01,0-0.0175,0.0025-0.02,0.0075c-0.0025,0.0025-0.0025,0.01-0.0025,0.02v0.03h0.0625l-0.0075,0.0675H0.5275v0.1975h-0.08v-0.1975h-0.04v-0.0675h0.04v-0.04c0-0.04,0.0125-0.0675,0.0425-0.08c0.0125-0.005,0.025-0.005,0.0375-0.005H0.59z" style="fill-rule:evenodd;clip-rule:evenodd;fill:#ffffff;"/>

Please dont forget to add this attribute style="fill-rule:evenodd;clip-rule:evenodd;fill:#ffffff;"
and fill with any color , it doesnt matter.
afterwards link your mask to the css element you desire:
for example:
  mask:url(images/fb.svg#fb);

the calculator is free to use , but please dont copy or publish anywhere else.

A: You can apply svg filters with css to HTML content in Gecko. Here is an example from a guy who likes to fiddle with mozilla code. It is from 2008 so it might be a bit outdated.


text:
Q: Actionscript math calculation behaving differently in browser This is really stumping me: I have a little app that allow the user to zoom in/out, rotate, flip horizontally and manipulate the colour of a photo. The photo is loaded via the Loader class. The app works perfectly in the dev environment however if fails once tested in the browser. I did a little debugging and I noticed a value for one of matrix calculations equates to a positive value in the dev environment but a negative value in the browser (under the exact same conditions). What am I missing here?
Here is my code for two of the functions that get called during my testing:
    function zoomOut(e:MouseEvent):void{
    matrix = imageLoader.content.transform.matrix;
    imageLoader.content.scaleY = imageLoader.content.scaleY*.90;
    imageLoader.content.scaleX = imageLoader.content.scaleX*.90;
    statusText.text = imageLoader.content.scaleY.toString();
    if(matrix.a < 0){
    matrix.a = -1*imageLoader.content.scaleY;
    matrix.tx = imageLoader.content.width;
    }else{
        matrix.a = imageLoader.content.scaleY;
    }
    matrix.d = imageLoader.content.scaleX;

matrix.transformPoint(newPoint(imageLoader.content.width/2,imageLoader.content.height/2));
        imageLoader.content.transform.matrix = matrix;
    }

        function flipHorizontal(e:MouseEvent):void {
            matrix =imageLoader.content.transform.matrix;
            matrix.transformPoint(new Point(imageLoader.content.width/2,imageLoader.content.height/2));
    if (matrix.a>0) {
    matrix.a=-1*matrix.a;
    matrix.tx=imageLoader.content.width+imageLoader.content.x;
    } else {
    matrix.a=-1*matrix.a;
    matrix.tx=imageLoader.content.x-imageLoader.content.width;
    }
    imageLoader.content.transform.matrix=matrix;
    }

From what I can tell, imageLoader.content.scaleY is equating differently in the browser environment.
Thanks so much for your help.
Jason

A: The most likely thing is that the function operating on the loader.content is getting called before the image has completely loaded, resulting is zeroes and NaN values that mess up your processes.
Try disabling this function until after the image is loaded and the Loader.contentLoaderInfo  has dispatched its COMPLETE event.


text:
Q: Is it safe to use npm install with --force on production? we are facing an interesting problem in our build server that prevents our app to install npm dependencies which causes most of our builds to fail.
We are using the build server Visual Studio Team Services which runs Windows. When we are trying to install npm dependencies we get the following error:
    2016-04-13T12:44:25.0931743Z npm ERR! Windows_NT 6.3.9600
    2016-04-13T12:44:25.0931743Z npm ERR! argv "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "--production"
    2016-04-13T12:44:25.0941742Z npm ERR! node v0.12.7
    2016-04-13T12:44:25.0941742Z npm ERR! npm  v2.11.3
    2016-04-13T12:44:25.0951737Z npm ERR! path C:\NPM\Cache\repeating\1.1.3\package\package.json
    2016-04-13T12:44:25.0951737Z npm ERR! code EPERM
    2016-04-13T12:44:25.0951737Z npm ERR! errno -4048
    2016-04-13T12:44:25.0981746Z npm ERR! Error: EPERM, rename 'C:\NPM\Cache\repeating\1.1.3\package\package.json'
    2016-04-13T12:44:25.0991748Z npm ERR!     at Error (native)
    2016-04-13T12:44:25.0991748Z npm ERR!  { [Error: EPERM, rename 'C:\NPM\Cache\repeating\1.1.3\package\package.json']
    2016-04-13T12:44:25.1001741Z npm ERR!   errno: -4048,
    2016-04-13T12:44:25.1001741Z npm ERR!   code: 'EPERM',
    2016-04-13T12:44:25.1011746Z npm ERR!   path: 'C:\\NPM\\Cache\\repeating\\1.1.3\\package\\package.json',
    2016-04-13T12:44:25.1011746Z npm ERR!   parent: 'babel-traverse' }
    2016-04-13T12:44:25.1021741Z npm ERR!
    2016-04-13T12:44:25.1021741Z npm ERR! Please try running this command again as root/Administrator.
    2016-04-13T12:44:28.0020021Z npm ERR! Please include the following file with any support request:
    2016-04-13T12:44:28.0029943Z npm ERR!     C:\a\1\s\src\OrderEze.Web\npm-debug.log
    2016-04-13T12:44:28.1069958Z ##[debug]rc:4294963248
    2016-04-13T12:44:28.1079955Z Npm failed with error: C:\Program Files\nodejs\npm.cmd failed with return code: 4294963248

We found that if we try to install our dependencies using the force command, everything works fine:
npm install --force

My question is simple. Will we have any issues with this configuration? Why npm warns us about this command? Any idea can help :)


text:
Q: GitHub Pages - CSS is incorrect on live site, fine on local host My github pages site works perfectly fine on my local host, but for some strange reason the css does not show on my live site. I've included images of the issue. I can't debug this on my localhost since it works perfectly fine on there, so I'm constantly reverting and pushing to debug this.
Has anyone encountered this issue? Any help would be greatly appreciated.
http://imgur.com/a/mClMc

A: Ok, found the answer. There were two things missing in my files and according to your post at least one of them is missing in yours:

*

*Sass assets files must start with two lines of triple dashes (see jekyll docs here).

*Apparently when referencing stylesheets in GitHub Pages you need to reference a specific version of the file. I found the following snippet in The Minimal Theme default layout source:
<link rel="stylesheet" href="{{ '/assets/css/style.css?v=' | append: site.github.build_revision | relative_url }}">


text:
Q: Why the sum of model.predict(x) is less than 1 with softmax and LSTM? I'm using keras, and the final layer uses a 'softmax' activation function.
However, when I use predict and sum the probabilities, I do not get 1.
Why is that?
N.B. :
I am really far from 1:
>>> m
<keras.models.Sequential object at 0x1083fdf60>
>>> m.layers[-1].activation
<function softmax at 0x1092bfea0>
>>> X.shape
(1940, 10, 48)
>>> m.input
<tf.Tensor 'lstm_1_input:0' shape=(?, 10, 48) dtype=float32>
>>> model.predict(X)[:10].sum(axis=-1)
array([ 0.46206102,  0.43193966,  0.4252567 ,  0.44023705,  0.46344867,
        0.48820126,  0.50369406,  0.49789378,  0.46433908,  0.44102359], dtype=float32)
>>> y=model.predict(X)
>>> y[0]
array([  0.00000000e+00,   6.10233226e-04,   0.00000000e+00,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
         0.00000000e+00,   0.00000000e+00,   1.12394022e-03,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
         0.00000000e+00,   1.55960268e-04,   0.00000000e+00,
         4.60170895e-01], dtype=float32)

EDIT:
I tested with a simple code
import numpy as np
from keras.models import *
from keras.layers import *
m = Sequential()
m.add(LSTM(3, input_shape=(3,2), activation='softmax'))
print(m.predict(np.random.rand(5,3,2)).sum(axis=-1))

And I get results like
[ 0.50027865  0.49804032  0.49545377  0.50514281  0.50069857]

OKAY, so with Dense and SimpleRNN, I get almost 1. The problem might simply be that activation has not the same behaviour with recurrent layers, since GRU has the same issues.
I asked on GitHub: https://github.com/fchollet/keras/issues/6255

A: @joelthchao said on GitHub (https://github.com/fchollet/keras/issues/6255):

Activation here is directly apply on each hidden unit. However, we won't use LSTM in this way. Usually, we do it by:

m.add(LSTM(hidden_unit, input_shape=(3,2)))
m.add(Dense(3, activation='softmax'))

Finally, I found more logical to use :
m.add(Lambda(K.softmax))

A: By construction, the softmax prediction should sum to one.  However, in practice, they might not sum to exactly one due to the limits of machine precision. How far from 1 are your cumulative probabilities?
I ran the mnist_mlp.py example found in the Keras example/ directory with Theano as the backend. Then I predicted the test set probabilities with the trained model.  The probabilities sum to almost one, as expected.
y_pred = model.predict(x_test)
y_sum = y_pred.sum(axis=1)
print('Min={}, Max={}, Range={}'.format(y_sum.min(),y_sum.max(),y_sum.max()-y_sum.min()))
# Min=0.9999999403953552, Max=1.0000001192092896, Range=1.7881393432617188e-07

The observed range is on the same order as machine epsilon for 32 bit floats.
import numpy as np
print(np.finfo(np.float32).eps)
#1.19209e-07

which is consistent with the use of
      "floatx": "float32",

in my ~/.keras/keras.hjson file.  If you need additional precision, you can can change "float32" to "float64".


text:
Q: Limit of stable vector bundles. Let $S$ be a $K3$ surface and $H$ be an ample line bundle on it. Given a flat family of coherent sheaves on $S$ whose generic point is a $\mu_H$-stable vector bundle, what can I say about the non-generic points? Are they always $\mu_H$-semistable and torsion free? I think that this is equivalent to requiring the existence of a compactification of the moduli space of $\mu_H$-stable vector bundles with fixed Chern classes, whose boundary points are $\mu_H$-semistable torsion free sheaves.

A: I think the answer to your question is no, because of the following example. For the details, see [Huybrechts-Lehn, The geometry of moduli space of sheaves, Section 5.3].
Let $\pi \colon X \to \mathbb{P}^1$ be an elliptic $K3$ surface with irreducible fibres and assume that there is a section $\sigma \subset X$. By adjunction $\sigma$ is a $(-2)$-curve. Let $f$ be the class of a fibre of $\pi$ and set  $H= H_m:= \sigma + (m+3) f$.
Then the Nakai-Moishezon criterion implies that $H$ is ample for $ m \geq 0$. Moreover, for $m >>0$, the $\mu_{H}$-semistability of a rank $2$ vector bundle $E$ such that $c_1(E) \cdot f \equiv 1$ (mod $2$) is equivalent to its $\mu_H$-stability.
Now let us consider an extension of the form
$$0 \to \mathcal{O}_X (f) \to E \to \mathcal{O}_X( \sigma - 2f) \to 0.$$
One proves that this extension is $\mu_H$-stable if and only if it does not split. Moreover, $c_1(E) \cdot f = (\sigma -f) \cdot f=1$, so $\mu_H$-stability and $\mu_H$-semistability are equivalent in this case (at least if $m$ is large enough).
Finally, $\textrm{Ext}^1(\mathcal{O}_X( \sigma - 2f), \mathcal{O}_X (f) ) \cong \mathbb{C}^2$, and the zero element of this cohomology group corresponds to the trivial extension. So if one takes a disk $\mathcal{D} \subset \mathbb{C}^2$ centered at the origin, there is a flat family
$$\{E_t\}_{t \in \mathcal{D}}$$
of sheaves on $X$ such that $E_t$ is $\mu_H$-stable for $t \neq 0$, whereas $E_0=\mathcal{O}_X (f) \oplus  \mathcal{O}_X( \sigma - 2f)$ is $\mu_H$-instable. In fact, the inclusion $ \mathcal{O}_X( \sigma - 2f) \hookrightarrow E_0$ provides a destabilizing sub-bundle of $E_0$.


text:
Q: Join multiple Pyspark dataframes based on same column name I am new to Pyspark so that is why I am stuck with the following:
I have 5 dataframes and each dataframes has the same Primary Key called concern_code.
I need to outer join all this dataframes together and need to drop the 4 columns called concern_code from the 4 dataframes.
For example:
Dataframe Df1 outer joins Df2 based on concern_code
Dataframe Df1 outer joins Df3 based on concern_code
and so on..
My current Pyspark syntax looks like this:
df1.join(df2,["concern_code"])\
  .join(df3,df1["concern_code"] == df3["concern_code"])\
  .join(df4,df1["concern_code"] == df4["concern_code"])\
  .join(df5,df1["concern_code"] == df5["concern_code"])\
   .show()

How do I need to fix the syntax to perform outer join and to have a final version of a new dataframe that has only one column of concern_code ?

A: You are close.
let's say you have following dfs:
d = [
    ("a", 5.2),
    ("b", 10.4),
    ("c", 7.8),
    ("d", 11.2),

]
df1 = spark.createDataFrame(d, ['concern_code','value'])

df2 = spark.createDataFrame(d, ['concern_code','value1'])

df3 = spark.createDataFrame(d, ['concern_code','value2'])

df4 = spark.createDataFrame(d, ['concern_code','value3'])

df5 = spark.createDataFrame(d, ['concern_code','value4'])

df1.show()

# output
+------------+-----+
|concern_code|value|
+------------+-----+
|           a|  5.2|
|           b| 10.4|
|           c|  7.8|
|           d| 11.2|
+------------+-----+

(
    df1
    .join(df2,on="concern_code", how="outer")
    .join(df3,on="concern_code", how="outer")
    .join(df4,on="concern_code", how="outer")
    .join(df5,on="concern_code", how="outer")
   .show()
)

# output
+------------+-----+------+------+------+------+
|concern_code|value|value1|value2|value3|value4|
+------------+-----+------+------+------+------+
|           c|  7.8|   7.8|   7.8|   7.8|   7.8|
|           d| 11.2|  11.2|  11.2|  11.2|  11.2|
|           a|  5.2|   5.2|   5.2|   5.2|   5.2|
|           b| 10.4|  10.4|  10.4|  10.4|  10.4|
+------------+-----+------+------+------+------+

A: If you join two data frames on columns then the columns will be duplicated, as in your case. So I would suggest to use an array of strings, or just a string, i.e. 'id', for joining two or more data frames.
The code below should not duplicate the column names:
df1.join(df2,on='id', how='outer')\
   .join(df3,on='id', how='outer')\
   .join(df4,on='id', how='outer')\
   .join(df5,on='id'  how='outer')\
   .show()


text:
Q: How to optimize a regular expression match search in Python The Program
I am building a program that tracks which feature file steps are covered by a step definition. For example, I may have a feature step that is I should not click on the panel. This feature step matches the step definition I {qualifier} click on the {place} assuming that {qualifier} maps to (should not|should) and {place} maps to (panel|page).
For every feature step that matches a step definition, I want to keep track of what step definition it actually matched with. So I need to have a connection between I should not click on the panel and I {qualifier} click on the {place}.
And for every feature step that does not match any of the step definitions, then I am going to generate a step definition and connect those two.
The Problem
Right now I take every step definition and convert them into a regular expression, something like...
I {qualifier} click on the {place} will be converted to (I (should not|should) click on the (panel|page))
I am using a Python dictionary where the key is the converted regular expression and the value is the original step definition.
My problem arises when I am going through every single feature step and trying to connect them to their matching step definitions. I am currently just looping through every single regular expression and trying to match it with the feature step, something like this...
# every feature_step gets sent through this check

for regex in all_step_definition_regex:
    if re.match(regex, feature_step):
        step_definition = regex_to_step_definition_map[regex]
        return True, step_definition

return False, None

This is taking an incredibly long time to run when every feature step has to be checked to see if it matches any of the individual regular expressions. One way to speed up the initial check is to join every regular expression together with an 'or' like re.match('|'.join(all_step_definition_regex), feature_step), but then I have no way to connect the feature step with it's matching step definition without looping back through all the individual regular expressions.
I was wondering if anyone has any idea how to speed up this process?

A: You can make each definition pattern a group, and then see which group matched, although you'll need to change your individual regexs to use non-capturing groups (?:) (which would be more efficient in any case, if you're not using the information):
definition_regex = re.compile(r'(' + r')|('.join(all_step_definition_regex) + r')')

def find_definition(feature_step):
    match = definition_regex.match(feature_step)
    if match is None:
        return None
    return match.lastindex - 1


text:
Q: Run last Photoshop script (again) This seems like a trivial issue but I'm not sure Photoshop supports this type of functionality:
Is it possible to implement use last script functionality?

*

*That is without having to add a function on each and every script that writes it's filename to a text file.

A: Well... It's a bit klunky, but I suppose you could read in the scriptlistener in reverse order and find the first mention of a script file:
// Switch off any dialog boxes
displayDialogs = DialogModes.NO; // OFF

var scripts_folder = "D:\\PS_scripts";

var js = "C:\\Users\\GhoulFool\\Desktop\\ScriptingListenerJS.log";
var jsLog = read_file(js);
var lastScript = process_file(jsLog);

// use function to call scripts
callScript(lastScript)

// Set Display Dialogs back to normal
displayDialogs = DialogModes.ALL; // NORMAL

function callScript (ascript)
{
  eval('//@include "' + ascript + '";\r');
}

function process_file(afile)
{
  var needle = ".jsx";
  var msg = "";

  // Let's do this backwards
  for (var i = afile.length-1; i>=0; i--)
  {
    var str = afile[i];

    if(str.indexOf(needle) > 0)
    {
      var regEx = str.replace(/(.+new\sFile\(\s")(.+\.jsx)(.+)/gim, "$2");

      if (regEx != null)
      {
        return regEx;
      }
    }
  }
}

function read_file(inFile)
{

    var theFile = new File(inFile);

    //read in file
    var lines = new Array();
    var l = 0;
    var txtFile = new File(theFile);
    txtFile.open('r');
    var str = "";

    while(!txtFile.eof)
    {
      var line = txtFile.readln();
      if (line != null && line.length >0)
        {
          lines[l++] = line;
        }
    }

    txtFile.close();

  return lines;
}


text:
Q: Mocha - unable to implement TestFunction interface methods I am trying implement following method in my test case from TestFunction interface from Moacha
(fn: Func): Test;
here is the implementation
describe("testing get request", () => {
    it(() => {
        const res = request(app).get("/get-page");
        expect(res.status).to.equal(200);
    });
});

The error I get is this:
TypeError: Test argument "title" should be a string. Received type "function"
when I add the title in it before the the anonymous function it works fine. any idea why I am not able to implement the method that only takes a function.
The interface from index.d.ts
interface TestFunction {
        (fn: Func): Test;
        (fn: AsyncFunc): Test;
        (title: string, fn?: Func): Test;
        (title: string, fn?: AsyncFunc): Test;
        only: ExclusiveTestFunction;
        skip: PendingTestFunction;
        retries(n: number): void;
    }

A: If you take a look at the code for the it keyword, there is no method that accepts only a function (without a title). As far as I can see in the documentation of Mocha, not a single time is an it keyword called without the title. So, your code should use it too:
describe("testing get request", () => {
    it("should return statuscode 200", () => {
        const res = request(app).get("/get-page");
        expect(res.status).to.equal(200);
    });
});

EDIT: If you take a look at the source of index.d.ts in the  DefinitelyTyped repository, you can see that the it, test and specify keywords all reference the TestFunction interface. This interface indeed specifies (fn: AsyncFunc): Test; as a valid signature, but this is nowhere to be found in the Mocha documentation.
We can see that the TestFunction interface was added to replace the ITestDefinition some 2 years back, and the original ITestDefinition does not allow the use of a function without a title. The message of the commit introducing these changes is "More robust Mocha definitions". Why this was added, I don't know. I suspect that it is due to another package, mocha-typescript, also depending on the DefinitelyTyped typings, and this package probably needed the (fn: Func): Test; signature in order to be correctly validated by typescript.
In the end, the result is that Mocha does not allow it to be used without a title.


text:
Q: Is Thirring model a particular case of Gross model? In the Wikipedia entry for the Gross–Neveu model, it is said that

If one takes $N=1$ (which permits only one quartic interaction) and makes no attempt to analytically continue the dimension, the model reduces to the massive Thirring model (which is completely integrable).

But the aditional term in the Thirring model is
$$\frac{g}{2}\left(\overline{\psi}\gamma^\mu\psi\right) \left(\overline{\psi}\gamma_\mu \psi\right).$$
I think this is different from $\frac{1}{2}g \left(\overline{\psi} \psi\right)^2$, the additional term of the Gross–Neveu model. So I think Wikipedia is wrong. Am I right?
If you do not mind, I would like that you respond to this question also: Could this model have soliton solutions?
Thanks in advance.

A: Yes, because the grassman expansion of a quartic fermi interaction can only be $\psi_1\psi_2\bar{\psi}_1\bar{\psi}_2$ in 2d, because there are only four grassman fields, so all other quartics are zero.


text:
Q: Read return value of $.ajax POST Method gives just return value Object object I want to use following ajax method to call a java function (I use Spring Boot and Hibernate) and read the return value afterwards. The function '/myFunction' is correctly called and the return value is a string and is correctly logged in the java function. But I don't get it, how I can use the return message  from the java-method in the success-part afterwards. (notifyUser is a little function(title, message) that shows a notification to an user, this function works correctly) By now, notifyUser just post Error [object Object]
$.ajax({
        type : 'POST',
        contentType : 'application/json',
        url : '/myFunction',
        data : JSON.stringify({
            fooM,
            fooO,
            fooS
        }),
        dataType : 'json',
        cache : false,
        timeout : 600000,
        success : function(data) {
            notifyUser('Info', data);
        },
        error : function(e) {
            notifyUser('Error', e);
        }
    });

@RestController
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public class MyController {

@RequestMapping(value = "/myFunction", method = RequestMethod.POST)
public String myFunction(@RequestBody MyRequestClass request ) {
String return_string = "Check if return value works " + request.getFooM() + request.getFooO() +request.getFooS();
    log.debug(return_string)
    //Up to this step, everything works
    return return_string;
}
}

What do I have to change, that I'm able to get the return value of the called function '/myFunction' in the success part and send the string to notifyUser?
Thank you for your answers.
Phil


text:
Q: Critical render path & 3rd party libraries I am trying to follow Ilya Grigoric's performance best practices by inlining critical css & js and loading all the rest async later.
My problem is when my page needs 3rd party libs in order to render its critical path. I guess when using MVC libs like Angularjs this is not reall an option, but what if I want to use 3rd party templating library? Is there a small enough templating library that I can inline?
I am really trying to follow those best practices ang build a super fast mobile web-app, bit this seams to be really difficult  using today's  modern front-end development  tools (Angularjs/Polymer etc.)

A: The question is broad and vague so it's hard to answer.
You've got a couple of issues here. First, the idea of 'small enough' is relative. You can inline any amount of javascript, so you can technically inline any template library you find.
I don't know what Grigoric's specific guidance is, but if you need the template library to render anything for the user then it IS part of your critical path and should be loaded asap. That said, if you're trying to create a fast experience for your user, it seems like you'd be better off rendering the html server side so  the mobile device can react quicker to the response. If your entire document is created with javascript templates on the device you're going to have to wait for the entire DOM to load, wait for the javascript to parse, and finally wait for your templates to be processed before anything is shown to the user.
EDIT:
Don't optimize for a performance problem until you HAVE a performance problem
The goal is not to make the 'fastest possible page'. Instead your goal should be to make a page that 'works well'. Your questions don't really have 'correct' answers - it really depends on your specific situation and goals.
Regarding 'what if js is in head, will it be an issue': the answer is simply yes. Sure you can make tweaks to speed things up, but the basic architecture still has the same limitations - when you render templates on the client you're doing a ton more processing on the client. Further, you have to wait significant amount of time to download resources on first request, more than you would if it were plain html coming down the line.
Either way, in both cases your app may function perfectly well. You should just implement something and come back if you have a more specific issue.


text:
Q: Writing Function on Data Frame in Pandas I have data in excel which have two columns 'Peak Value' & 'Label'. I want to add value in 'Label' column based on 'Peak Value' column.
So, Input looks like below
Peak Value 0 0 0 88 0 0 88 0 0 88 0
Label      0 0 0  0 0 0 0  0 0 0 0

Input

Whenever the value in 'Peak Value' is greater than zero then it add 1 in 'Label' and replace all the zeros below it. For the next value greater than zero it should get incremented to 2 and replace all the zeros by 2.
So, the output will look like this:
Peak Value 0 0 0 88 0 0 88 0 0 88 0
Label      0 0 0  1 1 1  2 2 2  3 3

Output

and so on....
I tried writing function but I am only able to add 1 when the value is greater than 0 in 'Peak Value'.
def funct(row):
    if row['Peak Value']>0:
        val = 1
    else:
        val = 0
    return val

df['Label']= df.apply(funct, axis=1)

A: May be you could try using cumsum and ffill:
import numpy as np

df['Labels'] = (df['Peak Value'] > 0).groupby(df['Peak Value']).cumsum()
df['Labels'] = df['Labels'].replace(0, np.nan).ffill().replace(np.nan, 0).astype(int)

Output:
    Peak Value  Labels
0            0       0
1            0       0
2            0       0
3           88       1
4            0       1
5            0       1
6           88       2
7            0       2
8            0       2
9           88       3
10           0       3


text:
Q: How to convert string to number in python? I have list of numbers as str
li = ['1', '4', '8.6']

if I use int to convert the result is [1, 4, 8].
If I use float to convert the result is [1.0, 4.0, 8.6]
I want to convert them to [1, 4, 8.6]
I've tried this:
li = [1, 4, 8.6]
intli = list(map(lambda x: int(x),li))
floatli = list(map(lambda x: float(x),li))
print(intli)
print(floatli)

>> [1, 4, 8]
>> [1.0, 4.0, 8.6]

A: Convert the items to a integer if isdigit() returns True, else to a float. This can be done by a list generator:
li = ['1', '4', '8.6']
lst = [int(x) if x.isdigit() else float(x) for x in li]
print(lst)

To check if it actually worked, you can check for the types using another list generator:
types = [type(i) for i in lst]
print(types)

A: One way is to use ast.literal_eval
>>> from ast import literal_eval
>>> spam = ['1', '4', '8.6']
>>> [literal_eval(item) for item in spam]
[1, 4, 8.6]

Word of caution - there are values which return True with str.isdigit() but not convertible to int or float and in case of literal_eval will raise SyntaxError.
>>> '1²'.isdigit()
True

A: You can use ast.literal_eval to convert an string to a literal:
from ast import literal_eval

li = ['1', '4', '8.6']
numbers = list(map(literal_eval, li))

As @Muhammad Akhlaq Mahar noted in his comment, str.isidigit does not return True for negative integers:
>>> '-3'.isdigit()
False

A: You're going to need a small utility function:
def to_float_or_int(s):
    n = float(s)
    return int(n) if n.is_integer() else n

Then,
result = [to_float_or_int(s) for s in li]

A: You can try map each element using loads from json:
from json import loads
li = ['1', '4', '8.6']
li = [*map(loads,li)]
print(li)

# [1, 4, 8.6]

Or using eval():
print(li:=[*map(eval,['1','4','8.6','-1','-2.3'])])

# [1, 4, 8.6, -1, -2.3]

Notes:

Using json.loads() or ast.literal_eval is safer than eval() when
the string to be evaluated comes from an unknown source


text:
Q: Kalarm install problem and "is configured multiple times" error I installed kalarm and got some errors, quoted below, and kalarm said it was unable to create the first alarm.  Now "New" alarm is grayed out as well as some other options.  Tried resetting to defaults and also removing and reinstalling but no change.
Errors installing kalarm:
W: Target Packages (main/binary-amd64/Packages) is configured multiple times in /etc/apt/sources.list.d/google-chrome-beta.list:3 and /etc/apt/sources.list.d/google-chrome.list:3
W: Target Packages (main/binary-all/Packages) is configured multiple times in /etc/apt/sources.list.d/google-chrome-beta.list:3 and /etc/apt/sources.list.d/google-chrome.list:3
W: Target DEP-11 (main/dep11/Components-amd64.yml) is configured multiple times in /etc/apt/sources.list.d/google-chrome-beta.list:3 and /etc/apt/sources.list.d/google-chrome.list:3
W: Target DEP-11 (main/dep11/Components-all.yml) is configured multiple times in /etc/apt/sources.list.d/google-chrome-beta.list:3 and /etc/apt/sources.list.d/google-chrome.list:3
W: Target DEP-11-icons-small (main/dep11/icons-48x48.tar) is configured multiple times in /etc/apt/sources.list.d/google-chrome-beta.list:3 and /etc/apt/sources.list.d/google-chrome.list:3
W: Target DEP-11-icons (main/dep11/icons-64x64.tar) is configured multiple times in /etc/apt/sources.list.d/google-chrome-beta.list:3 and /etc/apt/sources.list.d/google-chrome.list:3
W: Target DEP-11-icons-hidpi (main/dep11/icons-64x64@2.tar) is configured multiple times in /etc/apt/sources.list.d/google-chrome-beta.list:3 and /etc/apt/sources.list.d/google-chrome.list:3
W: Target DEP-11-icons-large (main/dep11/icons-128x128.tar) is configured multiple times in /etc/apt/sources.list.d/google-chrome-beta.list:3 and /etc/apt/sources.list.d/google-chrome.list:3
W: Target CNF (main/cnf/Commands-amd64) is configured multiple times in /etc/apt/sources.list.d/google-chrome-beta.list:3 and /etc/apt/sources.list.d/google-chrome.list:3
W: Target CNF (main/cnf/Commands-all) is configured multiple times in /etc/apt/sources.list.d/google-chrome-beta.list:3 and /etc/apt/sources.list.d/google-chrome.list:3


text:
Q: Capture number inside tag in Qt My tag struct looks like this:
<sml8/>

combination of < , sml , digits (one or two) and />
Is there anyway to capture number inside tag?
for example in above I want capture 8 inside
I've defined regular expression and I tried to capture it by digit position but it's not working for me.
QRegExp rxlen("<sml(.*)/>");
int index = rxlen.pos(3);

I guess it's not correct way and it gives me position of digit although I want value of digit (or digits).

A: You need to use capturedTexts() together with <sml(\\d{1,2})/> regex (it matches <sml literally, then 1 or 2 digits capturing them into Captured group 1, then />:
QString str = "<sml8/>";
QRegExp rxlen("<sml(\\d{1,2})/>");
int pos = rxlen.indexIn(str);
QStringList list = rxlen.capturedTexts();
QString my_number = list[1];


text:
Q: Convert PDF to image using ImageMagick on command line Hi I am trying convert a PDF to an image using ImageMagick and it is throwing the following error:
$ convert  error720.pdf  error720.png
convert.exe: FailedToExecuteCommand `"C:/Program Files (x86)/gs/gs9.09/bin/gswin
32c.exe" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -
dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pngalpha" -dTextAlphaBits=4 -dGraphicsA
lphaBits=4 "-r72x72"  "-sOutputFile=C:/Users/SURESH~1/AppData/Local/Temp/magick-
4680NzHfmhYvSbW4%d" "-fC:/Users/SURESH~1/AppData/Local/Temp/magick-4680Wqgv9awWP
WwC" "-fC:/Users/SURESH~1/AppData/Local/Temp/magick-4680KJ2X0fSVMwXJ"' (-1) @ er
ror/utility.c/SystemCommand/2051.
convert.exe: no images defined `error720.png' @ error/convert.c/ConvertImageComm
and/3187.

I am running Windows 8 64-bit.

A: There are a number of things you could try:
Check which version of ImageMagick you are using, and which delegates (helpers) are installed. Please run the following commands and click edit under your question and then paste in the output.
identify -version

and
configure -list delegates | grep -i delegate

Check which version of ghostscript you have installed and report:
gswin32c -v

Try adding a -density before reading in your PDF file:
convert -density 288 error720.pdf  error720.png

A: Hi Mark thanks for the reply. Downloaded the 64 bit version of ghostscript and now it is working fine.
Link:
http://downloads.ghostscript.com/public/gs910w64.exe


text:
Q: how to use geturl with an index.php in magento? the title may seem not clear. now this is my issues.
im using windows which is i need to run the magento with "index.php" on it.
example : "localhost/magentoproject/index.php/test/index/save"
now im using the getUrl function on form like this
<?php echo Mage::getUrl('test/index/save')?>

but after i inspect, the url shows like this
localhost/magentoproject/test/index/save

the url appear is not including the index.php, therefore, magento shows 404 not found.
how i solve this problem ? how to use geturl including the "index.php" on it.
currently im use the hardcode like this on the form
http://localhost/magentoproject/index.php/test/index/save

A: *

*Go to admin url of your site.

*Next go to System > configuration > web > Search Engines Optimization

*Then set Use Web Server Rewrites value to 'No'


text:
Q: UIImagePickerController supports portrait mode only. Any alternatives that support landscape mode? iOS documentation says "The UIImagePickerController class supports portrait mode only". Any alternatives to this if I want to display the photo library in landscape mode?

A: may be this will help you out .You can use ALAssetsLibrary and asset class to get the pictures in your device and you can use them to display in landscape mode and in portrait mode same like uiimagepicker.
- (void)viewDidLoad
{
    [super viewDidLoad];
    [activity startAnimating];

    appObj=(ImagePickerAppDelegate *)[[UIApplication sharedApplication]delegate];

    void (^assetEnumerator)(struct ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop)
    {
        if(result != NULL)
        {
            //assets is a mutualable array...for storing the images that are in the device..
            [assets addObject:result];
        }
    };

    void (^assetGroupEnumerator)(struct ALAssetsGroup *, BOOL *) =  ^(ALAssetsGroup *group, BOOL *stop)
    {
        if(group != nil)
        {
            [group enumerateAssetsUsingBlock:assetEnumerator];
        }
        //meth is a user defined method..
        [self meth];
        [activity stopAnimating];
        [activity setHidden:YES];
    };
    assets = [[NSMutableArray alloc] init];
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    [library enumerateGroupsWithTypes:ALAssetsGroupAlbum usingBlock:assetGroupEnumerator
                         failureBlock: ^(NSError *error) { NSLog(@"Failure");}];
}

-(void)meth
{
    NSLog(@"%i",[assets count]);

    if(userOrientation==UIInterfaceOrientationPortrait || userOrientation==UIInterfaceOrientationPortraitUpsideDown)
    {
        NSLog(@"haii");
        [scrollView removeFromSuperview];

        scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
        scrollView.backgroundColor=[UIColor whiteColor];

        NSLog(@"%i",[assets count]);
        for (int i = 0; i < [assets count]; i++)
        {
            imgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [imgBtn setFrame:CGRectMake((i%4*80)+2,(i/4*80)+2,75,75)];
            imgBtn.tag=i;
            [imgBtn addTarget:self action:@selector(imageClicked:) forControlEvents:UIControlEventTouchUpInside];
            ALAsset *asset=[assets objectAtIndex:i];
            [imgBtn setImage:[UIImage imageWithCGImage:[asset thumbnail]] forState:UIControlStateNormal];
            [scrollView addSubview:imgBtn];
        }
        scrollView.contentSize = CGSizeMake(320,(([assets count]/4)+1)*300 );
    }

    if(userOrientation==UIInterfaceOrientationLandscapeRight || userOrientation==UIInterfaceOrientationLandscapeLeft)
    {
        [scrollView removeFromSuperview];
        scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 480,320)];
        for (int i = 0; i < [assets count]; i++)
        {
            imgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [imgBtn setFrame:CGRectMake((i%6*80)+2,(i/6*80)+2,75,75)];
            imgBtn.tag=i;
            [imgBtn addTarget:self action:@selector(imageClicked:) forControlEvents:UIControlEventTouchUpInside];
            ALAsset *asset=[assets objectAtIndex:i];
            [imgBtn setImage:[UIImage imageWithCGImage:[asset thumbnail]] forState:UIControlStateNormal];
            [scrollView addSubview:imgBtn];
        }
        scrollView.contentSize = CGSizeMake(480,(([assets count]/4)+1)*300);
    }
    [self.view addSubview:scrollView];
}

-(void)imageClicked:(UIButton *)sender
{
    //for picking the images that the user has selected we are using other array "selectedImages" i.e declared in the app delegate
    ALAsset *asset=[assets objectAtIndex:sender.tag];
    [appObj.selectedImages addObject:[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]]];
    NSLog(@"%i",[appObj.selectedImages count]);
    [self.navigationController popViewControllerAnimated:YES ];
}

A: I haven't checked whether this is illegal, but it worked for me. If you want the UIImagePickerController to start(and stay) in Landscape orientation code:
//Initialize picker

UIImagePickerController * picker = [[UIImagePickerController alloc] init];
   picker.delegate = self;

//set Device to Landscape. This will give you a warning. I ignored it.
//warning: 'UIDevice' may not respond to '-setOrientation:'

[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];

//Set Notifications so that when user rotates phone, the orientation is reset to landscape.
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

//Refer to the method didRotate:
[[NSNotificationCenter defaultCenter] addObserver:self
              selector:@selector(didRotate:)
               name:@"UIDeviceOrientationDidChangeNotification" object:nil];

//Set the picker source as the camera
picker.sourceType = UIImagePickerControllerSourceTypeCamera;

//Bring in the picker view
[self presentModalViewController:picker animated:YES];

The method didRotate:
- (void) didRotate:(NSNotification *)notification

{
      //Maintain the camera in Landscape orientation
 [[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];

}


text:
Q: What is the best way to add the same code to every component in React? I am trying to build a simple page navigation loading screen while using react-router-dom. My first instinct to start is to do something like:
export default function PageOne = () => {

    const [show, setShow] = useState('show');

    useEffect(() => {
        setTimeout(() => {
            setShow('');
        }, 500)
    }, [])

    return (
        <>
            <div className={`loader ${show}`}>

                Here is my content for page one

        </>
    )
}

Here, the loader div would be displayed with a position: absolute, height: 100vh, and width: 100vw. Then after 500ms, it can be animated to fade out or slide off screen.
This doesn't feel like a great solution, and it means that the same code will be rewritten within every single page. Is there a simpler or more 'reacty' way to do this?

A: Yes, you have the right thinking. To be honest, React is all about code sharing. You can share functions, components, hooks, contexts, etc. There's no right or wrong what you want to share, however if you just want to extract couple of your lines involving useState etc, you can use a hook.
  const useMyOwnHook = () => {
    const [show, setShow] = useState('show');

    useEffect(() => {
        setTimeout(() => {
            setShow('');
        }, 500)
    }, [])

    return show
  }

Then you can use it as
export default function PageOne = () => {

    const show = useMyOwnHook()

    return (
        <>
            <div className={`loader ${show}`}>

                Here is my content for page one

        </>
    )
}

By the way, don't ask me what your code means. I'm only refactor your code, and that is what a hook is about.


text: Q: Missing folder in iCloud drive! Installed MWeb for iOS and it created a folder, its available in my phone's iCloud drive but not in Web or Mac iCloud drive! Created a test folder and made sure no sync issues. Any help is appreciated


text:
Q: Erro DLL Conexão FireDac com PostgreSQL Estou com o erro de DLL não encontrada ao fazer uma conexão com o PostgreSQL utilizando o componente FireDAC.
Erro:

[FireDAC][Phys][PG]-314. Cannot load vendor library [C:\EXE\libpq.dll]. Hint: check it is in the PATH or application EXE directories, and has x86 bitness.

O detalhe é que já copiei a DLL para o diretório da aplicação, também para teste copiei a dll para o System32 e o Syswow64, porém o erro persiste.
Estou com o Microsoft C++ package 2015 instalado, conforme pede na documentação documentação da embarcadero:
Wiki Embarcadero
Outro teste que realizei foi pelo componente FireDAC tentar realizar a conexão, inclusive no compoente do drive do Postgres apontei a propriedade VendorLib para a DLL, porém, novamente o mesmo erro.
Alguém possui mais alguma sugestão?
Grato desde já.

A: Para o conhecimento de todos, o problema foi resolvido. Para o PostgreSQL funcionar corretamente é necessário copiar as seguintes DLLs para a pasta da aplicação:

*

*Libeay32.dll

*SSLeay32.dll

*Intl.dll

*Libpq.dll

Copiar essas DLLs do diretório bin da instalação do PostgreSQL.

A: Sei q já seu problema foi resolvido, porem gostaria de deixar minha contribuição pra outros..
Recomendo fazer o download dessas dll e colocar na pasta do executável em produção,  na plataforma x86, porque os executáveis por padrão no Delphi é 32bis
no site oficial https://www.postgresql.org/ftp/odbc/versions/dll/

A: No meu caso, o problema foi resolvido quando adicionei no Form, o Object Inspector FDPhysPgDriverLink1. Na propriedade VendorHome, vai ter um diretório, apaguei o \lib e pronto.
Funcionou normalmente depois que eu fiz isso.

A: No caso, se você quer prototipar sua aplicação em tempo de design, precisa colocar as dlls no diretório do delphi (ver respostas acima, todas estão corretas)
No meu caso, eu copiei as dlls tanto para o diretório do meu projeto quanto para o diretório onde o delphi está instalado
C:\Program Files (x86)\Embarcadero\Studio\20.0\bin
D:\Projetos\Projeto1\Debug\Win32
D:\Projetos\Projeto1\Release\Win32\
eu coloquei as dlls dentro de uma pasta
\Drivers\Pg\x86\
entao ficou assim
C:\Program Files (x86)\Embarcadero\Studio\20.0\bin\Drivers\Pg\x86
D:\Projetos\Projeto1\Debug\Win32\Drivers\Pg\x86
D:\Projetos\Projeto1\Release\Win32\Drivers\Pg\x86\
Eu arrastei um componente PGDriverLib e na property VendorHome eu coloquei "Drivers\Pg\x86"
Funcionou em todos os cenários
Em modo de design
Em modo de debug
Compilado em modo Release
Para distribuir o software copie a mesma pasta Drivers\Pg\x86 para a mesma pasta da aplicacao


text:
Q: Add style from props to existing component styles in React Native I have the following component defined:
import React, { Component } from 'react';
import { StyleSheet, TouchableOpacity, View, Text } from 'react-native';

export default class Button extends Component {
  render() {
    return (
      <TouchableOpacity onPress={() => this.props.onPress}>
        <View style={styles.container}>
          <Text
            style={{
              color: this.props.foregroundColor,
            }}
          >
            {this.props.title}
          </Text>
        </View>
      </TouchableOpacity>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    paddingTop: 15,
    paddingBottom: 15,
    paddingRight: 20,
    paddingLeft: 20
  },
});

I'd like to pass a prop backgroundColor to this component. But how do I extend the current styles.container to dynamically set backgroundColor? I've tried
<View style={
    ...styles.container,
    backgroundColor: this.props.backgroundColor
}>...

But I get a SyntaxError when I do that...

A: Do it like this way:
<View style={[styles.container, {backgroundColor: this.props.backgroundColor}]}>

React native will use StyleSheet.flatten to combine two object to be one style instance.
This is the same:
const newStyle = StyleSheet.flatten([
    styles.container,
    {backgroundColor: this.props.backgroundColor},
]);

A: Basically, React native use an object for the stylesheet.
To fix the above error just add {} in styles.
like this.
<View style={{
    ...styles.container,
    backgroundColor: this.props.backgroundColor
}}>

For understanding purposes, the first bracket is used for evaluation
and a second bracket is a stylesheet object that returns to the component. now you're spreading an object (container styles) inside the main object so now it merges with the styles you provided.


text:
Q: Can We use string resources for code comment in android? Suppose we have some statement for comments which will be repeat many times. Can We use string resources for code comment in android?

A: No. Comments are ignored by the compiler and runtime engine, therefore there would be no point in referring to a String resource. If you are looking to create the same comment over and over in the source code,  recording a macro in Android Studio will do the job better:

Edit -> Macros -> Start Recording Macro

Type out your comment

Edit -> Macros -> Stop Recording Macro

Give your macro a name. Then to use your macro again:

Edit -> Macros -> Play saved macro...

You can also map your macro to a key combination via:

File -> Settings -> Keymap -> Macros

A:
Can We use string resources for code comment in android?

No You can't
Comments are just ignored by compiler and never get executed.


text:
Q: How to turn array into string in maco? I have an object in which array with strings are stored. I have tried different ways, but it didn't work.
For example:
${', '.join(data.array_of_strings)}

A: By "array of strings" do you mean a list/tuple of strings, or do mean this array of type char.  If you mean a list/tuple of strings, then the snippet you have in your question should work.  Here is a minimal working example.
Test.py
from mako.template import Template
class Data(object): pass
data = Data()
data.array_of_strings = ['a', 'b', 'c']
print Template("${', '.join(data.array_of_strings)}").render(data=data)

Which, when executed produces the following.
>> python test.py
a, b, c


text:
Q: Filter DOM nodes based on an array with multiple Ids using data attributes Given the following markup

I want to filter the nodes by using an array of data-id
So if I have ids=[1,2] I want as a result the two nodes corresponding to those in the array, inside one of the groups.
ids=[1,2]
nodes = $(".group-one").children();
#nice way of filtering the nodes using ids array. With Jquery.filter or Underscore

I know I can iterate trough all the child nodes and compare each of the nodes data-id againts the ids array. But I want to know if this can be achieved by using only selectors o some other on liner kind of solution.
Thanks!

A: Just filter based on the data attributes ?
var ids=[1,2];

$('div span').filter(function() {
    return ids.indexOf( $(this).data('id') ) !=  -1;
});

FIDDLE

A: Solution with only jQuery selectors:
var filteredNodes = nodes.filter(function() {
    // Attributes are strings, so you have to convert int.
    var i = parseInt($(this).attr('data-id'));
    return $.inArray(i, ids) >= 0;
});


text:
Q: Staged git lfs files not being intercepted by git-lfs I am trying to commit/push a 1.2gb tar file to git lfs server using Git on Windows 10
I have tracked the tar extension with:
C:\FilepathTo\Folder> git lfs track '*.tar'

Running git lfs track returns
Listing tracked patterns
    Folder\'*.tar' (Folder\.gitattributes)

I add the .gitattributes file
C:\FilepathTo\Folder> git add .gitattributes

I add the large file
C:\FilepathTo\Folder> git add file.tar

Then confirm the file is being tracked with
C:\FilepathTo\Folder> git lfs status

    On branch MyAwesomeBranch
    Git LFS objects to be pushed to origin/MyAwesomeBranch:

    Git LFS objects to be committed:

            .gitattributes  (Git: 136g1ea)
            file.tar (Git: 567d1ed)

    Git LFS objects not staged for commit:

I commit the file
C:\FilepathTo\Folder> git commit -m "foo"
    [MyAwesomeBranch ecf9735] foo
     2 files changed, 0 insertions(+), 0 deletions(-)
     create mode 100644 Folder/.gitattributes
     create mode 100644 Folder/file.tar

And check that the file is being tracked
C:\FilepathTo\Folder> git lfs track ls-files

Which returns nothing.
I check lfs status again and it isn't listed as an object to be pushed.
C:\FilepathTo\Folder> git lfs status
On branch MyAwesomeBranch
Git LFS objects to be pushed to origin/MyAwesomeBranch:

Git LFS objects to be committed:

Git LFS objects not staged for commit:

As expected, pushing fails with
remote: error: File Folder/file.tar is 1229.43 MB; this exceeds GitHub Enterprise's file size limit of 100.00 MB

What am i doing wrong? Why is the staged file not being committed to git lfs?

A: The issue was resolved.
This command was the issue:
C:\FilepathTo\Folder> git lfs track '*.tar'

I should have used double quotes as below:
C:\FilepathTo\Folder> git lfs track "*.tar"

Which resolved my issue.


text:
Q: By flagging a question can a moderator revise and delete it? I am JavaScript developer and create jQuery plugins for other developers. I'm developing a plugin like LazyLoad. I need it to be cross-browser so I asked the following question, https://stackoverflow.com/questions/13333904/seo-image-index-tag-img-and-tag-a.
Due to the insensitivity of some users who do not understand my good intentions (they thought I wanted to cheat Google-search) I had my question downvoted and closed .
I flagged my own question. Could the downvotes be reversed and can I re-ask my question?
I edited my question, tell me now it is easy to understand? Or still confused?

*

*If I create another question easier to understand, it may be closed (it will be a duplicate)?

*Or closed questions are not duplicates?

*I was told that SEO is not an issue for the SO. Why then has the tags SEO and seo-friendly?

A: It's hard to understand what you are saying. Your motivations are not as unfavourable to the stake than the way you construct a sentence.
A repeated phrase such as "I ride a LazyLoad" does not make sense.
Unclear English is often a large factor in why a question is closed as "not a real question".
You may flag your question, but a moderator will not and cannot reverse any votes. That is an issue between you and the users who have chosen to vote.
On top of that, asking about what affects SEO is off topic, or not constructive, as the algorithms used by search engines are always evolving in the world of snake oil.


text:
Q: how to create unique_ptr from inherited parent class Is there a way to create a unique_ptr from one of the inherited classes?
I need to be able to "register" MouseListeners with a manager but I cannot figure out how to create the unique_ptr of the inherited MouseListener.
The error is that it cannot find a conversion from Window * to MouseListener. I have tried a static_cast but that produces other errors. I have also tried passing in a raw pointer to the addMouseListener which did work but errored when you close the program as I think it did not create the appropriate memory which causes the delete to fail.
Also using std::move() transfers ownership which causes the listener to not fire the event.
// Window.h
class Window : public MouseManager, public MouseListener {
public:
    Window::Window(std::string title, int32_t width, int32_t height) {
        ...
        this->addMouseListener(std::make_unique<MouseListener>(this)); // ERROR
    }
};

// MouseManager.h
void MouseManager::addMouseListener(std::unique_ptr<MouseListener> listener) {
    m_listeners.emplace_back(listener);
}

// MouseListener.h

MouseListener() = default;

virtual ~MouseListener() = default;
MouseListener(const MouseListener& listener) = default;
MouseListener(MouseListener&& listener) noexcept ;
MouseListener& operator=(const MouseListener& listener) = delete;
MouseListener& operator=(MouseListener&& listener) = delete;

Error output
In file included from /Users/Programmer/CLionProjects/StormEngine/Engine/Window/Window.cpp:5:
In file included from /Users/Programmer/CLionProjects/StormEngine/Engine/Window/Window.h:8:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/memory:3141:32: error: no matching constructor for initialization of 'MouseListener'
    return unique_ptr<_Tp>(new _Tp(_VSTD::forward<_Args>(__args)...));
                               ^   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/Programmer/CLionProjects/StormEngine/Engine/Window/Window.cpp:17:33: note: in instantiation of function template specialization 'std::__1::make_unique<MouseListener, Window *>' requested here
    this->addMouseListener(std::make_unique<MouseListener>(this));
                                ^
/Users/Programmer/CLionProjects/StormEngine/Engine/Window/../Events/Listeners/MouseListener.h:19:5: note: candidate constructor not viable: no known conversion from 'Window *' to 'const MouseListener' for 1st argument; dereference the argument with *
    MouseListener(const MouseListener& listener) = default;
    ^
/Users/Programmer/CLionProjects/StormEngine/Engine/Window/../Events/Listeners/MouseListener.h:20:5: note: candidate constructor not viable: no known conversion from 'Window *' to 'MouseListener' for 1st argument; dereference the argument with *
    MouseListener(MouseListener&& listener) noexcept ;
    ^
/Users/Programmer/CLionProjects/StormEngine/Engine/Window/../Events/Listeners/MouseListener.h:16:5: note: candidate constructor not viable: requires 0 arguments, but 1 was provided
    MouseListener() = default;
    ^

Update:
de-referencing this adds a new problem where to add the variable listener you have to std::move() which causes the change of ownership which as stated above causes the events not to fire.

A: make unique makes an object of that type and returns a pointer to it.
It does not wrap a pre existing pointer to an object into a unique ptr.
Your addMouseListener(std::unique_ptr<MouseListener>) function takes ownership of the listener.  Passing a preexiting object is not generally a good idea here.
Probably Window should not inherit from MouseListener but instead create a MouseListener that in turn has a pointer to the Window and somehow does lifetime management to ensure the Window alive stays around, or us disconnected when the Window dies.
The MouseListener should relay messages to the window, not be the window.

A:
std::make_unique<MouseListener>(this)

This allocates a new MouseListener instance, with this as an argument to the constructor. As the error message explains, there is no constructor MouseListener:MouseListener(Window*) or any other constructor with a parameter to which Window* could be implicitly converted.
You probably didn't intend to create a new MouseListener instance, but instead want a unique pointer to this. You can create a unique_ptr to this using the constructor explicit unique_ptr(pointer p):
std::unique_ptr<Window>(this)

This pointer can be passed to MouseManager::addMouseListener. Note that while the conversion from a deriver unique pointer is implicit, a base unique pointer cannot be directly constructed from a bare derived pointer, because the constructor is explicit.

Note that creating a unique pointer to this is probably a dubious idea. It limits the creation of Window objects to using new, and apparently (from the perspective of the code that allocates) leaking the pointer. No other code can own any windows (unless moved from the container where it was initially stored), and you can never have automatic instances.


text:
Q: how to pass single digit to the next command I am trying to pass the RHEL version to the next command, but I can not:
my script is below:
### To Create Repo File

    - name: Check for the presence of the DIR. below
      stat: path=/etc/yum.repos.d
      register: dir
    - shell: mkdir -p /etc/yum.repos.d
      when: not dir.stat.exists
    - name: To get the RHEL Release
      shell: cat /etc/redhat-release | awk '{ print $7 }' |cut -c1
      register: RH_REL
#
    - shell: touch /etc/yum.repos.d/patch.repo
    - shell: echo [RHEL-{{ RH_REL }}-2020_{{ WW }}-OS] > /etc/yum.repos.d/patch.repo

the output from debugging I am getting is below:
ok: [dmzpnet6.wellsfargo.net] => {
    "RH_REL.stdout": "7"
}

but I need only to get 6 or 7  in the output to pass that single-digit how I can do it or maybe I can use something else instead of "register"?
Thank you.
Michael

A:
Q: "I need only to get 6 or 7 ... or maybe I can use something else instead of 'register'?"

A: Yes. You might want to use the variable ansible_distribution_major_version created by the setup module. It's not necessary to run it explicitly. The facts will be collected by default on start unless you ask to gather_facts: false. For example
- hosts: remote_hosts
  gather_facts: true
  tasks:
    - debug:
        var: ansible_distribution_major_version
    - shell: "echo {{ ansible_distribution_major_version }} > /tmp/my_ansible_test.txt"

See the content of the file /tmp/my_ansible_test.txt at remote_hosts.


text:
Q: Runtime type of interface I use entity framework with DbContext T4 code generator. The code generated includes entity objects with child entity collections. They are declared as ICollection<T>. Now, I found out at runtime they actually become HashSet<T>. How .NET handles such cases? Can someone point me to the documentation where I can find information on default implementation types of specific interface?

A: There is no "default implementation" for an interface. If a method returns an interface, that method decides which type is actually returned. In your case, that's most likely something inside Entity Framework.


text:
Q: heightForHeaderInSection not working I'm trying to get heightForHeaderInSection to set the height for my section header but it doesn't seem to be working. I've put this
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    return 60.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    NSString *SectionHeaderViewIdentifier = @"sectionHeaderIndentifier";

    HeaderSection *sectionHeaderView = [self.tableView dequeueReusableHeaderFooterViewWithIdentifier:SectionHeaderViewIdentifier];

    return sectionHeaderView;
}

In my ViewController.m file.
Here's a screenshot of how it's not working in the simulator.

I should also say I register the nib in the ViewDidLoad of my ViewController.
UINib *sectionHeaderNib = [UINib nibWithNibName:@"headerNib" bundle:nil];

    NSString *SectionHeaderViewIdentifier = @"sectionHeaderIndentifier";

    [self.tableView registerNib:sectionHeaderNib forHeaderFooterViewReuseIdentifier:SectionHeaderViewIdentifier];

Here's the storyboard layout and connections.

A: viewForHeaderInSection should be something like:
    myLabel = [[UILabel alloc] init];
    headerView = [[UIView alloc] init];

    myLabel.frame = CGRectMake(10, 0, self.view.bounds.size.width, 20);

    myLabel.text = [self tableView:self.meetingOverviewTable titleForHeaderInSection:section];
    [headerView setBackgroundColor:[UIColor lightGrayColor]];
    [headerView addSubview:myLabel];
    return headerView;


text:
Q: SplitViewController in Landscape Orientation. How Do I Hide the TableViewController? On iPad I have a UISplitViewController-based app. Has anyone figured out how to hide/show the tableViewController that is locked down on the left hand side - when in landscape orientation - stubbornly hogging precious screen real estate?
If you take a look at the iPad Dropbox app it has a nifty show/hide arrow that is exactly what I am after.


text:
Q: Restricting scripts to subsets of users Suppose I have a perl (or python) script that does something highly secretive; I'd only want to allow certain users to actually be able to use the script.   Currently, I gain this functionality by maintaining a read-only text file called allowedUsers.txt and check with the following:
my $username = `whoami`;
my %allowedUsers;
open ALLOWED_USERS, "allowedUsers.txt";
while(<ALLOWED_USERS>) {
    $allowedUsers{$_} = 1;
}
if($allowedUsers{$username} != 1) {
    die "Sorry, user $username does not have access.\n";
}

This works just fine, however since the script is necessarily readable (otherwise Perl itself would not be able to execute it), nothing is stopping people from simply making a copy of the script, commenting out this section of code, and then running their "hacked" version to circumvent the identity check!
Is there a better way to achieve the restriction of script execution to a subset of users?  For instance, can I have perl code that is not readable but somehow executable by everyone?

A: Only allow a certain group of users to read/execute your script, and put the relevant users in this group.
EDIT: more precisely:

*

*create a group named, for instance trusted_users with your preferred user management tool

*add the authorized users to this group

*set the script's group with chgrp: chgrp trusted_users my_script.pl

*set its permissions with chmod: chmod u=rwx,g=rx,o= my_script.pl (the owner may read, write, execute; the group members may read and execute; the others can do nothing)

A: The script checks if it can run and exits if it cannot, but having executable permission implies read permission for the script and so users can simply copy it, remove that silly check and run it.
Create a group of users, and allow only users from that group to read and execute that file. Then you simply add users you want to grant this privilege to that group and voilà! For an example, see Unix - File Permission / Access Modes.


text:
Q: How to transfer the live photos to Mac via AirDrop? Before the update to High Sierra, when I received live photos via AirDrop, the system always asked I want to save them to the downloads folder or import it into the Photos app. When I choosing the second option, the imported live photos could then be exported as files to a disc, where for each live photo there were two files — an image and a short video.
After the update to High Sierra, the system immediately, without asking, saves the photos received through AirDrop into the downloads folder, with only JPG/HEIF files, without the live component video files.
How can I fix it?

A: This is not the fix but a workaround.
I exactly have the same issue with you. The interesting thing is that if someone send me Live Photos via AirDrop, (he is using iPhone 6), my laptop running High Sierra would give me the option to import via Photos app. But if I try to send live photos via AirDrop from my iPhone 7, I have no way of importing them directly into Photo app, and all I get is JPGs in download folder. I have been googling to see if anyone can offer solutions but so far, nothing except people are guessing as it is a bug...
But I really wanted to transfer my Live Photos wireless. And my solution was to use "Shared Albums" in iCloud. (I'm not sharing the album necessarily. Simply this is for me only.) I tested a few times and I see that Live Photos are intact under Shared Albums in Photo app on my laptop. Then I select them and import into Photo app. I can also add Live Photos from my laptop in the Shared Album, and I can grab them in my iPhone as well.
Another cool thing about this is "A shared album can hold up to 5000 photos and videos. The photos and videos in your shared albums are kept in iCloud, but they don't count against your iCloud storage limit." Although for me, I'll keep the album empty after importing photos.
Here is more info on Shared Album from Apple website:
https://support.apple.com/en-us/HT202786
Till Apple can fix the bug, this is my workaround to import live photos on my iPhone without USB cable.

A: Tap on the share icon and then tap Options.

Then Turn on All Photos Data.

A: If you are sharing between two devices with the same Apple ID (or, I think, within the same family), it will automatically save the photo to downloads, but between different iCloud accounts, it should give you a prompt where you can select to open with Photos instead (which should preserve the live photo). See https://support.apple.com/guide/photos/use-airdrop-to-share-photos-pht1d4c62349/mac
Other options are:

*

*(if sending to yourself) Use the Photos app with iCloud, where you can just open Photos, sync, and get the live photo on you desktop.

*Copy and send iCloud link - the live photo will be playable from the link sent and it will download a zip containing all photos and videos.

*Save as video (from share menu) and share that


text:
Q: Use of isInternalUSerID for Adapter Based Authentication I am using IBM MobileFirst Studio Plugin 7.0 and was following the tutorials for adapter based authentication here Documentation.
I see that the isInternalUserID is not used to create the userIdentity object unlike the form base authenticator Dcumentation . Can it be used? Or is it specifially so that the code to create the userIDentity needs to be done in the adapter?

A: There are two parts to the answer:
a) When using a custom security test, "isInternalUserID" is used to identify a particular realm as the one that will be used for creating user identity. If a realm is marked with "isInternalUserID" it means that only this realm is used for user identification.
There must be exactly one such realm for every security configuration that is applied to a mobile or web resource.
b) Adapter based authentication allows the flexibility to develop custom authentication logic within a MobileFirst adapter. This is why you see that userIdentity is created and assigned with adapter logic ( unlike the form based sample).
However, you will note that the generated identity is still assigned to the realm , that is marked "isInternalUserId" in the security test.
More details:

*

*Understanding predefined Worklight authentication realms and security tests

*Security Tests

*Implementing adapter-based authenticators


text:
Q: How to return a numpy array as an image using FastAPI? I load an image with img = imageio.imread('hello.jpg').
I want to return this numpy array as an image. I know I can do return FileResponse('hello.jpg'), however, in the future, I will have the pictures as numpy arrays.
How can I return the numpy array img from FastAPI server in a way that it is equivalent to return FileResponse('hello.jpg')?

A: You shouldn't be using StreamingResponse, as suggested by some other answer. If the entire image bytes are loaded into memory from the beginning (e.g., into an in-memory bytes buffer), using StreamingResponse makes little sense. Please have a look at this answer for more details. You should instead use Response and pass the image bytes, after converting the numpy array into a BytesIO buffered stream, as described in the documentation of the Imageio library that you are using—if you instead wish to use PIL or Pillow library (the successor of PIL, which added Python 3.x support), see this answer. You can also define the media_type, as well as set the Content-Disposition header, as described here and here, so that the image is viewed in the browser (if you would like to have the image downloaded rather than viewed in the browser, then use attachment insetad of inline, as described in the linked answers above). Example below:
import io
import imageio
from imageio import v3 as iio
from fastapi import Response

@app.get("/image", response_class=Response)
def get_image():
    im = imageio.imread("test.jpeg") # 'im' could be an in-memory image (numpy array) instead
    with io.BytesIO() as buf:
        iio.imwrite(buf, im, plugin="pillow", format="JPEG")
        im_bytes = buf.getvalue()

    headers = {'Content-Disposition': 'inline; filename="test.jpeg"'}
    return Response(im_bytes, headers=headers, media_type='image/jpeg')

A: You can use StreamingResponse (https://fastapi.tiangolo.com/advanced/custom-response/#using-streamingresponse-with-file-like-objects) to do it e.g., but before you will need to convert your numpy array to the io.BytesIO or io.StringIO


text:
Q: Using rpad function to remote mySQL does not work I tried to execute rpad function to remote mySQL server version 5.7 in a query and it gives an error DB::Exception: Unknown function rpad. Maybe you meant: ['rand']. But executing the same query on mySQL works fine. Appreciate if there is any workaround.

A: It's the expected behavior. CH does not have such function. It can be emulated using length/repeat. CH does not push down this to Mysql because of two reasons 1. CH does not know Mysql SQL syntax, 2 Mysql engine exists to move ALL calculations into CH except basic filtering.
If you still need rpad in mysql you can create a view in mysql and query this view.


text:
Q: System diagram that users can drill down into I am soon going to be creating some system architecture at work.
Like any large system, there are different levels from which you can view the system. Very high, down to the nitty gritty.
I was wondering if there are any tools out there that allow you to create a single document (probably in html) whereby you can start the document with a high-level overview, and then drill down into sections or connections to give you a more detailed view, and then in turn, drill down into those sections in turn and then come back up at will.
I guess what I'm looking for is a simple visio clone for system diagrams, where clicking on the node or connection in a file takes you to a another visio file which is a more detailed view of what you clicked.
I have looked through the questions on SU, and haven't seen anything that can do what I ask without writing up the documentation myself in HTML. Please don't mark this as a duplicate off-the-cuff, though of course I'll gladly look at any suggested duplicates to see if they can do what I ask.
Many thanks.


text:
Q: Python FastAPI: Returned gif image is not animating Below is my Python and Html code:-
Python:
@app.get('/', status_code=200)
async def upload_file(file: UploadFile = File(...)):
     error_img = Image.open('templates/crying.gif')
     byte_io = BytesIO()
     error_img.save(byte_io, 'png')
     byte_io.seek(0)
     return StreamingResponse(byte_io, media_type='image/gif')

HTML:

function goBuster(file) {

    fetch('/', {
        method: 'GET',
        body: data
    })
        .then(response => response.blob())
        .then(image => {
            var outside = URL.createObjectURL(image);
            var mazeimg = document.getElementById("img-maze");
            mazeimg.onload = () => {
                URL.revokeObjectURL(mazeimg.src);
            }
            mazeimg.setAttribute('src', outside);
            mazeimg.setAttribute('style', 'display:inline-block');

        })
}

The image is not animating, I checked the generated html and found:

So the img src is using blob, I guess this is the reason why the gif is not animating, but I have no idea how to fix it.
Update 1
Now I have updated my code to:
      with open('templates/crying.gif', 'rb') as f:
        img_raw = f.read()
        byte_io = BytesIO()
        byte_io.write(img_raw)
        byte_io.seek(0)
        return StreamingResponse(byte_io, media_type='image/gif')

The generated HTML looks same:

but it gets worse, the image is not even showing up.

A: error_img.save(byte_io, 'png')

You're converting this image to png. PNG doesn't support animation.
I think you can use:
@app.get('/', status_code=200)
async def upload_file(file: UploadFile = File(...)):
     with open('templates/crying.gif', 'rb') as f:
         img_raw = f.read()
     byte_io = BytesIO(img_raw)
     return StreamingResponse(byte_io, media_type='image/gif')

A: (Posted solution on behalf of the question author, in order to post it in the answer space).
I fixed the problem by:

*

*using the code provided by @VadSim,

*change wb to rb
Notice: if you ran the program and then changed wb to rb, the code would have destroyed the original gif image to be a 0 bytes image. This is why it was not working at first.
Now, I have the gif working in html :)


text:
Q: Problems with instantiating of HttpServletRequest with Mockito The following line fails with an exception:
HttpServletRequest req = mock(HttpServletRequest.class);

Exception:
java.lang.ClassFormatError: Absent Code attribute in method
that is not native or abstract in class file
javax/servlet/http/Cookie

Has anyone faced this problem?
UPD
Solution was found here.

A: You should add implementation of Servlet API to your test/runtime classpath. I would suggest to use this dependency:
<dependency>
  <groupId>org.glassfish</groupId>
  <artifactId>javax.servlet</artifactId>
  <version>3.0</version>
  <scope>test</scope>
</dependency>


text:
Q: C#: Why is this code populating this listView out of order? Can anyone see where I am going wrong here? Code is supposed to open an xml document, then based on the contents of each node, populate the columns of a ListView with the innertext of each node/attribute. The List view should look like this:
Item1   Item2   Item3
Item4   Item5   Item6
Item7   Item8   Item9

However its ending up like this:
Item7 Item2 Item5
Item4
Item1

The code producing this error is as follows:
private void openPasswordFileToolStripMenuItem_Click(object sender, EventArgs e)
    {
        System.Xml.XmlDocument loadDoc = new System.Xml.XmlDocument();
        loadDoc.Load(Application.StartupPath + "\\database.xml");

        foreach (System.Xml.XmlNode descNode in loadDoc.SelectNodes("/Database/Account"))
        {
            lvItem = listView1.Items.Insert(index, descNode.Attributes["Description"].InnerText); ;
        }
        foreach (System.Xml.XmlNode userNode in loadDoc.SelectNodes("/Database/Account"))
        {
            lvItem.SubItems.Add(new ListViewItem.ListViewSubItem(lvItem, userNode.Attributes["Username"].InnerText)); ;
        }
        foreach (System.Xml.XmlNode passNode in loadDoc.SelectNodes("/Database/Account"))
        {
            lvItem.SubItems.Add(new ListViewItem.ListViewSubItem(lvItem, passNode.Attributes["Password"].InnerText)); ;
        }
        foreach(System.Xml.XmlNode node in loadDoc)
        {
            index += 1;
        }
    }

A: Not sure about the structure of the xml doc, but your foreach code is wrong.
If you are trying to add sub items for each parent then
    foreach (System.Xml.XmlNode descNode in loadDoc.SelectNodes("/Database/Account"))
    {
        lvItem = listView1.Items.Insert(index, descNode.Attributes["Description"].InnerText); ;
        lvItem.SubItems.Add(new ListViewItem.ListViewSubItem(lvItem, userNode.Attributes["Username"].InnerText)); ;
        lvItem.SubItems.Add(new ListViewItem.ListViewSubItem(lvItem, passNode.Attributes["Password"].InnerText)); ;
    }


text:
Q: Java user control desktop application I am developing a user control desktop application for windows 8.1 using Java with netbeans
I want the app to lock the desktop by itself after 30minute time out
You can only use the computer unless you have entered your user name and password into the application
The app should take a complete control over the desktop, without entering username and password into the app you can't use the destop
I need guidelines and the classes and methods I will need to archive this task. I am a beginner in Java language

A: You can solve this problem in the following steps:
1- Search the internet about .DLL files for locking and unlocking your windows Desktop.
2- .DLL files are written in C or C++ language.
3- You can invoke the .DLL file if and only if the java method from where you're invoking is declared as native(Also search the internet for this)
4- You must use the concept of multithreading(Sleep Timer like things) on the internet.
5- Because a sleep timer in java let you lock your desktop after some seconds or minutes and you can unlock your keyword by typing correct username and password into the fields.
6- Also search the internet about username authentication code in java.


text:
Q: B2C- Add button for changing email in custom policy I used this documentation to split email verification and sign up for my sign up process.
I found in other questions that to skip the email changing step, just hide the email change button. My need is to create a button in the 4th step to allow to change the email.
Is there a way to give the same behavior to the button created with JS as the one hidden in the previous step please?
PS : I tried to give it the same id and class name to the js button but it didn't work.

A: If you make the email field in 4th step not read only, and apply email.verified as the partnerClaimType (like default starter pack), it will force email verification if it's changed on that page to anything other than what was pre populated.


text:
Q: rpmbuild - how to disable check-buildroot? I'm doing some hackery with rpmbuild, and am really just leveraging rpm spec files, rpmbuild, and rpm packages to give users self-service of packages that are patched to work in an extremely locked down, specialized environment.
Everything works great until I need to build with cmake and set the prefix (along with a few other things to make the package work in said environment). Rpmbuild must be finding rpath'd binaries or something that include the $BUILDROOT in the path. I'm totally fine with this, and want to turn that check off. The error below is the type of error I'm getting, and I can't find any way to turn this check off from googling. Any ideas?
/usr/lib/rpm/check-buildroot
/var/tmp/libgssapi-0.11-root/usr/lib64/pkgconfig/libgssapi.pc:prefix=/var/tmp/libgssapi-0.11-root
Found '/var/tmp/libgssapi-0.11-root' in installed files; aborting
error: Bad exit status from /var/tmp/rpm-tmp.75914 (%install)
Thanks!

A: If you want to go crazy, you can turn off a lot of things by specifying the following:
# no debug infos with:
%global debug_package %{nil}

# disable check-buildroot (normally /usr/lib/rpm/check-buildroot) with:
%define __arch_install_post %{nil}

%define __os_install_post %{nil}

# disable automatic dependency and provides generation with:
%define __find_provides %{nil}
%define __find_requires %{nil}
%define _use_internal_dependency_generator 0
Autoprov: 0
Autoreq: 0

Hopefully this helps...


text:
Q: Debug mex code using visual studio Hi I have written a mex file and I would like to debug it using visual studio 2010. I followed steps mentioned in Mathwork website :
http://www.mathworks.com/help/matlab/matlab_external/debugging-on-microsoft-windows-platforms.html
I have also read following posts:
how to debug MATLAB .mex32/.mex64 files with Visual Studio 2010
I should mention that I can compile mex with -g code successfully but when I insert the breakpoint it says: the breakpoint cannot be currently hit. No symbols have been loaded for this document.
Then when I run the mex code from Matlab, it does not create any break point and it does not do the debugging.
According to the following :
Fixing "The breakpoint will not currently be hit. No symbols have been loaded for this document."
When I go to debug--> windows--> module--> next to matlab says cannot find or open the PDB file.  I do not understand what he means when he says
" In normal projects, the assembly and its .pdb file should always have been copied by the IDE into the same folder as your .exe. The bin\Debug folder of your project. Make sure you remove one from the GAC if you've been playing with it."
my Matlab is located in C:\Program Files\MATLAB\R2012a
 and the mex and pdb file is in C:\Documents\Matlab file but I copied the pdb file (I do not know it is necessary or not) to Matlab workspace. The Matlab current folder that code is running is also C:\Documents\Matlab.
Can anyone please help me to solve this problem.
Can anyone please hel me to solve this problem?


text:
Q: Georeferencing PNG image by GDAL in QGIS I am not familiar with GDAL so far. Thereby I don't know how to start. By knowing the problem from the question below:
Georeferencing PNG image in QGIS when the coordinates of image corners are known
I would like to georeference the image by using the GDAL library. I don't want to play with .pgw files, because they are don't accurate enough I am afraid. Therefore I decided to use the GDAL option only for this purpose.
I found similar problem here:
Georeferencing using GDAL?
but it didn't work for me
I found something better, which calls the GDAL library by Python code in pyQGIS
How to call gdal_translate from Python code?
and after applying the following code:
 from osgeo import gdal

 ds = gdal.Open('C:\my\Desktop current\Hey\cloakpN50E021.png')
 ds = gdal.Translate('C:\my\Desktop current\Hey\cloakpN50E021.tiff', ds, projWin = [-75.3,
 5.5, -73.5, 3.7])
 ds = None

I have only the following command:
>>>exec(open('C:/Users/k/AppData/Local/Temp/tmpxoz9p370.py'.encode('utf-8')).read())
which means, that the code is executed properly, but unfortunately I can see neither file transformed to .tiff nor the layer produced in QGIS.
What is missing here? Is it a chance to georeference the .png image this way?
I tried also the other method, by using the code below:
 gdal_translate --config GDAL_PDF_BANDS 4 --config GDAL_CACHEMAX 1024 -
 co NUM_THREADS=ALL_CPUS -co COMPRESS=DEFLATE -co ZLEVEL=9 -co
 PREDICTOR=2 -co TILED=YES -a_srs EPSG:31255 -a_ullr 9623.23 326346.38
 9933.23 326090.63 C:\my\GDAL\cloakpN50E021.png
 C:\my\GDAL\cloakpN50E021.tif

but i got the bunch of errors like this:
ERROR 1: PredictorSetup:Horizontal differencing "Predictor" not supported with 2-bit samples


text:
Q: Change the ACL for already uploaded object to firebase storage We have many objects in Firebase storage, which are already uploaded by an Android device with private ACL.
Is there any possibility that through firebase js SDK we can change the ACL from a web application? I have gone through all available resources but I don't see any valid option for doing this.

A: Short answer is No.
I actually don't think that those objects have private ACL. Project private I guess is the right term. Objects uploaded through Firebase SDKs inherit the default acls that was automatically added during firebase project creation.
Changing ACLs of a particular object can only be manipulated through cloud console or GCS libraries. If you have tons of objects that needs to be updated, using gsutil would be your best option.


text:
Q: How DotNetOpenAuth works I am just getting started using DotNetOpenAuth with an MVC app and I am having it a bit difficult understanding how it actually works.
As far as I understand, DotNetOpenAuth will take care of authenticating a user with Google/Twitter/Facebook (probably after some modification).
What happens afterwards? Is the user authenticated per request? Is the user information saved in a session using IPrincipal, IIdentity? How does it fit together with an MVC application which will store all user information in the application database (custom tables and not the default .NET membership provider ones)?
Also, if you know any good tutorials, documentation on the subject, please share this as well.
Thanks!

A: DotNetOpenAuth only deals with the authentication step -- how you decide to store and recall that authentication ticket is up to you. It is very common to use FormsAuthentication to log the user in:
FormsAuthentication.RedirectFromLoginPage(authResponse.ClaimedIdentifier);

Using this approach, a cookie is sent to the browser and comes in with every request -- just like if you had used the older username/password approach.
You can download a bunch of samples from SourceForge.


text:
Q: Color mismatch between legend and scatter plot elements I am unable to use the same colors in legend as coming from my cycled data. 'alldata' has a size 569x30 so defining that many colors is not feasible
for labels in ['benign', 'malignant']:
       scatter = plt.scatter(svd_pca_eqvt[:,0],svd_pca_eqvt[:,1],label=labels, c=alldata['target'])
plt.legend()

enter image description here

A: You can add the colors in the for loop instead like the following:
for labels, color in zip (['benign', 'malignant'], ['#FECB52','#7E1E9C']):
       scatter = plt.scatter(svd_pca_eqvt[:,0],svd_pca_eqvt[:,1],label=labels, c=color)
plt.legend()

#FECB52 --> yellow
#7E1E9C --> Dark Purple


text:
Q: Is there a way to turn off all Google Cast logging? I've set:

GCKLogger.sharedInstance().loggingEnabled = false

But I still see this printed out every time a Google Cast button appears on the page. It really pollutes my output log and is annoying (This is in GoogleCast framework version 3.5.0 / cast.ios.sdk_20170313.00_RC49):
> 2017-05-29 16:34:04.250 appName[22378:1706584] Logging 10, currently
> detected {(
>     1,
>     5 )}


text:
Q: Finite Element NDSolve with input data at node points I am trying to solve a steady-state advection-diffusion problem of the following form:
$-D \nabla^2 T + \nabla \cdot (\mathbf{u} T) = -1$. I will be solving this problem in a 3D geometry (typically the surface of revolution). However, here I am phrasing the question for a disk.
The velocity field $\mathbf{u}$ is precomputed numerically from a different simulation (using an integral equation). I can compute the velocity at any given node point of the finite element mesh (with spectral accuracy). Is there any way to input $\mathbf{u}$  computed at all the mesh points (as a list) to NDSolve?
Adding more details (code)
\[CapitalOmega] = Ellipsoid[{0, 0, 0}, {5, 5, 5}];
mesh = #1 -> #2 &~
    MapThread~{{"Coordinates", "MeshElements", "BoundaryElements",
      "PointElements"},
     ToExpression@Import["mesh_sphere_rad=5.txt"]} //
   ToElementMesh @@ # &;
Dimensions[mesh["Coordinates"]]

velocity = Import["nodevel3D.txt", "Table"];
ux = ElementMeshInterpolation[{mesh}, velocity[[All, 1]]];
uy = ElementMeshInterpolation[{mesh}, velocity[[All, 2]]];
uz = ElementMeshInterpolation[{mesh}, velocity[[All, 3]]];

\[CapitalDelta][f_] :=
  D[f, {x, 2}] + D[f, {y, 2}] + D[f, {z, 2}]; (* Define Laplacian *)
source = -1; bval = 0; nval = 0;
Pe = 50; (* Define Peclet Number *)
sol =
 NDSolveValue[{\[CapitalDelta][T[x, y, z]] +
     Pe (ux[x, y, z] D[T[x, y, z], x] +
        uy[x, y, z] D[T[x, y, z], y] +
        uz[x, y, z] D[T[x, y, z], z]) ==
    source + NeumannValue[nval, \[CapitalGamma]N],
   DirichletCondition[T[x, y, z] == bval, \[CapitalGamma]D]},
  T, {x, y, z} \[Element] \[CapitalOmega], AccuracyGoal -> 10,
  Method -> {"FiniteElement",
    "MeshOptions" -> {"MaxCellMeasure" -> 0.005,
      "MeshQualityGoal" -> 1}}]

I notice that if I put {x,y,z} \[Element] mesh then their is no error thrown at me. However, if I use {x, y, z} \[Element] \[CapitalOmega] (the region on which I constructed my mesh for interpolating velocity at the first place) it says: ```InterpolatingFunction::femdmval: Input value {2.77554,3.67892,-1.91818} lies outside the range of data in the interpolating function.''' However the final solution from both these cases look almost identical. So I guess this is okay. But it will be good to know why this is happening. Thanks!

A: The NDSolve when used with the finite element method never evaluates at node (mesh coordinate) points it always evaluates functions between these nodes at integration points.
The way to go about your data is to create an interpolating function with values from your function on the mesh nodes.
Needs["NDSolve`FEM`"]
mesh = ToElementMesh[Disk[]];
values = Sqrt[Total[mesh["Coordinates"]^2, {2}]];
if = ElementMeshInterpolation[mesh, values]

When given to the FEM, that interpolating function if will not be evaluated at the nodes, only at the integration points. Using an interpolating function that is based on the same mesh as the FEM mesh will be reasonably fast.
One other (slower) approach would be to take the mesh, find the integration points, (like shown in the other post), evaluate your function at the integration points, create a new Delaunay mesh of the integration points and use that for the interpolating function. This will be a bit slower, but then you'd get the evaluation at the integration points use your values.
One thing to keep in mind is that FEM is a machine precision numeric method; I am not sure how much it is going to help if your integration values are supper accurate compared to the accuracy of the FEM.
For your specific problem look at the examples in the heat transfer PDE models section. Specifically, the Thermal Decomposition model has a squential PDE solution; the the solution of the Navier-Stokes equation is returned as set of interpolating functions that are an input to the convection term in the heat equation.


text:
Q: Wine logo appearing for every Crossover Application in Unity If I start an application using Crossover (or Wine), the application will always be the Wine Logo instead of the application logo. This is the same independent of the application being run or using Wine instead of Crossover.
That makes sense if the application has no logo, but it gets confusing running multiple Microsoft Office programs - and all of them have the same logo.
The hint text for the icon is also "Wine Windows Program Loader" instead of "Document 1 - Microsoft Word" as it should be.
Is there a way to configure Wine/Crossover to use application icons and title text? I am using the Faenza Icon Set.
EDIT: I have confirmed that this issue does NOT occur in Gnome Classic.

A: In this question you find a workaround
Change Icon of Wine Application in Unity Launcher
Take a look at the answer from MHC
You need to add the following line into your .desktop-file

StartupWMClass=application.exe

(application.exe is the name of your EXE-file, it's case sensitive)