text:
Q: How to use GridBagConstraints to create the layout? I want to layout my JPane like so:
-------
|     |
|     |
|     |
-------
|     |
-------

This way, the top section is bigger/taller than the bottom section (the top section consists of another JPanel and uses the Graphics object to display an image, while the bottom section also consists of another JPanel but uses the Graphics object to draw some lines and text).
I've heard that the best way to do this was using the GridBagLayout and GridBagConstraints.
I'm trying to figure out the appropriate properties for the GridBagConstraints, and I'm having some difficulties. This is what I have so far...
For the top part, I have:
gridx = 0
gridy = 0
weighty = 1.0; // expand downwards, because the bottom should never expand in the Y direction
fill = GridBagConstraints.BOTH

For the bottom part, I have:
gridx = 0
gridy = 1
fill = GridBagConstraints.HORIZONTAL
anchor = GridBagConstraints.PAGE_END

Unfortunately, all the ends up happening is a large gray rectangle appears (I have a white background for the application) - no images load, no lines/text appear.
What should I do? What should I adjust?
I've read a few tutorials, but it just seems really confusing, I got it working in my first application, but now when I try to do this it just doesn't seem to work for me.

A: In general, for gridbag layout

*

*if you want a component scale, you must give its scale direction a weight, and any sizes (width/height) you set for that direction will be ignored by the layout manager.

*If you don't want a component scale, the component must have its size defined (if you want, you can dig into this topic in documents of java). In your case of the bottom panel, you need to give its, at least, a preferred height.
This can work as your expectation
pnlTop.setBackground(Color.WHITE);
pnlBottom.setBackground(Color.BLUE);

// Because you don't want the bottom panel scale, you need to give it a height.
// Because you want the bottom panel scale x, you can give it any width as the
// layout manager will ignore it.
pnlBottom.setPreferredSize(new Dimension(1, 20));

getContentPane().setLayout(new GridBagLayout());
GridBagConstraints cst = new GridBagConstraints();
cst.fill = GridBagConstraints.BOTH;
cst.gridx = 0;
cst.gridy = 0;
cst.weightx = 1.0; // --> You miss this for the top panel
cst.weighty = 1.0;
getContentPane().add(pnlTop, cst);

cst = new GridBagConstraints();
cst.fill = GridBagConstraints.HORIZONTAL;
cst.gridx = 0;
cst.gridy = 1;
cst.weightx = 1.0; // You miss this for the bottom panel
cst.weighty = 0.0;
getContentPane().add(pnlBottom, cst);

Further more, if you want to use gridbag layout, I recommend you to try the painless-gridbag library http://code.google.com/p/painless-gridbag/ (I'm the author of that library). It doesn't solve this problem for you (as your problem concerns managing component's size in gridbag layout) but it will save you a lot of typing and make your code easier to maintain
pnlBottom.setPreferredSize(new Dimension(1, 20));

PainlessGridBag gbl = new PainlessGridBag(getContentPane(), false);
gbl.row().cell(pnlTop).fillXY();
gbl.row().cell(pnlBottom).fillX();
gbl.done();

A: not sure from your question, maybe will help you Top at 70%, Bottom at 30%
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

public class BorderPanels extends JFrame {

    private static final long serialVersionUID = 1L;

    public BorderPanels() {
        getContentPane().setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        JPanel panel1 = new JPanel();
        Border eBorder = BorderFactory.createEtchedBorder();
        panel1.setBorder(BorderFactory.createTitledBorder(eBorder, "70pct"));
        gbc.gridx = gbc.gridy = 0;
        gbc.gridwidth = gbc.gridheight = 1;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.anchor = GridBagConstraints.NORTHWEST;
        gbc.weightx = gbc.weighty = 70;
        getContentPane().add(panel1, gbc);
        JPanel panel2 = new JPanel();
        panel2.setBorder(BorderFactory.createTitledBorder(eBorder, "30pct"));
        gbc.gridy = 1;
        gbc.weightx = 30;
        gbc.weighty = 30;
        gbc.insets = new Insets(2, 2, 2, 2);
        getContentPane().add(panel2, gbc);
        pack();
    }

    public static void main(String[] args) {
        new BorderPanels().setVisible(true);
    }
}

A: If you may use 3th party libs, you may consider the FormLayout as well. It allows you to specify the height of each row, and the resize behavior.
I did not test this but
FormLayout layout = new FormLayout(
 "pref", //columns
 "50dlu:grow(0.2)","25dlu:grow(0.1)" //rows
);

might do the trick. More information on the syntax can be found in the JGoodies Forms pdf


text:
Q: Editable List with checkbox I want to create a editable list with checkboxes for creating todo (just like checkboxes in Google Keep). Is there a control to achieve this ?
Edit: See the Image of Google Keep List.

A: There is no editable Checkbox provided by android what you can do is set listeners on your checkboxes, and then have to capture the events like when checkbox is checked and when is it unchecked to make your editexts work the way you want.A sample way to start is :
CheckBox someCheckBox= (CheckBox) findViewById (R.id.someID);
someCheckBox.setOnClickListener(new OnClickListener() {

  @Override
  public void onClick(View v) {
    if (((CheckBox) v).isChecked()) {
            //CODE TO MAKE THE EDITTEXT ENABLED
    }
    else
       //CODE TO MAKE THE EDITTEXT DISABLED

  }
});

However there are other ways too,to achieve this task, but you can kick off with this right away. Hope it helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error when running Glue studio job. (InvalidInputException:Invalid S3 resource) I am new to AWS glue. I have uploaded my csv to an S3 bucket and crawled into a Data Catalog database table. Looking fine with AWS Athena.
I then tried to start a glue studio job to remap the key. However it gives me an error I couldn't find the solution. The IAM role I used for the glue job has access to the S3 bucket. No idea about Lake Formation, I tried everything in LF to enable access (with the LF-tag, S3 location registration." No idea what's going on. Could someone shed some light? Thanks!
npy4j.protocol.Py4JJavaError: An error occurred while calling o93.getDynamicFrame.\n: java.lang.RuntimeException: class com.amazonaws.services.gluejobexecutor.model.InvalidInputException:Invalid S3 resource (Service: AWSLakeFormation; Status Code: 400; Error Code: InvalidInputException; Request ID: 208fb8b8-62d9-4ebb-9107-bd4b3b6e8119; Proxy: null) (Service: AWSGlueJobExecutor; Status Code: 400; Error Code: InvalidInputException; Request ID: 0685c719-d128-4596-87db-def2d5837a14; Proxy: null)

Error log:
2022-10-24 15:20:58,739 ERROR [main] glueexceptionanalysis.GlueExceptionAnalysisListener (Logging.scala:logError(9)): [Glue Exception Analysis] {
"Event": "GlueETLJobExceptionEvent",
"Timestamp": 1666624858735,
"Failure Reason": "Traceback (most recent call last):\n  File \"/tmp/shipping_remap_1_yxd.py\", line 19, in <module>\n    transformation_ctx=\"AmazonS3_node1666619146221\",\n  File \"/opt/amazon/lib/python3.6/site-packages/awsglue/dynamicframe.py\", line 629, in from_catalog\n    return self._glue_context.create_dynamic_frame_from_catalog(db, table_name, redshift_tmp_dir, transformation_ctx, push_down_predicate, additional_options, catalog_id, **kwargs)\n  File \"/opt/amazon/lib/python3.6/site-packages/awsglue/context.py\", line 188, in create_dynamic_frame_from_catalog\n    return source.getFrame(**kwargs)\n  File \"/opt/amazon/lib/python3.6/site-packages/awsglue/data_source.py\", line 36, in getFrame\n    jframe = self._jsource.getDynamicFrame()\n  File \"/opt/amazon/spark/python/lib/py4j-0.10.9-src.zip/py4j/java_gateway.py\", line 1305, in __call__\n    answer, self.gateway_client, self.target_id, self.name)\n  File \"/opt/amazon/spark/python/lib/pyspark.zip/pyspark/sql/utils.py\", line 111, in deco\n    return f(*a, **kw)\n  File \"/opt/amazon/spark/python/lib/py4j-0.10.9-src.zip/py4j/protocol.py\", line 328, in get_return_value\n    format(target_id, \".\", name), value)\npy4j.protocol.Py4JJavaError: An error occurred while calling o93.getDynamicFrame.\n: java.lang.RuntimeException: class com.amazonaws.services.gluejobexecutor.model.InvalidInputException:Invalid S3 resource (Service: AWSLakeFormation; Status Code: 400; Error Code: InvalidInputException; Request ID: 208fb8b8-62d9-4ebb-9107-bd4b3b6e8119; Proxy: null) (Service: AWSGlueJobExecutor; Status Code: 400; Error Code: InvalidInputException; Request ID: 0685c719-d128-4596-87db-def2d5837a14; Proxy: null)\n\tat com.amazonaws.services.glue.remote.LakeformationCredentialsProvider.refresh(LakeformationCredentialsProvider.scala:50)\n\tat com.amazonaws.services.glue.remote.LakeformationCredentialsProvider.<init>(LakeformationCredentialsProvider.scala:77)\n\tat sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)\n\tat sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)\n\tat sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)\n\tat java.lang.reflect.Constructor.newInstance(Constructor.java:423)\n\tat com.amazonaws.services.glue.remote.MichiganAWSCredentialProviderProxy$.get(MichiganAWSCredentialProviderProxy.scala:14)\n\tat com.amazonaws.services.glue.util.FileSchemeWrapper.setHadoopConfiguration(FileSchemeWrapper.scala:43)\n\tat com.amazonaws.services.glue.util.FileSchemeWrapper.executeWith(FileSchemeWrapper.scala:82)\n\tat com.amazonaws.services.glue.util.FileSchemeWrapper.executeWithQualifiedScheme(FileSchemeWrapper.scala:90)\n\tat com.amazonaws.services.glue.HadoopDataSource.getDynamicFrame(DataSource.scala:556)\n\tat com.amazonaws.services.glue.DataSource.getDynamicFrame(DataSource.scala:101)\n\tat com.amazonaws.services.glue.DataSource.getDynamicFrame$(DataSource.scala:101)\n\tat com.amazonaws.services.glue.HadoopDataSource.getDynamicFrame(DataSource.scala:246)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.invoke(Method.java:498)\n\tat py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)\n\tat py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)\n\tat py4j.Gateway.invoke(Gateway.java:282)\n\tat py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)\n\tat py4j.commands.CallCommand.execute(CallCommand.java:79)\n\tat py4j.GatewayConnection.run(GatewayConnection.java:238)\n\tat java.lang.Thread.run(Thread.java:750)\n",
"Stack Trace": [
    {
        "Declaring Class": "get_return_value",
        "Method Name": "format(target_id, \".\", name), value)",
        "File Name": "/opt/amazon/spark/python/lib/py4j-0.10.9-src.zip/py4j/protocol.py",
        "Line Number": 328
    },
    {
        "Declaring Class": "deco",
        "Method Name": "return f(*a, **kw)",
        "File Name": "/opt/amazon/spark/python/lib/pyspark.zip/pyspark/sql/utils.py",
        "Line Number": 111
    },
    {
        "Declaring Class": "__call__",
        "Method Name": "answer, self.gateway_client, self.target_id, self.name)",
        "File Name": "/opt/amazon/spark/python/lib/py4j-0.10.9-src.zip/py4j/java_gateway.py",
        "Line Number": 1305
    },
    {
        "Declaring Class": "getFrame",
        "Method Name": "jframe = self._jsource.getDynamicFrame()",
        "File Name": "/opt/amazon/lib/python3.6/site-packages/awsglue/data_source.py",
        "Line Number": 36
    },
    {
        "Declaring Class": "create_dynamic_frame_from_catalog",
        "Method Name": "return source.getFrame(**kwargs)",
        "File Name": "/opt/amazon/lib/python3.6/site-packages/awsglue/context.py",
        "Line Number": 188
    },
    {
        "Declaring Class": "from_catalog",
        "Method Name": "return self._glue_context.create_dynamic_frame_from_catalog(db, table_name, redshift_tmp_dir, transformation_ctx, push_down_predicate, additional_options, catalog_id, **kwargs)",
        "File Name": "/opt/amazon/lib/python3.6/site-packages/awsglue/dynamicframe.py",
        "Line Number": 629
    },
    {
        "Declaring Class": "<module>",
        "Method Name": "transformation_ctx=\"AmazonS3_node1666619146221\",",
        "File Name": "/tmp/shipping_remap_1_yxd.py",
        "Line Number": 19
    }
],
"Last Executed Line number": 19,
"script": "shipping_remap_1_yxd.py"

}


