text:
Q: the prediction function gives the same output everytime from keras.datasets import mnist
from keras.models import Sequential, load_model
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras.preprocessing import image
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import cv2
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.reshape((X_train.shape[0], 28, 28, 1)).astype('float32')
X_test = X_test.reshape((X_test.shape[0], 28, 28, 1)).astype('float32')
X_train = X_train / 255
X_test = X_test / 255
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
def larger_model():
    model = Sequential()
    model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation='relu'))
    model.add(MaxPooling2D())
    model.add(Conv2D(15, (3, 3), activation='relu'))
    model.add(MaxPooling2D())
    model.add(Dropout(0.2))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dense(50, activation='relu'))
    model.add(Dense(num_classes, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model
model = larger_model()
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200)
scores = model.evaluate(X_test, y_test, verbose=0)
print("Large CNN Error: %.2f%%" % (100-scores[1]*100))

model.save('good_model.h5')
print("Model saved")

After running this code, we get a '.h5' model, then to predict this image
i added this code:
import cv2
model = load_model('good_model.h5')
file = cv2.imread('screenshot.png')
file = cv2.resize(file, (28, 28))
file = cv2.cvtColor(file, cv2.COLOR_BGR2GRAY)
file = file.reshape((-1, 28, 28,1))
result = model.predict(file)
print(result[0])
t = (np.argmax(result[0]))
print("I predict this number is a:", t)

But I always get the same answer which is 4. above I tried to load the image with cv and convert it to gray and then reshape to the size of the input. It takes the input correctly but the answer is always the same no matter what image I give it as input

A: You need to invert the image before prediction. Once you invert the image, it will predict correctly. The given example is predicting as "2" but I checked with other images such as "7" and it is correctly predicting.
file = cv2.bitwise_not(file)

Other than the above, I made one change. I imported modules from Tensorflow 2.x. Please check the full code here.


text:
Q: MQL5 reversing the array gives error I am trying to copy the stochastic function buffers in the variables. But what I see is that the candles are copied in the array in descending order.
double KArray[],DArray[];
ArraySetAsSeries(KArray,true);
ArraySetAsSeries(DArray,true);
int stochastic_output = iStochastic(_Symbol,PERIOD_M1,5,3,3,MODE_SMA,STO_LOWHIGH);
CopyBuffer(stochastic_output,0,0,15,KArray);

CopyBuffer(stochastic_output,1,0,15,DArray);
for (int i=0;i < Candles_backtest_Stochastic_quantity;i++)
{
PrintFormat("K %d:  %f",i,KArray[i]);
PrintFormat("D %d:  %f",i,DArray[i]);

}

This works well and while printing the array values I am getting the 0th as the current value and the previous values later.
2018.03.22 18:07:23.622 2018.02.01 00:00:00   K 0:  57.291667
2018.03.22 18:07:23.622 2018.02.01 00:00:00   D 0:  63.194444
2018.03.22 18:07:23.622 2018.02.01 00:00:00   K 1:  61.458333
2018.03.22 18:07:23.622 2018.02.01 00:00:00   D 1:  68.754756
2018.03.22 18:07:23.622 2018.02.01 00:00:00   K 2:  70.833333
2018.03.22 18:07:23.622 2018.02.01 00:00:00   D 2:  69.294286
2018.03.22 18:07:23.622 2018.02.01 00:00:00   K 3:  73.972603
2018.03.22 18:07:23.622 2018.02.01 00:00:00   D 3:  57.177428
2018.03.22 18:07:23.622 2018.02.01 00:00:00   K 4:  63.076923

And so on.
But I want to have a reversed array, i.e. the 14th array element must be the 0th and the 0th must be the 14th element of the array.
I tried to make the CopyBuffer() statement to reverse the buffer, but got error, see the example:
2018.03.22 18:11:11.957   Total_back_lagANDvantage_required=3
2018.03.22 18:11:12.073 2018.02.01 00:00:00   K 0:  78.260870
2018.03.22 18:11:12.073 2018.02.01 00:00:00   D 0:  72.579331
2018.03.22 18:11:12.073 2018.02.01 00:00:00   array out of range in 'adxSTUDY.mq5' (173,33)
2018.03.22 18:11:12.073 OnTick critical error
2018.03.22 18:11:12.087 EURUSD,M1: 1 ticks, 1 bars generated. Environment synchronized in 0:00:00.312. Test passed in 0:00:00.594 (including ticks preprocessing 0:00:00.016).
2018.03.22 18:11:12.087 EURUSD,M1: total time from login to stop testing 0:00:00.906 (including 0:00:00.312 for history data synchronization)

Kindly, help me. I do not want to have another buffer to copy the array and reverse it, Is there a way through which I can reverse the array and use it?

A: Use the ArraySetAsSeries function. In your case it will be
ArraySetAsSeries(KArray,false);

A:
I do not want to have another buffer to copy the array and reverse it.

Right, each copy is expensive in two dimensions - in [TIME]-domain  and in [SPACE]-domain. There is for sure better way to avoid any copy to ever take place, for both of these reasons.

There are two principal approaches:
A )
the internal, native MetaTrader Terminal / MQL5 modus operandi, which uses a sort of flag to indicate a reversed-time-stepping addressing on TimeSeries data, where [0] is being always the "NOW" - so changing the flag changes from native-addressing to "natural"-addressing, where [0] is a statically oldest ever cell, but the "NOW"'s address keeps creeping as time is moving forwards. This is the fastest method, yet requires designer to keep attention in which mode the access is set ( uses an On-Off-FSA ).
B )
a proxy-mode, where one can use an access function, which internally translates the access mode without having to pay attention to FSA-state.
Using class-based proxy became even easier way to go in proxy-based operation, as more class-methods allow for designing iterators and other tools, re-using the concept of autonomous proxy-abstracted details and prevent user from "damaging" the state of proxy-abstracted operations and fall outside of proper addressing in either of the actual array[]'s native-states.
B)-is not any slower than A), yet very handy to use, as one can stop remembering in what native-state the array[] has been left by the last operation, so a comfortable ( similarly if array[]-s get used for emulations of stack-based ops and other higher-level of abstraction data-structures in MQL4/5 domains ).

redpajama_set_name: RedPajamaStackExchange


text:
Q: xserver not using hotplug keyboard and mouse I'm using a Linux desktop. My own customized distro, using debian packages, but no systemd stuff.
The problem is if I re-plug the USB keyboard or mouse, the X will not respond to them anymore. unless I kill xinit process then startx again.
Also if I plug a second keyboard or mouse, them will not be used automatically by X.
More information, the /dev is handled correctly. Because dbus-daemon --system and /lib/systemd/systemd-udevd are in the ps list. And evtest will work correctly on the hot-plug/re-plug mouse or keyboard.
So I think the problem is laying on the part of how the X using these input devices as it's input.
My question is  what software or module doing the absent work?
Any workaround automatically or manually to adding /dev/input/event* to be used by X is acceptable.
Thank you.


text:
Q: How to make page numbers to plain numbers in scrlttr2? I wrote a letter with multiple pages in scrlttr2. Now I get the page numbers "Seite 2" and so on, but I simply want "2" there.
I don't find an option how to turn this off, neither in the scrguide.pdf nor in the source code. This reproduces the error (I use lyx, but that doesn't matter):
\documentclass[ngerman,fromrule=off,addrfield=on,backaddress=off,fromalign=left,enlargefirstpage=off]{scrlttr2}
\usepackage[latin9]{inputenc}
\usepackage[a4paper]{geometry}
\usepackage{blindtext}
\geometry{verbose}
\pagestyle{plain}

\makeatletter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands.
\newif\ifletterclosed
\AtEndDocument{\ifletterclosed\else\end{letter}\fi}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.

\pagenumbering{roman}

\makeatother

\usepackage{babel}
\begin{document}

\setkomavar{fromaddress}{from me}

\begin{letter}{to adress}

\setkomavar{date}{today}

\setkomavar{subject}{spam}

\begin{letter}{}
\LoadLetterOption{DIN}
\makeatletter
%\@setplength{refvpos}{4cm}
%\@setplength{subjectaftervskip}{1cm}
\makeatother

\opening{Dear stranger,}

\Blindtext

\closing{Bye}

\setkomavar{signature}{My name}

\end{letter}
\end{document}

Commenting \LoadLetterOption{DIN} doesn't help. I don't see any further options that might be related to page numberings.

A: You have to redefine the \pagemark command:
\renewcommand\pagemark{\usekomafont{pagenumber}\thepage}

Additional remarks:
The letter-class-option file DIN is loaded by scrlttr2 automatically.
I do not understand why you are nesting letter environments and why you are closing the outer letter environment using \AtEndDocument. So in the following MWE there is only one letter environment:
\documentclass[ngerman,backaddress=off,fromalign=left]{scrlttr2}
\usepackage[latin9]{inputenc}
\usepackage[a4paper,verbose]{geometry}
\usepackage{babel}

\pagenumbering{roman}
\renewcommand\pagemark{\usekomafont{pagenumber}\thepage}

\usepackage{blindtext}% dummy text
\begin{document}

\setkomavar{fromaddress}{from me}
\setkomavar{signature}{My name}
\setkomavar{date}{today}
\setkomavar{subject}{spam}

\begin{letter}{to adress}

  \opening{Dear stranger,}
  \Blindtext
  \closing{Bye}
\end{letter}
\end{document}


text:
Q: Is there a way to automatically remove trailing spaces in Eclipse? Is there a way to automatically remove trailing spaces in Eclipse?
I see there are nice functionality in Source like Correct Indentation and Format.
But they dont remove trailing spaces.
Thanks
PS: What other functionalities of this kind you use to make the code nicer?

A: It's available as a Save action, at least. (I can't see it under the formatter options.)
Go to Window / Preferences, Java / Editor / Save Actions. Tick "Additional Actions" and click on Configure. In the "Code Organizing" tab, the first option is "Remove trailing whitespace".
Note that this will remove all trailing whitespace from Java files - not just those you've touched. If you're working with people who don't remove trailing whitespace, this can be messy in terms of later doing a diff.

A: You can easily remove all the trailing whitespace within a single file by using a regular expression with the Find/Replace dialog. Enter [ \t]+$ in the "Find:" box and leave the "Replace with:" box empty. Check the "Regular expressions" option then click "Replace All"

A: There is also the plugin "AnyEdit" from http://andrei.gmxhome.de/eclipse/.
This tool removes the whitespace in every file type on save.


text:
Q: Bug with the vote limit notification The bug here is the notification !
I must confess.
I upvoted this post up when I reached my daily vote limit.
Before the crime :

During the crime :

After the crime (refreshed):

You can go and see for yourself. It is still there.


