text:
Q: CMake cannot find QWidgets I have a CMakeLists.txt file which looks like this:
# CMakeLists.txt
project(myApp)

# Set minimum version of CMake
cmake_minimum_required(VERSION 3.5)

# Instruct CMake to run moc automatically when needed.
set(CMAKE_AUTOMOC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)

# Find Qt5Core and Qt5Widgets
find_package(Qt5Core REQUIRED)
find_package(Qt5Widgets REQUIRED)

# For finding Qt includes
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
include_directories(${Qt5Widgets_INCLUDE_DIRS})
include_directories(${Qt5Core_INCLUDE_DIRS})

# Collect source files
set(SOURCE
    main.cpp
    mainwindow.cpp
)

# Collect header files
set(HEADERS
    mainwindow.h
)

# Create executable
add_executable(prog ${SOURCE})

# Linking Editor with Qt libraries
target_link_libraries(prog Qt5::Core Qt5::Widgets)

When I run cmake and then make the following error message is presented;
Scanning dependencies of target Prog
[ 40%] Building CXX object CMakeFiles/Prog.dir/main.cpp.o
In file included from /path/main.cpp:7:0:
/path/mainwindow.h:7:20: fatal error: QWidgets: No such file or directory
compilation terminated.

Where am I doing wrong with the CMake file?
mainwindow.h looks like this:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
/*
 * mainwindow.h
 */
#include <QMainWindow>
#include <QWidgets>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidgets *parent = 0);
    ~MainWindow();

};

#endif

A: It should be
#include <QWidget>

class MainWindow : public QMainWindow
{

...


text:
Q: Highlighting selected menu item Page named index.php contains 1 menu with 3 options. Menu links lead to URL:index.php?id_product=xy. Then PHP reads id_product with GET and prints details from database. Now I want to highlight(change color of text) of the last clicked menu item. How to do this? Is it possible to read the value of id_product form URL with jQuery and then to add text effect to clicked menu item? Any ideas?

1

2

3

A: First, add some id tags to your elements:

1

2

3

Then add class "highlight" to the proper $_GET variable using javascript/jquery and a sprinkle of php:

Finally create the highlight class with css:

A: <?php
$menu_items = array(1, 2, 3);
$product_id = $_GET['id_product'];

echo "
";
foreach($menu_items as $menu_item){
    echo "
" . $menu_item . "
";
}
echo "
";
?>

This will add an active class to the menu item based on id_product

A: This should be work.
$(function()){
    var file_url = window.location.pathname.substring(window.location.pathname.lastIndexOf('/')+1)
    $("ul > li > a[href="+file_url+"]").addClass("selected");
}

another way should be
$(function(){
    $("ul > li > a[href$='"+window.location.search+"']").addClass("selected");
})

anyway it is easier only with php :)
foreach ($products as $p) {
  $selected = ($_GET["id_product"]==$p->id)?" class='selected'":"";
  echo "id."'".$selected.">".$p->id."";
}

or

redpajama_set_name: RedPajamaStackExchange


text:
Q: Optimizing django DB access when you perform multiple filters different times on one base QuerySet that filtered daterange I have a view that does something like this:
objectBase = MyModel.objects.filter(startDate__range=(start,end))
automatedObjects = objectBase.filter(automated = True).count()
userCreatedObjects = objectBase.filter(userCreated = True).count()
bookObjects = objectBase.filter(subClass = 'book').count()
pageObjects = objectBase.filter(subClass = 'page').count()
allObjectsCount = objectBase.count()

I am using 1.2.4 and the latest postgres
Anyways, I have about 20 different ways I need to filter my objectBase that filtered by date, and I noticed that each SQL query filters by date. Is there a more efficient way to make the subsequent queries not have to filter by date? Would there be a speed difference?
Also what do you think would be the best method for caching the objectBase query since theoretically it could hold hundreds or thousands of objects for the dates filtered and the likely hood of the start, end dates being the same for a request is very unlikely.
like say somebody could request the stats between dates t1 and t2, and then later request t3 to t4 where t1 < t3 < t2 and t2 < t4 so there is some overlap. Is there a way to cache it so where there is overlap between the requests that it would have to access the db for it?
sorry if this seems like a hefty request, but any help would be appreciated.

A: To reduce the number of queries...
objectBase = MyModel.objects.filter(startDate__range=(start,end))
automated, user_created, books, pages, total = 0,0,0,0,0
for o in objectBase:
    if o.automated: automated += 1
    if o.userCreated: user_created += 1
    if o.subClass == 'book': books += 1
    if o.subClass == 'page': pages += 1
    total += 1

This will only execute a single query, but it will probably be slower than what you're already doing, depending on your SQL indexes. If all of the fields you're counting on are indexed, along with the date range, your solution will be quick. I'm going to doubt that you have all these fields indexed however.
To your question on caching. There is no easy way to cache query set results without using the same query set instance. You could attempt using the django cache framework, but if you have many thousands of rows in your table, I don't think caching will help you.
My advice would be to create indexes on all the columns you are counting that are covered by the date range. This should make your .count queries extremely fast without having to iterate over a potentially massive collection.

A: The way you are doing it should be fine except you encounter some heavy performance problems. Creating the queryset objectBase doesn't hit the database, because the query is not executed yet. Retrieving all objects from the db and caching them via python/django might consume much memory and reduce your performance. Doing the counting via the database/sql queries should be the fastest way to get your results!


text:
Q: Read last integer file C++ I have a question. Why my program don't read the last integer if I don't put a space at the end of file? If I have a text file with a only number, without end space, the program don't read anything.
This is my program :
#include <iostream>
#include <fstream>

using namespace std;

int main(){
    fstream f1,f2;
    int k;
    int q;

    cout << "Inserisci numero lettere da leggere : ";
    cin >> q;

    f1.open("in.txt", ios::in);
    f2.open("out.txt", ios::out);

    if(f1.fail()){
        cout << "Impossibile aprire il file";
        exit(1);
    }

    f1 >> k;

    while( !f1.eof() && q > 0){
        q--;
        cout << k << '\n';
        f2 << k;
        f1 >> k;
    }

    f1.close();
    f2.close();

    return 0;
}

A: Your program read all the numbers, but you have !f1.eof() check after a read operation. And when there is an end of file after the last number, you never output it.
Replace
f1 >> k;

while( !f1.eof() && q > 0){
    q--;
    cout << k << '\n';
    f2 << k;
    f1 >> k;
}

with
while( f1 >> k && q > 0){
    q--;
    cout << k << '\n';
    f2 << k;
}

And read some articles about input/output via streams.


text:
Q: Admob interstitial ads on 2.2 I want to implement interstitial (full screen ads) from Admob in my game, but I want to support Android 2.2.
Now admob SDK go with Google play services and require 2.3+ android. There is services for froyo (2.2), but in this library there is now admob support (as I know)
Is there any way to implement interstitial ads from admob in 2.2?
Thanks