text:
Q: PHP with azure database I am trying to make connection between azure database and php. I come to know that i need to install sqlsrv driver on server.
Is it possible to install sqlsrv driver on linux/ubuntu.Please give your support.
Is there any alternate method to make connection between azure db and php on linux.?
Regards

A: a great article :

he SQL Server Driver for PHP allows
  PHP developers to access SQL Server
  databases that are hosted on SQL
  Server or SQL Azure. The SQL Server
  Driver for PHP relies on the Microsoft
  SQL Server ODBC Driver to handle
  low-level communication with SQL
  Server. As a result, the SQL Server
  Driver for PHP is only supported on
  Windows and Windows Azure. It can be
  downloaded and installed as a PHP
  extension

A: Another approach would be to use OData to access your SQL Azure (or Azure Table Storage) data from PHP.  Not sure what the perf differences would be, but you'd be able to avoid installing the database driver on your LAMP box.
http://odataphp.codeplex.com/


text:
Q: Why is my Telegram bot not responding to its name? The /commands work fine when chatting with the bot. However the bot does not respond in my channel.
pip install pyTelegramBotAPI
import telebot

bot = telebot.TeleBot(bottoken)

@bot.message_handler(commands=['start'])
def send_welcome(message):
    bot.reply_to(message, "Hello World")

@bot.message_handler(commands=['help'])
def send_welcome(message):
    bot.reply_to(message, "Need Help?")

bot.infinity_polling()

Typing @botname doesn't trigger the bot in the channel. Is there a piece of code missing or a setting that needs to be on?


text:
Q: Correction of systematic multiplicative confounder effect Dear community members,
I have a very simple question. I have thousands of independent large samples (>1000 data points each) from complex 1D distributions. To imagine the problem better, I describe it as thousands of blood pressure studies, performed in different hospitals with different cohorts of people, and the sphygmomanometers used in different hospitals introduce multiplicative constant (within one hospital) bias to measures. So the shape of these distributions is exactly the same, but the "scale" is different.
What would be the best way to normalize this data to one scale? The data is unpaired, so I can not just make a linear model to estimate the slope. I can not also use mean or median for comparisons - the distributions are complex and multi-modal, and mean/median become quite unstable so large sample size of each cohort does not actually help enough.
I can proceed with mixture of Normals fitting, but the distributions are not exactly normals, so it may lead to inaccurate normalization.
A simple example (in R) is (in reality the mixture contains up to 10 different components and some of them are quite extreme "outliers") - due to random sampling number of samples in small "extreme" components is different. Some small extreme components may be not even sampled in a particular set due to chance. Also the methods of robust statistics are inapplicable since the number of "outliers" is >50% since it is a mixture. Comparing many density quantiles should work fine on average, but I do not know how to do it.
bias = 1.5
distrib1 <- c(rnorm(990, mean=1), rnorm(10, mean=10));
distrib2 <- c(bias * rnorm(980, mean=1), bias * rnorm(20, mean=10));
plot(density(scale(distrib1),bw="SJ"));
lines(density(scale(distrib2),bw="SJ"), col="red")

One may say that the difference is not so crucial here - in my opinion the small right cluster is very different after such normalization. Also variance of the "big" component is different after z-scoring.


text:
Q: Decimal parameter error in Execute SQL TASK in SSIS 2014 I am working on SSIS 2014. I need to pass a decimal parameter in SQL Execute task in SSIS. Getting the below error:

[Execute SQL Task] Error: Executing the query  failed with the following error: "The type is not supported.DBTYPE_DECIMAL".

I tried searching online but couldn't get the solution. Did anyone have this type of issue. I cannot change the datatype of the parameter it should be decimal only.


text:
Q: git-lfs command not found webstorm I use WebStorm and after adding git-lfs I started to get this error

Error updating changes: git-lfs filter-process: git-lfs: command not found the remote end hung up unexpectedly

It prevents git updates. Lfs is working fine in every terminal.

A: I had the same problem with IntelliJ. In my case, I could not solve my problem via the confirmed answer.
However, I have no error opening the IDE from the terminal
https://stackoverflow.com/a/7836740/3202266
https://intellij-support.jetbrains.com/hc/en-us/articles/360011901879-How-to-start-IDE-from-the-command-line

A: Looks like git-lfs is not on your $PATH when running the IDE from Finder, etc.
On MacOSX the environment variables differ between GUI applications and within the terminal. Terminal environment is only available to applications started from terminal. To solve this problem, WebStorm tries to load terminal environment by executing the following command on startup:
 -l -i -c '/Applications/webstorm.app/bin/printenv.py'
Seems this command can't retrieve all needed stuff in your case - thus the issue.
Some links you may find useful: http://apple.stackexchange.com/questions/106355/setting-the-system-wide-path-environment-variable-in-mavericks, http://apple.stackexchange.com/questions/51677/how-to-set-path-for-finder-launched-applications.. The problem is that the way to define system-wide environment variables on Mac changes from one version to another (even minor system updates may break your environment)

A: For me (Mac M1), quitting and restarting PyCharm completely (not only a single Project) fixed the problem.


text:
Q: Find the average and total revenue by each sub-category for the categories which are among top 5 categories in terms of quantity sold?  For this question, I have two tables and are as follows :

*

*prod_cat_info --- This table has the following columns:

*

*prod_cat : It contains the products' category names

*prod_cat_id : It contains the products' category ID. Note that every product category has been assigned a unique ID. For example :: Lets say I have following product categories Books,Sports,Electronics. So these 3 product categories will be assigned product category ID as 1,2 & 3 respectively.

*prod_subcat : It contains products' subcategories

*prod_subcat_id : It contains products' subcategories ID

Now how this product subcategories are stored. For example : Lets say for product category "Books", I have 3 product subcategories like "Novels", "Schoolbooks" & "Fiction". So in this case also, each and every product subcategory would be assigned an ID like 1,2,3 and so on.

*

*Transactions --- This is another table which has the following columns :

*

*total_amt : It contains amount paid by customer when a transaction took place.

*Qty : It contains quantities ordered by customer of a particular product.

*prod_subcat_id : It contains products' subcategories ID

*prod_cat_id : It contains the products' category ID.

*Cust_ID : It contains customer ID [Irrelevant column in case of this question]

What I did is, I break this question into 2 parts & wrote 2 separate queries. Query is given below. I am not able to figure out how to join these 2 queries in order to achieve the output.
For my query1 - I have fetched all the product subcategories.
In query2 - I have fetched the top 5 product categories based on quantities sold.
Now I feel that Query2 can be used as a subquery in Query1 inside WHERE clause.
But It may require some modifications because what I know is that orderby can't be used in subquery & also result of a subquery will be a single output.
Therefore, I need some help on how can I combine/modify this query in order to achieve the result.
**Query1**
select P.prod_subcat as Product_SubCategory,
AVG(cast(total_amt as float)) as Average_Revenue,
SUM(cast(total_amt as float)) as Total_Revenue
from Transactions as T
INNER JOIN prod_Cat_info as P
ON T.prod_cat_code = P.prod_cat_code AND T.prod_subcat_code =
P.prod_sub_cat_code
group by P.prod_subcat

**Query2**
select top 5 P.prod_cat, sum(Cast(Qty as int)) AS Quantities_sold from
prod_cat_info as P
inner join Transactions as T
ON P.prod_cat_code = T.prod_cat_code AND P.prod_sub_cat_code =
T.prod_subcat_code
group by P.prod_cat
order by sum(Cast(Qty as int)) desc

A: If you have a TOP operator with ORDER BY, which is exactly your case, then you can use order by in a subquery. Because in this case the ORDER BY is used to determine the rows returned by the TOP clause.
And for multiple values you can use IN operator
select P.prod_subcat as Product_SubCategory,
AVG(cast(total_amt as float)) as Average_Revenue,
SUM(cast(total_amt as float)) as Total_Revenue
from Transactions as T
INNER JOIN prod_Cat_info as P
ON T.prod_cat_code = P.prod_cat_code AND T.prod_subcat_code =
P.prod_sub_cat_code
WHERE P.prod_cat_code IN (
select top 5 P.prod_cat_code
from prod_cat_info as P
inner join Transactions as T
ON P.prod_cat_code = T.prod_cat_code AND P.prod_sub_cat_code =
T.prod_subcat_code
group by P.prod_cat
order by sum(Cast(Qty as int)) desc
)
group by P.prod_subcat

A: Select prod_cat, prod_subcat , avg(total_amt) as average_amount , sum(total_amt) as total_amount
From transactions as t
inner join prod_cat_info as p
on t.prod_subcat_code=p.prod_sub_cat_code and t.prod_cat_code = p.prod_cat_code
Where prod_cat in
(Select Top 5 prod_cat
From transactions as t
inner join prod_cat_info as p
on t.prod_subcat_code=p.prod_sub_cat_code and t.prod_cat_code = p.prod_cat_code
Where total_amt > 0  and qty > 0
Group by prod_cat
Order by  count(qty) desc)
Group by prod_subcat
Order by prod_cat asc;


text:
Q: Interactive Shell on website in django I have a Django project up and running. I'd like to provide a user to interactively use JDB through the web app to debug an application. I want that the user can issue a command such as
stop in [function name]
next

And that he would get the back the response and then can proceed.
When I use os.system however, like so:
def AttachDebugger(pid):
    # enable port forwarding
    adb = ADB()
    adb.set_adb_path('~/Library/Android/sdk/platform-tools/adb')
    adb.forward_socket('tcp:8001', 'jdwp:' + pid)
    # attaching
    os.system('jdb -connect com.sun.jdi.SocketAttach:hostname=localhost,port=8001')