text:
Q: PyCharm cannot find existing Matplotlib installation or install new one I am trying to run and debug Python scripts with PyCharm that use Matplotlib plots. However I can't do either because PyCharm can't find my existing Matplotlib installation, and fails to download and install it's own version when I try to install Matplotlib through the settings/package manager interface.
However, I already have Matplotlib installed on my computer, and when I run the script through terminal, everything works just fine.
So my question is, how can I either:

*

*Successfully install Matplotlib through PyCharm or

*Direct PyCharm to my existing Matplotlib installation

System versions

*

*OS: Ubuntu 14.04

*Python: 3.7.0 (3.4 also installed)

*Pip: 18.1 from /usr/local/lib/python3.4/dist-packages/pip (python 3.4)

*Pip3: 18.1 from /home/matt/anaconda3/lib/python3.7/site-packages/pip (python 3.7)

*Matplotlib: 3.0.2

*PyCharm: PyCharm community v 2018.3.1

*PyCharm interpreter: Python 3.7

Error when installing Matplotlib through PyCharm
Collecting matplotlib==3.0.2
  Could not fetch URL https://pypi.org/simple/matplotlib/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/matplotlib/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
  Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/matplotlib/
  Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/matplotlib/
  Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/matplotlib/
  Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/matplotlib/
  Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/matplotlib/
  Could not find a version that satisfies the requirement matplotlib==3.0.2 (from versions: )
No matching distribution found for matplotlib==3.0.2
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.

A: Ubuntu 14.04 doesn't include OpenSSL 1.0.2 or higher, which is now required by Python 3.7. This means the ssl module of python will not be built in. Without the ssl module pip is unable to download packages from the repositories.
If you configure pycharms to use your system version of python (3.4) which is what will be used by the terminal you should be fine to get matplotlib.
My recommendation would be to upgrade to 16.04 or later.


text:
Q: Why can't I add this custom Node PATH to /etc/profile.d scripts? I may have a problem in the include chain for the profiles, or something may be awry in either my system, or my understanding of profile.d (RHEL7).
I added a /etc/profile.d .sh script which is for a node installation, whilst trying to clean up the .bashrc.  The problem is that it is not appending to the $PATH like I had hoped.
Note, the issue is happening both via my main terminal (ssh via putty), but also directly from the console itself as well.
$ cat ~/.bash_profile
#
# .bash_profile
#
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

$ cat /etc/profile.d/nvm_path.sh
# This adds node/nvm(node version manager) to path, and then initializes nvm, and its bash completion

#Load NVM
if [ -f ~/.nvm ]; then

    export NVM_DIR="$HOME/.nvm"
    [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"

    if [ -f $NVM_DIR/bash_completion ]; then

        [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion
    fi
fi

# Force npm onto the path (only needed if its not available on your node installation)
if [ -f ~/.npm/ ]; then
    PATH=$PATH:$HOME/.npm
fi

# Include node_mod bins in PATH, which are usually symlinked here (gulp,
# cordova, etc..)
if [ -f $HOME/.npm-packages/bin ]; then

    #note is a hyphen, not an underscore
    PATH=$PATH:$HOME/.npm-packages/bin
fi

export PATH

For /etc/profile itself, its my understanding the perms are ok as read-only since they are sourced, as opposed to executed, so i think this isnt an issue. -rw-r--r--. 1 root root 1795 May  4  2016 profile
What have i missed?
I'm thinking the problem is somewhere along the lines of since the scripts are initially loaded by root the paths are invalid.  The problem: where I try to load the user paths.  What can be done about this?  Do I need to add in a $LOGGED_USER variable in place of if [ -f ~/.nvm ] and maybe even $HOME?  What is that variable?
After further research, it appears the problem is that root is loading the script, so $HOME, even $USER, is never available, even if I set a condition in there to check if root is loading or not, since root is always sourcing the script.
e.g.
if [[ $EUID -ne 0 ]]; then
    USERDIR=$HOME
else
    USERDIR=/home/$USER
fi

if [ -f $USERDIR/.nvm ]; then
#...

I would need to have the var check happen once the user logs in, not when root sources it.
It appears something like this is destined for /etc/skel/.bash_profile, unless someone comes up with a clever bash script idea. Any ideas on how to accomplish this here, so that I don't have to use /etc/skel?


text:
Q: How to handling incoming sms when app is active I'm developing an iOS app that sends sms. What's the best way to handle a incoming message when the app is active. Is this done automatically or do I have to code for this in my app via the
applicationWillResignActive:(UIApplication *)application

method?

A: You don't need to/shouldn't need to deal with incoming SMSs.
When the device receives an SMS (or an iMessage these days), then the user will be notified by their method of choice. They may leave your application via that notification, but you cannot determine that it was the SMS that caused it.
CoreTelephony provides some abilities for people to deal with Calls, but nothing to do with SMS. Sorry. As such your app cannot determine the state of SMS messages. You're able to send SMS messages because the OS provides you with a view controller to do so, but you can't do anything else with them.


text:
Q: Using recycled components To what extent and which components can be salvaged from 5-15 years old electronic devices? In other words, what is feasible to dismantle for hobbyist use and what is not? Especially, is it ok to reuse surface-mounted ICs?
My own experience tells, that resistors, transistors, small capacitors survive quite well, but I am not sure about small diodes, small and surface-mounted electrolytic capacitors, crystals. Also, I have bad experience with recycling connectors (pins get out of plastic case).
Somewhat related, how to check non-trivial components? Do some of them loose precision a lot?
Maybe, there is some specialized web resource on the topic and or guides.
UPDATE: I am really interested in an answer from persons, who had more or less extensive practical experience with recycling different kinds of components. Personally I do not recall anything failed because of thermal impact of desoldering (but I have no experience with SMDs). And this makes this question even more interesting, because answers so far are discouraging the practice.

A: So much of this depends on the quality of your desoldering technique.  I have personally found that, when it comes to removing components, very short exposure to high heat is preferable to prolonged exposure to low heat.
   That being said, I would NEVER re-use an aluminum electro - (if you MUST, at least check it with a reliable ESR meter first).  Film caps take desoldering well as long as the barrel of the iron is kept away from the cap's body.
Metal film and wirewound resistors can reliably survive desoldering and keep their value within spec; carbon films and (especially) carbon comps will sometimes "open up" in value to a small degree - (sometimes this is acceptable, sometimes not; check them with an ohmmeter before using).
I've not had any problems desoldering diodes that are designed to take any degree of heat (such as DO-41's, DO-35's, DO-204's, etc.)  Also, these are usually mounted "off-the-board" slightly.  I've never bothered w/SMD diodes or small signal (1N914/1N4148) diodes as they're extremely cheap new.
But you asked about SMD chips in particular.  I can only impart my personal experience, which is as follows:
SOT's and SOIC's - Very doable, but having one of those threaded IC desoldering tips for your iron (which heats all pins simultaneously for easy removal) is a major plus.
SSOP's - Hit or miss.  I've had many successes (and a few failures), but I generally don't bother unless it's something I really need immediately.
QFP's/LCC's and the like:  Forget it!
Hope this helps.

A: I usually keep a couple of boards assembled as source for test parts, desoldering, measuring, sorting and labeling would be a huge waste of time.

A: Personally I wouldn't do it. Outside of stripping heatsinks and other hardware, you run the risk of transplanting heat or physically damaged components into the new circuit.
Perhaps socketed ICs are another exception.


text:
Q: Why Redis connection works from C# without specifying credentials? Why Redis connection works from C# without specifying credentials? I have this code working and connected to remote server. My client machine is windows and REMOTE-MACHINE is Linux server. Does this means anyone in my LAN can connect?
 public class RedisConnectorHelper
    {
        static RedisConnectorHelper()
        {
            RedisConnectorHelper.lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
            {
              return ConnectionMultiplexer.Connect("REMOTE-MACHINE");
            });
        }

        private static Lazy<ConnectionMultiplexer> lazyConnection;

        public static ConnectionMultiplexer Connection
        {
            get
            {
                return lazyConnection.Value;
            }
        }
    }

A: The default behavior of Redis allows it to accept connections without specifying any credentials to do so. If you want to change this then modify the Redis .conf file to configure it more to your liking. As far as your LAN question, I have no idea how your network is configured so I really can't answer that for you.

A: From the Redis Security page:

Redis is designed to be accessed by trusted clients inside trusted environments. This means that usually it is not a good idea to expose the Redis instance directly to the internet or, in general, to an environment where untrusted clients can directly access the Redis TCP port or UNIX socket.

Some very basic authentication with a password stored in the configuration file is provided but as the docs describe it, it provides a tiny layer of authentication.
Security has to be implemented at the network level with firewalls, port blocking, SSL. Redis itself doesn't provide SSL but you can use an SSL proxy, Cloud providers like Amazon and Azure for example, put an SSL proxy in front of their clusters.
Redis clients like StackExchange.Redis support SSL, eg by setting ssl=true in the connection string


text:
Q: main class jfx doesn't show anything Hello I'm very noob in javaFx, I have this main class,
when I start it from my eclipse, it doesn't show anything,
I have no error in log viewer, I strat it from run->runAs->java application, after selecting MainApp class.
public class MainApp extends Application {

    private Stage primaryStage;
    private BorderPane rootLayout;

    @Override
    public void start(Stage primaryStage) {
        this.primaryStage = primaryStage;
        this.primaryStage.setTitle("AddressApp");

        initRootLayout();

        showPersonOverview();
    }

    /**
     * returns the main stage.
     * @return
     */
    public Stage getPrimaryStage(){
        return primaryStage;
    }