A: No and quite honestly you should consider the business value of attempting to support Android 2.2 since it has such a minute (and falling0 market share.


text:
Q: Every update fails I have been using VSCode for months and enjoying it for Python. Every update done through the app (by clicking the "Update" button on bottom right popup) has resulted in a failure to close VSCode. I find it odd because the only executable VSCode.exe running in process is the installer. If I kill that process I kill the installation. Either way, it jacks up my VSCode installation and I have to re-download it from Microsoft. This happens on both my Windows 10 devices.
Is there another way to update VSCode where this is not an issue?


text:
Q: Not able to connect remote git repository through SSH I have got 2 remote git repositories on the same server. On one repository, I am able to connect properly while on other I am not able to do so. It keeps on asking for password.
I have connected to SSH bby adding ppk key using pageant.
Can anyone help in fixing this. Please let me know what server changes I have to do so that I can make the changes over there.


text:
Q: Non italic index text I'm using the following code for my index.
\documentclass[a4paper,11pt,twoside, openleft]{book}

\usepackage{makeidx}\makeindex
\newcommand*{\formatfirst}[1]{\MakeUppercase{#1}}
\makeatletter
\newcommand*{\mymacro}[1]{%
  \expandafter\formatfirst\expandafter{\@car #1\@empty\@nil}%
  \@cdr #1\@empty\@nil}
\newcommand*\boldindexhardcode[1]{%
  \def\@boldindexhardcode{\boldindexhardcode@i#1 \@nil}%
    {\itshape\@boldindexhardcode}\index{#1@\@boldindexhardcode}}
\def\boldindexhardcode@i#1 #2\@nil{%
  \mymacro{#1}%
  \ifx\\#2\\%
  \else
    \@ReturnAfterFi{%
      \space
      \boldindexhardcode@i#2\@nil
    }%
  \fi}
\long\def\@ReturnAfterFi#1\fi{\fi#1}
\makeatother

\newcommand{\boldindex}[1]{ \textcolor{DarkPurple}{\textbf{\boldindexhardcode{#1}}}}

\begin{document}
\chapter{Chapter}
\boldindex{Test}\\
\boldindex{tEst}\\
\boldindex{teSt}\\
\boldindex{tesT}

\printindex

\end{document}

It renders like this:
How am I able to remove the weird italic text, while keeping the bold text?

A: removing \itshape from newcommand*\boldindexhardcode[1]{…}


text:
Q: What is customer/service_head.tpl file in Xcart? Am newbie in X cart.
How load customer/service_head.tpl in Xcart and not included,I can't saw that file in skin/customer folder.Is there any process to run that file display in x cart?Am So confused don't know what's wrong.
Please Give me Solution.

A: The file is located here
./skin/common_files/customer/service_head.tpl
The file is loaded from the file like
skin/your_skin_name/customer/home.tpl:  {include file="customer/service_head.tpl"}
or from
skin/common_files/customer/home.tpl by default
Try our 'Webmaster mode' feature
https://demo.x-cart.com/demo_goldplus/admin/editor_mode.php
https://help.x-cart.com/index.php?title=X-Cart:Using_Webmaster_mode


text:
Q: Ruby(Chef) - Convert hash into array I have a chef cookbook with a hash.
foo = {
  'herp' => 42,
  'derp' => 84
}

I have a LWRP resource (bar) that can only take arrays
iis_root 'some string' do
  bar []
end

How can I convert 'foo' into an array so it can be used in the resource 'bar'
Looking for something like this:
[ "herp=42","derp=84"]

A: bar = foo.map{ |e| e.join("=")}
=> ["herp=42", "derp=84"]

A: You can iterate through the hash and turn it into an array like so.
ary = Array.New
foo.each do |key, value|
  ary << key + "=" + value
end

This will create the array you are looking for.

A: You can do it using map:
foo.map { |key, value| key + "=" + value.to_s}
=> ["herp=42", "derp=84"]

A: OscillatingMonkey answer correct, but with few changes:
For topic starter, this code doing exactly what you need.
bar = Array.new([])
foo.each do |key, value|
  bar << key + "=" + value.to_s
end
=> ["herp=42", "derp=84"]

A: I would just use map with string interpolation:
foo.map { |k, v| "#{k}=#{v}" }
#=> ["herp=42", "derp=84"]


text:
Q: 642% CPU used along with GPU during training. Is it normal? I have a PC configuration of
CPU: Intel Core i7 9700K @ 3.60 Ghz
GPU: Nvidia GeForce GTX1060
When I train using tensorflow-gpu, both my CPU and GPU are used. Is this  normal behavior?
The usage stats as below from
htop
)
nvidia-smi

A: Generally it is normal because Tensorflow uses CPU for certain operations like data preproccessing. For more you can check this. If you want to have a better insight about what utilizes your CPU, try the Profiler tools suite.


text:
Q: CSS ONLY Hover over button animate, hover out animate hi im trying to create navigation drawer button and want to animate it when hovering over it and than animate when hovering out wondering if its possible to do it only in css. here is how far i have gone and also i ran into problem when animation is finished scale of line changes back to regular instead of what animation has.
<button id="navbut" style="position: fixed;right: 0;">

</button>

#line1 {
  position         : relative;
  height           : 1px;
  width            : 3em;
  background       : rgb(255, 255, 255);
  margin-top       : 0.625rem;
  transform-origin : 100% 50% 0px;
  transform        : translate(0px);
  }
#line2 {
  position         : relative;
  height           : 1px;
  width            : 3em;
  background       : rgb(255, 255, 255);
  margin-top       : 0.725rem;
  transform-origin : 100% 50% 0px;
  transform        : translate(0px);
  }
#line3 {
  position         : relative;
  height           : 1px;
  width            : 3em;
  background       : rgb(255, 255, 255);
  margin-top       : 0.825rem;
  transform-origin : 100% 50% 0px;
  transform        : translate(0px);
  }
#navbut {
  background : none;
  width      : 3rem;
  top        : 0.rem;
  cursor     : pointer;
  border     : none;
  }
#navbut:hover>#line1 {
  animation: sha 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
  }
#navbut:hover>#line2 {
  animation: sh 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
  }
@keyframes sh {
  100% {transform: scale(0.75, 1); }
  }
@keyframes sha {
  100% {transform: scale(0.45, 1); }
  }

i want that when mouse is over item after animation finishes to stay on that scale instead of reverting back, and if possible to animate hover out

A: It's possible without animations. Just use transform.
Example:
button{
    transform: scale(1);
    transition: transform ease 1s;
}

button:hover{
    transform: scale(0.89);
}


text:
Q: How do I gain system permission so that I can compile emacs' etags? How do I gain permission to run compile in emacs?
I am in the middle of creating TAGS file in a specific directory (/usr/share/emacs/24.3/lisp) - following through intro to programming in Emacs Lisp by Robert Chassell.
I have run the compile command,

M-x compile RET etags *.el RET

In return I am told that permission has been denied. This is my personal computer, running ubuntu 14.04 LTS with sudo privilege (my personal computer).
I have found some information permission denied when running sh scripts which may be applicable and is worth trying (perhaps try chmod +x *.el instead of chmod + x filename.sh in the example?) but is a little scared as these are not exact solutions and I am fairly new to programming let alone linux (I have already corrupted some files and had to install ubuntu 14.04 all over again a few days ago
The below is the actual message shown in the bufer:
-*- mode: compilation; default-directory: "/usr/share/emacs/24.3/lisp/" -*-
Compilation started at Sat Jun  4 05:36:16

etags *.el
TAGS: Permission denied

Compilation exited abnormally with code 1 at Sat Jun  4 05:36:16

A: First off, you can get half of tags functionality (for Emacs lisp, anyway) for free with find-function.  I bind it to C-h C-f.  There's also find-variable, but I find describe-variable (C-h v) to be much more useful.

You're probably running Emacs as a regular user rather than an administrator.  This is absolutely the correct thing to do, but will not allow you to write to system directories like anything under /usr.  You can either run Emacs as root (sudo emacs), or use a package called tramp that allows you to work as a different user (it also allows you to edit files on remote machines).
Open the directory as root with C-x C-f /sudo:localhost:/usr/share/emacs/24.3/lisp/.  When you have the directory open, run compile.
Also, I doubt that command will do what you want.  Most Emacs installations gzip the lisp source, and while etags seems to be smart enough to handle this, the glob pattern *.el will not match.  Furthermore, there are subdirectories.  It's best to use the find command: find -name "*.el" -o -name "*.el.gz" -exec etags '{}' +.

The real solution is to not put the TAGS file in that directory.  Simply put it somewhere else where you have write permission.
cd; find /usr/share/emacs/24.3/lisp -name "*.el" -o -name "*.el.gz" -exec etags '{}' +`


text:
Q: How to refer pat token present under setting.xml in pom file I have below scm tag in pom.xml file. I am currently passing pat token in connection so that it can autrozie azure pipeline to comit the next version number in pom file after release.
How can I remove the pat-token from this connecton and refer it from setting.xml file or how to use it a variable so that its not visible to everyone
scm
connection
scm:git:https://pat-token@dev.azure.com/microservice-git-code

A: According to your description, you could try to install the Replace Token extension first.Then you could use the #{PAT}# in your pom.xml file.
scm connection scm:git:https://#{PAT}#@dev.azure.com/microservice-git-code

And create the PAT variable as secret in you pipeline and set the target file as **/pom.xml.

A: I was able to achieve that by using the project.scm.id tag in the properties file of pom.xml


text:
Q: Using Reflection to auto-fill in defaults in an object where possible Here is some code I've been twiddling with to try and lazily fill in fields in object, mostly for object factories in JUnit but it could be quite a useful method to have.
    private void lazyObjectFill(Object profil) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    final Method[] list = profil.getClass().getDeclaredMethods();
    for (Method m : list) {
        if (Modifier.isPublic(m.getModifiers()) && m.getName().startsWith("set")) {

            final Class< ?>[] parameterTypes = m.getParameterTypes();
            if (parameterTypes.length == 1) {
                final Class< ?> clazz = parameterTypes[0];
                if (clazz == String.class) {
                    log.info("Invoking " + m.getName() + " with [\"\"]");
                    m.invoke("");
                } else if (clazz.isPrimitive() && Defaults.defaultValue(clazz) != null) {
                    log.info("Invoking " + m.getName() + " with [" + Defaults.defaultValue(clazz) + "]");
                    m.invoke(Defaults.defaultValue(clazz));
                }
            }

        }
    }
}

We get the following exception when running this code on an object.
java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:592)

The exception occurs when running m.invoke(""); on a string setter.

Updated source code for the benefit of the googlers.
private void lazyObjectFill(Object obj) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    final Method[] list = obj.getClass().getDeclaredMethods();
    for (Method method : list) {
        method.setAccessible(true);
        if (Modifier.isPublic(method.getModifiers()) && method.getName().startsWith("set")) {

            final Class< ?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length == 1) {
                final Class< ?> clazz = parameterTypes[0];
                if (clazz == String.class) {
                    log.info("Invoking " + method.getName() + " with [\"\"]");
                    method.invoke(obj, "");
                } else if (clazz.isPrimitive() && Defaults.defaultValue(clazz) != null) {
                    log.info("Invoking " + method.getName() + " with [" + Defaults.defaultValue(clazz) + "]");
                    method.invoke(obj, Defaults.defaultValue(clazz));
                }
            }

        }
    }
}

A: You are almost there, but methods are static and they need an object on which to invoke them.
i.e.
m.invoke(profil, "");

and
m.invoke(profil, Defaults.defaultValue(clazz));

You were (unknowingly) trying to execute the method on a string object without parameters. And since the string class does not have that method, it had to fail. Details can be found in the Method javadoc.
BTW: Static methods are invoked like this:
method.invoke(null, params);

A: You know that invoke method of Method takes two arguments ? As a consequence, I guess you wrote
m.invoke(profil, "")

Besides, I would personnally not have separated String from other objects.
And finally, to correctly identify obejct fields, i would have preferred a mixed approach

*

*Use an enumeration of non static Field members

*Use BeanInfo to access bean properties.

A: The first parameter of the Method.invoke() is the object which will invoke the method.
For example in your case m.invoke(profil, ""); or m.invoke(profil, Defaults.defaultValue(clazz));


text:
Q: Persistent BottomSheet Below Fragment Contents? Using a Persistent BottomSheet, within a CoordinatorLayout, how can one prevent the BottomSheet from covering other user interface elements when the BottomSheet is in its COLLAPSED aka peeked state?
I've successfully added a BottomSheet to my Navigation Drawer & Fragment based application; however, as mentioned above, the BottomSheet covers user interface elements within my fragment container when it's either COLLAPSED or EXPANDED
Covering part of the fragment is ok when the BottomSheet is expanded since, if needed, users can collapse the BottomSheet to its peek state. However, I've explicitly disabled* the user from hiding the BottomSheet and thus need a way of ensuring the fragment container remains above the BottomSheet at all times when the BottomSheet is in its collapsed state. Photos are worth a thousand words so hopefully the following clarify the issue

Above: A redacted screenshot of a fragment with two buttons, A & B, near the bottom of the screen. Note: The fragment's root is a scrollview which is why button B is cut off by the System's Back and Home buttons

Above: The same fragment as seen above but with the BottomSheet fully expanded. For reference the BottomSheet is everything below and including the green bar. Note: The fact that the BottomSheet covers button A & B is ok since the BottomSheet is fully expanded

Above: The same fragment as seen above but with the BottomSheet in its collapsed state. Note: Now that the BottomSheet is fully collapsed and cannot be collapsed further the issue can be seen in that it covers part of button B and more importantly the fragment scrolls below the BottomSheet

Originally I was hoping to fix the issue by subclassing  AppBarLayout.ScrollingViewBehavior similar to this answer. Sadly I was unable adjust the child view's height within CoordinatorLayout.Behavior#onDependentViewChanged. When called, the child's height appears unset (-1) and adding a OnLayoutChangedListener requires the child to be final making it impossible to update the height once the height is defined in the layout changed listener callback. I'd still like to solve the problem using a subclassed Behavior but for the time being I'm stumped
My next thought was to add a "spacer" view to each of my fragment layouts using the <include/> tag. I then could provide add/show and remove/hide helper methods to an abstract base fragment class which all fragments needing to display the BottomSheet would extend. This spacer view would be programmatically assigned the peek height of the BottomSheet making room for it within the fragment. The BottomSheet would then cover the spacer view which is fine since I don't consider it part of the fragment's usable view area. I'm currently working on implementing this approach and while I think it'll work I'm skeptical it's good solution
Any advice, suggestions, and potential solutions are welcome and thanks in advance!
And to clarify below is a condensed version of my top-level application layout
<android.support.v4.widget.DrawerLayout>

    <android.support.design.widget.CoordinatorLayout>

        <android.support.design.widget.AppBarLayout>

            <android.support.design.widget.CollapsingToolbarLayout>

                <ImageView ... />

                <android.support.v7.widget.Toolbar ... />
            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>

        <!-- All fragments assume the following view container via a FragmentTransaction's
             replace method which in pseudocode looks something like
             FragmentTransaction.replace(R.id.main_activity_fragment_container,
             fragment, ...).commit();
        -->
        <FrameLayout android:id="@+id/main_activity_fragment_container" ... />

        <com.xyz.abc.view.BottomSheetView ... />

        <android.support.design.widget.FloatingActionButton ... />
    </android.support.design.widget.CoordinatorLayout>

    <android.support.design.widget.NavigationView ... />
</android.support.v4.widget.DrawerLayout>

*It appears BottomSheetBehavior#mHideable} is false by default


text:
Q: Text-to-speech libraries for iPhone
Possible Duplicate:
Text to speech on iPhone

How do I get started with text-to-speech conversion in iPhone?
I want to read the text typed by the user. Are there any available libraries or demos? I have gone through some of them, but I didn't understand where to start it from.

A: For online,you can use my Google-TTS-Library-For-iOS to achieve your goal.
Offline iPhone TTS implementation is easy to do. You can see the details here.
There are many paid and free iOS TTS libraries are available .
They are ,
Free (Offline/Online)

*

*iphone-tts  Note: read "HOW TO USE" section .

*TTSOverview-iOS

*flite-1.4-iphone

*Openears

*cmu.edu

*RJGoogleTTS

*VocalKit
Paid (Online)

*

*iSpeech iOS SDK (TTS and ASR)

*nuance Dragon-dictation

*Acapala

*ivona

*neospeech


text:
Q: How can I wait a while and then change variable? I have a little code using jquery and I want to wait like, 300ms and then change a variable. I tried setTimeout but it wouldn't work, it just made the variable change instantly.
setTimeout(animationWait = 0, 300);

(I defined animationWait earlier globally in the document) Basically what I'm trying to do is wait for a click to end before another click can be done. So i thought I'd set a variable and then wait 300ms,
$('#up-arrow').live('click', function(e) {

    if(animationWait == 0) {
        animationWait = 1;
        .... /* Code */
    }
}

So I need to change the animationWait back to 0 again after a delay to run the code. I've tried a bunch of stuff but it's still not working, any ideas?

A: You are not using setTimeout quite right. It must be passed either a function name or an anonymous function.
//anonymous function
setTimeout( function() { animationWait = 0 }, 300);

//or give it a function name
function change() { animationWait = 0; }
setTimeout(change, 300);

A: The parameter what you pass should be an evaluation statement. For me this works fine:
var animationWait = -1;    //Initially set the value to -1
alert(animationWait);      //alert to see the value
setTimeout("animationWait = 0", 300);    //Setting the value to 0
setTimeout("alert(animationWait)", 400);  //Alert after 400 ms

A: Have you tried using jQuery function delay() ?
A standard use case would look something like this:
$('item').delay(300).delayedEffectFunction();

Where delayedEffectFunction() is a made-up function you want to be delayed.

A: The answer to your question as asked is that setTimeout() expects the first parameter to be a function reference - either the name of a function declared elsewhere or an anonymous function. (Or a string, but for several reasons using a string is almost always the wrong solution.) Your code as is simply executes the expression animationWait = 0 and passes the result of that expression (0) to setTimeout().
So to execute your single line of code via setTimeout() I'd recommend wrapping it in an anonymous function and passing that function to setTimeout():
setTimeout(function(){ animationWait = 0; }, 300);

However, if you are doing animation with jQuery its animation methods allow you to pass a callback function to be executed when the animation ends, so you can do this type of processing there rather than independently setting your own timeout. For example, if your animation was like this:
$("#someelement").animate({someproperty:"somevalue"},
                          300);

Then you could add a callback function that will be called after this animation completes:
$("#someelement").animate(({someproperty:"somevalue"},
                          300,
                          function(){ animationWait = 0; });

To my eye this is neater than a separate setTimeout() call, but also it is easier to maintain because the duration only has to be specified in one place rather than you having to sync your own timeout to the animation.
A similar syntax applies to other jQuery methods like .fadeIn(), .hide(), etc. See the .animate() doco for more information and examples.


text:
Q: scroll page selenium webdriver JS I am trying to test on selenium webdriver JS. I have functions that look for an element on the site.
 createAccount() {
        return this.driver.findElement(By.css(".button"));
    }

There is a function that scrolls the page to the desired item. I want to scroll through the function, pass the search function as an argument.
scrollToElement(el) {
        this.driver.manage().window().maximize();
         return  this.driver.executeScript('arguments[0].scrollIntoView(true);', el );
    }

The test runs in a separate file.
 async main() {
    const page = this.Page;
    page.open();
    page.scrollToElement(createAccount);
    await page.createAccount().click();
}

And when I run it, an error appears:

UnhandledPromiseRejectionWarning: JavascriptError: javascript error: Cannot read property 'scrollToElement' of null

A: Looks like it cannot find the createAccount element.
Try finding the element using the id or by xpath.


text:
Q: Electromagnetic waves: The speed of light and relative permittivity In the chapter about transmission lines, there was the following question:
Given a frequency of 1GHz and a relative permittivity of 2.25, what is the wavelength of the sinusoidal wave?
In an unofficial solution they do the following:
$$c = \frac{1}{\sqrt{\mu\epsilon}} = \frac{1}{\sqrt{\mu_0\epsilon_0 \cdot \epsilon_r}} = \frac{3\cdot10^8}{\sqrt{2.25}} = 2 \cdot 10^8 = \lambda f$$
Which results in a wavelength of $0.2m$. The fact that this solution equals the numerical solution given by our prof makes me believe that this is the right method.
There's one thing I don't understand, why can you write $\sqrt{\mu\epsilon} =\sqrt{\mu_0\epsilon_0 \cdot \epsilon_r}$?
Any help is really appreciated, thanks!

A: The relative permittivity is defined as the ratio $$\epsilon_r = \frac{\epsilon}{\epsilon_0}$$


text:
Q: Reduced cone of $S^n$ Reduced cone of $S^n$. I could prove that the cone of $S^n$ is isomorphic to $D^{n+1}$. I can sense that that the reduced cone of $\tilde{C}(S^n)$ is $D^{n+1}$. But I cannot give an exact homeomorphism from $\tilde{C}(S^n)$ to $D^{n+1}$.

A: Note, the basepoint of $D^{n+1}$ is not the origin. Rather it is the unit vector $e_1=(1,0,\dots,0)$, which is also the basepoint of its subspace $S^n$. Using the convexity of $D^{n+1}$ we see that the map $D^{n+1}\times I\rightarrow D^{n+1}$ given by
$$F_t(x)=(1-t)\cdot x+t\cdot e_1$$
is a well-defined pointed contraction. Now restrict $F$ to $S^n\times I$ so that it becomes a pointed null-homotopy of the inclusion $S^n\hookrightarrow D^{n+1}$. Then for all $z\in S^n$ and $t\in I$ we have
$$F_1(z)=e_1,\qquad F_t(e_1)=e_1.$$
In particular $F$ factors over the quotient
$$CS^n=(S^n\times I)/(S^n\times\{1\}\cup\{e_1\}\times I)$$
to give a map
$$\widetilde F:CS^n\rightarrow D^{n+1}.$$
We check that $\widetilde F$ is one-to-one and onto. Since $CS^n$ is compact and $D^{n+1}$ is Hausdorff, $\widetilde F$ is a homeomorphism.


text:
Q: c++ and MySQL connection I'm totally new to c++ and I havn't done that much so far.
Right now, I need to setup a DB-connection to a mysql-server, to retrieve some data.
So I found this question MySQL C++ Connector getting a string with SELECT query. I tried to setup everything like it is explained in the question, but I ended up with having several errors.
My code:
// important part for the mysql-stuff
#include <mysql/mysql.h>

// Basic setup for the DB
static char const *opt_host_name = "localhost"; /* HOST */
static char const *opt_user_name = "root"; /* USERNAME */
static char const *opt_password = "mypass"; /* PASSWORD */
static unsigned int opt_port_num = 3306; /* PORT */
static char const *opt_socket_name = NULL; /* SOCKET NAME, DO NOT CHANGE */
static char const *opt_db_name = "mydb"; /* DATABASE NAME */
static unsigned int opt_flags = 0; /* CONNECTION FLAGS, DO NOT CHANGE */

And here is the method, where I am trying to get an output:
int main(void) {
    try {

        // setup the connection
        MYSQL *conn; /* pointer to connection handler */
        MYSQL_RES *res; /* holds the result set */
        MYSQL_ROW row;

        /* INITIALIZE CONNECTION HANDLER, DO NOT CHANGE */
        conn = mysql_init(NULL);

        /* THIS CONNECTS TO SERVER, DO NOT CHANGE ANYTHING HERE */
        mysql_real_connect(conn, opt_host_name, opt_user_name, opt_password,
            opt_db_name, opt_port_num, opt_socket_name, opt_flags);

        /* show tables in the database (test for errors also) */
        mysql_query(conn, "SELECT * FROM plates");
        res = mysql_store_result(conn);

        // get the number of the columns
        int num_fields = mysql_num_fields(res);

        while ((row = mysql_fetch_row(res))) {
            // Print all columns
            for (int i = 0; i < num_fields; i++) {
                // Make sure row[i] is valid!

                cout << row[i];
            }
        }
    }
}

After calling make in the specific folder, where the file is located, it prints this:

undefined reference to mysql_init
undefined reference to mysql_real_connect

... and every function listed in that code.
This here is the Makefile
SAMPLES = cpd01.out

.PHONY: all
all: $(SAMPLES)

.PHONY: clean
clean:
    rm -f $(SAMPLES)

%.out : %.cpp
    g++ -g3 -o $@ $< -DLINUX -I/usr/include/gx -ldl -DGX_NAMESPACES

I didn't make that Makefile, and as mentioned above, I have no idea what PHONY (or else) stand for. Will have to dig a bit deeper, i guess.
If I understand  PaulMcKenzie correclty, I have to add something here, right?

A: MySQL comes with a script you can run that tells you which libraries to link to: mysql_config --libs.
On my system it gives:
$ mysql_config --libs
-L/usr/lib64/mysql -lmysqlclient -lpthread -lz -lm -lssl -lcrypto -ldl

You need to add those flags to the link command (or the compiler command if you link all at the same time).
If you are using GNU Make you should be able to do this:
SAMPLES = cpd01.out

MYSQL_LIBS = $(shell mysql_config --libs)

.PHONY: all
all: $(SAMPLES)

.PHONY: clean
clean:
    rm -f $(SAMPLES)

%.out : %.cpp
    g++ -g3 -o $@ $< -DLINUX -I/usr/include/gx -ldl -DGX_NAMESPACES $(MYSQL_LIBS)


text:
Q: Keras tuner takes long time between trials I have recently noticed wierd behavior of Keras Tuner. The elapsed time is around 6 houres but the algorythm is running around 20 houres. Also I have noticed that there is really long time between trials.
I am using code bellow:
tuner_neurons = kt.BayesianOptimization(
model_builder,
max_trials = 1000,
num_initial_points = 500,
seed = 420,
objective='val_mean_absolute_percentage_error',
directory='hyperopt',
project_name='hyperopt_neurons_bayesian_1'
)
history_hyperopt = tuner_neurons.search(
    X_train_dict[0],
    y_train_dict[0],
    batch_size = BATCH,
    epochs = 1000,
    validation_data = (X_valid_dict[0], y_valid_dict[0]),
    verbose = 1,
    steps_per_epoch=X_train_dict[0].shape[0] // BATCH,
    callbacks=[learning_rate_reduction, early_stopping]
)

The cell bellow is running without any log from calculation:

Also the processor is on full speed so it is calculating something, just don't have any idea what. To find what parameters to find in BO should be pretty fast. Any ideas?


text:
Q: How to generate all files when making a new directory using "rails new" When I use rails new to create a new projet with Rails 6.0.2.2, Rails generates only these files:
c:\Users\computer>rails new .
       exist
      create  README.md
      create  Rakefile
      create  .ruby-version
      create  config.ru
      create  .gitignore
      create  Gemfile
         run  git init from "."

I don't understand why.

A: The rails new command expects a name for the directory to generate the application in (which also becomes the application name), but . seems to not be acceptable.
Try invoking the command like this:
rails new my_app_name

It could also be that it is trying to initialize a git repository and fails. Hard to tell from the output of your post whether that finishes or not. Maybe you don't have git installed, or maybe there's a problem with the command (maybe you are already inside another git repository?). You could try to skip that part only by passing the --skip-git flag:
rails new --skip-git my_app_name


text:
Q: Why is my webhook call fulfillment deleting my parameter in Dialogflow? I'm working on a dialogflow chatbot. It retrieves the user's name and email at the start of the conversation, and I have a sessions-vars output context with a lifespan of 60 to keep these parameters throughout the conversation. I know they are kept by checking diagnostic info and referring to them in chatbot replies as #context.parameter.
Near the end of my conversation path there in an intent called 110checklistemail.sendemail where my chatbot asks the user if they want information emailed to their email or sent in the chat. If the user says "Email it to me" I have webhook call enabled, where it redirects to fulfillment code, pasted below.
I followed a guide to integrate the chatbot with sendgrid, and the email is sent and does work if I prompt for the email at that specific intent. However, if I don't prompt for the email address (eg. the user says 'email it to me') then the agent is not able to send the email because the email parameter is now blank, despite being populated before in a context with a long lifespan.
Fulfillment code is the following:

'use strict';

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const sgMail = require('@sendgrid/mail');

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
process.env.SENDGRID_API_KEY = 'SG._APIKEYHERE';

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

    function sendEmail(agent) {
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
    const emailParam = agent.parameters.email;

    const msg = {
      to: emailParam,
      from: 'tyler@mailfence.com',
      subject: 'Just a quick note',
      text: 'Just saying Hi ${agent.parameters.given-name} from Dialogflow...',
      html: 'Just saying Hi Hi ${agent.parameters.given-name} from Dialogflow...',
    };
    console.log(msg);
    sgMail.send(msg);

    agent.add(`What a beauty!`);
  }

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('110checklistemail.sendemail', sendEmail);
  // intentMap.set('your intent name here', yourFunctionHandler);
  // intentMap.set('your intent name here', googleAssistantHandler);
  agent.handleRequest(intentMap);
});

Snippet from Diagnostic info:
{
  "responseId": "130742d9-7453-41c6-8b27-ee8f91d9d02d-5a74d3f9",
  "queryResult": {
    "queryText": "Email it to me",
    "parameters": {
      "email": ""
    },
    "allRequiredParamsPresent": true,
    "fulfillmentText": "What a beauty!",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "What a beauty!"
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/tyler-vhyo/locations/global/agent/sessions/aef22896f9/contexts/1await_checklist_type",
        "lifespanCount": 4,
        "parameters": {
          "Jobtype.original": "custom shower",
          "email.original": "",
          "Jobtype": "custom shower",
          "email": ""
        }
      },
      {
        "name": "projects/tyler-vhyo/locations/global/agent/sessions/aef3d36-18d696f9/contexts/session-vars",
        "lifespanCount": 54,
        "parameters": {
          "last-name.original": "",
          "email.original": "",
          "email": "",
          "given-name.original": "Tim",
          "Jobtype": "custom shower",
          "Jobtype.original": "custom shower",
          "given-name": "Tim",
          "last-name": ""
        }

I was wondering why it wasn't working unless I prompt for the email in that specific intent, and I realised it's because the email parameters are now all blank (and definitely populated before!) I don't want to reprompt for the email when the user already has to input it at the start of the conversation.
How can I solve this issue and get the email to send off the pre-existing email parameter?
Also, how can I get the ${agent.parameters.given-name} code to reference the name parameter correctly in the email body? It hasn't been working for me and I don't know if there is a better way to pull parameters in the email.
I'm an extreme novice at coding at the code above is something I made following a guide. I really do have no idea what is happening so any advice is very welcome and appreciated. Thank you in advance!

A: Managed to solve the issue. Steps that I think led to it working:

*

*Added all the parameters to 'action and parameters' of the intent

*Checkmarked 'Is list'

*Added a default value for each parameter referring to itself from the earlier context in the form #session-vars.parametername

I don't understand 100% why it wouldn't work without the above steps, as the intent shouldn't modify or clear the parameters, but it seems to have done the trick.


text:
Q: MySQL query: Single Table multiple comparisions I have the following mysql table:
id     |  member     |
1      | abc
1      | pqr
2      | xyz
3      | pqr
3      | abc

I have been trying to write a query which would return the id which has exact same members as a given id. For example, if given id is 1 then the query should return 3 because both id 1 and id 3 have exact same members viz. {abc, pqr}. Any pointers? Appreciate it.
EDIT: The table may have duplicates, e.g. id 3 may have members {abc, abc} instead of {pqr, abc}, in which case the query should not return id 3.

A: Here's a solution that finds matching pairs for the entire table - you can add a where clause to filter as needed. Basically it does a self-join based on equal "member" and unequal "id". It then compares the resulting count grouped by the 2 ids and compares them to the total count of those ids from the original table. If they both match, it means they have the same exact members.
select
    t1.id, t2.id
from
    table t1
    inner join table t2
        on  t1.member = t2.member
            and t1.id < t2.id
    inner join (select id, count(1) as cnt from table group by id) c1
        on  t1.id = c1.id
    inner join (select id, count(1) as cnt from table group by id) c2
        on  t2.id = c2.id
group by
    t1.id, t2.id, c1.cnt, c2.cnt
having
    count(1) = c1.cnt
    and count(1) = c2.cnt
order by
    t1.id, t2.id

This is some sample data I used which returned matches of (1,3) and (6,7)
insert into table
values
    (1, 'abc'), (1, 'pqr'), (2, 'xyz'), (3, 'pqr'), (3, 'abc'), (4, 'abc'), (5, 'pqr'),
    (6, 'abc'), (6, 'def'), (6, 'ghi'), (7, 'abc'), (7, 'def'), (7, 'ghi')

A: try this:
declare @id int
set @id=1
select a.id from
(select id,COUNT(*) cnt from sample_table
where member in (select member from sample_table where id=@id)
and id <>@id
group by id)a
join
(select count(distinct member) cnt from sample_table where id=@id)b
on a.cnt=b.cnt

A: similar (to Derek Kromm's) approach using sub-queries:
SELECT id
FROM mc a
WHERE
  id != 1 AND
  member IN (
    SELECT member FROM mc WHERE id=1)
GROUP BY id
HAVING
  COUNT(*) IN (
    SELECT COUNT(*) FROM mc WHERE id=1) AND
  COUNT(*) IN (
    SELECT COUNT(*) FROM mc where id=a.id);

a logic here is we need all ids that match following 2 conditions:

*

*member is among those that belong to id 1

*total number of members is same as number of those that belong to id 1

*total number of selected members equal to total number of members for current id


text:
Q: Probability of drawing all red balls before any green ball Question:
Suppose that a box contains $r$ red balls, $g$ green balls,
and $b$ blue balls. Suppose also that balls are drawn from
the box one at a time, at random, without replacement.
What is the probability that all $r$ red balls will be obtained
before any green balls are obtained?
Solution(Partial):
I know this solution for $1$ red, $1$ green and $1$ blue balls:
$$\begin{array}{c|l|c}
\color{red}{red} & \color{green}{green} & \color{blue}{blue}  \\
\hline \\
\color{blue}{blue} & \color{red}{red} & \color{green}{green}  \\
\hline \\
\color{red}{red} & \color{green}{green} & \color{blue}{blue}   \\\hline \\
\color{green}{green} & \color{red}{red} & \color{blue}{blue}    \\\hline \\\color{green}{green} & \color{blue}{blue}  &  \color{red}{red} \\\hline \\ \color{blue}{blue}  & \color{green}{green} & \color{red}{red} \\
\end{array}$$
This means,that there are $3$ outcomes for this event with the sample space of $6$.So, probability is $\frac{1}{2}$.
But I don't know how to generalize this.
Please help.Thank you.

A: To count the sequences of $r+b+g$ draws in which all of the red balls precede all of the green balls, note that they are obtained by starting with the sequence
$$\underbrace{RR\ldots RR}_r\underbrace{GG\ldots GG}_g$$
and inserting the $b$ blue balls arbitrarily into the sequence. This is a straightforward stars-and-bars problem; the link has both a formula and a pretty decent explanation of it, but if you have questions, leave a comment. Bear in mind that in any given sequence the $r$ red balls can actually be arranged in $r!$ orders, the blue balls in $b!$, and the green balls in $g!$, so that a given sequence of colors actually corresponds to $r!b!g!$ different sequences of balls drawn. However, since this is the same for each sequence of colors, it does no harm to count sequences of colors instead of sequences of balls.
Once you have that, you need only count the possible sequences of colors. You have to choose $r$ positions for the red balls, $b$ for the blue balls, ...

A: The presence of blues is not relevant to the probability. Imagine that the reds and greens are all distinct, and lined up in a row at random.  We remove them one at a time, starting on the left.
There are $(r+g)!$ equally likely ways that the balls can be arranged. There are $r!g!$ ways to arrange them so that the reds are all before the greens. Thus the required probability is $\dfrac{r!g!}{(r+g)!}$.
This can be rewritten more compactly as $\dfrac{1}{\binom{r+g}{r}}$.

A: Here is a variation on Brian's answer. The ball colors can occur in ${(r+g+b)!\over r!g!b!}$ distinct orders, all of which are equally likely to occur.
We now count the number of "good" orders. Start with $r+g+b$ blank spaces and choose $b$ of them to be filled with blue balls. The remaining spaces can only be filled in one "good" way, so the number of good orders is $r+g+b\choose b$.
The required probability is $${{r+g+b\choose b} \over {(r+g+b)!\over r!g!b!}},$$ which  simplifies to the expression in André's answer.


text:
Q: Concurrency Issue in ISORequestListener I am using jpos library for transaction management(Spring boot project). I am implementing ISORequestListener as below.
@Component
public class MyRequestListner implements ISORequestListener, Configurable {

    protected String var1;
    protected String var2;

    @Override
    public void setConfiguration(Configuration cfg) throws ConfigurationException {
        var1 = cfg.get("var1");
        var2 = cfg.get("var2");
    }

    @Override
    public boolean process(ISOSource source, ISOMsg m) {
        Context ctx = new Context();
        ctx.put("ctx1", var1);
        ctx.put("ctx2", var2);
        return true;
    }
}

On running SonarQube (code analyzing tool), I got the error message as:

Annotate global variables with "@Autowired", "@Resource", "@Inject", or "@Value", or don't use on Spring @Component, @Controller, @Service, and @Repository classes.
Spring @Component, @Controller, @Service, and @Repository classes are singletons by default, meaning only one instance of the class is ever instantiated in the application.
Such a class might have a few static members, such as a logger, but all non-static members should be managed by Spring. That is, they should have one of these annotations: @Resource, @Inject, @Autowired or @Value.

Does this cause any concurrency issue(or thread issue) or internally handled by jpos? What could be the correct implementation if it really causes the problem?

A: Not a problem if you run jPOS within its own Q2 micro-kernel. If that's not the case, I'm afraid you're mostly on your own. Running inside Q2 is extremely simple, it's a one liner: new Q2().start(); that you can run from any other framework, and then let Q2 configure your jPOS components.


text:
Q: Europe validation expression validation expression ValidationExpression="\d{3}-\d{3}-\d{4}" for the format is this  ErrorMessage="Format: XXX-XXX-XXXX", I want the vaidatin expression to form like it can accept this europe format also of this kind XXXX-XXXXXX what I need to add in the above expression so that it can accept any.

A: Use the "or" operator (|)
"\d{3}-\d{3}-\d{4}|\d{4}-\d{6}"

This is a great introduction to regular expresssions if you are interested:
http://www.codeproject.com/Articles/9099/The-30-Minute-Regex-Tutorial


text:
Q: @Cacheable and @CachePut different return type (Will Spring's @CachePut annotation work with a void return type?)
I encountered the same problem
Because the problem has been for a long time, I do n't know if there is a solution
created a cache:
public static final String Key = "CacheKey";

@Cacheable(cacheNames = "userCache", key = "Key")
public List<User> getAllUsers() {
...
}

update this cache using the @CachePut
@CachePut(cacheNames = "userCache", key = "Key")
public User addUser(User user) {
...
}

output:
com.example.demo.dto.UserDTO cannot be cast to java.util.List

I searched for information for several days, but did not find the answer
In addition to using @CacheEvict (cacheNames = userCache, allEntries = true)
Is there a way to solve it using @Cacheable and @CachePut?
Thank you

A: I suggest reading up on how Spring Cache Abstraction works. https://docs.spring.io/spring-framework/docs/5.0.0.BUILD-SNAPSHOT/spring-framework-reference/html/cache.html
Very basically, caches are essentially key-value stores.. For the same parameters passed into a method, check the cache and return the cached result.  If the method is void, there is nothing to cache.  @CachePut needs a 'value' to pair with the 'key'.  If you want to cache the users added, addUser needs to return a User. Or have addUser call another method and move the @CachePut to that method.
Another issue you're facing, is your userCache from getAllUsers is List<User> and you're intending (although not working because of void) to put a User into the same cache that is expecting a List<User>
To put it another way, when you addUser, your userCache of List is now not in sync with the actual state of the result of getAllUsers so you need to evict the userCache of List
Change
@CachePut(cacheNames = "userCache", key = "Key")
to
@CacheEvict(cacheNames = "userCache", allEntries = true )
When you addUser, you will clear out your List cache, and next time you call getAllUsers, the cache will be updated with the now current result set.
This post is pretty much a duplicate of https://stackoverflow.com/a/59361298/3625077 where Federico touches on a point that this is a common misunderstanding.  The Cached value, is not an object that can be operated on, ie. in your case, you can't .add(user) to the userCache.  It's basically a snapshot of the input/output of a method.


text:
Q: Algorithm complexity in for loop I have an algorithm and I would like to know how many times each line is called.
There I wrote which lines I understand and some lines is left.
j := 1   ---------------------- 1 time
while j < n do  --------------- n times
  x := B[j]    ---------------- n-1 times
  k := j    ------------------- n-1 times
  for i := j + 1 to n do  ----- ?
    if B[i] < x then     ------ ?
      x := B[i]     ----------- ?
      k := i    --------------- ?
  B[l] := B[j]   -------------- n-1 times
  B[j] := x     --------------- n-1 times
  j := j + 1   ---------------- n-1 times

Note: k := i means that line is called once but for i := j + 1 to n do - twice: assign and comparison.

A: Since B[i] can change depending on some as yet unknown thing (maybe some values of B[1], B[2], B[3],.. will behave differently than others, at this point e don't know maybe it will maybe it won't), let's start off by simplifying, getting rid of the stuff we don't know about and leaving unconditional operations:
j := 1   ---------------------- 1 time
while j < n do  --------------- n times
  k := j    ------------------- n-1 times
  for i := j + 1 to n do  ----- ?
    k := i    ----------------- ?
  j := j + 1   ---------------- n-1 times

(This is the point of worst-case analysis, because of the conditional and the data in B, things may go much faster, but at least it'll be no worse than the analysis we're about to do.
The inner loop will occur altogether $n-1$ times (think of it just like the other assignments). But each operation in that inner loop (incrementing the $i$, comparing it to $n$, setting $k$ to $i$) how many times will they take place? Well, from $j+1$ to $n$ times. Which is $n - j - 1$. So as $j$ goes from 1 to $n$, $i$ goes from $j+1$ to $n$. This can be expressed as a summation:
$$\sum^n_{j=1} \ \sum^n_{i=j+1} ???$$
What is the question mark? What is the inner thing being summed? Well, let's be simple, ignore the extra comparisons and additions in the 'for' command' and just count the 'k := i ' assignment or 1 operation. So the summation looks like this:
$$\sum^n_{j=1} \ \sum^n_{i=j+1} 1.$$
Now you should be able to find it easier to manipulate this sum than it is to manipulate the programming language operations. For example, summing 1 from $a$ to $b$ is the same as summing 1 from 0 to $b-a$ which is equal to $b-a+1$ (why the '$+1$'?).
Once you can manipulate the summation, then you can go back to adding in complexities, like multiple assignments. You'll realize that those simplifications I made were not really important,they only change a constant in front of the final answer.
Since for this algorithm (insertion sort), it ends up being dependent on the actual data $B$ being sorted, the worst case is the most exact answer you'll get (you really don't want to worry about the conditional) unless you know something about what $B$ looks like (is it already sorted, in reverse, some interesting subset of permutations, etc.

A: Hint: You enter the for loop n-1 times as shown from the line above.  Then how many loops to you do?  It should be something like n-j, but you have to figure out the ends-there may be a +1 or -1 or something.  Does your definition of for do the loop with i=n or not?  so the for will be executed 2*(n-1)*(something like n-j) times.  Given the if statement, you can't say for sure how many times the lines within it are executed.  All you can do is find a maximum, assuming the if always evaluates as true.


text:
Q: Multiple step MODEL rails I want to create an event by users using multiple steps for the creation.
At the moment I have the following problem that it redirects to the first step after completing the second step.
The following is my controller
def new
  @event = Event.new(params[:event])
  @user = current_user
  respond_to do |format|
    if @event.save
      format.html { render :template => "events/new2" }
      format.json { render json: event_new2, status: :created, location: @event }
    else
      format.html { render action: "new" }
      format.json { render json: @event.errors, status: :unprocessable_entity }
    end
  end
end

def event_new2
  @event = Event.find(params[:id])
  respond_to do |format|
    if @event.update_attributes(params[:event])
      format.html { render :template => "events/new3" }
      # format.json { render json: event_new2, status: :created, location: @event }
    else
      format.html { render action: "event_new2" }
      format.json { render json: @event.errors, status: :unprocessable_entity }
    end
  end
end

 # POST /events
 # POST /events.json
def create
  @event = Event.new(params[:event])
  @user = current_user
  respond_to do |format|
    if @event.save
      format.html { redirect_to @event, notice: 'event erfolgreich erstellt.' }
      format.json { render json: @event, status: :created, location: @event }
    else
      format.html { render action: "new" }
      format.json { render json: @event.errors, status: :unprocessable_entity }
    end
  end
end

My model requires only title and description to be present.
The views are as follows:
Step1
<%= simple_form_for (@event), :method => 'new' do |f| %>
  <%= f.error_notification %>
  <%= f.input :title,:label => 'Event Titel' ,:placeholder=>"Titel des Events"%>
  <%= f.text_area :description,:label => 'Beschreibung',:placeholder=>"Beschreibung"%>
  <%= f.submit "Event erstellen", class: "btn btn-large btn-primary pull-right"%>

Step2
<%= simple_form_for (@event), :method => 'new' do |f| %>
  <%= f.error_notification %>
  <%= f.input :category%>
  <%= f.input :website, :label=>"Website"%>

Any help? Thanks in advance.

A: The normal one step method to create a model is for someone to go to the new page which will call the new controller and render the new page. The user fills in a form and hits submit which drives the create controller. If that works, it redirects to the show page.
If I were to do a two step creation, I would probably still go to the new page first and have it call the create action, but then rather than saving the model, I'd render the step2 page and have them fill in more details and also include the first page of details in hidden fields. I would have that form call a different action than the first at which point I would save the model. Conversely, I could have the first form call the step2 action then have that page call the create action. Another option is to save the model after step1 and retrieve it on step2. This option would be kind of ugly if step1 succeeds, but step2 fails.
Your new controller as it is will save a model to the database (without getting any user input) then render the new2 page. I highly doubt this is what you want. If it is, I'd highly recommend against it.
I assume Step1 is what you render for new2 and Step 2 is what you're rendering for new3. However, both of these forms as is will call the update controller (not shown). Also the method new is not standard, I'm a little surprised it didn't choke on it. Standard methods are :get, :post, :put, and :delete. You may be able to create non-standard one in your routes configuration, but I wouldn't recommend it. If you want to direct your form to your new2 controller then you'll need to setup a route and use the :url option to form_for to get it there.
I hope that helps.


text:
Q: Rasterize error: Polygon to raster conversion produces horizontal lines I am working with shapefiles in R that I need to convert from polygon to raster. While the vectors look perfect when plotted, when converted to raster using 'rasterize' they produce erroneous horizontal lines. Here is an example of the problem:

Here is a generic example of the code that I am using (sorry that I cannot upload the data itself as it is proprietary):
spdf.dat <- readOGR("directory here", "layer here")

# Plot polygon
plot(spdf.dat, col = 'dimgrey', border = 'black')

# Extract boundaries
ext <- extent(spdf.dat)

# Set resolution for rasterization
res <- 1

# determine no. of columns from extents and resolution
yrow <- round((ext@ymax - ext@ymin) / res)
xcol  <- round((ext@xmax - ext@xmin) / res)

# Rasterize base
rast.base <- raster(ext, yrow, xcol, crs = projection(spdf.dat))

# Rasterize substrate polygons
rast <- rasterize(spdf.dat, rast.base, field = 1, fun = 'min', progress='text')
plot(rast, col = 'dimgrey')

Does this seem to be a problem with the source data or the rasterize function? Has anyone seen this sort of error before? Thank you for any advice that you can provide.

A: To make it official so the question is considered answered, I'll copy my commented responses here.  You can therefor accept it.
When I look at your figure, it seems to me that the problematic appearing lines in the raster are situated at the same latitude of some islands. Try to removes these islands from your dataset. If the problem disappear, you'll know that your data is the problem and where in your data the problem lies.
An other option is to try the gdalUtils package which has a function: gdal_rasterize.  Maybe gdal is less exigent in the input data.

A: I had a similar problem rasterizing the TIGER areal water data for the San Juan Islands in Washington State , as well as for Maui - both of these spatial polygon data frames at the default resolution returned by package Tigris using a raster defined by points 1 arc-second of lat/lon apart. There were several horizontal stripes starting at what appeared to be sharp bends of the coastline.  Various simplification algorithms helped, but not predictably, and not perfectly.
Try package Velox, which takes some getting used to as it uses Reference Classes. It probably has size limits, as it uses the Boost geometry libraries and works in memory.  You don't need to understand it all, I don't.  It is fast compared to raster::rasterize (especially for large and complicated spatial lines dataframes), although I didn't experience the hundred-fold speedups claimed, I am not gonna complain about a mere factor of 10 or 20 speedup.  Most importantly, velox$rasterize() doesn't leave streaks for the locations I found where raster::rasterize did!
I found that it leaves a lot of memory garbage, and when converting large rasterLayers derived from velox$rasterize, running gc() was helpful before writing the raster in native R .grd format (in INT1S format to save disk space).

A: Just as a follow up to this question based on my experiences.
The horizontal lines are as a result of these 'islands' as described above. However, it only occurs if the polygon is 'multi-part'. If 'islands' are distinct polygons rather than a separate part of one polygon, then raster:rasterize() works fine.


text:
Q: JavaScript/HTML/CSS Halftone Lines Effect I am trying to find a library/API to convert an image and add an Halftone effect with lines, just as this image.
.
The original image is just a koala, example of this use was taken from photocarver
Basically i want to develop a web app that allows users to submit any image/photo and then apply this effect only, as a preview, and then they can submit for printing.
I just want to implement the same functionality as the one in photocarver, but i only care about the image upload and apply the effect.
The only problem i have is that i cannot find any library/API that allows me to apply this effect, i would like it to be through JavaScript. I have found 2 ways of applying this filter but it uses only dots and the effect isn't the desired one.
Questions

*

*Is there any library or API that already allows me to do this ? I have looked everywhere on GitHub, codepen and found nothing.

*I thought about implementing my own module for this but is it required to have a solid knowhow about photo effects and pixel manipulation in order to implement my own ? I have experience with JS but i understand nothing about photography/effects.

*Can i use the source code of the site that i gave above (where i got this image example) ? I tried to look at their code but i couldn't see how to take only the parts that i need in order to use on my own.

*I have an .exe that allows me to do exactly this but it is UI based. Is there any way to spawn the process through JavaScript and apply effect programatically ? I think not, because it was problably develop with .NET framework and i do not know of a way to do this using JS. The app isn't even a DLL that i could use for API calls.

*About implementing my own, has i have seen that there is no NPM module for this i'm also thinking about making one, could someone provide a guideline ? I basically just need the algorithm to apply to each image file.

Thanks in advance.

A: I try to search many solution, I reference this sample, and write this code for you, if you want to set line border and gutter, check js line 51.
JS
function drawLine(imageData){
  // settings variable
  let _width = imageData.width;
  let _height = imageData.height;
  let lineWidth = 4;
  let lineGutter = 7;
  for(let i = 0; _height>i;i+=lineGutter){
    console.log(i)
    context.beginPath();
    context.moveTo(0, i);
    context.lineTo(_width, i);
    context.lineWidth = lineWidth;
    context.strokeStyle = '#ffffff';
    context.stroke();
  }
}


text:
Q: Getting this error in flutter after import flutter_pdfview package FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':app:checkDebugAarMetadata'.

Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
Could not find com.github.barteksc:android-pdf-viewer:3.2.0-beta.1.
Searched in the following locations:
- https://dl.google.com/dl/android/maven2/com/github/barteksc/android-pdf-viewer/3.2.0-beta.1/android-pdf-viewer-3.2.0-beta.1.pom
- https://repo.maven.apache.org/maven2/com/github/barteksc/android-pdf-viewer/3.2.0-beta.1/android-pdf-viewer-3.2.0-beta.1.pom
- https://storage.googleapis.com/download.flutter.io/com/github/barteksc/android-pdf-viewer/3.2.0-beta.1/android-pdf-viewer-3.2.0-beta.1.pom
Required by:
project :app > project :flutter_pdfview

*

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org
BUILD FAILED in 26s
Exception: Gradle task assembleDebug failed with exit code 1

A: I had the same problem until I added jcenter() in my project-level build.gradle file, you do the same, and voila!! it will work

A: Same problem here, it seems like they changed some files in the API but they didn't solve it in the package.
I tried to visit the next URL for example, and I've reached the following path
https://repo.maven.apache.org/maven2/com/github/barteksc
where I noticed that the files have changed.


text:
Q: Django Foreign key that could contain objects of different classes is there a way to be able to use a foreign key to reference objects of diffrent classes
for example, this is what i'm doing :
Class discussion(models.Model):
    id_discussion = models.CharField(db_column='id_Discussion', primary_key=True, max_length=100)
    id_worker =   models.ForeignKey('Worker', models.CASCADE, db_column='id_user', blank=True, null=True)
    id_director = models.ForeignKey('Director', models.CASCADE, db_column='id_user', blank=True, null=True)

Class Message(models.Model):
    #some other fields
    id_sender = models.CharField(db_column='id_Sender', max_length=100, blank=True, null=True)
    id_receiver = models.CharField(db_column='id_Receiver', max_length=100, blank=True, null=True)
    id_discussion = models.ForeignKey('discussion', models.CASCADE, db_column='id_Discussion', blank=True, null=True)

I want to turn id_receiver and id_sender into foreign keys, my problem is that the sender could be an object of class "Worker" or of class "Director".

A: Yes. You can use GenericForeignKey see here:
https://docs.djangoproject.com/en/2.0/ref/contrib/contenttypes/#generic-relations
NOTE: this can be pretty inefficient. Read this article to learn more about it https://lukeplant.me.uk/blog/posts/avoid-django-genericforeignkey/


text:
Q: JavaFX programmatically highlight selected tableview row I've got a tableview that sets the background of a row based on the value of one of the row's columns. This is working and I'm doing it using a RowFactory as follows:
`
tv.setRowFactory(tv -> new TableRow<ticketRow>()
{
    @Override
    protected void updateItem(ticketRow p_ticketRow, boolean empty)
    {
        super.updateItem(p_ticketRow, empty);

        if ( p_ticketRow != null )
        {
            if (!(p_ticketRow.getTBP().trim().equalsIgnoreCase("0.00")))
            {
                setStyle("-fx-font-size: 18 !important; -fx-background-color: #ffb2b2; -fx-text-fill : #000000; -fx-font-size: 18 !important; -fx-selection-bar: blue !important;");
            }
            else
            {
                setStyle( ".tree-table-row-cell:odd {-fx-background-color: #f9f9f9; -fx-text-fill : #000000; -fx-font-size: 18 !important; -fx-selection-bar: blue;}");
            }
        }
        else
        {
            setStyle( "-fx-font-size: 18 !important; -fx-selection-bar: blue; .tree-table-row-cell:odd {-fx-background-color: #f9f9f9; -fx-text-fill : #000000; -fx-font-size: 18 !important;}; .tree-table-row-cell:even {-fx-background-color: #ffffff; -fx-text-fill : #000000; -fx-font-size: 18 !important;}" ); // -fx-font-size: 18;}" );
        }
    }
});

`
However, whenever I select a row whose background has been set by the if clause, the selected row color does not display. That row is not highlighting. The background color seems to take precedence.
How can I get the selected row to highlight when it's background has already been set because it met the column value condition?
Thanks

A: I'll be the first to admit I don't know much about CSS and I'm also just starting to work with JavaFX. In any case, after scouring more Stackoverflow posts I came across a problem/solution similar to mine where the solution was to use -fx-control-inner-background: and -fx-control-inner-background-alt:
I honestly don't know what these are or how they worked but I used them instead of -fx-background-color: and that worked.


text:
Q: Is there way to change the labeling name in ggplotly I have a challenge solving the below issue. Request experts here to help me in this. Before I put the proper reprex, let me explain the problem here:
df
   sd   x      y        x1         y1
1  1    12    1019    0.3867382  1.3484106
2  2    20    1016    1.7618076  0.8860984
3  3    7     1006   -0.4726801 -0.6549423
4  4    3     1009   -1.1602147 -0.1926301

Well, I have to plot x and y but their scales are different. So what I have done is I have normalized the data and came up with x1 and y1. Normalizing formula is
((x - mean(x)) / sd(x)
Now I need to plot x1 and y1. So have made some data wrangling and below is the reprex of that. I am getting the output, but the main issue here is that since x1 and y1 are getting plotted, when I move the cursor over it shows x1 and y1 values, which I do not want. Even though x1 and y1 are plotted, I need to have the actual values being shown (x and y values). Is there a way to achieve this?
library(ggplot2)
library(plotly)
require(reshape)
df <- structure(list(sd = c(1, 2, 3, 4), x = c(12, 20, 7, 3),
                     y = c(1019, 1016, 1006, 1009),
                     x1 = c(0.386738249968166, 1.76180758318831, -0.472680083294425, -1.1602147499045),
                     y1 = c(1.34841060188091, 0.886098395521742, -0.654942292342157, -0.192630085982987)),
                row.names = c(NA, -4L), class = "data.frame")

df$x <- NULL
df$y <- NULL
df1 <- melt(df,id=c("sd"))
ggplotly(ggplot(data = df1, aes(x = sd, y = value, color = variable))
          + geom_line(size=0.2))

A: There might be many ways to this but after formatting the dataframe then you can use tooltip="text" to show the desired tooltip here.
df1 <- df
df1$x <- NULL
df1$y <- NULL
dfx <- melt(df1,id=c("sd"))

df2 <- df
df2$x1 <- NULL
df2$y1 <- NULL
dfy <- melt(df2,id=c("sd"))
names(dfy) <- c("sd1", "variable1", "value1")

df <- cbind(dfx,dfy)

ggplotly(ggplot(data = df,aes(x=sd, y=value, color=variable, text=value1))+
           geom_line(size=0.2), tooltip = "text")


text:
Q: Convert SSMS .rpt output file to .txt/.csv I want to export my big SSMS (SQL Server Management Studio) query result (2.5m lines, 9 fields) as .csv or comma-delimited .txt (with headings). (MS SQL Server 2005 Management Studio.)
So that I can then either read it line-by-line into VBA program (to do certain calculations on the data) or do queries on it in Excel (e.g. with Microsoft Query). The calculations are complicated and I prefer to do it somewhere else than SSMS.
If I choose 'query result to text' in SSMS and a small answer (few lines e.g. up to 200k) I could of course simply copy and paste to a text editor. For my large answer here I could of course copy and paste 200k or so lines at a time, 10 times, into a text editor like Ultra-Edit. (When I try all 2.5m at once, I get a memory warning inside SSMS.) But for the future I'd like a more elegant solution.
For 'query result to file', SSMS writes to an .rpt file always.  (When you right-click in the results window and choose 'save as', it gives a memory error just like above.)
--> So it looks like my only option is to have SSMS output its result to a file i.e. .rpt and then afterwards, convert the .rpt to .txt.
I assume this .rpt is a Crystal Reports file? Or isn't it. I don't have Crystal Reports on my PC, so I cannot use that to convert the file.
When opening the .rpt in Ultra-Edit it looks fine. However in Microsoft Query in Excel, the headings doesn't want to show.
When I simply read & write the .rpt using VBA, the file halves in size. (330meg to 180meg). In Microsoft Query the headings do show now (though the first field name has a funny leading character, which has happened to me before in other totally different situations). I do seem to be able to do meaningful pivot tables on it in Excel.
However when I open this new file in Ultra-Edit, it shows Chinese characters! Could there still be some funny characters in it somewhere?
--> Is there perhaps a free (and simple/ safe) converter app available somewhere. Or should I just trust that this .txt is fine for reading into my VBA program.
Thanks

A: Well with the help of a friend I found my solution: Rpt files are plain text files generated in MS SQL Server Management Studio, but with UCS-2 Little Endian encoding instead of ANSI.
--> In Ultra-Edit the option 'file, conversion options, unicode to ASCII' did the trick. The text file reduces from 330meg to 180 meg, Microsoft Query in Excel can now see the columns, and VBA can read the file & process lines*.
P.s. Another alternative would have been to use MS Access (which can handle big results) and connect with ODBC to the database. However then I would have to use Jet-SQL which has fewer commands than the T-SQL of MS SQL Server Management Studio.  Apparently one can create a new file as .adp in MS Access 2007 and then use T-SQL to a SQL Server back end. But in MS Access 2010 (on my PC) this option seems not to exist anymore.

A: Simple way: In SQL Server Management Studio, go to the "Query" menu & select "Query Options…" > Results > Text > Change "Output Format" to "Comma Delimited". Now, run your query to export to a file, and once done rename the file from .rpt to .csv and it will open in Excel :).

A: You can use BCP
Open a command prompt, then type this:
SET Q="select * from user1.dbo.table1"
BCP.EXE %Q% queryout query.out -S ServerName -T -c -t

*

*You can use -U -P (instead of -T) for SQL Authentication.

*Your app have a problem with UNICODE. You can force a code page using -C {code page}. If in doubt, try 850.

*-t will force tab as field delimiter, you can change it for comma -t,
The nice thing is you can call this directly from your VBA running shell command.

A: This is the recommended way I see you can do it.

My Source (Answer from DavidAir)
Pick "results to grid" then then right-click on the grid and select "Save Results As..." This will save a CSV.
Actually, there is a problem with that if some values contain commas - the resulting CSV is not properly escaped. The RPT file is actually quite nice as it contains fixed-width columns. If you have Excel, a relatively easy way of converting the result to CSV is to open the RPT file in Excel. This will bring up the text import wizard and Excel would do a pretty good job at guessing the columns. Go through the wizard and then save the results as CSV.

A: Here is my solution.

*

*Use Microsoft SQL Server Management Studio

*Configure it to save Tab delimited .rpt files: Go to 'Query' > 'Query Options' > 'Results' > 'Text' > 'Output Format' and choose 'Tab delimited' (press OK)

*

*Now, when you create a report, use the 'Save With Encoding...' menu, and select 'Unicode' (by default, it's 'UTF8')

*

*You can now open the file with Excel, and everything will be in columns, with no escaping nor foreign characters issues (note the file may be bigger due to unicode encoding).

A: I recommend using the "SQL Server Import and Export Wizard" for a couple reasons:

*

*The output file will not have a status message at the bottom like a .rpt file does (ie. "(100 rows affected)") which may mess up your data import

*Ability to specify custom row and column delimiters of a length greater than 1 character

*Ability to specify custom source to destination mapping (ie. column FirstName can be mapped to first_name in the CSV)

*Ability to perform a direct transfer to any other database accessible from the SSMS machine

*Ability to explicitly select your file encoding and locale

It can be accessed by right-clicking on your database in the management studio (you must right-click the database and not the table) and selecting Tasks > Export Data.

When asked for data source you can select the "SQL Server Native Client" and when asked to select a destination you can select "Flat File Destination".
You are then asked to specify a table or query to use.
You can find more info about the tool here:
https://learn.microsoft.com/en-us/sql/integration-services/import-export-data/start-the-sql-server-import-and-export-wizard?view=sql-server-2017

A: In my case, I execute a query on SSMS (before that press CTRL+SHIFT+F) the result open a window to save it as an rpt file, I couldn´t read it (no Crystal Report install in my computer) so...next time I runned the query I saved it as (all files) set with extension *.txt, and that´s it I was able to read it as text file.

A: First get your data in .rpt file by using any of above method.
Default .rpt with fixed space column. (262MB)
Comma delimited with Unicode. (52MB) - I used this.
Change file extension to .csv.
Open/Import it in excel and verify data. File type is 'Text Unicode'.
Save it as CSV (Comma Delimited), which reduced size to 25 MB.


text:
Q: How to map a friend request entity in spring data jpa i am creating a small social media, but i don't know the best way to map the friends request entity. if it should me a many to one or a one to many, since the friend request class references the user entity class twice. one for receiver of the request and one for the sender of the request. please can you help me look at my code and see if i am doing the right thing?
    @Component
@Entity
@Table(name = "Users")
public class User extends DefaultEntity {

    @Column(name = "FirstName")
    @NotNull(message = "Enter a FirstName")
    private String firstName;

    @Column(name = "LastName")
    @NotBlank(message = "Enter a LastName")
    private String lastName;

    @Column(unique = true,name = "UserName")
    @NotBlank(message = "Enter a UserName")
    private String userName;

    @Column(unique = true, name = "Email")
    @NotBlank(message = "Please enter an Email address")
    @Email(message = "Enter a valid Email")
    private String email;

    @Column(name = "Password")
    @NotBlank(message = "Enter a Password")
    private String password;

    @Enumerated(EnumType.STRING)
    @Column(name = "Gender")
    private Gender gender;

    @Column(name = "Address")
    @NotBlank(message = "Please enter your Home Address")
    private String address;

    @Column(name = "Country")
    @NotBlank(message = "Please enter your Country")
    private String country;

    @Column(name = "Picture")
    private String picture;

    @Column(unique = true, name = "PhoneNumber") //make this accept only numbers
    private String phoneNumber;

    @Column(name = "Bio")
    private String bio;

    @Column(name = "OnlineStatus")
    private OnlineStatus onlineStatus;

    @Enumerated(EnumType.STRING)
    @Column(name = "UserType")
    private UserType userType;

    @Column(name = "Money")
    private long money;

    //@MapsId()
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "playerstats")
    private PlayerStats playerStats;
}

and here is the friend request entity:
   @Component
@Entity
@Table(name = "FriendRequest")
public class FriendRequest extends DefaultEntity {

    private User sender;

    private FriendRequestStatus friendRequestStatus;

    private User recipient;

    public User getSender() {
        return sender;
    }

    public void setSender(User sender) {
        this.sender = sender;
    }

    public User getRecipient() {
        return recipient;
    }

    public void setRecipient(User recipient) {
        this.recipient = recipient;
    }

    public FriendRequestStatus getFriendRequestStatus() {
        return friendRequestStatus;
    }

    public void setFriendRequestStatus(FriendRequestStatus friendRequestStatus) {
        this.friendRequestStatus = friendRequestStatus;
    }
}

Please is my friend request entity especially the user objects in it mapped properly?

A: Let's consider the association between a request and its sender. A request has one sender. Otherwise the sender field would be a collection of users, and would be named senders. So it can't possibly be a ToMany association: it refers to one user.
Now, is it a OneToOne or a ManyToOne? Can multiple requests be sent by the same user. I gess so. A life where everyone can have only one friend would be a little sad, wouldn't it? So, multiple requests can refer to the same sender or, if you prefer, a user can send multiple requests. So it's a ManyToOne.
I'll let you do the reasoning for the other association.
Note that annotating your entities with Component makes absolutely no sense. Those are not Spring beans. Spring does not instantiate them nor inject them.


text:
Q: How do I investigate how long it takes one variable to affect another in a time series I am a total newbie when it comes to time series, so it is quite possible this question is duplicated somewhere else, only that I cannot find it because I don't know what this feature is called.
My data:
I have weekly measurements of a variable "change in rank". I also have weekly measurements of another variable loosely described as "change in goodness". I believe that "change in rank" is dependent on "change in goodness", but I also believe that whenever "goodness" improves, it takes some time before rank improves. A simplistic representation of the data would look like this:
change_in_rank = c(0,0,0,0,-10,0,0,0)
change_in_goodness = c(0,2,0,0,0,0,0,0)

where this constructed example shows that a improvement of 2 in goodness took 3 time steps to lead to an improvement in rank.
My question:
What analysis method do I use to detect whether such a relationship actually exists between "change in goodness" and "change in rank", and if such a relationship exists, how do I find out how long it takes for a change in "goodness" to flow on to a change in rank.
The motivation behind this question:
Some additional, non necessary background: it is claimed that search engine optimisation takes time to affect your site's ranking in Google. E.g.:
"Why does SEO take so long?"
I am trying to find a statistical way of calculating how long it takes for a change in a site to actually reflect in the site's Google ranking.
More motivation:
Slightly different type of data but similar question...
"How long does it take before a change in diet starts to take effect?"

A: Try looking at cross-correlations between the two series:
correlate series 1 with series 2;
correlate series 1 with series 2 lagged by 1 period;
correlate series 1 with series 2 lagged by 2 periods;
etc.
Explore as many lags as can reasonably be expected to be plausible in the context you are in. Also, depending on the context of the application, you may need to look at lagged series 1 against (non-lagged) series 2.
Note which lag gives the highest absolute correlation - this will be a rough estimate of the "true" lag.
It is comfortable to inspect the cross-correlations visually. In R, you may use function ccf(.) to obtain and plot the correlogram.

A: As often in regression, there are several ways to proceed, but the most straightforward one is probably given by the moving-average approach. That is, you assume a linear (linear-in-the-parameters) relationship between your target $y_t$ (change_in_rank) and your regressand $x_t$ (change_in_goodness) given by
$$
y_t = \sum_{i=1}^p \beta_{t-k} \, x_{t-k}
$$
Here, the input-parameter $p$ determines the maximum lag-time. Next, you fit your model using some seleted data of the form $(x_{j-1}, \ldots, x_{j-p}; y_j)$ where $j\in \{1,\ldots, N_\text{data}\}$, e.g. by using standard least-squares regression.
Finally, you can use the result either to forecast (in this case more flexible models like neural networks might be doing better), or to interprete the result using the fitted parameters $\boldsymbol \beta$ (--in interpretability, almost nothing beats linear models).
If that model is not flexible enough, you can extend it to higher dimensions and more general functions $f(x_{t-1}, \ldots, f_{t-p})$, and also to autoregressive-moving-average models where you further include some previous regression results $y_j$ for $j<t$.


text:
Q: XPATH append text or new line I want to append a new line or text in xpath/xmllint output
I tried a lot of ways but xmllint doesn't provide much control on the output
find . -type f -name pom.xml|xargs -n 1 /usr/bin/xmllint  --xpath "/[name()='project']/[name()='groupId']/text()|/[name()='project']/[name()='artifactId']/text()|/[name()='project']/[name()='version']/text()"
output of each pom file in a new line instead of a whole big string

A: May be.. not the best code
for file in `find . -type f -name pom.xml`
do
/usr/bin/xmllint --xpath "/[name()='project']/[name()='groupId']/text()|/[name()='project']/[name()='artifactId']/text()|/[name()='project']/[name()='version']/text()"
echo -e "\n\n\n" # add new line for each xpath
done

could you share the pom.xml file


text:
Q: Azure Active Directory - Access Denied in New Portal Using old azure portal, I am able to navigate to Azure Active Directory. But with the new portal 'Portal.Azure.com', I am seeing 'Access Denied' error message.
This is the below exact message I am seeing in the portal.
"Access denied.
You do not have access
Looks like you don't have access to this content. To get access, please contact the owner."

A: If you use the external account to access Azure AD, such as MSA account(e.g. outlook.com, hotmail.com), and the account from other Azure AD tenant. You may experience the error message as below.

There are two methods to resolve this issue.
Method 1
Log in to new Azure Portal by using the account with Global Administrator permission for Azure AD. Navigate to the Azure Active Directory extension, from the User settings tab, toggle the setting Guest users permissions are limited to No.

Method 2
Log in to new Azure Portal by using the account with Global Administrator permission for Azure AD. Navigate to the Azure Active Directory extension, from the Users and Groups tab, search for the external account, and change the Directory Role to Global Administrator.

A: In my case the solution was different.
The clock on my machine got de-synchronized (lagging 13 hours behind) and when my browser was encrypting a security token to request a sensitive page at Azure Portal, this token was rejected by server and I received "Access denied" error page.
It seams like "time.windows.com" was providing a wrong world time to my computer (yes, it is insane) - I changed it to "time.nist.gov" via Control Panel / Date and Time / Internet Time / Change Settings. It immediately updated my computer with correct time.
Then I signed-out and singed-in to Azure Portal and it started working just fine.

A: As for me, is was to activate a subscription (adding a card bank).
Then I could access the services on my new Azure account


text:
Q: Can the New Relic Python agent track external service requests that don't use httplib? Using New Relic on a Tornado application, some external services are being tracked and some are not. I've noticed that the ones that work utilize httplib while the others are using Tornado's HTTP client, which directly communicates with a socket.
My assumption is that the New Relic agent is hooked into the httplib, because under the hood httplib uses the same socket.
Is there anyway to track these requests as well?

A: The New Relic python agent does not currently support Tornado's HTTP client, but keep an eye on the release notes for any changes in the future:
https://docs.newrelic.com/docs/releases/python
You can also find a list of currently instrumented external service modules here:
https://docs.newrelic.com/docs/python/instrumented-python-packages#external-web-services


text:
Q: Get value from header JQuery I need to extract the address from a returned header - the data being returned is as follows
{
    "error": false,
    "error_msg": "",
    "body": {
        "records": [
            {
                "address": "/Clients/I/imi_bit_contact_dev/web/app_dev.php/api/v/1/address/46813"
            }
        ]
    },
    "validation_errors": []
}

Currently there is only one address being returned and I need to grab this address (full url) for further usage.

A: Simply
data.body.records[0].address
where data is your returned response
Or
for (var i = 0; i < data.body.records.length; i++)
{
 var address = data.body.records[i].address;
 alert (address);
}

to get the multiples rows.


text:
Q: SIgnalR - An item with the same key has already been added i am having an issue regarding a signalr (version 1.2.2. I cannot update toto 2+)/autofac/Nunit implementation. I am using an MVC client with a WCF service whixh pushes notifications to client. When I' m running the app using the web client and the service everything works as expected. When i try to test my service through NUnit everytime i try to create the hubcontext
GlobalHost.ConnectionManager.GetHubContext<ProductHub>()

i get
An item with the same key has already been added.

here is the full stack trace

   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
   at Microsoft.AspNet.SignalR.Hubs.ReflectedHubDescriptorProvider.BuildHubsCache()
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.LazyInitValue()
   at System.Lazy`1.get_Value()
   at Microsoft.AspNet.SignalR.Hubs.ReflectedHubDescriptorProvider.TryGetHub(String hubName, HubDescriptor& descriptor)
   at Microsoft.AspNet.SignalR.Hubs.DefaultHubManager.c__DisplayClass1.b__0(IHubDescriptorProvider p)
   at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
   at Microsoft.AspNet.SignalR.Hubs.DefaultHubManager.GetHub(String hubName)
   at Microsoft.AspNet.SignalR.Hubs.HubManagerExtensions.EnsureHub(IHubManager hubManager, String hubName, IPerformanceCounter[] counters)
   at Microsoft.AspNet.SignalR.Infrastructure.ConnectionManager.GetHubContext(String hubName)
   at Microsoft.AspNet.SignalR.Infrastructure.ConnectionManager.GetHubContext[T]()

Here is the autofac and signalr registration in global.asax service file
        protected void Application_Start(object sender, EventArgs e)
    {
        RouteTable.Routes.MapHubs(new HubConfiguration { EnableCrossDomain = true });
        var builder = new ContainerBuilder();
        builder.RegisterType<Product_WCF_Service>().AsSelf();
        builder.RegisterType<DbFactory>().As<IDbFactory>();
        builder.RegisterType<UnitOfWork>().As<IUnitOfWork>();
        builder.RegisterAssemblyTypes(
            new[] {
                typeof(ProductService).Assembly
            })
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces();

        builder.RegisterAssemblyTypes(
            new[] {
                typeof(ProductRepository).Assembly
            })
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces();

        builder.RegisterType<ProductHub>().ExternallyOwned();
        var container = builder.Build();
        container.Resolve<IUnitOfWork>();
        container.Resolve<IDbFactory>();
        GlobalHost.DependencyResolver = new AutofacDependencyResolver(container);
        AutofacHostFactory.Container = container;
        AutoMapperConfiguration.Configure();
    }

My service implementation
public class Product_WCF_Service : IProduct_WCF_Service
{
    IUnitOfWork UnitOfWork;
    IProductService ProductService;

    public Product_WCF_Service(IUnitOfWork unitOfWork, IProductService productService)
    {
        this.ProductService = productService;
        this.UnitOfWork = unitOfWork;
    }

}
And my NUnit test which causes the exception to be thrown
[TestFixture]
public class WCF_Product_Service_Tests
{
    private Mock<IProduct_WCF_Service> ProductWCFService;
    private Mock<IUnitOfWork> UnitOfWork;
    private Mock<IProductService> ProductService;
    public WCF_Product_Service_Tests()
    {
        this.ProductWCFService = new Mock<IProduct_WCF_Service>();
        this.UnitOfWork = new Mock<IUnitOfWork>();
        this.ProductService = new Mock<IProductService>();
    }

    [Test]
    public void RetreiveDataFromWCF_Service()
    {
        byte commitStatus = 1;
        string response = string.Empty;
        var service = new Product_WCF_Service(this.UnitOfWork.Object, this.ProductService.Object);
        service.CreateProduct("", out response, out commitStatus);
    }}

It's driving me crazy as i cannot test my service at all!

A: OK I searched around and finally i found a solution. I' leave it here just in case someone finds this useful
when registering autofac i enabled the property injection
                        var signalRConfig = new HubConfiguration();
        var builder = new ContainerBuilder();
        builder.RegisterType<ServiceHub>().ExternallyOwned(); // SignalR hub registration
        builder.Register(i => signalRConfig.Resolver.Resolve<IConnectionManager>().GetHubContext<ServiceHub>()).ExternallyOwned();
        builder.RegisterType<Product_WCF_Service>().AsSelf();
        builder.RegisterType<DbFactory>().As<IDbFactory>().InstancePerLifetimeScope();
        builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerLifetimeScope();
        builder.RegisterAssemblyTypes(
            new[] {
                typeof(ProductService).Assembly
            })
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces();

        builder.RegisterAssemblyTypes(
            new[] {
                typeof(ProductRepository).Assembly
            })
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces();

        builder.RegisterType<Product_WCF_Service>()
            .PropertiesAutowired();
        var container = builder.Build();
        signalRConfig.Resolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(container);
        signalRConfig.EnableCrossDomain = true;
        RouteTable.Routes.MapHubs(signalRConfig);
        AutofacHostFactory.Container = container;
        AutoMapperConfiguration.Configure();

In my service i added the hubcontext as a property in
public class Product_WCF_Service : IProduct_WCF_Service{

    IUnitOfWork UnitOfWork;
    IProductService ProductService;
    public IHubContext InstanceHubContext { get; set; }

    public Product_WCF_Service(IUnitOfWork unitOfWork, IProductService productService)
    {
        this.ProductService = productService;
        this.UnitOfWork = unitOfWork;
    }

and it worked as expected! I can now access the hubcontext as usual
this.InstanceHubContext.Clients.All.onNotSavedProduct(message);

Of course you will also need the Autofac.Integration.SignalR and Autofac.Integration.Wcf packages


text:
Q: What resources are available to learn how to create an app in Android Studio? Im a noob when it comes to Android Studio and would like to know any websites or books that would help me get started. I know some of the basics but get stuck on moving from one activity to another. I've searched online and even tried youtube with no luck. At this point I don't mind paying for some online courses.

A: I used YouTube alot for a 2d side stroller paymon wang-lotfi has a great engine.  theNewBoston was also has some great tutorials and ThechernoProject is good for Java game programming.

A: The new boston is good as far as learning the very basics for free. But the best that I've found are on Udacity, although not all of their courses are free. So if you really want to understand your code with project-based learning, I would recommend Udacity, as long as you are willing to pay a bit (Although their free courses are still good).