then it opens up a JDB session in the background, but it freezes there and doesn't return control to the python code except stopping it via CTRL+C. Is there any way to provide such an interactive session?
What I would like to have is similar to the GITHUB-Tutorial-Page here:
https://try.github.io/levels/1/challenges/1
where the user can interact with the JDB instance
Thanks in advance.

A: I got it done with the pexpect module.


text:
Q: Jacobi Symbol walk through questions I am reading the book Introduction to Modern Cryptography second edition by Katz et al.
The Jacobi Symbol is defined on page 536 and I have included a picture below.
I was able to understand most of this video on solving Jacobi Symbol equations. Provided this is not off topic to what the book requires, I have some questions about some of the different examples from the video.

*

*1:14 Why did he flip the fraction here, take away one, and then divide?

*2:28 If the top (called 'a') is a number that can be expressed as a square, then it equals 1? Why did he not flip the fraction like he earlier at 1:14?
I think the answer for the above question 1 and 2 is you only flip it when there is not a number at the top which can be the product of a square?

*4:51 Why is this answer -1, I thought 2 (mod 3) = 2?

*I did think when using Jacobi Symbols the top number had to be larger than the bottom number, but it does not always seem to be the case here?
The above questions I have seem to happen throughout the video, so I will avoid asking the same question numerous times.


text:
Q: Node cannot find required modules with non-relative path after transpiling them with tsc We are building an application with plain typescript. To make the imports easier to read, we configured typescript to be able to resolve non-relative paths via the tsconfig.
Transpiling the code into JS code with tsc works fine. But whenever we want to start the app with node dist/demo/demonstration.js we get an cannot find lib/input/parser module error. This is the first import of the generated .js file. Its a general problem with all the imports.
At first we thought it might be a problem with our tsconfig.json. But any tries to modify the paths and baseurl keys were met with the same or different errors upon running the js file. The case that tsc itself is completing without errors also invalidates this.
Running jest through the jest.config.js in Webstorm is also working.
We found two possible workarounds. One is copying the folders inside dist into nodes_modules. Doing this via symbolic links removes some of the manual work.
The other is running the app through the terminal like this NODE_PATH=dist dist/demo/demonstration.js.
Both of these feel very hacky. Am I missing a concept here or is this how you do non-relativ imports in typescript? How can I configure Webstorm Run Configurations to be able to run our app?
Example of an import in typescript:
import {Parser} from "lib/input/parser";

tsc is able to resolve these.
tsconfig.json, cleared of unused options. Left the ones we played around with:
{
    "compilerOptions": {
        /* Basic Options */
        "target": "es2018", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
        "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */

        "outDir": "dist", /* Redirect output structure to the directory. */
        //     "rootDir": ".",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */

        /* Strict Type-Checking Options */
        "strict": true, /* Enable all strict type-checking options. */

        /* Module Resolution Options */
        "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
        "baseUrl": "src", /* Base directory to resolve non-absolute module names. */
        //     "paths": {
        //       "lib/*": ["lib/*"],
        //       "demo/*": ["demo/*"],
        //       "test/*": ["test/*"]
        //     },                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */

        "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */

        /* Source Map Options */

        "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
        "inlineSources": true /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    }
}

jest.config.js:
module.exports = {
  "roots": [
    "<rootDir>/src/lib", //src is our folder where sources reside
    "<rootDir>/src/test",
    "<rootDir>/src/demo"
  ],
  "transform": {
    "^.+\\.tsx?$": "ts-jest" //tells jest to use ts-jest for ts / tsx files
  },
  //"testRegex": "(/test/.*|(\\.|/)(test|spec))\\.tsx?$", //tells Jest to look for test in any __tests__ folder
  // AND also any files anywhere that use the (.test|.spec).(ts|tsx) extension e.g. asdf.test.tsx etc.
  "testRegex": "/test/.*",
  "moduleFileExtensions": [
    "ts",
    "tsx",
    "js",
    "jsx",
    "json",
    "node"
  ],
  moduleDirectories: ['node_modules', 'src']
};

package.json
{
  "name": "questionsys",
  "version": "0.1.0",
  "description": "Context-based questionnaire engine",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Tagman",
  "license": "ISC",
  "devDependencies": {
    "@types/axios": "^0.14.0",
    "@types/jest": "^24.0.17",
    "@types/node": "^12.7.2",
    "@types/uuid": "^3.4.5",
    "jest": "^24.8.0",
    "ts-jest": "^24.0.2",
    "typedoc": "^0.15.0",
    "typescript": "^3.5.3"
  },
  "dependencies": {
    "axios": "^0.19.0",
    "uuid": "^3.3.2"
  }
}

A: TypeScript uses paths and baseUrl only for compile checks and expects you to convert path aliases physically in a separate build step:

Our general take on this is that you should write the import path that works at runtime, and set your TS flags to satisfy the compiler's module resolution step, rather than writing the import that works out-of-the-box for TS and then trying to have some other step "fix" the paths to what works at runtime. (core developers' standpoint)

*Preserve runtime behavior of all JavaScript code. (TypeScript design goals)

Downstream runtime environments like Node.js won't have notion of your mapped absolute paths and emit an error, if paths are not converted yet. There is a proposal called Import Maps (see the corresponding Node.js issue), which might ease up mapped path resolution in future. Until then, here are some examples for common build tools:
babel-plugin-module-resolver
Example: Convert @/foo/bar/index → ./src/foo/bar/index
.babelrc:
{
  // ...
  "plugins": [
    [ "module-resolver", { "alias": { "^@/(.+)": "./src/\\1" }} ]
  ]
}

In a separate build step after tsc compilation:
babel src --out-dir dist # or similar

tsconfig-paths / tsconfig-paths-webpack-plugin
webpack.config.js:
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = {
  // ...
  resolve: {
    plugins: [new TsconfigPathsPlugin({/* options */})]
  }
}

More infos

*

*Path aliases for Parcel bundler

*List of possible alternatives (not exhaustive)

*Deno import maps


text:
Q: Trigger hover event on another element Here is my html:
<!DOCTYPE html>

    <title></title>
    <link href="style/hover-min.css" rel="stylesheet" />

                1 - Some text in here

                1 - Some text in here

                1 - Some text in here

The hover css being used is found here
When I hover over the image, the hover effect works fine. My issue is that I would also like this hover effect to display when I hover over anything in the parent li. No matter what I do I cant seem to trigger that hover event.
I think the problem lies with this line..
$(this).closest('.dxnb-item').find('.dxnb-img').mouseenter();

I must be doing something wrong, any help would be appreciated. Thanks.

A: EDIT
Try this code:
$(document).ready(function () {
    $('.vidgroup .dxnb-img').addClass('hvr-buzz-out');

    $('.dxnb-item').on('mouseenter mouseleave', function(e) {
        var image = $(this).find('.dxnb-img');
        image.trigger(e.type);
    });
});

If it throws an error, please paste it here.


text:
Q: error TS2769: No overload matches this call... while upgrading elasticsearch I am trying to use firestore and elasticsearch. With the help of elasticstore. Elasticstore is dated but was working great in the past and now when i try to update all the dependencies, like updating ts and @elastic/elasticsearch 8.6.1 from 16.7.1, I am running into some errors I can't figure out. This being:
error TS2769: No overload matches this call.
which refers to:
  ping = () => {
    return new Promise((resolve, reject) => {
      this.esClient.ping((err, result) => {
        if (err) return reject(err)
        else return resolve(result)
      })
    })
  }