    /**
     *
     * Initializes the root layout
     */
    public void initRootLayout() {
        // Load root layout from fxml file.
        try {
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(MainApp.class.getResource("view/RootLayout.fxml"));
            rootLayout = (BorderPane) loader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Show the person overview insiede the root layout
     */
    public void showPersonOverview() {
        try{
            //Load person overview
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(MainApp.class.getResource("view/PersonOverview.fxml"));
            AnchorPane personOverview = (AnchorPane) loader.load();

            // Set person overview into the center of root layout
            rootLayout.setCenter(personOverview);
        }
        catch (IOException e){
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        launch(args);
    }
}


text:
Q: Should multiple cities in publisher names, like "Amsterdam–New York", use en-dash or hyphen? Often, publishers list multiple cities in their address, like "Amsterdam–New York–London"; these appear very frequently in bibliographies.  Should these be typeset with an en-dash, or a hyphen, or is this style-dependent?
I can't find any style guides or typography guides mentioning this explicitly, and general rules for dash use seem to imply that en-dashes would be appropriate — it seems analogous to e.g. concatenating names of authors in a multi-author theorem.
On the other hand, most published papers seem to use hyphens, and major bibdata repositories (e.g. MathSciNet, DBLP) provide bibdata using hyphens for this.  But then again, you also find numerical page ranges given with hyphens in many such places, which is definitely not correct — so "common practice" (even in professional publishing) sometimes just reflects common errors, rather than established best practices.
Are there any authoritative guidelines on this point?


text:
Q: Why did drop down list cannot display value in browser when variable still keeps correct value after exception? My drop down list cannot display selected value for those correct and existing records after exception. I wonder if anyone can give me a hint about direction.
In our team's application, the front end is written in AngularJS. When user wants to add a new record and does not input a mandatory value for a field, he will encounter an exception due to a validation in back end written in Java.
Here is some code:
function save() {
    vm.saving = true;
    convertReferenceIdsToNum(vm.waivers);
    waiversService.post(vm.waivers).then(function (response) {
        if (response.importance.toLowerCase() !== 'failure') {
            messagesService.logSuccess("Waivers Updated", "Waivers Updated", null);
            initialize();
        }
        vm.saving = false;
    }).catch(function () {
        vm.saving = false;
    });
}

I expect that if the user input is invalid, the screen will return to original GUI that when user input, and those records that have exist should be displayed correctly.
I found my html code was like this for an existing record for vm.waivers, and none of value is selected:
<option value="?" selected="selected"></option>
<option label="8260.3B" value="string:5">8260.3B</option>

while I expect like this:
<option value="" class=""></option>
<option label="8260.3B" value="string:5" selected="selected">8260.3B</option>

and I found The if statement ( if (response.importance.toLowerCase() !== 'failure')) was never executed as exception directly jump to catch clause. vm.waiver keeps correct value for all items.


text:
Q: Save image file from Android I'm trying to save the image file from Android, but get an error. I have already added a read and write permissions to manifest. I'm trying to save the image file this way (the file path is like this "content://media/external/images/media/12"):
File source = new File(filePath);
blob.upload(new FileInputStream(source), source.length());

The error I get:
04-13 09:27:05.453 6947-7534/com.example.gaya.searchpeople W/System.err: java.io.FileNotFoundException: content:/media/external/images/media/12: open failed: ENOENT (No such file or directory)
04-13 09:27:05.453 6947-7534/com.example.gaya.searchpeople W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:452)
04-13 09:27:05.453 6947-7534/com.example.gaya.searchpeople W/System.err:     at java.io.FileInputStream.<init>(FileInputStream.java:76)
04-13 09:27:05.453 6947-7534/com.example.gaya.searchpeople W/System.err:     at com.example.gaya.searchpeople.PhotoInfoActivity$NetworkConnector.doInBackground(PhotoInfoActivity.java:103)
04-13 09:27:05.453 6947-7534/com.example.gaya.searchpeople W/System.err:     at com.example.gaya.searchpeople.PhotoInfoActivity$NetworkConnector.doInBackground(PhotoInfoActivity.java:75)
04-13 09:27:05.453 6947-7534/com.example.gaya.searchpeople W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
04-13 09:27:05.453 6947-7534/com.example.gaya.searchpeople W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-13 09:27:05.453 6947-7534/com.example.gaya.searchpeople W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
04-13 09:27:05.453 6947-7534/com.example.gaya.searchpeople W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
04-13 09:27:05.453 6947-7534/com.example.gaya.searchpeople W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
04-13 09:27:05.453 6947-7534/com.example.gaya.searchpeople W/System.err:     at java.lang.Thread.run(Thread.java:818)
04-13 09:27:05.453 6947-7534/com.example.gaya.searchpeople W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
04-13 09:27:05.453 6947-7534/com.example.gaya.searchpeople W/System.err:     at libcore.io.Posix.open(Native Method)
04-13 09:27:05.453 6947-7534/com.example.gaya.searchpeople W/System.err:     at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
04-13 09:27:05.453 6947-7534/com.example.gaya.searchpeople W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:438)
04-13 09:27:05.453 6947-7534/com.example.gaya.searchpeople W/System.err:    ... 9 more

A: That is not a file path. You have taken a Uri, turned it into a String, and are attempting to use it as a file path. This will not work.
Instead, call openInputStream() on a ContentResolver to get an InputStream on the content identified by your Uri.

A: Try to use this, it worked for me to get absolute file path from URI
public static String getAbsolutePath(final Context context, final Uri uri) {

final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
    final String docId = DocumentsContract.getDocumentId(uri);
    final String[] split = docId.split(":");
    final String type = split[0];

    if ("primary".equalsIgnoreCase(type)) {
        return Environment.getExternalStorageDirectory() + "/" + split[1];
    }

    // TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {

    final String id = DocumentsContract.getDocumentId(uri);
    final Uri contentUri = ContentUris.withAppendedId(
            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

    return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
    final String docId = DocumentsContract.getDocumentId(uri);
    final String[] split = docId.split(":");
    final String type = split[0];

    Uri contentUri = null;
    if ("image".equals(type)) {
        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    } else if ("video".equals(type)) {
        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
    } else if ("audio".equals(type)) {
        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    }

    final String selection = "_id=?";
    final String[] selectionArgs = new String[] {
            split[1]
    };

    return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {

// Return the remote address
if (isGooglePhotosUri(uri))
    return uri.getLastPathSegment();

return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}

 return null;
}

 public static String getDataColumn(Context context, Uri uri, String selection,
                            String[] selectionArgs) {

Cursor cursor = null;
final String column = "_data";
final String[] projection = {
    column
};

 try {
 cursor = context.getContentResolver().query(uri, projection, selection,
 selectionArgs,null);
  if (cursor != null && cursor.moveToFirst()) {
    final int index = cursor.getColumnIndexOrThrow(column);
    return cursor.getString(index);
}
} finally {
if (cursor != null)
    cursor.close();
}
 return null;
}

public static boolean isExternalStorageDocument(Uri uri) {
 return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

 public static boolean isDownloadsDocument(Uri uri) {
 return "com.android.providers.downloads.documents".equals(uri.getAuthority());
 }

 public static boolean isMediaDocument(Uri uri) {
 return "com.android.providers.media.documents".equals(uri.getAuthority());
 }

 public static boolean isGooglePhotosUri(Uri uri) {
 return "com.google.android.apps.photos.content".equals(uri.getAuthority());
 }


text:
Q: Is there a way to stop my :active button from displaying parent's hover effect on ::before/::after? When I click my button element with a class of .btn, the inside of the button displays the red bars on its top and bottom. I do not want this to be the behavior but can't figure out why this is the case.
As far as I can tell, I only have a hover effect on the parent element .project that displays its ::before and ::after pseudo elements (the same red bars I mentioned above). I want this to continue but just don't want the bars on the button when I click on it.
I have tried moving my :active pseudo class to various parts of my code to see if it may be a cascade issue, but it doesn't look like that's the case. I also placed the :active styles at the end of the code to make sure pseudo classes like :hover came before it (i believe if these were out of order there could be more issues). I even used the developer tools to force an active state (oddly enough the bars didn't show up then).

To-Do List App

This project demonstrates my understanding of HTML, CSS, and Javascript.

       <button class="btn btn--pos">Go to Project</button>

```CSS

    .projects {
      display: grid;
      grid-gap: .625em;
    }

    .project {
      position: relative;
      box-sizing: border-box;
      width: 100%;
      max-width: 400px;
      padding: 1.25em;
      border-radius: 10px;
      background: black;

      &:hover > ::before, &:hover > ::after {
       content: '';
       position: absolute;
       height: 10px;
       background: red;
       animation: fillin .3s linear forwards;
      }

      &:hover > ::before {
       top: 0;
       left: 0;
       border-top-left-radius: 10px;
      }

      &:hover > ::after {
       bottom: 0;
       right: 0;
       border-bottom-right-radius: 10px;
      }

      &__title {
       font: bold 1.5rem/1.4 serif;
       color: white;
       text-align: center;
       margin: 0;
      }

      &__description {
       font: 1rem/1.4 serif;
       color: white;
       text-align: center;
       margin: .625em;
      }
    }

    .btn {
      display: block;
      background: transparent;
      color: white;
      padding: 7px 30px;
      border: 1px solid white;
      border-radius: .625em;
      margin: 0 auto;
      transition: background .25s, color .25s;
      cursor: pointer;

      &:hover {
       background: white;
       color: black;
      }

      &:active {
       transform: translateY(4px);
      }
    }

    @keyframes fillin {
      from { width: 0; }
      to { width: 60%; }
    }

A: Just comment below lines from css code:
 &:active {
   transform: translateY(4px);
  }


text:
Q: Bootstrap Datetimepicker get time part as long I'm using BS Datetimepicker with Timeformat. My goal is to get the selected time, for example 8:30am, as a duration (long).
timepicker.data('DateTimePicker').date() returns a Moment, but this Moment also includes the Date dimension (current day), so if I then use Moment.valueOf() I'm not getting what I want.
The solution I have in mind would be getting (Moment.hours() * 60 + Moment.minutes()) * 60 * 1000, but I don't like it.
Is there a cleaner way to do it?

A: Here two possible solutions:

*

*Get the startOf the day and then calculate the difference in millisecond using diff

*Build a moment duration object from hour and minute of the selected time and then showing it asMilliseconds
Here a live sample:

var timepicker = $("#datetimepicker1").datetimepicker({
  format: 'HH:mm'
});

$('#btn1').click(function(){
  // Get selected time
  var dateSelected = timepicker.data('DateTimePicker').date();
  if( !dateSelected ) return;
  // Get start of the day
  var startDay = dateSelected.clone().startOf('day');
  // Get difference (millseconds) from the start of the day and the selected time
  var duration = dateSelected.diff(startDay);
  console.log(duration);
});

$('#btn2').click(function(){
  // Get selected time
  var dateSelected = timepicker.data('DateTimePicker').date();
  if( !dateSelected ) return;
  // Create duration from hours and minutes slected
  var duration = moment.duration({
    h: dateSelected.hours(),
    m: dateSelected.minutes()
  });
  // Print duration as milliseconds
  console.log(duration.asMilliseconds());
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"/>

  <input type="text" class="form-control" />

<button id="btn1" class="btn btn-default" type="button">Get date as duration V.1</button>
<button id="btn2" class="btn btn-default" type="button">Get date as duration V.2</button>


text:
Q: What is the third value in CSS padding? I am playing around with the Less Framework 3 and I saw this line in the css:
body {
    padding: 60px 42px 0;
    width: 396px;
}

what does padding: 0 do?
This does not look like  normal css shorthand,  and top-right-bottom seems weird.

A: The padding and margin properties specify top right bottom left.
If left is omitted, it will default to right.
Thus, padding: a b c is equivalent to padding: a b c b.
If bottom is also omitted, it will default to top.
Thus, padding: a b is equivalent to padding: a b a b.
If right is also omitted, the single value is used for all 4 sides.
Thus, padding: a is equivalent to padding: a a a a.

A: When you specify three values the second is implicitly used for the fourth, i.e.  padding: 60px 42px 0 42px;

A: There are three shorthand versions when specifying the four thickness values.  These shortcuts also apply to similar properties, such as margin, outline and border.
Specifying 1 value:
margin: 10px;
/*same as*/
margin: 10px 10px 10px 10px;

...means use 10px for all 4 sides.
margin: 10px 15px;
/*same as*/
margin: 10px 15px 10px 15px;

...means use  10px for top and bottom and 15px for left and right.
margin: 10px 15px 20px;
/*same as*/
margin: 10px 15px 20px 15px;

...means use 10px for top, 15px for left and right, and 20px for bottom.

A: The best ever explain by W3School:-
http://www.w3schools.com/css/css_padding.asp
So, here is how it works:
If the padding property has four values:
padding: 25px 50px 75px 100px;
    top padding is 25px
    right padding is 50px
    bottom padding is 75px
    left padding is 100px

If the padding property has three values:
padding: 25px 50px 75px;
    top padding is 25px
    right and left paddings are 50px
    bottom padding is 75px

If the padding property has two values:
padding: 25px 50px;
    top and bottom paddings are 25px
    right and left paddings are 50px

If the padding property has one value:
padding: 25px;
    all four paddings are 25px


text:
Q: Sequence difference equatiom For $n \ge 2$ the terms in the sequence
$a = \{1, 6, 17, 45, 118, 309, \ldots\}$ are related by the difference equation
$$a_{n+2} = \boxed{\phantom{XX}} \, a_{n+1} + \boxed{\phantom{XX}} \, a_n $$
The values are positive or negative integers.
Can anyone help me with the equation please.
appreciated

A: Hint: Our recurrence relation is of the form $a_{n+2} = x a_{n+1} + y a_n$, and we would like to determine $x$ and $y$. For $n=1$, we get the equation $17 = 6x+y$, and for $n=2$, we get $45 = 17x+6y$. We now solve this linear system.

A: HINT: A quick eyeball estimate says that each term is very roughly three times the previous term, so do a little arithmetic:
$$\begin{array}{rcc}
n:&0&1&2&3&4&5\\
a_n:&1&6&17&45&118&309\\
3a_{n-1}:&-&-&18&51&135&354\\
a_n-3a_{n-1}:&-&-&?&?&?&?
\end{array}$$
Added: There are of course mechanical solutions, but it's also useful to be able to spot patterns.

A: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
$a_{n + 2} = xa_{n + 1} + ya_{n}$.
$$
\!\!\!\!{\cal F}\pars{x,y}
\equiv
\half\bracks{%
\pars{x + 6y - 17}^{2} + \pars{6x + 17y - 45}^{2} + \pars{17x + 45y - 118}^{2} +\pars{45x + 118y - 309}^{2}}
$$
Minimize ${\cal F}\pars{x,y}$ respect $x$ and $y$. If the minimum of ${\cal F}\pars{x,y}$ is $\large\tt zero$, then the values of $x$ and $y$ you found are the right ones $\pars{~\mbox{it assumes}\ x\ \mbox{and}\ y\ \mbox{are}\ n-\mbox{independents}~}$.
That procedure yields the global minimum ${\cal F}\pars{x, y} = 0$ at $\color{#0000ff}{\large x = -1,\quad y = 3}$.
Then
$$\color{#0000ff}{\large%
a_{n + 2} = -a_{n + 1} + 3a_{n}}
$$


text:
Q: Maven Dependency plugin throwing Sonatype Error We implemented Dependency-check-maven and this was working fine up till now. But suddenly getting this error now,
[WARNING] An error occurred while analyzing 'oldui/includes/ckeditor/lang/no.js' (Sonatype OSS Index Analyzer).
Not sure where this is originating from?

A: I think the reason is due to https://ossindex.sonatype.org/ certificate is expired on 25th May. When you go to that website, you can see that you get the SSL error.


text:
Q: Ansible - List assistance | 2 lists | 1 unique key value between the lists First time posting, go gentle.
Looking for some assistance on how to accomplish the following.
2 lists
1 shared key/value between the lists
looking how I can associate the all elements/(key/values of element?) of list1 to list2 based the one 1 shared key/value present in both lists
using: usecase_key4 as they shared key / usecase_valuse4-A / B for the example data, the value changes but will be same for the data sets required to associate.
Appreciate any feedback
Revised based off of replies.
I have tried some variations of [ selectattr and json_query ]
unsure if that is even the correct approach.
"list-1": [
        {
            "list1_key1": "list1_value1-A"
            "list1_key2": "list1_value2-A"
            "list1_key3": "list1_value3-A"
            "usecase_key4": "usecase_value4-A"
            "list1_key5": "list1_value5-A"
            "list1_key6": "list1_value6-A"
            "list1_key7": "list1_value7-A"
            "list1_key8": "list1_value8-A"
            "list1_key9": "list1_value9-A"
            "list1_key10":"list1_value10-A"
        },
        {
            "list1_key1": "list1_value1-B"
            "list1_key2": "list1_value2-B"
            "list1_key3": "list1_value3-B"
            "usecase_key4": "usecase_value4-B"
            "list1_key5": "list1_value5-B"
            "list1_key6": "list1_value6-B"
            "list1_key7": "list1_value7-B"
            "list1_key8": "list1_value8-B"
            "list1_key9": "list1_value9-B"
            "list1_key10": "list1_value10-B"
        }
]

"list-2": [
        {
            "list2_key1": "list2_value1-A"
            "list2_key2": "list2_value2-A"
            "list2_key3": "list2_value3-A"
            "usecase_key4": "usecase_value4-A"
            "list2_key5": "list2_value5-A"
            "list2_key6": "list2_value6-A"
        },
        {
            "list2_key1": "list2_value1-B"
            "list2_key2": "list2_value2-B"
            "list2_key3": "list2_value3-B"
            "usecase_key4": "usecase-value4-B"
            "list2_key5": "list2_value5-B"
            "list2_key6": "list2_value6-B"
        }
]

Expected result:

"new_list": [
        {
            "list1_key1": "list1_value1-A"
            "list1_key2": "list1_value2-A"
            "list1_key3": "list1_value3-A"
            "usecase_key4": "usecase_value4-A"
            "list1_key5": "list1_value5-A"
            "list1_key6": "list1_value6-A"
            "list1_key7": "list1_value7-A"
            "list1_key8": "list1_value8-A"
            "list1_key9": "list1_value9-A"
            "list1_key10":"list1_value10-A"
            "list2_key1": "list2_value1-A"
            "list2_key2": "list2_value2-A"
            "list2_key3": "list2_value3-A"
            "list2_key5": "list2_value5-A"
            "list2_key6": "list2_value6-A"
        },
        {
            "list1_key1": "list1_value1-B"
            "list1_key2": "list1_value2-B"
            "list1_key3": "list1_value3-B"
            "usecase_key4": "usecase_value4-B"
            "list1_key5": "list1_value5-B"
            "list1_key6": "list1_value6-B"
            "list1_key7": "list1_value7-B"
            "list1_key8": "list1_value8-B"
            "list1_key9": "list1_value9-B"
            "list1_key10": "list1_value10-B"
            "list2_key1": "list2_value1-B"
            "list2_key2": "list2_value2-B"
            "list2_key3": "list2_value3-B"
            "list2_key5": "list2_value5-B"
            "list2_key6": "list2_value6-B"
        }
]

A: you have a specific problem, this playbook does the job:
- name: testplaybook
  hosts: localhost
  gather_facts: no
  vars:
    list_1:
    - list1_key1: list1_value1-A
      list1_key2: list1_value2-A
      list1_key3: list1_value3-A
      usecase_key4: usecase_value4-A
      list1_key5: list1_value5-A
      list1_key6: list1_value6-A
      list1_key7: list1_value7-A
      list1_key8: list1_value8-A
      list1_key9: list1_value9-A
      list1_key10: list1_value10-A
    - list1_key1: list1_value1-B
      list1_key2: list1_value2-B
      list1_key3: list1_value3-B
      usecase_key4: usecase_value4-B
      list1_key5: list1_value5-B
      list1_key6: list1_value6-B
      list1_key7: list1_value7-B
      list1_key8: list1_value8-B
      list1_key9: list1_value9-B
      list1_key10: list1_value10-B
    list_2:
    - list2_key1: list2_value1-A
      list2_key2: list2_value2-A
      list2_key3: list2_value3-A
      usecase_key4: usecase_value4-A
      list2_key5: list2_value5-A
      list2_key6: list2_value6-A
    - list2_key1: list2_value1-B
      list2_key2: list2_value2-B
      list2_key3: list2_value3-B
      usecase_key4: usecase-value4-B
      list2_key5: list2_value5-B
      list2_key6: list2_value6-B
  tasks:
    - name: group
      set_fact:
        new_list: "{{ new_list | d([]) + [item.0 | combine(item.1)] }}"
      loop: "{{ list_1 | zip(list_2) }}"
    - name: group
      debug:
        var: new_list

result:
    "new_list": [
        {
            "list1_key1": "list1_value1-A",
            "list1_key10": "list1_value10-A",
            "list1_key2": "list1_value2-A",
            "list1_key3": "list1_value3-A",
            "list1_key5": "list1_value5-A",
            "list1_key6": "list1_value6-A",
            "list1_key7": "list1_value7-A",
            "list1_key8": "list1_value8-A",
            "list1_key9": "list1_value9-A",
            "list2_key1": "list2_value1-A",
            "list2_key2": "list2_value2-A",
            "list2_key3": "list2_value3-A",
            "list2_key5": "list2_value5-A",
            "list2_key6": "list2_value6-A",
            "usecase_key4": "usecase_value4-A"
        },
        {
            "list1_key1": "list1_value1-B",
            "list1_key10": "list1_value10-B",
            "list1_key2": "list1_value2-B",
            "list1_key3": "list1_value3-B",
            "list1_key5": "list1_value5-B",
            "list1_key6": "list1_value6-B",
            "list1_key7": "list1_value7-B",
            "list1_key8": "list1_value8-B",
            "list1_key9": "list1_value9-B",
            "list2_key1": "list2_value1-B",
            "list2_key2": "list2_value2-B",
            "list2_key3": "list2_value3-B",
            "list2_key5": "list2_value5-B",
            "list2_key6": "list2_value6-B",
            "usecase_key4": "usecase-value4-B"
        }
    ]
}


text:
Q: Python, read log exception from logging.exception I use the scrapy library for scraping and it handels all the logging for me. The log file is very big and I was hoping for another way than to read through the whole file. I'm only interested in the exception.
Is it posible to get the raw logging.exception and read from that without creating another log file?

A: Use the python logging facility which is what Scrapy uses. At the program entry point you need to customize this logging facility, it can be in the __init__.py file for example or anything else before you use any log related calls.
What you need to do is set different handlers  for different levels (ERROR, WARNING, ...). Exception level do not exist, you might be mistaking with Error or Critical levels.
This is the "Logging How To", you should check it.
Your solution would look like :
import logging

#this is the logger Scrapy uses throughout the app.
logger = logging.getLogger()

my_exception_handler = logging.FileHandler()
my_exception_handler.setLevel(Logging.ERROR)

logger.addHandler(my_exception_handler)

Finally, if you are really talking about exception and not error or critical levels. You'll need to inherit from your Exception class or overwrite it so you can use the same logging approach I just explained.


text:
Q: Using Rome RSS in OSGI/ Adobe AEM I ran into a problem using the rome library for creating RSS Feeds. https://rometools.github.io/
If I just add the lib to my pom.xml and deploy it to an AEM instance and call a servlet which should use the library it just fails. Iam unable to debug into the servlet.
I think it is a class loading issue and on the website of the rome tools is a hint to set the system property 'rome.pluginmanager.useloadclass' to true. How can I achieve this? just as startup parameter or is there a way to do in inside apache felix console or another place inside AEM?
In the error log i got the following message:
failure loooking up method bindRssFeed(org.osgi.framework.ServiceReference) in class class com.xxx.aem.relaunch.servlets.rssfeed.RssFeedServlet. Assuming no such method. (java.lang.NoClassDefFoundError: com/rometools/rome/io/FeedException)
java.lang.NoClassDefFoundError: com/rometools/rome/io/FeedException
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.getDeclaredMethod(Unknown Source)
at org.apache.felix.scr.impl.helper.BaseMethod.getMethod(BaseMethod.java:316)
at org.apache.felix.scr.impl.helper.BindMethod.getServiceReferenceMethod(BindMethod.java:392 )
at org.apache.felix.scr.impl.helper.BindMethod.doFindMethod(BindMethod.java:113)
at org.apache.felix.scr.impl.helper.BaseMethod.findMethod(BaseMethod.java:171)
at org.apache.felix.scr.impl.helper.BaseMethod.access$400(BaseMethod.java:37)
at org.apache.felix.scr.impl.helper.BaseMethod$NotResolved.resolve(BaseMethod.java:558)
at org.apache.felix.scr.impl.helper.BaseMethod$NotResolved.methodExists(BaseMethod.java:580)
at org.apache.felix.scr.impl.helper.BaseMethod.methodExists(BaseMethod.java:513)
at org.apache.felix.scr.impl.helper.BindMethod.getServiceObject(BindMethod.java:643)
at org.apache.felix.scr.impl.manager.DependencyManager.getServiceObject(DependencyManager.ja va:2137)
at org.apache.felix.scr.impl.manager.DependencyManager$SingleStaticCustomizer.prebind(Depend encyManager.java:1048)
at org.apache.felix.scr.impl.manager.DependencyManager.prebind(DependencyManager.java:1457)
at org.apache.felix.scr.impl.manager.AbstractComponentManager.collectDependencies(AbstractCo mponentManager.java:983)
at org.apache.felix.scr.impl.manager.SingleComponentManager.getServiceInternal(SingleCompone ntManager.java:812)
at org.apache.felix.scr.impl.manager.SingleComponentManager.getService(SingleComponentManage r.java:774)
at org.apache.felix.framework.ServiceRegistrationImpl.getFactoryUnchecked(ServiceRegistratio nImpl.java:347)
at org.apache.felix.framework.ServiceRegistrationImpl.getService(ServiceRegistrationImpl.jav a:247)
at org.apache.felix.framework.ServiceRegistry.getService(ServiceRegistry.java:344)
at org.apache.felix.framework.Felix.getService(Felix.java:3699)
at org.apache.felix.framework.BundleContextImpl.getService(BundleContextImpl.java:470)
at org.apache.felix.scr.impl.manager.SingleRefPair.getServiceObject(SingleRefPair.java:72)
at org.apache.felix.scr.impl.manager.DependencyManager.getService(DependencyManager.java:139 6)
at org.apache.felix.scr.impl.manager.DependencyManager.getService(DependencyManager.java:137 0)
at org.apache.felix.scr.impl.manager.ComponentContextImpl.locateService(ComponentContextImpl .java:135)
at org.apache.sling.servlets.resolver.internal.SlingServletResolver.createServlet(SlingServl etResolver.java:979)
at org.apache.sling.servlets.resolver.internal.SlingServletResolver.bindServlet(SlingServlet Resolver.java:941)
at sun.reflect.GeneratedMethodAccessor55.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.felix.scr.impl.helper.BaseMethod.invokeMethod(BaseMethod.java:222)
at org.apache.felix.scr.impl.helper.BaseMethod.access$500(BaseMethod.java:37)
at org.apache.felix.scr.impl.helper.BaseMethod$Resolved.invoke(BaseMethod.java:615)
at org.apache.felix.scr.impl.helper.BaseMethod.invoke(BaseMethod.java:499)
at org.apache.felix.scr.impl.helper.BindMethod.invoke(BindMethod.java:41)
at org.apache.felix.scr.impl.manager.DependencyManager.doInvokeBindMethod(DependencyManager. java:1660)
at org.apache.felix.scr.impl.manager.DependencyManager.invokeBindMethod(DependencyManager.ja va:1636)
at org.apache.felix.scr.impl.manager.SingleComponentManager.invokeBindMethod(SingleComponent Manager.java:370)
at org.apache.felix.scr.impl.manager.DependencyManager$MultipleDynamicCustomizer.addedServic e(DependencyManager.java:319)
at org.apache.felix.scr.impl.manager.DependencyManager$MultipleDynamicCustomizer.addedServic e(DependencyManager.java:295)
at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.customizerAdded(ServiceTracker.j ava:1215)
at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.customizerAdded(ServiceTracker.j ava:1136)
at org.apache.felix.scr.impl.manager.ServiceTracker$AbstractTracked.trackAdding(ServiceTrack er.java:945)
at org.apache.felix.scr.impl.manager.ServiceTracker$AbstractTracked.track(ServiceTracker.jav a:881)
at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.serviceChanged(ServiceTracker.ja va:1167)
at org.apache.felix.scr.impl.BundleComponentActivator$ListenerInfo.serviceChanged(BundleComp onentActivator.java:120)
at org.apache.felix.framework.util.EventDispatcher.invokeServiceListenerCallback(EventDispat cher.java:991)
at org.apache.felix.framework.util.EventDispatcher.fireEventImmediately(EventDispatcher.java :839)
at org.apache.felix.framework.util.EventDispatcher.fireServiceEvent(EventDispatcher.java:546 )
at org.apache.felix.framework.Felix.fireServiceEvent(Felix.java:4557)
at org.apache.felix.framework.Felix.registerService(Felix.java:3549)
at org.apache.felix.framework.BundleContextImpl.registerService(BundleContextImpl.java:348)
at org.apache.felix.scr.impl.manager.AbstractComponentManager$3.register(AbstractComponentMa nager.java:869)
at org.apache.felix.scr.impl.manager.AbstractComponentManager$3.register(AbstractComponentMa nager.java:857)
at org.apache.felix.scr.impl.manager.RegistrationManager.changeRegistration(RegistrationMana ger.java:133)
at org.apache.felix.scr.impl.manager.AbstractComponentManager.registerService(AbstractCompon entManager.java:915)
at org.apache.felix.scr.impl.manager.AbstractComponentManager.activateInternal(AbstractCompo nentManager.java:715)
at org.apache.felix.scr.impl.manager.DependencyManager$SingleStaticCustomizer.addedService(D ependencyManager.java:954)
at org.apache.felix.scr.impl.manager.DependencyManager$SingleStaticCustomizer.addedService(D ependencyManager.java:915)
at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.customizerAdded(ServiceTracker.j ava:1215)
at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.customizerAdded(ServiceTracker.j ava:1136)
at org.apache.felix.scr.impl.manager.ServiceTracker$AbstractTracked.trackAdding(ServiceTrack er.java:945)
at org.apache.felix.scr.impl.manager.ServiceTracker$AbstractTracked.track(ServiceTracker.jav a:881)
at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.serviceChanged(ServiceTracker.ja va:1167)
at org.apache.felix.scr.impl.BundleComponentActivator$ListenerInfo.serviceChanged(BundleComp onentActivator.java:120)
at org.apache.felix.framework.util.EventDispatcher.invokeServiceListenerCallback(EventDispat cher.java:991)
at org.apache.felix.framework.util.EventDispatcher.fireEventImmediately(EventDispatcher.java :839)
at org.apache.felix.framework.util.EventDispatcher.fireServiceEvent(EventDispatcher.java:546 )
at org.apache.felix.framework.Felix.fireServiceEvent(Felix.java:4557)
at org.apache.felix.framework.Felix.registerService(Felix.java:3549)
at org.apache.felix.framework.BundleContextImpl.registerService(BundleContextImpl.java:348)
at org.apache.felix.scr.impl.manager.AbstractComponentManager$3.register(AbstractComponentMa nager.java:869)
at org.apache.felix.scr.impl.manager.AbstractComponentManager$3.register(AbstractComponentMa nager.java:857)
at org.apache.felix.scr.impl.manager.RegistrationManager.changeRegistration(RegistrationMana ger.java:133)
at org.apache.felix.scr.impl.manager.AbstractComponentManager.registerService(AbstractCompon entManager.java:915)
at org.apache.felix.scr.impl.manager.AbstractComponentManager.activateInternal(AbstractCompo nentManager.java:715)
at org.apache.felix.scr.impl.manager.AbstractComponentManager.enable(AbstractComponentManage r.java:399)
at org.apache.felix.scr.impl.config.ConfigurableComponentHolder.enableComponents(Configurabl eComponentHolder.java:676)
at org.apache.felix.scr.impl.BundleComponentActivator.initialEnable(BundleComponentActivator .java:339)
at org.apache.felix.scr.impl.Activator.loadComponents(Activator.java:360)
at org.apache.felix.scr.impl.Activator.access$000(Activator.java:53)
at org.apache.felix.scr.impl.Activator$ScrExtension.start(Activator.java:260)
at org.apache.felix.utils.extender.AbstractExtender.createExtension(AbstractExtender.java:25 9)
at org.apache.felix.utils.extender.AbstractExtender.modifiedBundle(AbstractExtender.java:232 )
at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:482)
at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:415)
at org.osgi.util.tracker.AbstractTracked.track(AbstractTracked.java:232)
at org.osgi.util.tracker.BundleTracker$Tracked.bundleChanged(BundleTracker.java:444)
at org.apache.felix.framework.util.EventDispatcher.invokeBundleListenerCallback(EventDispatc her.java:916)
at org.apache.felix.framework.util.EventDispatcher.fireEventImmediately(EventDispatcher.java :835)
at org.apache.felix.framework.util.EventDispatcher.fireBundleEvent(EventDispatcher.java:517)
at org.apache.felix.framework.Felix.fireBundleEvent(Felix.java:4541)
at org.apache.felix.framework.Felix.startBundle(Felix.java:2172)
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:998)
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:984)
at org.apache.sling.installer.core.impl.tasks.BundleStartTask.execute(BundleStartTask.java:9 7)
at org.apache.sling.installer.core.impl.OsgiInstallerImpl.doExecuteTasks(OsgiInstallerImpl.j ava:894)
at org.apache.sling.installer.core.impl.OsgiInstallerImpl.executeTasks(OsgiInstallerImpl.jav a:729)
at org.apache.sling.installer.core.impl.OsgiInstallerImpl.run(OsgiInstallerImpl.java:286)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: com.rometools.rome.io.FeedException not found by com.xxx.aem.xx-com-relaunch.core

SOLUTION:
Add your Rome libs also in the embedded dependencies in your pom.xml
<Embed-Dependency>
              rome,
              rome-utils,
              jdom2
 </Embed-Dependency>

A: SOLUTION:
Add your Rome libs also in the embedded dependencies in your pom.xml
<Embed-Dependency>
              rome,
              rome-utils,
              jdom2
 </Embed-Dependency>


text:
Q: Firestore get access to user ID in other functions im creating a app with the firestore database. I have a problem where i want to acces to user id in other functions, how can i do that?
Im using the firebase.auth().onAuthStateChanged function
to watch if the user is logged in, and i can acces the user id in here.
How can i access it when i click on the btnName? now i have to following error:
Uncaught ReferenceError: uid is not defined
HTML

  <meta charset="utf-8">

  <title></title>

  <meta name="description" content="">
  <meta name="viewport" content="user-scalable=no, initial-scale=1.0, width=device-width, maximum-scale=1.0" />

Welcome

    <button id="btnLogout" class="hide">Logout</button>

    <input id="txtName" type="" placeholder="Name">
    <button id="btnName">Add name</button>

js
// Initialize Firebase
var config = {
  apiKey: "AIzaSyBAQYQxSU0JkskvXKqBKzAHHWViutuP_lg",
  authDomain: "crypto-3171a.firebaseapp.com",
  databaseURL: "https://crypto-3171a.firebaseio.com",
  projectId: "crypto-3171a",
  storageBucket: "crypto-3171a.appspot.com",
  messagingSenderId: "86923986632"
};
firebase.initializeApp(config);

const db = firebase.firestore();

const txtName = document.getElementById('txtName');
const btnName = document.getElementById('btnName');

// log user out of app
btnLogout.addEventListener('click', e => {
    firebase.auth().signOut();
});

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
      addToUsers(user)
  } else {
  }
});

// add users to database 'users'
function addToUsers(user) {
    var email = user.email;
    var uid = user.uid;
    var users = db.collection("users").doc(uid);
    users.set({
        email: email,
        id: uid
    });
}

// when user clicks add name to 'users' document
btnName.addEventListener('click', e => {
    console.log(db.collection("users").doc(uid))
});

A: you can use firebase.auth().currentUser get current logged in user , checkout this code
btnName.addEventListener('click', e => {
    let user = firebase.auth().currentUser;
    console.log(user);
    if (user) {
        console.log(db.collection("users").doc(user.uid))
    } else {
        alert('user not logged in')
    }
});


text:
Q: how to prevent error in checkShinyVersion? My R Shiny App was running fine in R-studio server. But today when I run it in R-studio server, I got an error:

Error in checkShinyVersion() :    Please upgrade the 'shiny' package
to (at least) version 1.1

My app.R script has .libPaths(c('/home/jack/R/SLE_shinyApp/3.5')) in the beginning, because I intended to set up a dedicated path for this App, so that the packages won't be altered by other R scripts.
So here are all the paths; the 2nd one is the system default R library path which I have no control over.

> .libPaths()
[1] "/home/jack/R/SLE_shinyApp/3.5" "/app/x86_64/R/v3.5.0/lib64/R/library"

It turns out that htmlwidgets package, a dependency of shiny, is located only in the 2nd path and was updated by system admin since my last run, thus causing the error.
Here are my solutions and questions:

*

*Make R search ONLY /home/jack/R/SLE_shinyApp/3.5, so I can install all needed packages and dependencies there. but how to make R search ONLY that path in app.R?

*Update the shiny package in /home/jack/R/SLE_shinyApp/3.5. But if I run app.R line by line, it uses the shiny v1.1 in /home/jack/R/SLE_shinyApp/3.5 and runs OK. But if I run app.R by clicking "Run App" button, it uses the old shiny in the 2nd path and still gives the error, even with library(shiny, lib.loc = .libPaths()[1]) following .libPaths(c('/home/e0380702/R/SLE_shinyApp/3.5')).
Can anyone help?


text:
Q: What is the preferred way of specifying a transformer for the response of an outgoing gateway using DSL I have the following piece of code:
@Configuration
@EnableConfigurationProperties(ISOGatewayProperties::class)
class ISOGatewayConfig {

    @Bean
    fun isoGatewayFlow(
        isoProps: ISOGatewayProperties,
        isoTransformer: ISOTransformer) : IntegrationFlow =
            IntegrationFlows
                .from(MessageChannels.direct("isoInChannel"))
                .log()
                .transform(isoTransformer)
                .handle(Tcp.outboundGateway(
                    Tcp.netClient(isoProps.host, isoProps.port)))
                .get()
}

This code correctly converts the request which is an object to a byte[] for sending to the remote server
My questions are the following:

*

*What is the preferred way of transforming the response from the server?

*Is it possible to use a single class for both transformations?

Answered by Artem
The correct way of doing custom protocols is to use custom serializer/deserializer.

A: You just need to add a .transform(...) after that .handle(Tcp.outboundGateway(...)) in the flow.
Well, you can use the same class for both request and response, but I believe in case of response you need to create an ISO object from the byte[], therefore you would need to specify a method name as a second .transform() argument to make things clear for the target transformation endpoint.


text:
Q: Google_DriveFile Class Not Found Google Drive API I'm using the google-api-php-client Library in my project. I'm using Composer to auto load the library in my project. The other classes (ie: Google_Client) are working fine. When I go to instantiate an object, per the Google documentation, I get the following error:
Fatal error: Class 'Google_DriveFile' not found

This is the line causing the error:
$file = new Google_DriveFile();

A: When the Library was updated, the class name was changed to Google_Service_Drive_DriveFile, per this article. The documentation was not updated.


text:
Q: How to send a POST request with after create or update of a user (RAILS) This is my first time working with Requests and i'm a little confused, any guidance would be greatly appreciated.
Task: after a user is created i would like to send that user's information (name, email, etc) to another site that we are integrating with. The goal is when a user leaves our site and goes to the next site (we're also setting up SSO) they would see the same information.
Here is what I put in the Model:
  after_validation :send_new_user_to_hivebrite, on: [ :create, :update ]

  def send_new_user_to_hivebrite

    payload = {user:{email:Email.find_by(person_id:self.id).address,sub_network_ids:[0],firstname:self.given_name,lastname: self.family_name,is_active:true}}

    begin
      response = RestClient::Request.execute(
        method: :post,
        url: 'https://mysite.us.hivebrite.com/api/admin/v1/users',
        payload: payload.to_json,
        headers: {content_type: :json, accept: :json, Authorization: 'my_token'}
      )
      self.description = "Response code: #{response.code}"
    rescue RestClient::ExceptionWithResponse => e
      self.description = "It didn't work"
    end

  end

I tried doing the same thing but with a GET request (without the payload) and stored the response in self.description and it worked. so the authorization works and the url works. which means something is wrong with my payload right? am i formatting it wrong?
this exact format worked in postman:
{
  "user":
    {
        "email": "MoeTest@postman.com",
        "sub_network_ids": [ 0 ],
        "firstname": "Moe",
        "lastname": "Test",
        "external_id": "test_person_id",
        "sso_identifier": "test_identifier",
        "is_active": true,
        "headline": "Nothing to fear, POSTMAN is here",
        "summary": "This is my test summary, you will only see it if this post request worked!"
    }
}

I thought maybe it couldn't find the email because it was not created yet or something, so i tried updating an existing user and it still goes to rescue.
In rails C i did
payload = {user:{email:Email.find_by(person_id:Person.last.id).address,sub_network_ids:[20548],firstname:Person.last.given_name,lastname:Person.last.family_name,is_active:true}}

then i did
irb(main):016:0> payload.to_json
=> "{\"user\":{\"email\":\"temp@temptemp.temp\",\"sub_network_ids\":[20548],\"firstname\":\"temp\",\"lastname\":\"tempsir\",\"is_active\":true}}"

I checked https://jsonlint.com/ to see if that is valid json and it was. sooo what am I doing wrong?


text:
Q: Python matplotlib how to clear previous drawing point? My code is present below. I expect the during the animation, each frame only draws one point which should be in the head of the line, but in fact all the previous point are shown. It seems each time the plt only adds point to the drawing, how to change that to make it clear previous point?all the red point are shown which is not wanted, the df is list below for reference.
0.0 0.0
0.26 186780.0
0.27 197556.0
0.53 519439.0
0.54 533579.0
0.8 946285.0
0.81 960288.0
1.07 1306550.0
1.08 1320020.0
1.34 1642600.0
from matplotlib import pyplot as plt
from matplotlib import animation,rc
import pandas as pd

fig = plt.figure()
df=pd.read_csv('radialforce.csv', sep=';',skipinitialspace=True,na_values="
NaN")
df.dropna(axis="columns", how="any", inplace=True)
df.columns.values[1] = 'Y'

def animate(n):
    plt.plot(df['X'][:n], df['Y'][:n],color='g',lw='0.5')
    plt.scatter(df['X'][n], df['Y'][n],10,facecolor='r',edgecolor='r')
    return fig

anim = animation.FuncAnimation(fig, animate,frames=len(df['X']),
interval=100)
plt.show()

A: You don't want to redraw everything each iteration. Instead you want to update the line and scatter.
from matplotlib import pyplot as plt
from matplotlib import animation,rc
import pandas as pd

fig = plt.figure()
df=pd.read_csv(...)
df.dropna(axis="columns", how="any", inplace=True)
df.columns.values[1] = 'Y'

line, = plt.plot(df['X'][:1], df['Y'][:1],color='g',lw='0.5')
scatter = plt.scatter(df['X'][0], df['Y'][0],10,facecolor='r',edgecolor='r')

def animate(n):
    x,y=df['X'][:n+1], df['Y'][:n+1]
    line.set_data(x,y)
    scatter.set_offsets([df['X'][n], df['Y'][n]])
    plt.gca().relim()
    plt.gca().autoscale_view()

anim = animation.FuncAnimation(fig, animate,frames=len(df['X']), interval=100)
plt.show()


text:
Q: Issue with jQuery validate : TypeError: t.data(...) is undefined I'm currently running the following jQuery plugin to validate all of my forms within our system.
http://jqueryvalidation.org/
As our html relies on css classes, I am using the following code to apply a rule to all fields that have the class .required:
$('form').each(function(){
    $(this).validate();
    $('.required').each(function(){
        $(this).rules('add',{
            required: true,
            messages: {
                required: "This field is required"
            }
        });
    });
});

However, when trying this in Firefox, Firebug gives me the following error:
       TypeError: t.data(...) is undefined

This is within the plugin itself and not my code although I believe that when my code makes a call to this plugin the plugin cannot handle the way it needs to be executed. Has anyone else encountered this error?
My form is currently a mixture of text fields, drop-down menus and radio buttons all with the same class of .required. Unfortunately I cannot change the HTML as it is dynamic and built into our underlying system (so it is generated using PL/SQL procedures).
Unfortunately I cannot post a link to the form in question as our system would require you to login however I can try and replicate it in a fiddle if the code above is not enough to go on.
Any help would be greatly appreciated.
Kind regards,
Jason Espin
EDIT:
If it helps, the plugin code is hot linked from here and I have not made any modifications to it:
   <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
   <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>

A: Your each function is redundant as if the field has a class of "required" the it will have the required method applied to it as a class rule, and the default message is 'this field is required'
$('form').each(function(){
    $(this).validate();
    //$('.required').each(function(){
    //    $(this).rules('add',{
    //        required: true,
    //        messages: {
    //            required: "This field is required"
    //        }
    //    });
    //});
});

you can verify the 'required' rule is still applied to your fields by running this in the browser console:
$('#fieldtotest').rules();

A: $(document).ready(function () {
    $('#mytable').dataTable({
        "processing": true,
        "serverSide": true,
        "ajax": "jsond",
        "columns": [
            {"userList": "userId"},
            {"userList": "user_name"},
            {"userList": "age"}
        ]
    });
});


text:
Q: Purpose of POM.xml in Maven I am very new to Maven. I have the following questions:

*

*Do we need to create POM file our own?Do we need to understand POM file fully to use Maven?

*We are mentioning Plugin in the POM. will that plugins only be downloaded by Maven when use Maven? or by default all plugins will be downloaded?
Please explain.

A: First you need to understand the pom content otherwise you are not able to influence the build process. The pom file should be created manually but there are some exceptions like Spring Roo which will create the pom but it's better to understand the pom to see if something is going wrong.
The plugins mentioned in the pom will be downloaded automatically by Maven but there are plugins which are by default in the life cycle which will be downloaded as well in contradiction to naming them in the pom file.

A: *

*You need at least to understand some basics of Maven: dependencies, how to configure plugins, how to start a new POM (you can do this in IDE or create a project from an archetype), basic commands: mvn compile, mvn  package, mvn install. If your only need is to build your classes into JARs, Maven configuration would be as small as a list of dependencies.

*Everything in Maven is downloaded by default - all artifacts are being searched in Central and any other configured repositories. Once downloaded, they are stored on your machine at $HOME/.m2/repository.

Might be helpful: Maven Quick-start Guide.


text:
Q: iOS - Control over "${App} wants to open ${Another App}" dialog In my app, I have functionality where the user could open another app lets call it as 'App2'. If App2 is not present on the device, then user will be present with an app not available alert that I created, lets call this as Alert1.
However if App2 is present on the device and user tries to open it, Apple's "${App} wants to open App2" dialog is presented. If user clicks 'Cancel' on this, the callback executes my code to present Alert1.
I don't want my app to display Alert1 when user clicks 'Cancel' on Apple's dialog. Is there a way to control Apple's dialog?
Below is my code:
        if let url = urlComponents.url {
            UIApplication.shared.open(url, completionHandler: { success in
                if !success {
                    showAppNotAvailableAlert(url.absoluteString, actionLabel: action.label)
                }
            })
            return
        }

A: try
        if let url = urlComponents.url {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, completionHandler: { didURLOpen in
                    if !didURLOpen {
                        debugPrint("User pressed cancel button")
                    }
                })
            }
            else {
                showAppNotAvailableAlert(url.absoluteString, actionLabel: action.label)
            }
            return
        }

idea is to check if app exists by using canOpenURL, if it exists then try to open the app and handle error in completion block


text:
Q: Yii2 imagecreatefrompng do not work with transparent I use custom model to crop and commpress my image file when uploading. The problem is when upload image/png ... it crop and compress the image, but transparent background replace with black background ... i can not see my mistake ...
here is upload function in controller
$model->imageFiles = UploadedFile::getInstances($model, 'imageFiles[' . $imgKey . ']'); // get the imageFiles
$pic = Yii::getAlias('@frontend/web') . '/product_photos/thumb-270/' . $model->getImageFolderName() . '/' . $fileName;  // set the thumb path
$pic2 = Yii::getAlias('@frontend/web') . '/product_photos/' . $model->getImageFolderName() . '/' . $fileName; // set reale image path
$file->saveAs(Yii::getAlias('@frontend/web') . '/product_photos/' . $model->getImageFolderName() . '/' . $fileName);
$image = file_get_contents(Yii::getAlias('@frontend/web') . '/product_photos/' . $model->getImageFolderName() . '/' . $fileName);
file_put_contents($pic, $image);
$model->resizeImg($pic);
if($file->type!='image/png') {
    $settings->compress($pic, $pic, 90);
    $settings->compress($pic2, $pic2, 90);
}

here is a model function resizeimg:
 public function resizeImg($img) {
        $sz = getimagesize($img);
        $ratio = $sz[0] / $sz[1]; // w/h

        $w2 = Yii::$app->params['thumbswidth']; // thumb 1 width

        $image = new SimpleImage();

        $image->load($img);

        $image->resize($w2, round($w2 / $ratio));
        $image->save($img);
    }

and here is all model SimpleImage:
 var $image;
   var $image_type;

   function load($DATA, $FORMNAME = NULL) {

      $image_info = getimagesize($DATA);
      $this->image_type = $image_info[2];

      if( $this->image_type == IMAGETYPE_JPEG ) {

         $this->image = imagecreatefromjpeg($DATA);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {

         $this->image = imagecreatefromgif($DATA);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {

         $this->image = imagecreatefrompng($DATA);

      }
   }

   function save($filename, $image_type=IMAGETYPE_JPEG, $compression=100, $permissions=null) {

      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF ) {

         imagegif($this->image,$filename);
      } elseif( $image_type == IMAGETYPE_PNG ) {

         imagepng($this->image,$filename);
      }
      if( $permissions != null) {

         chmod($filename,$permissions);
      }
   }

   function output($image_type=IMAGETYPE_JPEG) {

      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image);
      } elseif( $image_type == IMAGETYPE_GIF ) {

         imagegif($this->image);
      } elseif( $image_type == IMAGETYPE_PNG ) {

         imagepng($this->image);
      }
   }

   function getWidth() {

      return imagesx($this->image);
   }

   function getHeight() {

      return imagesy($this->image);
   }

   function resizeToHeight($height) {

      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
   }

   function resizeToWidth($width) {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }

   function scale($scale) {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100;
      $this->resize($width,$height);
   }

   function resize($width,$height) {

      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      imagesavealpha($new_image, true);
      $this->image = $new_image;
   }


text:
Q: Pythonic solution for writing management commands I am using django 1.3 and python 2.7.
CLIENT REQUIREMENT :
I have a client requirement which says that an email against a user activity should be generated to the user based on his/her preference. These preferences are based on time, therefore, can be daily, weekly or monthly.
The preferences are multi-selectable, meaning that one user can receive for example daily as well as weekly notifications.
MODELS.PY :
class Preference(models.Model):
    description = models.CharField(max_length=200)

class Notification(models.Model):
    user = models.ForeignKey(User)
    preferences = models.ManyToManyField(Preference)

Class Preference contains only the time preference i.e daily, weekly, monthly
Class Notification would keep the specific users preference. The management command would use this table to send emails to the user.
QUESTION :
I have some doubts while writing a management command.

*

*Should I write only one command that would handle all 3 or more cases or 1 command per case?

*Should I add any further information to the preference models. For example the number of hours after which the daily mail should be sent?

*Is the cron responsible to run the command according to the time preference?

*What is the most pythonic way to solve this problem (if any one wants to suggest)?

A: *

*Since you have predefined intervals, (daily, weekly, monthly), you can just have one command that handles everything.

*You might want to include a field which keeps track of when the last email was sent out, which is updated every time email is sent out for the user.

*No, cron is like a polling system - executes a piece of code if certain conditions are valid. However, the developer can define when and how frequently the cron executes

*I would implement it as a straight forward management command for simplicity. If it is really complex, consider using django-celery (I would rather keep it simple)
One more thing you can do is add options to Management command which gives more control over things like - run command for only preference_type=daily or for specific user, etc if you want more flexibility.

A: *

*I would create one command (as entry point) because it is easier to register in cron

*Yes, Keeping last sent email will be nothing but beneficial, keeping the time that the preference was added might be beneficial too, django provides auto_now_add for this purpose.  Any information that could help yourself down the road, or provide more information about the users action

*Cron will be registered to run in certain intervals, it can be the "entry point" to your management command.  It will just call the management command for a certain user, every X minutes. The management commmand should implement the logic involved with determining if an email has already been sent or not

*Management command, with well structured/thought out internal functions


text:
Q: Look Back N Months and add the them as columns spark sql aggregate I have to look back every three months and add the previous month amount using the withcolumn.
val data = Seq(("1","201706","5"),("1","201707","10"),("2","201604","12"),("2","201601","15")).toDF("id","yyyyMM","amount")

+---+------+------+
| id|yyyyMM|amount|
+---+------+------+
|  1|201706|     5|
|  1|201707|    10|
|  2|201604|    12|
|  2|201601|    15|
+---+------+------+

The required output should be like the following. For each month we have to look back threemonth, I can do that by using the spark windowing lag function. How should we include the functionality to add the additional records
+---+---------+------+-----------+-------+-----------+-------+
| id|yearmonth|amount|yearmonth-1|amount2|yearmonth-2|amount3|
+---+---------+------+-----------+-------+-----------+-------+
|  1|   201709|     0|     201708|      0|     201707|     10|
|  1|   201708|     0|     201707|     10|     201706|      5|
|  1|   201707|    10|     201706|      5|     201705|      0|
|  1|   201706|     5|     201705|      0|     201706|      0|
|  2|   201606|     0|     201605|      0|     201604|     12|
|  2|   201605|     0|     201604|     12|     201603|      0|
|  2|   201604|    12|     201603|      0|     201602|      0|
|  2|   201603|     0|     201602|      0|     201601|     15|
|  2|   201602|     0|     201601|     15|     201512|      0|
|  2|   201601|    15|     201512|      0|     201511|      0|
+---+---------+------+-----------+-------+-----------+-------+

I mean the first record in the table is like look forward. Like adding couple of more months. taking about following records.
+---+---------+------+-----------+-------+-----------+-------+
| id|yearmonth|amount|yearmonth-1|amount2|yearmonth-2|amount3|
+---+---------+------+-----------+-------+-----------+-------+
|  1|   201709|     0|     201708|      0|     201707|     10|
|  1|   201708|     0|     201707|     10|     201706|      5|

A: I wouldn't know if there is a better way, but you need to create te records somewhere. Lag does not do that.
So first you need to generate new records based on the current ones.
Then you could use the lag function.
Maybe something like this:
data
  // convert the string to an actual date
  .withColumn("yearmonth", to_date('yyyyMM, "yyyyMM"))
  // for each record create 2 additional in the future (with 0 amount)
  .select(
  explode(array(
    // org record
    struct('id, date_format('yearmonth, "yyyyMM").as("yearmonth"), 'amount),
    // 1 month in future
    struct('id, date_format(add_months('yearmonth, 1), "yyyyMM").as("yearmonth"), lit(0).as("amount")),
    // 2 months in future
    struct('id, date_format(add_months('yearmonth, 2), "yyyyMM").as("yearmonth"), lit(0).as("amount"))
  )).as("record"))
  // keep 1 record per month
  .groupBy($"record.yearmonth")
  .agg(
    min($"record.id").as("id"),
    sum($"record.amount").as("amount")
  )
  // final structure (with lag fields)
  .select(
    'id,
    'yearmonth,
    'amount,
     lag('yearmonth, 1).over(orderByWindow).as("yearmonth-1"),
     lag('amount, 1, 0).over(orderByWindow).as("amount2"),
     lag('yearmonth, 2).over(orderByWindow).as("yearmonth-2"),
     lag('amount, 2, 0).over(orderByWindow).as("amount3")
  )
  .orderBy('yearmonth.desc)

It's not perfect, but it's a start
+---+---------+------+-----------+-------+-----------+-------+
|id |yearmonth|amount|yearmonth-1|amount2|yearmonth-2|amount3|
+---+---------+------+-----------+-------+-----------+-------+
|1  |201709   |0.0   |201708     |0.0    |201707     |10.0   |
|1  |201708   |0.0   |201707     |10.0   |201706     |5.0    |
|1  |201707   |10.0  |201706     |5.0    |201606     |0.0    |
|1  |201706   |5.0   |201606     |0.0    |201605     |0.0    |
|2  |201606   |0.0   |201605     |0.0    |201604     |12.0   |
|2  |201605   |0.0   |201604     |12.0   |201603     |0.0    |
|2  |201604   |12.0  |201603     |0.0    |201602     |0.0    |
|2  |201603   |0.0   |201602     |0.0    |201601     |15.0   |
|2  |201602   |0.0   |201601     |15.0   |null       |0.0    |
|2  |201601   |15.0  |null       |0.0    |null       |0.0    |
+---+---------+------+-----------+-------+-----------+-------+


text:
Q: String mismatch in ajax call to WebApi I have an ajax call to a WebAPI method like so:
function GetGroupDetails(Id, StudentType, GrpID) {
    var result = "";
    $.ajax({
        url: GetGrpDetails + Id + "&studenttype=" + StudentType + "&GrpId=" + GrpID, dataType: 'json',
        success: function (data) { if (data != null && data != "") { result = data; } },
        error: function (XHR, textStatus, errorThrown) { alert(textStatus + ":" + errorThrown); }
    });
    return result;
}

Here's the URL that goes to the WebAPI
/api/Students/GetGroups?Id=107&studenttype="Captain"&GrpId=88
During debugging, if the value in StudentType = "Captain" it comes in as "\"Captain\"".
Now in the debugger if I replace that with "Captain" it works fine.
The actual WebApi is a simple LINQ query on an EF context object which will return a valid value if the string is as expected, null otherwise.
So, how do I get the string as required.
Regards.

A: You are looking the value in VS Debugger. The actual value of the string is "Captain". I think the correct value of the string should be Captain without any double quotes. So fix your client side AJAX call.
The request should look like this:
/api/Students/GetGroups?Id=107&studenttype=Captain&GrpId=88

So basically it's your StudentType javascript variable that needs fixing. Also I would recommend you passing parameters like this to ensure proper encoding:
function GetGroupDetails(id, studentType, grpID) {
    $.ajax({
        url: GetGrpDetails,
        data: { id: id, studentType: studentType, grpId: grpID },
        success: function (data) {
            if (data != null && data != "") {
                // Do something with the data here but do not attempt to assign
                // it to some external variable that you will be returning
            }
        },
        error: function (XHR, textStatus, errorThrown) {
            alert(textStatus + ":" + errorThrown);
        }
    });
}

Another remark about your code is returning a value from the GetGroupDetails function. You are making an AJAX call and inside the success callback you are assigning a value to the result variable which you are returning from the function. This obviously won't work because AJAX is asynchronous and by the time the success callback executes, the function would have long finished running. So never attempt to be returning any values from an AJAX call. Use it inside.

A: Remove the quotes in the url, your request url should not have it. Try this
/api/Students/GetGroups?Id=107&studenttype=Captain&GrpId=88

and the function you have written, will NEVER return any values other than "", try calling the required function in the success method of the ajax call where you will get the response.
Hope this helps.


text:
Q: Finding period in this sin graph (http://media.collegeboard.com/digitalServices/image/clep/pcal.q1.2.png)
I cannot find any common points in which I can take the distance in this graph. How would you find the period then?

A: It looks like it traverses one and a half periods by $2\pi$, so its period will be $\frac{4\pi}{3}$.


text:
Q: LINQ query to get record with maximum values I have following values in a table and I need a LINQ query which satisfies the conditions below.
Select a single record, which has the maximum RevOrder.
If there are multiple records with same maximum RevOrder, then select the record with maximum RevDate
If RevDate's are equal too then get the record with maximum RevisionStatusID.
RevisionStatusID      RevDate         RevOrder
1                     12/01/2012      0
2                     14/02/2013      1
3                     10/02/2013      2
4                     11/01/2013      2
5                     11/01/2013      3

I tried the below query but it gives an error.
var DocRevIDs = (from tbh in context.tblDocumentHeaders
                 join tbr in context.tblDocumentRevisions
                 on tbh.DocumentHeaderID equals tbr.DocumentHeaderID
                 where tbh.DocumentHeaderID == tb.DocumentHeaderID
                 select tbr).Max(o => new { o.RevOrder,o.RevisionDate,o.DocumentRevisionID });

Unable to process the type
  '<>f__AnonymousType523[System.Nullable1[System.Double],System.Nullable`1[System.DateTime],System.Int32]',
  because it has no known mapping to the value layer.

A: Instead of trying to use Max(), use a combination of orderby clauses and then use FirstOrDefault(). This would be the approach you would take to do it via straight SQL.
So that would give you something similar to:
var docRevision = (from tbh in context.tblDocumentHeaders
                 join tbr in context.tblDocumentRevisions
                 on tbh.DocumentHeaderID equals tbr.DocumentHeaderID
                 where tbh.DocumentHeaderID == tb.DocumentHeaderID
                 orderby tbr.RevOrder descending, tbr.RevisionDate descending, tbr.DocumentRevisionID descending
                 select tbr).FirstOrDefault();

A: you should Order the records in the linq:
var DocRevIDs = (from tbh in context.tblDocumentHeaders
             join tbr in context.tblDocumentRevisions
             on tbh.DocumentHeaderID equals tbr.DocumentHeaderID
             where tbh.DocumentHeaderID == tbr.DocumentHeaderID
             orderby tbr.RevOrder descending, tbr.RevDate descending, tbr.RevisionStatusID descending
             select tbr).First();


text:
Q: Flutter only import library in debug mode I am using Android 11 Wireless Debugging to develop my app. Whenever the device automatically locks itself, it takes a while to re-establish the connection for hot reloading.
To overcome this I am using wakelock, which I only need to use if my app is in debug mode, not in release mode.
In lib/main.dart I have the following code:
import 'package:flutter/foundation.dart' as Foundation;
import 'package:wakelock/wakelock.dart';

...

void main() {
  if (Foundation.kDebugMode) {
    Wakelock.enable();
  }
  runApp(App());
}

As you can see the wakelock package is only used if the app is running in debug mode.
Is there a way to only import wakelock if the app is running in debug mode?

A: Tested it as
pubspec.yaml
dev_dependencies:
  wakelock: ^0.2.1+1

Usage
import 'package:flutter/foundation.dart';
import 'package:wakelock/wakelock.dart';
import 'package:flutter/material.dart';

main() async {
  WidgetsFlutterBinding.ensureInitialized();

  if (kDebugMode) {
    print('activating wakelock in debug');
    Wakelock.enable();
  }

  runApp(App());
}

Sidenote:
If all you need is the device to stop locking itself after some time then try increasing the sleep delay under the Display setting on the device itself, or use a setting in developer options called Stay awake while charging which allows the device to stay on forever while charging.


text:
Q: Time complexity of depth-first graph algorithm I am starting to learn time complexity, and I looked in the examples for the time complexity for some simple sort.
I wanted to know how do we calculate average time complexity for a depth-first search in a graph with |V|=n and |E|=m,let the start node be 'u' and end node be 'v'.

A: The time complexity for DFS is O(n + m). We get this complexity considering the fact that we are visiting each node only once and in the case of a tree (no cycles) we are crossing all the edges once.
For example, if the start node is u, and the end node is v, we are thinking at the worst-case scenario when v will be the last visited node.
So we are starting to visit each the first neighbor's of u connected component, then the second neighbor's connected component, and so on until the last neighbor's connected component, where we find v. We have visited each node only once, and didn't crossed the same edge more than once.

A: it will be O(n+m) if the graph is given in the form of adjacency list but
  if the graph is in the form of adjacency matrix then the complexity is O(n*n),
as we have to traverse through the whole row until we find an edge.