the line in question here is:
this.esClient.ping((err, result) => {
Please advise on how this should be re written.
Thank you!


text:
Q: Starting new project using ArcGIS Server Silverlight API I'm about to start a new mapping project for a client, and am considering using the ArcGIS Server Silverlight API, since it gives a lot of the required functionality out-of-the-box (especially with the Silverlight Viewer).
A colleague suggested this is a bad idea, since "Silverlight is dead technology". He says that most new internal Microsoft projects are moving to HTML5 instead of Silverlight.
This is a small project so I don't have the luxury of developing everything from scratch, which the JavaScript API entails. Using the Silverlight Viewer I can have the core functionality running almost immediately.
Does anyone have any opinions/inside information on whether Silverlight is a good idea for a new ArcGIS Server website?

A: Have you not heard?  HTML6 is the latest greatest thing.  Why arent you developing in that?
- Moral here is its like buying a new computer.  You can always wait for the next best thing, but theres always something better around the corner.  (see comments in that post as well).
I also like James Fee summary of Q&A question for UC2011, which is kind of related:

Q: How is Esri planning to support
  HTML5? A: I love the answer, basically
  HTML5 is awesome, but they realize
  that most of their user base is stuck
  on old versions of IE. Thus as awesome
  as it can be, it isn't.

IMO, the safest and most futureproof option will be Javascript, later tapping into HTML5 where need be.
You have not mentioned your requirements so I am not sure why you think you will have to do so much more work with Javascript.
Can you not leverage frameworks like Dojo/ExtJS to do the heavy lifting?
These frameworks compliment Javascript to match Silverlight, no?
I am a Flex fan myself, but have dabbled with Silverlight and like it.
Your application will need a makeover in a few years anyhow - if you can code in it, shoot for Silverlight!

A: I am not at all convinced that Silverlight is dead. Yes, MS talked about HTML5 and javascript and NOT SL in their windows 8 preview  but in reality for LOB apps I think Silverlight provides what the other technologies can not. But maybe thats just me.
Some other facts- there is the rumour that there is an agreement between Apple and MS for Apple to support SL on iPhones and iPads. SL IS the development platform for windows 7 phone. Nokia will be shipping their phones with Windows 7 only. Smartphones (they say) is (or will be) the new PC. Large companies like SAP have moved part of their apps to Silverlight. Maybe its just me, but to me all these sound like SL is a long way away of being pronounced dead.

A: The rumors about Silverlight's premature death have already been thoroughly addressed and debunked.
Here is an article about support for XAML (the language used to provide the front-end for Silverlight applications) in Windows 8:
http://davidburela.wordpress.com/2011/06/14/premature-cries-of-silverlight-wpf-skill-loss-windows-8-supports-all-programming-models/
Quoting:

I'm more excited about the new
  possibilities coming in the new
  Jupiter XAML programming model than
  the misconception that HTML+JS is the
  only way to create apps.

Here is some further information about current job growth in Silverlight positions:
https://softwareengineering.stackexchange.com/questions/15857/did-microsoft-kill-silverlight/75841#75841
As far as your question about starting a project with the ArcGIS API for Silverlight, it is worth noting that this is an award winning API which has been around for more than 2 years and receives significant support from ESRI.
As an alternative to learning the API, the ArcGIS Viewer for Silverlight provides a good out-of-the-box solution to create a map viewer without writing any source code.


text:
Q: TL074 or TL072 VOL (output voltage swing low)? TL074 or TL072 VOL (output voltage swing low)?
I can't find it in any datasheet.
I want to know how low the output can get if Vdd=9V and Vss=ground (0V).
If I read the datasheet right, VOH (output swing high) should be at least 6V. Am I correct?
Another really annoying thing is that I can't find a maximum output current.
Can you help? Thank you very much.

A: The datasheet provides this information in the Electrical Characteristics table as \$V_{OM}\$, "Maximum peak output voltage swing." The output swing is symmetric. In your case, the output will typically be able to swing between 1.5V and 7.5V, but is only guaranteed to swing from 3V to 6V (for a 10kΩ load).
These amplifiers are really not designed for single-supply operation. If you want the output voltage to be able to swing near 0V, you should select a different amplifier.

A: My interpretation of the 1st graph on page 11 of this datasheet is that you'll see an output swing of around 1.5V to 7.5V (into a 10k load).
The TL07x opamps aren't really designed for single-supply applications, so you need to read the datasheet with that in mind.
As such, I look at the 4.5V point on the Vcc+/- axis since that's effectively what you're giving it with a single 9V supply.


text:
Q: Define multiple tags and remove suites in behat.yml I want to define multiple tags in behat.yml which correspond to suite names.
There are 4 suites inside the features folder and each of them have multiple .feature files.
Ex: admin, themes
Tags to be defined: @admin, @themes.
Previously the behat.yml file contained suites for admin and themes. Now I want to define 3 different profiles (server1, server2 and server3) corresponding to different testing environments and use tags instead of suites to run the feature files containing those tags. I have added the tags @admin and @themes in every feature file of themes and admin folder.
How should I implement this specific case in my config file?
Any assistance is greatly appreciated

A: You can have different profiles and themes as per the docs
So one possible way to do it, would be to group the suites for each profile.
server1:
  suites:
    default:
        contexts:
            - FeatureContext
        filters:
            tags: "@admin"
server2:
    suites:
        default:
            contexts:
                - FeatureContext
            filters:
                tags: "@admin"

server3:
    suites:
        default:
            contexts:
                - FeatureContext
            filters:
                tags: "@admin,@themes"


text:
Q: What could cause random 1074 shutdown calls? I have a fairly new desktop computer I built in december. RTX 3090 GPU, i9-10850K CPU, SF 750W PSU, 32GB RAM, Windows 10.
I play quite a lot of games, and among them one specific game (Spiritfarer) causes my computer to properly shut down after a random time span - so far ranging from 5 minutes to about 8 hours.
My GPU and CPU temperatures and loads are fine so far as I can see, and I can run way more demanding games in top quality 120fps with no issue whatsoever, but this one acts up. My drivers are all up-to-date.
The event viewer system log shows this message (latest to date) - ID 1074 :
Le processus C:\WINDOWS\SysWOW64\shutdown.exe (PC) a lancé l'arrêt de l'ordinateur PC pour l'utilisateur AUTORITE NT\Système pour la raison suivante : Aucun titre à cette raison n'a pu être trouvé
  Code : 0x800000ff
  Type d'extinction : s'arrêter.
 Commentaire :

Apparently it is a 32-bit app that initiates the shutdown, but the game is 64 bits. I've been scratching my head over this and questioning the developers, but we can't seem to figure it out. I do not believe it is a hardware problem, and I doubt the game simply initiates shutdowns randomly.
What could be happening ?


text:
Q: What happened to .gzip option in 7-zip? I am not sure if this is just a coincident or not but I have recently upgraded my OS to Win 10.
I noticed only now (after the upgrade) that the .gzip archive format is not available in 7-zip anymore.
Perhaps I am missing something. But is there a way to archive a file/directory in a .gzip format in Win10?
If so, could anyone please advise where/how to select the .gzip option?
Thanks!

Edit:
I tested 7-zip on Win 7 and also I tried to gzip .txt file and a .tar file in Win10.
Here are my findings:
I can gzip a .txt file in Win 7.

I can also gzip a .tar file in Win 10 but I can't gzip a .txt file in Win 10.
This option is no longer available in Win 10.

A: You cannot gzip multiple files. Create a tar file first then gzip.

A: I'm running 15.0.5 beta, on Windows 10 x64, and I definitely have gzip as an option. (See below.)
I'd reinstall using the latest package.


text: Q: Managing CUDA with Conda environments I work with Tensorflow and PyTorch and manage each project that I work on inside of a Conda environment. This allows me to share projects and update my stack without breaking old projects. I am trying to get Conda to manage Cuda within an environment as well. Is this possible? I want old projects to be maintained whenever I update to newer versions of Cuda and CUDnn. Is there a way for Anaconda do this?


text:
Q: Ordenamiento Topologico C# esto es un problema que tengo que no tengo ni la mínima idea de que esta pasando
Quiero ordenar de forma topologica una matriz pero por alguna razon no me imprime lo que debe de imprimir
public int EncontradoIO()
        {
            bool encontrado = false;
            int n = 0;
            for(n = 0; n < nodos; n++)
            {
                if (grado[n] == 0)
                {
                    encontrado = true;
                    break;
                }
            }

            if (encontrado)
                return n;
            else
                return -1;
        }

        public void DecrementaGrado(int pNodo)
        {
            grado[pNodo] = -1;
            int n = 0;
            for(n = 0; n < nodos; n++)
            {
                if(mAdyacencia[pNodo,n] == 1)
                {
                    grado[n]--;
                }
            }
        }

con este código que esta en una clase debe de ordenarlo y después con este código debe de imprimir
do
            {
                nodo = mg.EncontradoIO();
                if (nodo != -1)
                {
                    Console.Write("{0} --> ", nodo);
                    mg.DecrementaGrado(nodo);
                }
            } while (nodo != -1);

el error es que no imprime correctamente la matriz de adyacencia, se supone que deberia de imprimir 0--> 1--> 4-->3-->-->6-->2-->5 o deberia de ser de otro orden creo pero solo me imprime 5-->6


text:
Q: How does the ORDER BY CASE Clause Work in the following Code? How does this part of code work?
ORDER BY
  CASE WHEN subject IN ('Chemistry','Physics') THEN 1 ELSE 0 END,
  subject,
  winner;

A: It orders by the result of the case, then by subject, then winner.
Rows that are not chemistry or physics come out first, in order by subject and winner. Then chemistry, then physics.
Try it.

A: First it checks if subjet is Chemistry or Physics.
If it does the sorting score will be 1.
If the subject does not contain any of "Chemistry" or "Physics" the score will be 0.
After that it sorts the results by score so the results that contains Chemistry or Physics will come first after that those that dont contain.

A: i think this is what you want SELECT winner, subject FROM nobel WHERE yr = '1984'  AND subject IN ('Chemistry','Physics') ORDER BY CASE;


text:
Q: Как вставить пробелы? У меня есть текст в RichTextBox, мне надо чтоб считывались все пробелы(если у меня 2 пробела, то они не считывались как один). Это мне надо для выравнивания текста по ширине, в программе оно выглядит коряво.
Пример: есть текст "01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49", сам элемент RichTextBox такого размера, что этот текст выглядит как массив 7х7. Мне надо чтоб цифры располагались дальше чем на один пробел, если применить выравнивание, то все выглядит как надо, за исключением последней строки.


text:
Q: Open CTI Connector - Salesforce Professional I'm trying to install Open CTI Connector to Salesforce (Professional license). The installation always fails giving me this: installing this package requires the following feature and its associated permissions apex classes. Is there any solution besides purchasing API access?

A: Purchasing API access won't solve that problem, API and Apex are 2 different features.  Your only option for professional would be to either find an appexchange solution, which would be allowed to install and execute the Apex related to the solution.  Or, find a completely external cloud based solution that only integrated via the browser, and not internal to Salesforce.  Last option, of course, would be to upgrade to Enterprise Edition.

A: I agree with JimRae on this one, purchasing API access won't solve this issue. The only option for pro would be to find an external cloud base solution that integrates only through a browser and not internally to Salesforce. Or you can look for an app exchange solution that would install and execute your apex solution. Or just upgrade to Enterprise Edition like what JimRae said.


text:
Q: How to use "where" through cmd shortcut? On Windows 10, I lost all my path variables and now I want to recover every shortcut (code, notepad, npm, java, etc).
'where' is not recognized ...  ,
'code' is not recognized ...
I don't want to look for each file individually through the explorer. Now I wanted to use "where" to gather paths quickly, but it turns out that it does not work because I've deleted its own path.
I noticed that I have this file C:\Windows\System32\where.exe installed, but changing PATH from System (or User ??) variable won't work. How to fix it in order to run it anywhere?

A:
I noticed that I have this file C:\Windows\System32\where.exe installed, but changing PATH from System (or User ??) variable won't work. How to fix it in order to run it anywhere?

The "basic" (default) Path (System) variable under Windows 10 for Windows\System32 is %SystemRoot%\system32. Adding this path to your Path (System) variables should enable where from the command line, I believe.
Note that this doesn't include any other standard Path (System) variables, including:
%SystemRoot%
%SystemRoot%\System32\Wbem
%systemroot%\System32\WindowsPowerShell\v1.0\

and likely C:\Program Files (x86)\Windows Live\Shared. This also doesn't include standard PATH (User) variables such as C:\Users\Your_User_Name\AppData\Local\Microsoft\WindowsApps.

I don't want to look for each file individually through the explorer. Now I wanted to use "where" to gather paths quickly, but it turns out that it does not work because I've deleted its own path.

As already indicated in harrymc's answer, where cannot do what you wish. It doesn't "discover" executable files or "remember" Path\PATH variables. If the relevant paths do not exist in your environment variables, where cannot "find" those paths. You are going to have to go through Explorer\executables manually unless you use a system restore, as already detailed.

A: Where works by searching the PATH. If the path is incorrect,
it will not find anything.
The easiest way to recover your PATH is, if you have System Restore enabled,
to rollback Windows to a time before this change was done.
For more details see the tutorial
How to Do a System Restore of Windows 10.


text:
Q: Spring Security OAuth2 (google) web app in redirect loop I am trying to build a Spring MVC application and securing it with Spring Security OAuth2 and the provider is Google. I was able to get the web app working without security and with form login. However, I am not able to get OAuth with google to work. Google app setup is fine as I can get the call backs etc to work with a non Spring Security app.
My security config is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns:sec="http://www.springframework.org/schema/security"
         xmlns:b="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
    <sec:http use-expressions="true" entry-point-ref="clientAuthenticationEntryPoint">
        <sec:http-basic/>
        <sec:logout/>
        <sec:anonymous enabled="false"/>

        <sec:intercept-url pattern="/**" access="isFullyAuthenticated()"/>

        <sec:custom-filter ref="oauth2ClientContextFilter" after="EXCEPTION_TRANSLATION_FILTER"/>
        <sec:custom-filter ref="googleAuthenticationFilter" before="FILTER_SECURITY_INTERCEPTOR"/>
    </sec:http>

    <b:bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"/>

    <sec:authentication-manager alias="alternateAuthenticationManager">
        <sec:authentication-provider>
            <sec:user-service>
                <sec:user name="user" password="password" authorities="DOMAIN_USER"/>
            </sec:user-service>
        </sec:authentication-provider>
    </sec:authentication-manager>
</b:beans>

The OAuth2 protected resource is as follows:
@Configuration
@EnableOAuth2Client
class ResourceConfiguration {
    @Autowired
    private Environment env;

    @Resource
    @Qualifier("accessTokenRequest")
    private AccessTokenRequest accessTokenRequest;

    @Bean
    public OAuth2ProtectedResourceDetails googleResource() {
        AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
        details.setId("google-app");
        details.setClientId(env.getProperty("google.client.id"));
        details.setClientSecret(env.getProperty("google.client.secret"));
        details.setAccessTokenUri(env.getProperty("google.accessTokenUri"));
        details.setUserAuthorizationUri(env.getProperty("google.userAuthorizationUri"));
        details.setTokenName(env.getProperty("google.authorization.code"));
        String commaSeparatedScopes = env.getProperty("google.auth.scope");
        details.setScope(parseScopes(commaSeparatedScopes));
        details.setPreEstablishedRedirectUri(env.getProperty("google.preestablished.redirect.url"));
        details.setUseCurrentUri(false);
        details.setAuthenticationScheme(AuthenticationScheme.query);
        details.setClientAuthenticationScheme(AuthenticationScheme.form);
        return details;
    }

    private List<String> parseScopes(String commaSeparatedScopes) {
        List<String> scopes = newArrayList();
        Collections.addAll(scopes, commaSeparatedScopes.split(","));
        return scopes;
    }

    @Bean
    public OAuth2RestTemplate googleRestTemplate() {
        return new OAuth2RestTemplate(googleResource(), new DefaultOAuth2ClientContext(accessTokenRequest));
    }

    @Bean
    public AbstractAuthenticationProcessingFilter googleAuthenticationFilter() {
        return new GoogleOAuthentication2Filter(new GoogleAppsDomainAuthenticationManager(), googleRestTemplate(), "https://accounts.google.com/o/oauth2/auth", "http://localhost:9000");
    }
}

The custom authentication filter which I have written to throw a Redirect exception to get the OAuth2 authorization is as follows:
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        try {
            logger.info("OAuth2 Filter Triggered!! for path {} {}", request.getRequestURI(), request.getRequestURL().toString());
            logger.info("OAuth2 Filter hashCode {} request hashCode {}", this.hashCode(), request.hashCode());
            String code = request.getParameter("code");
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            logger.info("Code is {} and authentication is {}", code, authentication == null ? null : authentication.isAuthenticated());
            // not authenticated
            if (requiresRedirectForAuthentication(code)) {
                URI authURI = new URI(googleAuthorizationUrl);

                logger.info("Posting to {} to trigger auth redirect", authURI);
                String url = "https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + oauth2RestTemplate.getAccessToken();
                logger.info("Getting profile data from {}", url);
                // Should throw RedirectRequiredException
                oauth2RestTemplate.getForEntity(url, GoogleProfile.class);

                // authentication in progress
                return null;
            } else {
                logger.info("OAuth callback received");
                // get user profile and prepare the authentication token object.

                String url = "https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + oauth2RestTemplate.getAccessToken();
                logger.info("Getting profile data from {}", url);
                ResponseEntity<GoogleProfile> forEntity = oauth2RestTemplate.getForEntity(url, GoogleProfile.class);
                GoogleProfile profile = forEntity.getBody();

                CustomOAuth2AuthenticationToken authenticationToken = getOAuth2Token(profile.getEmail());
                authenticationToken.setAuthenticated(false);
                Authentication authenticate = getAuthenticationManager().authenticate(authenticationToken);
                logger.info("Final authentication is {}", authenticate == null ? null : authenticate.isAuthenticated());

                return authenticate;
            }
        } catch (URISyntaxException e) {
            Throwables.propagate(e);
        }
        return null;
    }

The filter chain sequence from the Spring web app is as follows:
o.s.b.c.e.ServletRegistrationBean - Mapping servlet: 'dispatcherServlet' to [/]
o.s.b.c.e.FilterRegistrationBean - Mapping filter: 'metricFilter' to: [/*]
o.s.b.c.e.FilterRegistrationBean - Mapping filter: 'oauth2ClientContextFilter' to: [/*]
o.s.b.c.e.FilterRegistrationBean - Mapping filter: 'googleOAuthFilter' to: [/*]
o.s.b.c.e.FilterRegistrationBean - Mapping filter: 'org.springframework.security.filterChainProxy' to: [/*]
o.s.b.c.e.FilterRegistrationBean - Mapping filter: 'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0' to: [/*]
o.s.b.c.e.FilterRegistrationBean - Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
o.s.b.c.e.FilterRegistrationBean - Mapping filter: 'applicationContextIdFilter' to: [/*]
o.s.b.c.e.FilterRegistrationBean - Mapping filter: 'webRequestLoggingFilter' to: [/*]

The redirect to Google works fine and I get the callback to the filter and the authentication is successful. However after that, the request results in a redirect and it invokes the filter again (the request is the same, I have checked the hasCode). On the second call the authentication in the SecurityContext is null. As part of the first authentication call the Authentication object was populated in the security context, so why does it disappear?
I am working with Spring Security for the first time so may have made newbie mistake.

A: After playing around with Spring Security configuration and the filters I was finally able to get this working. I had to make couple of important changes

*

*I used a standard Spring OAuth2 filter (org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter) instead of the custom filter I was using.

*Change the intercept URL of the authentication filter to be /googleLogin and added an authentication entry point which redirects to this URL on authentication failure.

Overall the flow is as follows

*

*Browser accesses / and the request passes through the OAuth2ClientContextFilter and OAuth2ClientAuthenticationProcessingFilter as the context does not match. The configured context path for login is /googleLogin

*The security interceptor FilterSecurityInterceptor detects that the the user is anonymous and throws an access denied exception.

*Spring security's ExceptionTranslationFilter catches the access denied exception and asks the configured authentication entry point to handle it which issues a redirect to /googleLogin.

*For the request /googleLogin, the filter OAuth2AuthenticationProcessingFilter tries to access the Google protected resource and an UserRedirectRequiredException is thrown which is translated into a HTTP redirect to Google (with the OAuth2 details) by OAuth2ClientContextFilter.

*On successful authentication from Google the browser is redirected back to /googleLogin with the OAuth code. The filter OAuth2AuthenticationProcessingFilter handles this and creates an Authentication object and updates the SecurityContext.

*At this point the user is fully authenticated and redirect to / is issued by the OAuth2AuthenticationProcessingFilter.

*FilterSecurityInterceptor allows the request to proceed as the SecurityContext contains an Authentication object which is authenticated.

*Finally the application page which is secured using an expression like isFullyAuthenticated() or similar is rendered.

The security context xml is as follows:
<sec:http use-expressions="true" entry-point-ref="clientAuthenticationEntryPoint">
    <sec:http-basic/>
    <sec:logout/>
    <sec:anonymous enabled="false"/>

    <sec:intercept-url pattern="/**" access="isFullyAuthenticated()"/>

    <!-- This is the crucial part and the wiring is very important -->
    <!--
        The order in which these filters execute are very important. oauth2ClientContextFilter must be invoked before
        oAuth2AuthenticationProcessingFilter, that's because when a redirect to Google is required, oAuth2AuthenticationProcessingFilter
        throws a UserRedirectException which the oauth2ClientContextFilter handles and generates a redirect request to Google.
        Subsequently the response from Google is handled by the oAuth2AuthenticationProcessingFilter to populate the
        Authentication object and stored in the SecurityContext
    -->
    <sec:custom-filter ref="oauth2ClientContextFilter" after="EXCEPTION_TRANSLATION_FILTER"/>
    <sec:custom-filter ref="oAuth2AuthenticationProcessingFilter" before="FILTER_SECURITY_INTERCEPTOR"/>
</sec:http>

<b:bean id="oAuth2AuthenticationProcessingFilter" class="org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter">
    <b:constructor-arg name="defaultFilterProcessesUrl" value="/googleLogin"/>
    <b:property name="restTemplate" ref="googleRestTemplate"/>
    <b:property name="tokenServices" ref="tokenServices"/>
</b:bean>

<!--
    These token classes are mostly a clone of the Spring classes but have the structure modified so that the response
    from Google can be handled.
-->
<b:bean id="tokenServices" class="com.rst.oauth2.google.security.GoogleTokenServices">
    <b:property name="checkTokenEndpointUrl" value="https://www.googleapis.com/oauth2/v1/tokeninfo"/>
    <b:property name="clientId" value="${google.client.id}"/>
    <b:property name="clientSecret" value="${google.client.secret}"/>
    <b:property name="accessTokenConverter">
        <b:bean class="com.rst.oauth2.google.security.GoogleAccessTokenConverter">
            <b:property name="userTokenConverter">
                <b:bean class="com.rst.oauth2.google.security.DefaultUserAuthenticationConverter"/>
            </b:property>
        </b:bean>
    </b:property>
</b:bean>

<!--
    This authentication entry point is used for all the unauthenticated or unauthorised sessions to be directed to the
    /googleLogin URL which is then intercepted by the oAuth2AuthenticationProcessingFilter to trigger authentication from
    Google.
-->
<b:bean id="clientAuthenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
    <b:property name="loginFormUrl" value="/googleLogin"/>
</b:bean>

Also the Java Config for the OAuth2 resources is as follows:
@Configuration
@EnableOAuth2Client
class OAuth2SecurityConfiguration {
    @Autowired
    private Environment env;

    @Resource
    @Qualifier("accessTokenRequest")
    private AccessTokenRequest accessTokenRequest;

    @Bean
    @Scope("session")
    public OAuth2ProtectedResourceDetails googleResource() {
        AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
        details.setId("google-oauth-client");
        details.setClientId(env.getProperty("google.client.id"));
        details.setClientSecret(env.getProperty("google.client.secret"));
        details.setAccessTokenUri(env.getProperty("google.accessTokenUri"));
        details.setUserAuthorizationUri(env.getProperty("google.userAuthorizationUri"));
        details.setTokenName(env.getProperty("google.authorization.code"));
        String commaSeparatedScopes = env.getProperty("google.auth.scope");
        details.setScope(parseScopes(commaSeparatedScopes));
        details.setPreEstablishedRedirectUri(env.getProperty("google.preestablished.redirect.url"));
        details.setUseCurrentUri(false);
        details.setAuthenticationScheme(AuthenticationScheme.query);
        details.setClientAuthenticationScheme(AuthenticationScheme.form);
        return details;
    }

    private List<String> parseScopes(String commaSeparatedScopes) {
        List<String> scopes = newArrayList();
        Collections.addAll(scopes, commaSeparatedScopes.split(","));
        return scopes;
    }

    @Bean
    @Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
    public OAuth2RestTemplate googleRestTemplate() {
        return new OAuth2RestTemplate(googleResource(), new DefaultOAuth2ClientContext(accessTokenRequest));
    }
}

I had to override some of the Spring classes as the format of the token from Google and the one expected by Spring don't match. So there is some custom handiwork required there.

A: Not to impose a better answer, but another reason for this redirect looping is the session cookie handling when the session cookie sameSite attribute is set to Strict. Then, if the authority service has broken the redirect chain, the session cookie will not be transmitted.
See: How can I redirect after OAUTH2 with SameSite=Strict and still get my cookies?


text:
Q: Issues with equi-join query I have a problem with this query  :
select
    distinct count(avancementtotal1.id_Module) as 'number module not realised'
    ,count(avancementtotal2.id_module) as 'number module  realised'
    ,Groupe.name_Groupe,Groupe.Year
From
    AvancementTotal avancementtotal1
join
    Module on Module.id_Module = avancementtotal1.id_Module
join
    Affilate on Module.id_Affilate = Affilate.id_Affilate
join
    Groupe on Groupe.id_Groupe = avancementtotal1.id_Groupe
join
    AvancementTotal avancementtotal2 on avancementtotal1.id = avancementtotal2.id
where
    avancementtotal2.State_efm = 'EFM Realised'
    and avancementtotal1.State_efm = 'EFM Not REALISEd'
    and avancementtotal1.id <> avancementtotal2.id
Group by
    Groupe.id_Groupe, Groupe.name_Groupe, Groupe.Year, Affilate.name_Affilate

It returns null and I want to know why.
I want to have the number of module not realised and in the same moment have the module who have state of EFM REALISEd
here the structure :

A: I think you want to do this as a conditional aggregation:
select sum(case when avt.State_efm = 'EFM Not REALISEd' then 1 else 0 end) as NumNotRealized,
       sum(case when avt.State_efm = 'EFM Realised' then 1 else 0 end) as NumRealized,
       g.name_Groupe, g."Year"
From AvancementTotal avt join
     Module m
     on m.id_Module = avt.id_Module join
     Affilate a
     on m.id_Affilate = a.id_Affilate join
     Groupe g
     on g.id_Groupe = avt.id_Groupe
Group by g.id_Groupe, g.name_Groupe, g."Year", a.name_Affilate;

Notice that this only joins to the AvancementTotal table once and replaces the counts in the select with conditional sum()s.
I also made the following changes:

*

*Added table aliases to make the query more readable

*Removed the single quotes around identifiers.  Although allowed, you should only use single quotes for string and date constants

*Added double quotes around year because it is a reserved word

I also suspect that a.name_Affilate should either be in the select clause or not in the group by clause.


text:
Q: Can a database name start with a number? I'm wondering if a database name can start with a number e.g 143doors.
I found some answer here http://markmail.org/message/yw57rt3tweldtxet but I'm not quite sure since it's 1999.
Will there be disadvantages if I start with a number?

A: Within MySQL Workbench, you are going to have trouble querying if you do something like {db_name}.{table} and your db_name starts with a number.
The solution to this is the backtick mentioned in the accepted answer.  An example is like:
select * from `2013e93`.blurb

where the db_name is 2013e93 and the table is blurb.

A: A quick test says, yes you can.  Using spaces in database names will lead to trouble, though. You'll have to use `143 doors` (with the backtick) if you really want to do this.


text:
Q: GAE : How to deploy various environments with secrets? I have a staging and a production project on App Engine, with 6 services on each.
For the moment, we deploy from the developers computer, using
gcloud app deploy app.staging.yaml --project staging-project
or gcloud app deploy app.production.yaml --project production-project
It works but it causes issues with environment variables, and especially with secrets.
Our apps gets their Api keys, database credentials and other things from the environment variables - that allows us to have the exact same app running locally, in a Docker Container or in App Engine without knowing where it is deployed.
If I follow the documentation way to deploy, our app.yaml files would look like this:
app.production.yaml
runtime: nodejs
env: flex

manual_scaling:
  instances: 1
env_variables:
  DATABASE_PASSWORD: "topsecret"
  MY_API_KEY: "ultrasecret"

I think everybody easily understands why it's a bad idea to store that on a Git repository.
For the moment, we have this shadow file that every developer have to fill before deployment
app.production.yaml.shadow
runtime: nodejs
env: flex

manual_scaling:
  instances: 1
env_variables:
  DATABASE_PASSWORD: "set me"
  MY_API_KEY: "set me"

But as the team grows and we want everybody to be able to deploy on staging, it becomes more and more difficult to have the right settings for each developpers and each service.
I found out 3 workarounds, and their reason to not be used:

*

*Use Google KMS - allows us to put encrypted secrets directly into the project, but it requires us to put custom code in our apps to decrypt them. It creates a different environment management between local, staging and production. It increases the risk of bugs due to the complexity.

*Store secrets in Google Datastore - I tried it, I created a helper that searches env vars in proccess.ENV, then in cache and ultimately in Datastore. But like KMS, it increases complexity a lot.

*Store secrets in a JSON file and put in on Google Cloud Storage : again, it requires to load env variables through an helper that checks env vars, then loads the file etc...

Ultimately, we are exploring the feasibility to use a deployment server that would be triggered by developers or Continuous Integration and handle all the secrets injection when deploying to App Engine. But these tools like Ansible, Salt, Puppet, Chef only have plugins for Compute Engine and do not support App Engine.
+-------------------------+    +-------------------+   +---------------------+
|                         |    |                   +--->                     |
| Developer workspace     |    |    Ansible        |   | App Engine STAGING  |
|                         +---->   (or other)      |   |                     |
+-------------------------+    |                   |   +---------------------+
                               |                   |
+-------------------------+    |                   |   +---------------------+
|                         +---->   Injects secrets |   |                     |
| Continous Integration        |                   |   | App Engine PROD.    |
|                         |    |                   +--->                     |
+-------------------------+    +-------------------+   +---------------------+

This leads me to 3 questions:

*

*Do you think using a deployment server with App Engine is a good idea ?

*How can I make sure that production and staging secrets keep synchronisation so that deployments from developers are always right ?

*Is there a way to use classical environment variables for secrets on App Engine ?

A: I would strongly encourage you to consider using a combination of KMS and Cloud Storage, as Google outlines here.
You're right that it can be a bit of a pain in the neck to set up, but once it's in place it's very easy to work with. We set up separate keyrings for each environment (dev, test, staging, prod) and then separate keys for each application and wrote a command line utility that makes it trivial for any developer on our team to write secrets into the secret store (while at the same time preventing them from reading production secrets back).
Ultimately, the management of secrets remains a hard problem. Managing secrets for multiple applications/environments as your team grows is tough. But I'd really encourage you to just pay the cost of investing in something like KMS up front, because it'll make your life easier essentially forever and really reduce the risk of you accidentally shooting yourself in the foot.

A: As you said, it is not possible to use either of those solutions (Ansible, Salt, etc), with App Engine. If you were to use them, you would have to move to GCE. Google has some official tutorials on how to start with either of those technologies.
If you stay on App Engine, you can use one of the mentioned solutions, KMS being the better oriented for this purpose.
Another possible solution would be migrating to a Custom Runtime. Based on your application, you can generate a Dockerfile with:
$ gcloud beta app gen-config --custom
Your Dockerfile will look like this:
FROM gcr.io/google_appengine/nodejs
RUN /usr/local/bin/install_node '>=4.3.2'
COPY . /app/
RUN npm install --unsafe-perm || \
  ((if [ -f npm-debug.log ]; then \
      cat npm-debug.log; \
    fi) && false)
CMD npm start

You can then modify it to include the secret keys, stored in your environment variables, with something like this example of how to input the keys in your file:
sed 's/topsecret/'"$KEY_1"'/g;s/ultrasecret/'"$KEY_2"'/g' app.production.yaml.shadow > app.production.yaml
Mind the use of singles and doubles quotes before and after both KEY_1 and KEY_2, as you need them to enter environment variables using sed.

A: A few times later, here is what I can say about this issue:

*

*Create one app.yaml per environment. You're able to specify the app.yaml file to use at deployment time according to your environment.

*Put your not secret environment parameters (like endpoints urls) in the env_variables section.

*For your secrets (api keys, secret tokens...), use a dedicated tool like Hashicorp Vault or AWS Secrets Manager. This will allow you to share them between your projects and to handle who can access them among your team.


text:
Q: General Solution and Particular Solution of Recurrence Equation I am given:
$S_{n+2} = S_{n+1}+S_{n} + {2}$ for $\forall n \in N$
My question is how do I find the general solution of the recurrence equation. And the particular solution where $S_0=1$ and $S_1 = 5 $?

A: First you go from inhomogeneous to homogeneous:
$$
S_{n+2} = S_{n+1} + S_n + 2 \\
S_{n+3} = S_{n+2} + S_{n+1} + 2 \\
$$
so
$$
S_{n+3} - S_{n+2} = S_{n+2} - S_{n}
$$
or
$$
S_n  = 2 S_{n-1} + 0 \cdot S_{n-2} - S_{n-3}
$$
then you solve that one, using the initial conditions.
The characteristic polynomial is:
$$
p(t) = t^3 - 2 t^2 + 1
$$
We guess the root $r_1 = 1$ and have
$$
p(t) = (t - 1)(t^2 - t - 1)
$$
so the other two roots are
$$
r_{2,3} = \frac{1 \pm \sqrt{5}}{2}
$$
where $r_2$ is the golden ratio. This gives
$$
S_n =
k_1 1^n +
k_2 \left( \frac{1 + \sqrt{5}}{2} \right)^n +
k_3 \left( \frac{1 - \sqrt{5}}{2} \right)^n
$$
We have
$$
S_2 = S_1 + S_0 + 2 = 5 + 1 + 2 = 8
$$
We get the linear system
$$
\begin{pmatrix}
1 & 1 & 1 \\
1 & \frac{1 + \sqrt{5}}{2} & \frac{1 - \sqrt{5}}{2} \\
1 & \left(\frac{1 + \sqrt{5}}{2}\right)^2 & \left(\frac{1 - \sqrt{5}}{2}\right)^2
\end{pmatrix}
\begin{pmatrix}
k_1 \\
k_2 \\
k_3
\end{pmatrix}
=
\begin{pmatrix}
1 \\
5 \\
8
\end{pmatrix}
$$
The numerical solution is $k_1 = -2$, $k_2 = 3.95967$, $k_3 = -0.95967$, so
$$
S_n =
-2 +
3.95967 \left(\frac{1 + \sqrt{5}}{2}\right)^n
-0.95967 \left(\frac{1 - \sqrt{5}}{2}\right)^n
$$
Algebraic solution:
$$
\left(
\begin{array}{rrr|r}
1 & 1 & 1 & 1 \\
1 & \frac{1 + \sqrt{5}}{2} & \frac{1 - \sqrt{5}}{2} & 5 \\
1 & \left(\frac{1 + \sqrt{5}}{2}\right)^2 & \left(\frac{1 - \sqrt{5}}{2}\right)^2 & 8
\end{array}
\right)
\to \\
\left(
\begin{array}{rrr|r}
1 & 1 & 1 & 1 \\
0 & -1 & -1 & -3 \\
1 & \left(\frac{1 + \sqrt{5}}{2}\right)^2 & \left(\frac{1 - \sqrt{5}}{2}\right)^2 & 8
\end{array}
\right)
\to \\
\left(
\begin{array}{rrr|r}
1 & 0 & 0 & -2 \\
0 & 1 & 1 & 3 \\
1 & \left(\frac{1 + \sqrt{5}}{2}\right)^2 & \left(\frac{1 - \sqrt{5}}{2}\right)^2 & 8
\end{array}
\right)
\to \\
\left(
\begin{array}{rrr|r}
1 & 0 & 0 & -2 \\
0 & 1 & 1 & 3 \\
0 & \left(\frac{1 + \sqrt{5}}{2}\right)^2 & \left(\frac{1 - \sqrt{5}}{2}\right)^2 & 10
\end{array}
\right)
\to \\
\left(
\begin{array}{rrr|r}
1 & 0 & 0 & -2 \\
0 & 1 & 1 & 3 \\
0 & 0 &
\left(\frac{1 - \sqrt{5}}{2}\right)^2
- \left(\frac{1 + \sqrt{5}}{2}\right)^2 &
10 - 3 \left(\frac{1 + \sqrt{5}}{2}\right)^2
\end{array}
\right)
\to \\
\left(
\begin{array}{rrr|r}
1 & 0 & 0 & -2 \\
0 & 1 & 1 & 3 \\
0 & 0 &
\frac{1 - \sqrt{5}}{2} - \frac{1 + \sqrt{5}}{2} &
7 - 3 \frac{1 + \sqrt{5}}{2}
\end{array}
\right)
\to \\
\left(
\begin{array}{rrr|r}
1 & 0 & 0 & -2 \\
0 & 1 & 1 & 3 \\
0 & 0 & 1 & \left( 3 \frac{1 + \sqrt{5}}{2} - 7 \right)/\sqrt{5}
\end{array}
\right)
\to \\
\left(
\begin{array}{rrr|r}
1 & 0 & 0 & -2 \\
0 & 1 & 0 & \frac{11}{2\sqrt{5}} + \frac{3}{2} \\
0 & 0 & 1 & -\frac{11}{2\sqrt{5}} + \frac{3}{2}
\end{array}
\right)
$$
So this gives
$$
S_n = -2 +
\frac{3+11/\sqrt{5}}{2} \left(\frac{1 + \sqrt{5}}{2}\right)^n +
\frac{3-11/\sqrt{5}}{2} \left(\frac{1 - \sqrt{5}}{2}\right)^n
$$

A: Just rewrite it as $S_{n+2} + a = S_{n+1} + a + S_{n} + a$
What is $a$? Apparently $a = 2$ in your example.
Now put: $T_n = S_n + 2$.
You get: $T_{n+2} = T_{n+1} + T_{n}$
This is a linear recurrence relation.
From here you can find the characteristic polynomial, and its roots $x_1$
and $x_2$ (in this case these are the golden ratio and its conjugate).
The general solutions is then:
 $T_{n} = C_1 . x_1^n + C_2 . x_2^n$
Now you just have to find the constants $C_1$ and $C_2$.
For doing this use what you know about $T_0$ and $T_1$,
build a system and solve it for $C_1$ and $C_2$.

A: The key point is: consider the sequence $$R_n:=S_n+2$$
then $R_{n+2}=R_{n+1}+R_n$ and you have a Fibonacci-type recurence (the standard Fibonacci is for $R_1=R_2=1$). Apply the standard method of solving linear recurrences (just google for "method of solving linear recurrences")


text:
Q: Saving an image from PIL results in image which is totally different from the original I'm trying to hide text inside an image and using PIL to save the encoded image from the neural network with embeds the data into the image.
https://futureboy.us/stegano/compinput.html
I'm using this site to compare difference between the original image and the one which is encoded.
When I used opencv2 to save the image and compared the output on the website I mentioned it shows very less difference but when I used PIL to save the image it results in image which is very dim and comparing the original image and output shows all the pixel values have been changed.

import numpy as np
from tensorflow.keras.layers import *
from tensorflow.keras.losses import *
from tensorflow.keras.callbacks import *
from tensorflow.keras.models import *
from tensorflow.keras.metrics import *
from tensorflow.keras.preprocessing.image import img_to_array, load_img, array_to_img
import cv2
import matplotlib
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
from PIL import Image

def rand_img(size):
    return np.random.randint(0, 256, size) / 255.0

def rand_sentence(len, max):
    return np.random.randint(0, max, len)

def onehot(sentece, max):
    onehot = np.zeros((len(sentece), max))
    for i, v in enumerate(sentece):
        onehot[i, v] = 1
    return onehot

def data_generator(image_size, sentence_len, sentence_max_word, batch_size=32):
    while True:
        x_img = np.zeros((batch_size, image_size[0], image_size[1], image_size[2]))
        x_sen = np.zeros((batch_size, sentence_len))
        y_img = np.zeros((batch_size, image_size[0], image_size[1], image_size[2]))
        y_sen = np.zeros((batch_size, sentence_len, sentence_max_word))
        for i in range(batch_size):
            img = rand_img(image_size)
            sentence = rand_sentence(sentence_len, sentence_max_word)
            sentence_onehot = onehot(sentence, sentence_max_word)
            x_img[i] = img
            x_sen[i] = sentence
            y_img[i] = img
            y_sen[i] = sentence_onehot
        yield [x_img, x_sen], [y_img, y_sen]

def get_model(image_shape, sentence_len, max_word):
    input_img = Input(image_shape)
    input_sen = Input((sentence_len,))
    embed_sen = Embedding(max_word, 100)(input_sen)
    flat_emb_sen = Flatten()(embed_sen)
    flat_emb_sen = Reshape((image_shape[0], image_shape[1], 1))(flat_emb_sen)
    trans_input_img = Conv2D(20, 1, activation="relu")(input_img)
    enc_input = Concatenate(axis=-1)([flat_emb_sen, trans_input_img])
    out_img = Conv2D(3, 1, activation='relu', name='image_reconstruction')(enc_input)
    decoder_model = Sequential(name="sentence_reconstruction")
    decoder_model.add(Conv2D(1, 1, input_shape=(100, 100, 3)))
    decoder_model.add(Reshape((sentence_len, 100)))
    decoder_model.add(TimeDistributed(Dense(max_word, activation="softmax")))
    out_sen = decoder_model(out_img)
    model = Model(inputs=[input_img, input_sen], outputs=[out_img,out_sen])
    model.compile('adam', loss=[mean_absolute_error, categorical_crossentropy],
                  metrics={'sentence_reconstruction': categorical_accuracy})
    encoder_model = Model(inputs=[input_img, input_sen], outputs=[out_img])
    #return model, encoder_model, decoder_model
    return model, encoder_model, decoder_model

def ascii_encode(message, sentence_len):
    sen = np.zeros((1, sentence_len))
    for i, a in enumerate(message.encode("ascii")):
        sen[0, i] = a
    return sen

def ascii_decode(message):
    return ''.join(chr(int(a)) for a in message[0].argmax(-1))

def main():
    image_shape = (100, 100, 3)
    sentence_len = 100
    max_word = 256
    gen = data_generator(image_shape, sentence_len, max_word, 64)
    model, encoder, decoder = get_model(image_shape, sentence_len, max_word)
    try:
        model.load_weights("best_weights.h5")
    except:
        model.fit(gen, epochs=512, steps_per_epoch=400, callbacks=[
            ModelCheckpoint("best_weights.h5",monitor="loss",verbose=1,save_weights_only=True,save_best_only=True)])
    print(model.summary())
    img = np.expand_dims(img_to_array(load_img("img.jpg")) / 255.0, axis=0)
    x = input("Enter sentence:\n")
    sen = ascii_encode(x, sentence_len)
    y = encoder.predict([img, sen])
    x = np.reshape(y,(100,100,3))
    #img = cv2.cvtColor(x, cv2.COLOR_BGR2RGB)
    img = x
    '''out = array_to_img(x)
    out.save("out.jp2")'''
    cv2.imshow("img",img)
    #rescaled = (255.0 / img.max() * (img - img.min())).astype(np.uint8)
    rescaled = (img/img.max()*255).astype(np.uint8)
    im = Image.fromarray(rescaled)
    im.save('out.png')
    cv2.waitKey(0)
    y = np.expand_dims(img_to_array(load_img("out.png")) / 255.0, axis=0)
    y_hat = decoder.predict(y)
    print(ascii_decode(y_hat))

if __name__ == "__main__":
    main()


text:
Q: I have a bunch of data and I need a data filter using Grails I am trying to make a filter for my data so other people can see it, lets say I have a bunch of Events, like a calendar, and I want to see all that have a name or title with the word "Soccer".
I've been trying to figure out how to do it but nothing works for me, I also tried to use  filterPane plugin but did not work quite as well and I prefer to write something myself and maybe upload it to the Grails plugins webpage for future references,
Any help would be greatly appreciated.

A: If it's in a domain class try:
def matches = Book.findAllByTitleLike("wonderful")

of if you don't want to worry about upper/lower case:
def matches = Book.findAllByTitleILike("wonderful")

If your book titles are in a collection:
def books = ['Wonderful Tonight', 'Atlas Shrugged', 'A Tale of Two Cities']
def matches = books.findAll{it.indexOf("wonderful") > -1} // returns []
matches = books.findAll{it.indexOf("Wonderful") > -1} // returns ['Wonderful Tonight']
matches = books.findAll{it.toLowerCase().indexOf("wonderful") > -1} // returns ['Wonderful Tonight']

Update:
So now that we have a more complete description of your problem, let's figure out a simplified way to solve it.
Today, you want to search by event title and its date so we'll start there then look at how we might generalize this and make more complete solution down the road.
Our general flow is going to be something like:

*

*You display a search form to your user

*User enters a date and/or title to search for and submits the form

*You find the matching entries

*You display the matching entries to the user

First, let's create a view for the search form, in grails-app/views/entry/ create a file called search.gsp with the following content:
<g:form controller='entry' action='searchResults'>
   Entry Title: <g:textField name="title" value="${title}" />
   Entry Date: <g:datePicker name="day" value="${day}" precision="day" />
   <g:submitButton name="submit" value="Search" />
</g:form>

Next, we'll create the controller.  In grails-app/controllers/ create a new controller EntryController.groovy.  You can do this by executing the 'grails create-controller Entry' if you don't already have the EntryController created.
Now, we'll create two controller closures:
def search = {
  render(view:'search')
}

and
def searchResults = {
  def entryCriteria = Entry.createCriteria()
  def results = entryCriteria.list {
    if(params?.title) {
      ilike{"title","%${params.title}%"
    }
    if(params?.day) {
      eq("eventDate", params.day)
    }
  }
  render(view:'searchResults', model:['results':results])
}

Finally, let's create a searchResults.gsp in grails-app/views/entry

Results

<g:each in=${results}>
  ${it}
</g:each>

So, now putting it all together:

*

*Run your app and go to localhost:8080/${appName}/entry/search, and that should bring up your search form.

*Enter a title and/or date, submit the form and that should send your form data into the searchResults closure in your controller

*The criteria search in the closure will find all the Entries that match your search criteria

*You render the search results view and pass it your matching entries, then on the gsp we loop through each of the results and display it.

As a disclaimer, I'm writing this code on the fly in the stack overflow text editor, so I won't be surprised if there are a couple syntax issues that I missed.  Hopefully the explanation will be enough to get you on your way.  Now let's talk about taking this basic example and polishing it up to a more respectable solution.
I would recommend you try to do the following after you get the hang of this basic example:

*

*Try building a command object to represent your search form, it will allow you to validate your user's input and is a more manageable approach than dealing directly with the request parameters like I did above.

*Build some unit tests for your command object and the controller flow; check that error messages are being populated for your various validations.

*Take the criteria search that we have defined in the searchResults closure, and move it out to a separate Grails Service, pass your command search object to the service to get your results.  Then, you can re-use the search functionality if you need it else where in your application later.

*Build some unit tests for your service; mock out the Entry domain object and verify that your search functionality is working correctly.

If you're struggling to get the above solution to work, try to simplify it even further.  Eliminate the date search and just search by title.  Replace all the criteria logic in the searchResults action with:
def results = Entry.findByTitleILike(params?.title)

Start simple and improve and you'll get the hang of it in no time.
Good Luck!

A: You could query by example or use the findAllWhere if you only need to filter by equality. Otherwise you will need to use the criteria builder to generate the appropriate query.

A: The filter plugin seems to meet your requirements.


text:
Q: AJAX response not obtained I am working on page where I am sending AJAX request on click of radio button. Three radios are there to list out users which are 'Unapproved', 'Approved' and 'All'. Based on the radio selection I want to show there respective data in a table. Currently I am not getting the response from the requested page in AJAX function. I will be highly thankful and appreciating any help.
My code,

And now my approval_ajax.php
   <?php

session_start();

require("../includes/config.php");
require("../classes/Database.class.php");
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);

$return_arr = array();
$status='';

   if($_SERVER['REQUEST_METHOD'] == 'POST')
   {
       $value = filter_input(INPUT_POST, "selected_value");

       if (isset($value))
       {
         $users=$value;

}else{
    $users='';
}

switch ($users)

{

case "all":
  $sqlQuery = "SELECT * FROM tbl_user WHERE type =3";

break;

case "approved":
  $sqlQuery = "SELECT * FROM tbl_user WHERE type =3 AND status =1";
break;

case "unapproved":
  $sqlQuery = "SELECT * FROM tbl_user WHERE type =3 AND status =0";

break;

}

$sq = $db->query($sqlQuery);

if ($db->affected_rows > 0) {

while ($row = mysql_fetch_array($sq)) {
    $disabled = '';
    if ($status == '1') {

        $disabled = "disabled = 'disabled' checked='checked' ";
    }

    $id = $row['id'];
    $email = $row['email'];
    $employee_id = $row['employee_id'];
    $first_name = $row['first_name'];
    $middle_name = $row['middle_name'];
    $last_name = $row['last_name'];
    $mobile = $row['mobile'];
    $created_on1 = $row['created_on'];
    $created_on = date("d-m-Y", strtotime($created_on1));

    $return_arr[] = array("id" => $id,
    "email" => $email,
    "employee_id" => $employee_id,
    "first_name" => $first_name,
    "middle_name" => $middle_name,
    "last_name" => $last_name,
    "mobile" => $mobile,
    "created_on" => $created_on
    "disabled" => $disabled
    );
}
}
header('Content-Type: application/json', true, 200);
echo json_encode($return_arr);

}

A: You have a syntax error in the $return_arr array. You should have a comma on the created_on => value. Modify the array to this
$return_arr[] = array("id" => $id,
    "email" => $email,
    "employee_id" => $employee_id,
    "first_name" => $first_name,
    "middle_name" => $middle_name,
    "last_name" => $last_name,
    "mobile" => $mobile,
    "created_on" => $created_on,
    "disabled" => $disabled

Also please do not use mysql_* functions. Either use mysqli_* or pdo


text:
Q: How can I get Orientation Scale Position information of keypoints in OPENCV implementation? I only can get image features form MAT file, but I also want some other information such as positions, orientation and scale. How can I get these information, could anyone offer its code? Thank you in advance.

A: The output of feature detection is a std::vector<cv::KeyPoint>, where every keypoint contain:

*

*Point2f pt: coordinates of the keypoint

*float size: diameter of the meaningful keypoint neighborhood

*float angle: computed orientation of the keypoint (-1 if not applicable). Its possible values are in a range [0,360) degrees. It is measured relative to image coordinate system (y-axis is directed downward), ie in clockwise.

*float response: the response by which the most strong keypoints have been selected. Can be used for further sorting or subsampling

*int octave: octave (pyramid layer) from which the keypoint has been extracted

*int class_id: object id that can be used to clustered keypoints by an object they belong to


text:
Q: DependencyInjection cannot find the assembly I have a two dlls WebApp and MyUtils.EntityFramework they are both in the same directory and WebApp references MyUtils.EntityFramework.
This is how WebApp looks
public class Program
{
    public static void Main()
    {
        var appServiceProivder = new ServiceCollection()
            .AddDbContext<DerivedContext1>()
            .BuildServiceProvider();

        using (var serviceScope = appServiceProivder
            .GetRequiredService<IServiceScopeFactory>()
            .CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetService<DerivedContext1>();

            Debug.Assert(context.GetService<IDbContextOptions>()
                .GetType() == typeof(DbContextOptions<DerivedContext1>));
        }
    }
}

[DbSchema("test")]
public class DerivedContext1 : DbContext
{
    public DerivedContext1(DbContextOptions options) : base(options) { }

    protected override void OnConfiguring(DbContextOptionsBuilder builder)
    {
        builder.UseSqlServer("secret connection string");
        builder.ReplaceService<IHistoryRepository,
            MigrationHistoryRepository<DerivedContext1>>();
    }
}

this is how MyUtils.EntityFramework looks
public class DbSchemaAttribute : Attribute
{
    public DbSchemaAttribute(string name)
    {
        Name = name;
    }

    public string Name { get; private set; }
}

public class MigrationHistoryRepository<TDbContext>
    : SqlServerHistoryRepository where TDbContext : DbContext
{
    public MigrationHistoryRepository(HistoryRepositoryDependencies dependencies)
        : base(dependencies)
    {
    }

    protected override string TableName { get { return "migration_history"; } }

    protected override string TableSchema
    {
        get
        {
            var dsSchemaAttr = typeof(TDbContext)
                .GetCustomAttributes(typeof(DbSchemaAttribute), true)
                    .SingleOrDefault() as DbSchemaAttribute;

            if (dsSchemaAttr != null)
                return dsSchemaAttr.Name;

            return null;
        }
    }

    protected override void ConfigureTable(EntityTypeBuilder<HistoryRow> history)
    {
        base.ConfigureTable(history);

        history.HasKey(h => h.MigrationId).HasName($"{TableName}_pkey");
        history.Property(h => h.MigrationId).HasColumnName("id");
        history.Property(h => h.ProductVersion).HasColumnName("product_version");
    }
}

and this is the error I get because of this line
builder.ReplaceService<IHistoryRepository, MigrationHistoryRepository<DerivedContext1>>();

bin output contains both dlls so I don't understand what the problem is (I'm using fedora 33)
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Microsoft.EntityFrameworkCore.dll: 'Could not load file or assembly 'MyUtils.EntityFramework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.'
   at WebApp.DerivedContext1.OnConfiguring(DbContextOptionsBuilder builder) in /src/api/Program.cs:line 92
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
   at Microsoft.EntityFrameworkCore.Infrastructure.Internal.InfrastructureExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
   at WebApp.Program.Main() in /src/api/Program.cs:line 78

A: It's because efcore utils is compiled multiple times, here is more detail How to organize multiple git packages in dotnet core


text:
Q: How to share images that are not stored on device? I have a application where i convert the text coming from user into a QR code and display the QR code in imageView. My problem is how can i use sharing Intent on this image as their no path specified for it nor the image is stored anywhere ?

A: You can do it by saving the bitmap of image in cache followed by sharing it.
//To get the bitmap from Imageview
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();

//To share it via Intent**
try {
    File file = new File(getContext().getCacheDir(), fileName + ".png");
    FileOutputStream fOut = new FileOutputStream(file);
    bitmap.compress(CompressFormat.PNG, 100, fOut);
    fOut.flush();
    fOut.close();
    file.setReadable(true, false);
    final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
    intent.setType("image/png");
    startActivity(intent);
} catch (Exception e) {
    e.printStackTrace();
}


text:
Q: Changing an image in a listview I'm using the tutorial code at http://redth.info/2010/10/12/monodroid-custom-listadapter-for-your-listview and after modifying the code so that it builds under monodroid 4.2.3, I've extended it so that the list class looks like this
public class Animal
    {
        public string Name
        {
            get;
            set;
        }
    public string Description
    {
        get;
        set;
    }

    public int Image
    {
        get;
        set;
    }

    public int ImageCheck
    { get; set; }

    public bool Checked
    { get; set; }
}

With the ItemClick event code looking like this
// ViewGroup parent = listView;

    void listView_ItemClick(object sender, Android.Widget.AdapterView.ItemClickEventArgs e, ViewGroup parent)
    {
        var item = this.listAdapter.GetItemAtPosition(e.Position);
        var view = (e.View ?? this.LayoutInflater.Inflate(Resource.Layout.customlistitem, parent, false)) as LinearLayout;
        ImageView iv = FindViewById<ImageView>(Resource.Id.imageChecked);
        if (item.Checked == false)
        {
            item.Checked = true;
            item.ImageCheck = Resource.Drawable.@checked;
        }
        else
        {
            item.Checked = false;
            item.ImageCheck = Resource.Drawable.checkbox;
        }
        iv.SetImageResource(item.ImageCheck);
    }

While this works in so far as if I add in
Console.WriteLine("Animal clicked = {0}", item.Name);

the emulator output will show the name of the animal clicked, the ImageView is always at the top of the list.
Is there a way to have the tick in the correct place (so for example, if I click on the 5th item. the 5th ImageView shows a tick or just a box)?
Thanks

A: Simplest way
ImageView iv = e.View.FindViewById<ImageView>(Resource.Id.imageChecked);

Job done!


text:
Q: Is it possible to style an iFrame I'm working in ServiceNow and have created a simple donut chart using Reports basically showing percentage of tasks completed.  I want to pull this into my portal page's dynamic block and style it (i.e. mess around with the sizing, give it a background color).  Is this possible?  I know I can pull the report in via iFrame, but is there any flexibility there in terms of formatting?
Thanks!

A: In order to style an iframe, you will need to have access to whatever is generating it, just like with any other web document.
An iframe is a different (child) document loading inside a designated area of your parent one.
Mainly as a precaution against cross-frame scripting, communication between the iframe and the parent is disabled by default but can be enabled if the child document allows it. With this communication closed, responsiveness becomes a major issue.
Note it is possible for a page to check if it is rendered inside an iframe and forbid it (refuse to render) or display a nasty custom message informing the visitor it doesn't belong there.
Also, please note iframes should be avoided for accessibility reasons, as many handheld devices display them awkwardly and some don't display the iframe contents at all.

A: One and only rule to be able to style your iframe or have any way of control over it is
Your webpage and the iframe both have to be under same domain
Else there is no way you can do it. The browser restricts you from doing so. Its a security standard followed by all the browser's.