text:
Q: How can I validate for whitespaces in textbox I am validating a text box using javascript, now what happens is that if the text box = '' or in other words is empty, then a message appears stating "Please Enter in a Room Number", if not then display an empty string "".
Now this is fine if the text box is empty but if I type in a space or enter for example and then submit the form, then the validation message does not appear in this instance.
How is it supposed to be coded so that if a textbox is empty of contains whitespaces, then it should display a message?
Below is my code:

            <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
            <title>Create a Session</title>

    <form action="create_session.php" method="post" name="sessionform">

8: Room: <input type="text" id="room">

    </form>

A: You can trim the contents of the textbox first:
roomTextO.trim().value


text:
Q: fetching random json getting first undefined then result Beginner on reactjs here, trying to fetch random json, getting the result i want to get, but not the way i want it, for some reason it prints first 'undefined' then after that the result. Why cant i get just the result and without this '?'
my code:

import { useEffect, useState } from "react";
import "./App.css";

function App() {
  const [thumbnail, setThumbnail] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/photos")
      .then((response) => response.json())
      .then((json) => {
        setThumbnail(json);
      });
  }, []);

  console.log(thumbnail[0]?.thumbnailUrl);
  return (

Build

  );
}

export default App;

A: console.log() inside App() directly will use the initial state of. thumbnail which is the empty, so it will show undefined.
To check the thumbnail, you should use another useEffect with adding a thumbnail dependency.
useEffect(() => {
  if (thumbnail.length > 0) {
    console.log(thumbnail[0].thumbnailUrl);
  }
}, [thumbnail]);

import { useEffect, useState } from "react";
import "./App.css";

function App() {
  const [thumbnail, setThumbnail] = useState([]);
  const [isLoaded, setLoaded] = useState(false);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/photos")
      .then((response) => response.json())
      .then((json) => {
        setLoaded(true);
        setThumbnail(json);
      });
  }, []);

  useEffect(() => {
    if (isLoaded) {
      console.log(thumbnail[0]?.thumbnailUrl);
    }
  }, [thumbnail]);

  return (

Build

  );
}

export default App;

A: While the response of your http does not come, you can simply render a loading component (a text in this example), then when thumbnail state changes, React will re-render your component and update it with the new data.
Just a working example:
import React, { useEffect, useState } from "react";
import "./App.css";

function App() {
  const [thumbnail, setThumbnail] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    setIsLoading(true);
    fetch("https://jsonplaceholder.typicode.com/photos")
      .then((response) => response.json())
      .then((json) => {
        setThumbnail(json);
      })
      .finally(() => {
        setIsLoading(false);
      });
  }, []);

  return (

Build

      {isLoading ? (

Loading...

      ) : (
        thumbnail.map((item) => {
          return {item.title};
        })
      )}

  );
}

export default App;

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to select right amount of buttons I have a textbox and a set of buttons below the text box. What is suppose to happen is that a user fills in a number in the text box and that number determines how many buttons can be clicked. E.g if the text box has a value of 2, then the user can only select two button, a button is selected if the button turns red, it is not selected if it turns or stays white.
The problem is what is happening is that if the value is 1 or above, the user can select all the buttons, in other words if they just keep clicking on buttons then all the buttons would turn red, when what should happen is if the user goes over the value, then an error message appears stating you have went over the limit, please deselect a button if you want to choose another button.
How can I get it so that the number of buttons selected matches the value from the textbox?
code is in jsfiddle, click here (for some strange reason it is not letting me click on any button and text box is allowing entry of letters in jsfiddle, even though in my app with the exact code it works fine. Please look at function btnclick (btn) to help you.)

A: You're resetting the total on each click, so you're not really counting. Move the currenttotal = 0; outside the click function (and declare it with var).
Secondly, you have really much of the same code. You could also iterate to make the .className assignments on the buttons a bit more concise:
for(var i = 65; i <= 90; i++) { // iterate over character codes for A to Z
    var letter = String.fromCharCode(i);
    document.getElementById("answer" + letter).className = "answerBtnsOff";
}

You could also put the class names in HTML with the class="answerBtnsOff" attribute. You could even create the buttons through JavaScript. That would make for some cleaner and more readable code, but of course these optimizations are not necessary.
http://jsfiddle.net/7WwaK/3/
(For the jsFiddle to work, you have to select no wrap (body) in the left panel, but that's just how jsFiddle inserts the JavaScript.)

A: If I'm getting you right, you should do (IMHO) the following this:

*

*Move var currenttotal = 0; outside your function. You are resetting it on each click on a button.

*Edit the currenttotal after the user changes the number of answers. Add therefore the line currenttotal = document.getElementById('numberAnswerTxt').value(); to the function called getButtons().

*You could implement the loop that pimvdb suggested to reduce your code (=

Please tell me if this is working.


text:
Q: Is it better to go for armor sets or different armor parts? As a new Monster Hunter player, I recently learnt that skills are obtained through: armor, talismans and decorations and that these three elements should be chosen in such a way that the desired set of skills is obtained.
Now, when it comes to armor specifically, I know that armor sets (e.g. the Tetsucabra armor set) come with specific features (good and bad). My hunter currently has the "Rathalos Armor Set" and it grants me Attack Up (M) and Recovery Down. But I read some articles posted by hunters who actually were going for different armor parts that were not from the same set (e.g. Rathalos Helm, Tetsucabra Vest...). So my question is: "Is this the optimal way to do things?"
This question is bothering me, especially since I learnt that a skill becomes active only if it has 10 points from the different pieces of equipment.
Thank you for your response.

A: For a new player, you'll want to stick with regular armor sets. Once you become more acquainted with the armor skill mechanic, you can start branching out into mixed sets.
However, mixed sets are by no means required. Regular sets typically have a theme to their armor skills, so just going with a regular set is more than fine if you can utilize it. Mixed sets simply give you more control over what armor skills to put together, allowing you to craft a set that fits your particular style.
This is how the armor skill mechanic works: if you look on page 4 of your armor info, you'll see some names with positive and negative numbers. These are skill points. To acquire an armor skill, you total up all the pluses and minuses for a particular skill on all of your equipment. If that total reaches a certain threshold (10), you gain that armor skill. Having points below the threshold does not benefit you at all.
Now, most armor skills also come with a penalty skill. If you accumulate enough negative points in a skill (-10), you'll gain a penalty skill. Most regular sets also come with one penalty skill. For example, your Rathalos set has Recovery Down. These penalty skills are usually bad for you and you'll typically want to get rid of them by inserting gems into your gear. In your case, Recovery Down decreases the effectiveness of healing items like Potions and Herbal Medicine.
Also, note that many armor skills and their respective penalty skills have tiers. If you go over the first threshold and reach another, you'll gain an increased effect from your armor/penalty skill. For example, +10 in Attack will get you Attack Up (S) with a small boost in damage, but +25 in Attack will award you with Attack Up (XL) with a very large boost in damage.

A: You should wait until late g-rank to get into mixed armor sets. As an example, for a great sword user the best skills to have are Crit Draw and Punish Draw, but very few (if any) armor sets have both of these skills.
Most players could use gems to get it, but some might want a 3rd skill that they could only get by using gems, so to solve this they find a mix of armor pieces that give enough skill points to get Punish and Crit Draw without having to use many gems.
This is usually something only professionals do, but it can be fun to mix and match armor pieces and make your own custom armor.


text:
Q: Limit the no. of instances in windows service I'm writing a windows service that fired up by a timer and does a time consuming for every minute. I want to limit the no. of service instances running at a time say 100. How I can do that? Any Idea?
EDITED: I want to limit the no. of threads started by the timer.

A: If you're using System.Threading.ThreadPool, there's a function called SetMaxThreads that lets you control the maximum number of concurrently running threads.  Also, make note of the remarks on that page about changing the number of concurrent threads.

A: That sounds like a very poor design -- and a memory/cpu hog.  I'm not sure I understand what you mean when you say 100 windows services -- as a service is one service.  At least in the sense of having a unique service.  Are you firing up 100 applications running hidden in the background through a task manager?  If so, you may be able to make that much nicer by creating a real windows service and having logic within that service to control the flow of the application (and the execution of multiple instances of your code running).
For instance, you could have a windows service with one main thread which would sleep for n. seconds and then execute.  After the main thread wakes up, it would be responsible for spinning off new threads.  As an example, you could use a thread pool whereas you could control the number of threads that were active.  Your main thread would check the thread pool to determine if it's reached capacity, and if valid, spin off a new thread.
Main Service Thread
 > Sleep n. seconds
   > ThreadPool < 100?
     > New Thread

A: This code demonstrates what you need.
Just use theSemaphoreSlim (Same as Semaphore, better performance) object to do it.
Think about the Semaphore as a counter. Each time you wait the counter goes one number down. In the end of the operation need to release it.
When the counter is 0, can't get Semaphore.
About the ThreadPool suggestions, I don't think it's a good idea because the thread pool is used in many parts of your application, not only this one.
class Program
    {
        private static SemaphoreSlim threadsSemaphore = new SemaphoreSlim(5, 5);

        static void Main(string[] args)
        {
            Timer timer = new Timer(DoSomeWork, null, 0, 100);

            Console.ReadKey();
        }

        private static void DoSomeWork(object state)
        {
            if (threadsSemaphore.Wait(TimeSpan.FromSeconds(1)))
            {
                try
                {
                    Console.WriteLine("Doing work ...");
                    Thread.Sleep(1000);
                }
                finally
                {
                    threadsSemaphore.Release();
                }
            }
            else
            {
                Console.WriteLine("Skipping work", threadsSemaphore.CurrentCount);
            }

        }
    }


text:
Q: unable to verify the first certificate ionic 4 I tried to install Browser Tab plugin on my application:
ionic cordova plugin add cordova-plugin-browsertab
and the output was this:
    > ionic integrations enable cordova
    [INFO] Downloading integration cordova
    Error: unable to verify the first certificate
    at TLSSocket.onConnectSecure (_tls_wrap.js:1051:34)
    at TLSSocket.emit (events.js:189:13)
    at TLSSocket._finishInit (_tls_wrap.js:633:8)

I tried to use
npm config set strict-ssl false
but the error continues


text:
Q: HTTP request in Ubuntu i need to call a HTTP request in ubuntu how do i do it? I can't seem to find an answer around on how to to do it?
How do run the following url without calling a browser like lynx to do it?
http://www.smsggglobal.com/http-api.php?action=sendsms&user=asda&password=123123&&from=123123&to=1232&text=adsdad

A: to display the results:
curl http://www.smsggglobal.com/http-api.php?action=sendsms&user=asda&password=123123&&from=123123&to=1232&text=adsdad

or
to save the results as a file
wget http://www.smsggglobal.com/http-api.php?action=sendsms&user=asda&password=123123&&from=123123&to=1232&text=adsdad

A: in your command prompt, run the following:
curl http://www.smsggglobal.com/http-api.php?action=sendsms&user=asda&password=123123&&from=123123&to=1232&text=adsdad

the curl command executes an http request for a given url and parameters.
if you need to specify another HTTP method, use curl -X <TYPE> <URL>, like this:
curl -X POST http://www.smsggglobal.com/http-api.php?action=sendsms&user=asda&password=123123&&from=123123&to=1232&text=adsdad

curl documentation: http://curl.haxx.se/docs/manpage.html


text:
Q: Making Private Transactions on the ethereum network I've been working on a mechanism to make private transactions achievable on the ethereum network using zk-snarks and verifiable hashes.
I took alot of help from an existing work done on this mechanism. below is the link.
https://github.com/EYBlockchain/nightfall
Right now all this is functional on a local chain but when i move it to the geth network, transaction fails.
Any help on how to configure the above mechanism on etheruem network or a test network like rinkeby or ropsten will be highly appreciated.


text:
Q: tracks () function from ggbio does not allow italic expression in the title I'm trying to combine plain text with italic text in the title of a combined tracks() plot generated by ggbio, but I can not include the part of the title that I want in italic fonts.
Here you have several examples of titles that allow italics using expression(italic(x)) and the last one is the one that does not work for me.
library(ggbio)
library(grDevices)

This is the title that I want to use: "Variation in AAAA gene"
I can get it with this code:
plot_title <- expression(paste("Variation in ", italic("AAAA"), " gene"))

It works for me in this first example using the plot()
x <- c(2*5)
y <- c(2^5)
plot(x,y, main = plot_title)

It also works for me in the second example using the autoplot()
test_a = GRanges('chr1', IRanges(start = 150, end = 180))
t_a <- autoplot(test_a, main = plot_title)
fixed(t_a) <- TRUE
t_a

test_b = GRanges('chr1', IRanges(start = 100, end = 200))
t_b <- autoplot(test_b,  main = plot_title)
fixed(t_b) <- TRUE
t_b

This is the plot that I would like to have with the title including the AAAA in italics
combined_tracks <-   tracks(t_a, t_b, title = "Variation in AAAA gene") + xlim (100, 200)
combined_tracks

When I use the tracks() and I try to use the plot_title to generate the final plot, R crashes
combined_tracks2 <-   tracks(t_a, t_b, title = plot_title) + xlim (100, 200)
combined_tracks2

I get the following error:
Error in validObject(.Object) :
  invalid class "Tracks" object: invalid object for slot "main" in class "Tracks": got class "expression", should be or extend class "characterORNULL"

Does anybody how to get around this error,
I have looked on the Internet, but I haven't found an answer for this specific tracks() function.
Thank you very much,
Best,
R version 3.3.1 (2016-06-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats4    parallel  stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] Homo.sapiens_1.3.1                      TxDb.Hsapiens.UCSC.hg19.knownGene_3.2.2
 [3] org.Hs.eg.db_3.3.0                      GO.db_3.3.0
 [5] OrganismDbi_1.14.1                      GenomicFeatures_1.24.5
 [7] AnnotationDbi_1.34.4                    Biobase_2.32.0
 [9] GenomicRanges_1.24.3                    GenomeInfoDb_1.8.7
[11] IRanges_2.6.1                           S4Vectors_0.10.3
[13] biovizBase_1.20.0                       ggbio_1.20.2
[15] ggplot2_2.1.0                           BiocGenerics_0.18.0

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.7                   lattice_0.20-34               Rsamtools_1.24.0
 [4] Biostrings_2.40.2             digest_0.6.10                 mime_0.5
 [7] R6_2.1.3                      plyr_1.8.4                    chron_2.3-47
[10] acepack_1.3-3.3               RSQLite_1.0.0                 httr_1.2.1
[13] BiocInstaller_1.22.3          zlibbioc_1.18.0               data.table_1.9.6
[16] rpart_4.1-10                  Matrix_1.2-7.1                labeling_0.3
[19] splines_3.3.1                 BiocParallel_1.6.6            AnnotationHub_2.4.2
[22] stringr_1.1.0                 foreign_0.8-67                RCurl_1.95-4.8
[25] biomaRt_2.28.0                munsell_0.4.3                 shiny_0.14
[28] httpuv_1.3.3                  rtracklayer_1.32.2            htmltools_0.3.5
[31] nnet_7.3-12                   SummarizedExperiment_1.2.3    gridExtra_2.2.1
[34] interactiveDisplayBase_1.10.3 Hmisc_3.17-4                  XML_3.98-1.4
[37] reshape_0.8.5                 GenomicAlignments_1.8.4       bitops_1.0-6
[40] RBGL_1.48.1                   grid_3.3.1                    xtable_1.8-2
[43] GGally_1.2.0                  gtable_0.2.0                  DBI_0.5-1
[46] magrittr_1.5                  scales_0.4.0                  graph_1.50.0
[49] stringi_1.1.1                 XVector_0.12.1                reshape2_1.4.1
[52] latticeExtra_0.6-28           Formula_1.2-1                 RColorBrewer_1.1-2
[55] ensembldb_1.4.7               tools_3.3.1                   dichromat_2.0-0
[58] BSgenome_1.40.1               survival_2.39-5               colorspace_1.2-6
[61] cluster_2.0.4                 VariantAnnotation_1.18.7


text:
Q: Number validation for JavaScript simple calculator with RegEx I am making a simple calculator with HTML, CSS and JavaScript. The input field must be validated with regex to accept only numbers and the mathematical signs + - * / .
This is the input field in the HTML code:
<input type="text" name="answer" id="answer-field" oninput="checking()" />

And this is the JavaScript function checking():
function checking(){
  var x = document.calculator.answer.value;  // the value of the input field
  var regex=/[0-9]\b/;  // my failing regex
    if (x.match(regex) || (x==="+") || (x==="-") || (x==="*") || (x==="/"))
    {
      document.getElementById("problemWithInputMessage").innerHTML="";
      console.log("true, it IS a number");
      return true;
    }
    else if(!(x.match(regex))){
      console.log("false, not a number");
      document.getElementById("problemWithInputMessage").innerHTML="You can only input numbers and the following signs + - * /";
      x = x.substring(0, x.length - 1);   // removing the wrong symbol
      document.calculator.answer.value = x;
      return false;
    }
}

The problems are several. For starters, the regular expression is not working properly, because it only searches at the beginnings and endings of the input string. Also, some signs, different than +-*/. do stay inside the input field and don't get excluded.
Can you help me to validate the input field properly for numbers and the signs +-*/. only?

A: I ended up submitting this code:
function checking() {
  var x = document.calculator.answer.value;
  document.getElementById("problemWithInputMessage").innerHTML="";
    var regexNumbers = /[0-9]+$/;                       //Regular Expression for the numbers
    var regexSigns = new RegExp(/[\+\-\/\*]+$/g);       //Regular Expression for the Special Signs

    if(x.match(regexSigns) || x.match(regexNumbers)) {  //checking for Numbers and the Special allowed signs
        return true;
    }
    else {
      document.getElementById("problemWithInputMessage").innerHTML="You can only input numbers and the following signs + - * /";
      x = x.substring(0, x.length - 1); //Deleting the last symbol if it is not allowed
      document.calculator.answer.value = x;
      return false;
    }
}

I separated the 2 tasks in 2 different Regular Expressions. The first one

/[0-9]+$/

checks for numbers only, and the second one

/[+-/*]+$/g

checks for the special symbols +-/* (although I forgot to put in the dot .) Thanks for the answer, it helped a lot :)
It is not 100%-proofed because if you type at the back of the string it is all ok, but if you put the cursor inside a string of numbers you entered, it will still allow you to enter letters and other symbols in the middle.


text:
Q: Paramiko .exec_command stops working half way through script I am attempting to run some configuration commands on a Cisco switch using paramiko, However after running a few exec commands the command no longer works unless i once again log into the switch, why is this? Is there anything I can do to work around this as I need to complete all of the commands in one session and cant afford to log back in halfway through:
The error message:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\paramiko\client.py", line 414, in exec_command
    chan = self._transport.open_session(timeout=timeout)
File "C:\Python27\lib\site-packages\paramiko\transport.py", line 703, in open_session
    timeout=timeout)
File "C:\Python27\lib\site-packages\paramiko\transport.py", line 824, in open_channel
    raise e EOFError
It Seems to have an issue with opening the channel but im not sure


text:
Q: HTML Email fonts automatically scaling in Opera Mail? I've got an HTML email with fonts sized using pixels (16px) in inlined CSS. Things work as expected in most clients, but in Opera's Mail panel (v12.01), as I shrink the width of the viewport, the font size scales down as well.
This happens in all the other HTML emails I've tested as well.
Has anyone else ever encountered this, and does anyone have a workaround?
UPDATE 2012-08-29:
I found an option under the spanner menu that appears in the top-right corner of email messages called "Fit to width". Unchecking this option results in Opera Mail behaving more like a standard email client.
So the question about a workaround remains... can this behavior be over-ridden by a line of code in emails, when the email creator knows that the email automatically adapts to the viewport width? I'm looking for something similar to the solution available for websites: https://developer.mozilla.org/en-US/docs/Mobile/Viewport_meta_tag

A: You should use the values of the font-sizes inside the inner most elements that need that font sizes. for example giving a font-size:15px; to table wont work, rather you should give font-size:15px; to individual td elements of this table.


text:
Q: Using NSArray for C-type int comparisons I would like to iterate through an NSArray of ints and compare each one to a specific int. All ints are C type ints.
The code I am using is as follows:
-(int)ladderCalc: (NSArray*)amounts: (int)amount
{
    int result;

    for (NSUInteger i=0; i< [amounts count]; i++)
    {
        if (amount < [amounts objectAtIndex:i]);
        {
            // do something
        }
        // do something
    }
}

However I get an error when comparing the int amount to the result of [amounts objectAtIndex:i] because you cannot compare id to int. Why is the id involved in this case? Shouldn't objectAtIndex just return the object at the index specified? Is it possible to cast the object returned to an C int and then do the comparison?
Or should I just dispense with NSArray and do this type of thing in C?

A: You're missing a call to intValue in there (assuming that your array contains instances of NSNumber, which is fair to assume).
Also for sake of performance you'll probably want to call [amounts count] only once, like so:
-(int)ladderCalc:(NSArray *)amounts:(int)amount
{
    int result;
    NSUInteger amountCount = [amounts count];
    for (NSUInteger i = 0; i < amountCount; i++)
    {
        if (amount < [[amounts objectAtIndex:i] intValue]);
        {
            // do something
        }
        // do something
    }
}

And here's an even faster thanks to (system-optimized) fast enumeration:
-(int)ladderCalc:(NSArray *)amounts:(int)amount
{
    int result;
    for (NSNumber *amount in amounts) {
        if (amount < [amount intValue]) {
            // do something
        }
        // do something
    }
}

And one that's even faster than the previous one, thanks to concurrent execution:
-(int)ladderCalc:(NSArray *)amounts:(int)amount
{
    int result;
    [amounts enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSNumber *amount, NSUInteger idx, BOOL *stop) {
        if (amount < [amount intValue]) {
            // do something
        }
        // do something
    }];
}

Word of caution: The last version requires your // do somethings to be NOT dependent on each other, due to concurrency.

A: NSArray is an array that contains objects, not primitive types. To put C integers into an array you typically wrap those in instances of the NSNumber class. The NSArray would then contain NSNumber objects, from which you can easily get the primitive values using the intValue method, as @Regexident demonstrates the other posted answer.


text:
Q: How to pass random variable in runner class, for html report path? I'm trying to pass the random variable in cucumber runner class, But as this code is out of the method (Top of the method) script is not allowed to concatenate the date or any random values for the output report path.

A: You can pass the information by using -Dcucumber.options in maven command.
clean test  -Dtest=stepsAndRunner.Runner -Dcucumber.options="-p com.cucumber.listener.ExtentCucumberFormatter:target/cucumber-reports/report-7/22/2019.html"

A: You can also configure the report location by using ExtentProperties enum as follows. Leave the plugin configuration empty, and configure the report location in your @BeforeClass method:
plugin = {"com.cucumber.listener.ExtentCucumberFormatter:"}
……
……
@BeforeClass
public static void setup() {
ExtentProperties extentProperties = ExtentProperties.INSTANCE;
extentProperties.setReportPath("output/myreport.html");
}

See documentation here - http://www.vimalselvam.com/cucumber-extent-reporter/


text:
Q: django multiple filter options on queryset We have 2 approach ideas that we are trying to consider here for the Django REST api.
At the moment, we have implemented 1 filter option:
class APINewsViewSet(viewsets.ModelViewSet):
    serializer_class = APINewsSerialiser

    def get_queryset(self):
        queryset = NewsBackup.objects.all()
        source = self.request.query_params.get('source', None)
        if source is not None:
            queryset = queryset.filter(news_source = source)
        return queryset

This achieves: 127.0.0.1/news?source=xxx
Something additional that we would like to do is have other filter options that the user can type in such as 127.0.0.1/news?source=xxx&sourcename=xxx which would then return them the JSON object with only data that has a source_id of xx and source_name of xx.
Is this possible with the Django REST framework? We have tried to add other options within the method:
query_params.get()

A: You can place the filters in a dictionary and then use the dictionary as the filter.  Even better you can create a valid filters that safeguards invalid filters.  Something like below:
# {'queryparam': 'db_field'}
valid_filters = {
    'source': 'news_source',
    'source_name': 'source_name',
}

filters = {valid_filters[key]: value for key, value in self.request.query_params.items() if key in valid_filters.keys()}

# So if the query_params is like this: source=xxx&source_name=xxx
# filters value will look something like below:
{
    'news_source': 'xxx',
    'source_name': 'xxx',
}
# **filters transforms the filters to: (news_source='xxx', source_name='xxx')
queryset = queryset.filter(**filters)

Or if you don't want to customize it heavily, you can use third party packages like Django Filter
UPDATE
If you want to get the multiple values for example: id=1&id=2, you can use getlist
ids = self.request.query_params.getlist('id')
# ids will have the list of id
# ids = [1, 2]
# you can then query the id
queryset = queryset.filter(id__in=ids)

UPDATE 2
If you want to support multiple filters, you can create a dictionary again:
keys = [
    'id',
    'source_name',
]
filters = {}
for key in keys:
    filter = query_params.getlist(key)
    if filter:
        filters['{}__in'.format(key)] = filter

queryset = queryset.filter(**filters)

You can add the validation if you want.


text:
Q: Simple way to prove that $\mathbb{Z}[\sqrt[3]{2}]=\mathcal{O}_{\mathbb{Q}(\sqrt[3]{2})}$
Leting $\delta:=\sqrt[3]{2}$, prove that $\mathbb{Z}[\delta]$ is the ring of integers of $\mathbb{Q}(\delta)$.

Here's what I've done: let $K:=\mathbb{Q}(\delta)$. Since $[K:\mathbb{Q}]=3$, then $1, \delta, \delta^2$ are $\mathbb{Q}$-linearly independent (in particular, they are $\mathbb{Z}$-independent). Since $1, \delta, \delta^2$ are integers of $K$, we have that $\mathbb{Z}[\delta]=<1, \delta, \delta^2>_{\mathbb{Z}}\subset\mathcal{O}_{K}$.
To prove $\supset$, I did the following: if $z=a+b\delta+c\delta^2$ is an integer of $K$, its minimal polynomial $p(x)=x^3+c_2x^2+c_1x+c_0$ lies in $\mathbb{Z}[x]$ and has roots $\sigma_1(z),\sigma_2(z)$ and $\sigma_3(z)$, where
\begin{align*}
\sigma_1 &:\delta\mapsto\delta\\
\sigma_2 &:\delta\mapsto\omega\delta\\
\sigma_3 &:\delta\mapsto\omega^2\delta
\end{align*}
are the embeddings fixing $\mathbb{Q}$ and $\omega^3=1$. Using Viète's relations we get:
\begin{align*}
 c_2&=-\sum_{i}\sigma_i(z)= -3a\\
 c_1&= \sum_{i<j}\sigma_i(z)\sigma_j(z)=3a^2-6bc\\
 c_0&= -\prod_{i}\sigma_i(z)=-(a^3+2b^3+4c^3-6abc)
\end{align*}
which gives us restrictions for $a, b, c$, since $c_0, c_1, c_2\in\mathbb{Z}$. Since $\delta z$ and $\delta^2 z$ are also integers of $K$, we calculate its respective minimal polynomials and find new restrictions for $a, b, c$.
After a very tiresome case analysis, I could prove that $a, b, c\in\mathbb{Z}$, concluding the proof.
This solution was given as a hint by the professor, and seems to me not very natural and, above all, way too long. My question is: is there a more natural and/or shorter solution for this? Thanks!

A: This from book algebraic number theory, J.S. MILNE, p.34
In general we have $\mathbb Z[\alpha] \subseteq O_k \subseteq d^{-1} \mathbb Z[\alpha] $ where $k=\mathbb Q[\alpha] , d=disc\{ 1,\alpha,...,\alpha^{n-1} \}$


text:
Q: Autofill username password web form "GeckoWebBrowser" I'm developing program and I'm using Skybound Gecko browser !
i want to inter the username and password automatically when i open the page!
I'm using this code to do this :
Private Sub login_Click(sender As Object, e As EventArgs) Handles login.Click
    GeckoWebBrowser1.Document.GetElementById("codeTerminal").SetAttribute("value", "xxxxxx")
    GeckoWebBrowser1.Document.GetElementById("userName").SetAttribute("value", "xxxxxx")
    GeckoWebBrowser1.Document.GetElementById("pass").SetAttribute("value", "xxxxxx")
End Sub

i test this on google and on Facebook its work !!
but not working with the site i want :(
this is the site : http://www.youphone.co.il/loadingSystem.aspx
when i use the above code i face this error :
An unhandled exception of type 'System.NullReferenceException' occurred in Noor Phone.exe
Additional information: Object reference not set to an instance of an object.
this the web page text information :
1-"<"input name="codeTerminal" type="text" id="codeTerminal" style="float:left;display:inline;background-image:url('imges/login_box_white.png');width:243px;height:44px;background-repeat:no-repeat;border:none;line-height:44px;">"
2-"<"input name="userName" type="text" id="userName" style="float:left;display:inline;background-image:url('imges/login_box_white.png');width:243px;height:44px;background-repeat:no-repeat;border:none;line-height:44px;">
3-"<"input name="pass" type="password" id="pass" style="float:left;display:inline;background-image:url('imges/login_box_white.png');width:243px;height:44px;background-repeat:no-repeat;border:none;line-height:44px;">
how i can fix this i want this so badly
any help please..


text:
Q: got an error Null reference exception was Handled I am trying to show the reporting chart by clicking  on the  one chart by using following
code but it was showing an error
ERROR : null reference exception was Handled
          Object reference not set to an instance of an object.                              at this line targetcontrol.ChartAreas.Clear();
and this is click event for chart control
 using System.Windows.Forms.DataVisualization.Charting;

private void kpiChartControl_Click(object sender, EventArgs e)
{
  Chart targetcontrol = null;
  Series series = null;
  Title title;
  string are;

  targetcontrol.ChartAreas.Clear();
  targetcontrol.Series.Clear();
  targetcontrol.Titles.Clear();

  DataTable accepts = null;
  accepts = KPIData.AcceptedvisitsByMembership(mf ,"accepted");

 are = " acceptedvisitsmshiptypes";
  targetcontrol.ChartAreas.Add(are);
  series = targetcontrol.Series.Add(are);
  series.ChartArea = are;

  title = targetcontrol.Titles.Add("Accepted Visits By MemberShip Type");
  title.DockedToChartArea = are;
  title.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold);
  title.Alignment = ContentAlignment.TopLeft;

  foreach (Title titles in targetcontrol.Titles)
  {
    titles.IsDockedInsideChartArea = false;
  }

  foreach (Series serie in targetcontrol.Series)
  {

    serie.ChartType = SeriesChartType.Pie;

    serie["PieLabelStyle"] = "Outside";
    serie["DoughnutRadius"] = "30";
    serie["PieDrawingStyle"] = "SoftEdge";

    serie.BackGradientStyle = GradientStyle.DiagonalLeft;

  }
  foreach (Legend legend in targetcontrol.Legends)
  {
    legend.Enabled = false;
  }

  foreach (ChartArea chartArea in targetcontrol.ChartAreas)
  {
    chartArea.Area3DStyle.Enable3D = true;
    chartArea.Area3DStyle.Inclination = 45;
    //chartArea.AxisX.LabelStyle.IsEndLabelVisible = !overview;
  }

  targetcontrol.Series[0].Points.DataBindXY(accepts.Rows, "mshiptypenumbers", accepts.Rows, "mshipType_Name");
  foreach (Series chartSeries in targetcontrol.Series)
  {
    foreach (DataPoint point in chartSeries.Points)
    {

      switch (point.AxisLabel)
      {
        case "Silver membership": point.Color = Color.Green; break;
        //case "Refused": point.Color = Color.Red; break;

      }
      point.Label = string.Format("{0:0}", point.YValues[0]);
    }

  }
}

A: You set a variable
Chart targetcontrol = null;

then trying to use
targetcontrol.ChartAreas.Clear();

targetcontrol is null and don't have ChartAreas property. Try change the third line
Chart targetcontrol = null;

to
Chart targetcontrol = new Chart();

A: Of course you get that error, you're declaring
Chart targetcontrol = null;

Then you're trying to use it without actually instantiating it to anything.


text:
Q: Python - Portfolio Open Position Flag I have a dataframe below:
 ticker       date  buy_fg  sell_fg
50      ABC 2010-01-01     0.0      2.0
51      ABC 2010-01-08     0.0      2.0
52      ABC 2010-01-15     0.0      2.0
53      ABC 2010-01-22     0.0      2.0
1512    ABC 2010-01-29     1.0      0.0
54      ABC 2010-02-05     0.0      2.0
55      ABC 2010-02-12     0.0      2.0
56      ABC 2010-02-19     0.0      2.0
57      ABC 2010-02-26     0.0      2.0
58      ABC 2010-03-05     0.0      2.0
59      ABC 2010-03-12     0.0      2.0
60      ABC 2010-03-19     0.0      2.0
61      ABC 2010-03-26     0.0      2.0
1417    ABC 2010-04-02     1.0      0.0
1409    ABC 2010-04-09     1.0      0.0
62      ABC 2010-04-23     0.0      2.0
63      ABC 2010-05-07     0.0      2.0
64      ABC 2010-05-14     0.0      2.0
65      ABC 2010-05-21     0.0      2.0
66      ABC 2010-05-28     0.0      2.0

I am trying to develop a column that provides a summary of the action that my script needs to take. I have tried to develop a cumulative score approach and haven't been able to get it to work. I have also tried lambda, however the logic isn't right as it just repeats the buy_fg column.
# Initiate the global, default buy flag
hold_flag =  False

# Custom function to flick the global flag based on `buy_fg` column
def hold(value):
    global hold_flag
    if value == 1:
        if hold_flag is False:
            hold_flag = True
            return '3'
        if hold_flag is True:
            hold_flag = False
            return '1'
    else:
        return '0'

new_report['hold_fg'] = new_report['buy_fg'].apply(hold)

This created hold_fg column. But now I need to expand upon this to consider all three *_fg columns to provide the final action.
      ticker       date  buy_fg  sell_fg  action hold_fg
50      ABC 2010-01-01     0.0      2.0       0       0
51      ABC 2010-01-08     0.0      2.0       0       0
52      ABC 2010-01-15     0.0      2.0       0       0
53      ABC 2010-01-22     0.0      2.0       0       0
1512    ABC 2010-01-29     1.0      0.0       0       1
54      ABC 2010-02-05     0.0      2.0       0       0
55      ABC 2010-02-12     0.0      2.0       0       0
56      ABC 2010-02-19     0.0      2.0       0       0
57      ABC 2010-02-26     0.0      2.0       0       0
58      ABC 2010-03-05     0.0      2.0       0       0
59      ABC 2010-03-12     0.0      2.0       0       0
60      ABC 2010-03-19     0.0      2.0       0       0
61      ABC 2010-03-26     0.0      2.0       0       0
1417    ABC 2010-04-02     1.0      0.0       0       1
1409    ABC 2010-04-09     1.0      0.0       0       3
62      ABC 2010-04-23     0.0      2.0       0       0
63      ABC 2010-05-07     0.0      2.0       0       0
64      ABC 2010-05-14     0.0      2.0       0       0
65      ABC 2010-05-21     0.0      2.0       0       0
66      ABC 2010-05-28     0.0      2.0       0       0

I have tried the following, but this doesn't work:
new_report['action'] = 0

buy_flag = False

def action(value):
    global buy_flag
    if new_report['hold_fg'] == 1:
        buy_flag = True
        return 'BUY'
    if new_report['hold_fg'] == 3:
        buy_flag = True
        return 'HOLD'
    if new_report['sell_fg'] == 2:
        buy_flag = False
        return 'SELL'
    else:
        return '0'

Any ideas on how I can solve this?
updated expected output:
     ticker       date  buy_fg  sell_fg action hold_fg
50      ABC 2010-01-01     0.0      2.0    NIL       0
51      ABC 2010-01-08     0.0      2.0    NIL       0
52      ABC 2010-01-15     0.0      2.0    NIL       0
53      ABC 2010-01-22     0.0      2.0    NIL       0
1512    ABC 2010-01-29     1.0      0.0    BUY       1
54      ABC 2010-02-05     0.0      2.0   SELL       0
55      ABC 2010-02-12     0.0      2.0    NIL       0
56      ABC 2010-02-19     0.0      2.0    NIL       0
57      ABC 2010-02-26     0.0      2.0    NIL       0
58      ABC 2010-03-05     0.0      2.0    NIL       0
59      ABC 2010-03-12     0.0      2.0    NIL       0
60      ABC 2010-03-19     0.0      2.0    NIL       0
61      ABC 2010-03-26     0.0      2.0    NIL       0
1417    ABC 2010-04-02     1.0      0.0    BUY       1
1409    ABC 2010-04-09     1.0      0.0    HOLD      3
62      ABC 2010-04-23     0.0      2.0    SELL      0
63      ABC 2010-05-07     0.0      2.0    NIL       0
64      ABC 2010-05-14     0.0      2.0    NIL       0
65      ABC 2010-05-21     0.0      2.0    NIL       0
66      ABC 2010-05-28     0.0      2.0    NIL       0

A: I think you'd need to keep track of the status and apply your required logic based on that. Here is an example using a custom function to do that. Hope this helps!
 # Initiate the global, default buy flag
 >>> buy_flag =  False

 # Custom function to flick the global flag based on `buy_fg` column
 >>> def sell_or_buy(value):
    global buy_flag
    if value == 1:
        if buy_flag is False:
            buy_flag = True
            return 'BUY'
        if buy_flag is True:
            return 'HOLD'
    if value == 0:
        if buy_flag == 1:
            buy_flag = False
            return 'SELL'
        if buy_flag == 0:
            return 'NIL'

>>> df['action'] = df['buy_fg'].apply(sell_or_buy)

>>> df
    ticker            date  buy_fg  sell_fg action
0       50  ABC 2010-01-01     0.0      2.0    NIL
1       51  ABC 2010-01-08     0.0      2.0    NIL
2       52  ABC 2010-01-15     0.0      2.0    NIL
3       53  ABC 2010-01-22     0.0      2.0    NIL
4     1512  ABC 2010-01-29     1.0      0.0    BUY
5       54  ABC 2010-02-05     0.0      2.0   SELL
6       55  ABC 2010-02-12     0.0      2.0    NIL
7       56  ABC 2010-02-19     0.0      2.0    NIL
8       57  ABC 2010-02-26     0.0      2.0    NIL
9       58  ABC 2010-03-05     0.0      2.0    NIL
10      59  ABC 2010-03-12     0.0      2.0    NIL
11      60  ABC 2010-03-19     0.0      2.0    NIL
12      61  ABC 2010-03-26     0.0      2.0    NIL
13    1417  ABC 2010-04-02     1.0      0.0    BUY
14    1409  ABC 2010-04-09     1.0      0.0   HOLD
15      62  ABC 2010-04-23     0.0      2.0   SELL
16      63  ABC 2010-05-07     0.0      2.0    NIL
17      64  ABC 2010-05-14     0.0      2.0    NIL
18      65  ABC 2010-05-21     0.0      2.0    NIL
19      66  ABC 2010-05-28     0.0      2.0    NIL

EDIT:
This is to accommodate your latest requirement. As it gets a bit messy now with the way you've updated the question, I will just modify my answer to add to the above dataframe.
>>> d={'NIL': 0, 'BUY': 1, 'SELL': 2, 'HOLD' : 3}
>>> df['hold_fg'] = df.action.map(d)
>>> df
    ticker            date  buy_fg  sell_fg action  hold_fg
0       50  ABC 2010-01-01     0.0      2.0    NIL        0
1       51  ABC 2010-01-08     0.0      2.0    NIL        0
2       52  ABC 2010-01-15     0.0      2.0    NIL        0
3       53  ABC 2010-01-22     0.0      2.0    NIL        0
4     1512  ABC 2010-01-29     1.0      0.0    BUY        1
5       54  ABC 2010-02-05     0.0      2.0   SELL        2
6       55  ABC 2010-02-12     0.0      2.0    NIL        0
7       56  ABC 2010-02-19     0.0      2.0    NIL        0
8       57  ABC 2010-02-26     0.0      2.0    NIL        0
9       58  ABC 2010-03-05     0.0      2.0    NIL        0
10      59  ABC 2010-03-12     0.0      2.0    NIL        0
11      60  ABC 2010-03-19     0.0      2.0    NIL        0
12      61  ABC 2010-03-26     0.0      2.0    NIL        0
13    1417  ABC 2010-04-02     1.0      0.0    BUY        1
14    1409  ABC 2010-04-09     1.0      0.0   HOLD        3
15      62  ABC 2010-04-23     0.0      2.0   SELL        2
16      63  ABC 2010-05-07     0.0      2.0    NIL        0
17      64  ABC 2010-05-14     0.0      2.0    NIL        0
18      65  ABC 2010-05-21     0.0      2.0    NIL        0
19      66  ABC 2010-05-28     0.0      2.0    NIL        0


text:
Q: react-data-table-component: access the selected row and assign it to setState hi i'm really new in react, so i have a table which contains a bunch of data, i would like to assign the value of selected row to my setState but the output doesnt seems like what i expected to be, i made a simpler version of the code so here it is.
App.js :
import React from "react";
import DataTable from "react-data-table-component";

const app = () => {
  const [selectedData, setSelectedData] = React.useState();

  const data = [
    { name: "Jade", age: "25" },
    { name: "Brian", age: "15" }
  ];

  const columns = [
    {
      name: "Name",
      selector: "name"
    },
    {
      name: "Age",
      selector: "age"
    }
  ];

  const handleChange = (state) => {
    setSelectedData(state.selectedRows);
    console.log(selectedData);
  };

  return (

      <DataTable
        data={data}
        columns={columns}
        selectableRows
        onSelectedRowsChange={handleChange}
      />

  );
};

export default app;

Codesandbox

A: solved this issue by moving the data variable to global scope, this happen because the data variables keeps re-rendering inside the component
import DataTable from "react-data-table-component";

  const data = [
    { name: "Jade", age: "25" },
    { name: "Brian", age: "15" }
  ];

const app = () => {
  const [selectedData, setSelectedData] = React.useState();

  const columns = [
    {
      name: "Name",
      selector: "name"
    },
    {
      name: "Age",
      selector: "age"
    }
  ];

  const handleChange = (state) => {
    setSelectedData(state.selectedRows);
    console.log(selectedData);
  };

  return (

      <DataTable
        data={data}
        columns={columns}
        selectableRows
        onSelectedRowsChange={handleChange}
      />

  );
};

export default app;```

A: So your code is complete. There is no problem with it. This is just how React functions. Any state changes in React are batched. So after you have set the state, your setState method does not immediately update the state in the state variable. Instead it waits for the synchronous scope around the setState to complete. Only after that your state variable has the updated value.
  return (

      <DataTable
        data={data}
        columns={columns}
        selectableRows
        onSelectedRowsChange={handleChange}
      />

{selectedData[0] ? selectedData[0].name : ''}

If you add the line I have added here, you will see that your selectedData does get updated with the selected value.But if you will try to access the selectedData in the synchronous scope of where you are setting the selectedData by calling setSelectedData, you will never see the currently selected data. Also, if you would like to experiment further with this, try changing your selection again and again, you will see that the line  console.log(selectedData); will display the previously selected value.
This is a property of react to batch all state updates made in a synchronous scope altogether and make all the state changes once the control has reached the end of the scope.
Also if you do want to show your selected data, better use event.selectedRows for the same instead of selectedData.
Elaborate example of how setstate works :
const [someState, setSomeState] = useState(0);
//Assume we call this function on some event
const eventHandler = () => {
//line 1 setSomeState(someState + 1);
//line 2 setSomeState(someState + 1);
//line 3 setSomeState(someState + 1);
}

Now what will be the value of someState after line 3. It will be 1. Why? The first line takes the value of someState which is '0' and adds 1 to it, tries to set the new state with value as 1. But when we go to line 2, where we are again trying to access someState and we expect someState to be updated by line1, that is not going to happen. The value of someState will still be 0.Why? Because react waits for the entire block to first finish and only after that it really updates the state. This is an optimization technique that React has within itself. Also, if you want to see the previously set state, there is one workaround for that too.
const eventHandler = () => {
setSomeState(someState + 1);
setSomeState((prevState) => {
 return prevState + 1;
});
setSomeState((prevState) => {
 return prevState + 1;
});
}

Now this will update your state on each line.


text:
Q: In Chisel test bench, how to write two independent interface processes? Suppose a DUT has two independent interface with different sequential protocols. It should be easy to test each of them in one "process/thread". But the current peekpoketester seems difficult to do this. For example, one push and one pull interfaces:
one.valid = 1;
@(posedge clock) begin
if (one.ready)
    one.data <= next
end

two.ready = 1;
@(posedge clock) begin
if (two.valid)
    handle(two.data)
end

A: One way of approaching this is to use the chisel-testers AdvTester. There is a example using the AdvTester in a manner related to your problem in the ConcurrentDecoupledTestingSpec which shows how to implement an asynchronous test of a DUT.  Improving the tester eco-system is a current project with Chisel, please contribute specific needs like this as issues at the chisel3.


text:
Q: What is and what isn't a "closed form solution" I had a friendly discussion with someone about closed form solutions. They contended that the backpropagation algorithm used in calculating the gradients of deep neural networks can't be called a closed form expression in itself, though it is computing a closed form and can be easily converted to one. I pointed them to the Wikipedia entry on closed forms which says -

"In mathematics, a closed-form expression is a mathematical expression that can be evaluated in a finite number of operations. It may contain constants, variables, certain "well-known" operations (e.g., + − × ÷), and functions (e.g., nth root, exponent, logarithm, trigonometric functions, and inverse hyperbolic functions), but usually no limit."

On the one hand, backpropagation can be completed in a finite number of steps. But the next question becomes, is it a "Mathematical expression".
From the Wikipedia entry, it isn't clear if function composition should be an operation that qualifies.
For me, backpropagation should certainly be qualified as a "closed form solution" but I can't come up with a water-tight argument for why.
Also, other examples came up in the discussion. Let's say I have an algorithm for finding the smallest prime number larger than some integer. This involves checking each number greater than that integer and stopping when I find a prime. This algorithm can be completed in a finite number of steps and calculates the solution exactly. But can we say there is "no Mathematical expression" here and hence no closed form?

EDIT: My question is different from the linked question since it focuses on these two cases in particular. The first one being backpropagation for deep neural networks. This basically involves the following:
In general we get a loss function that looks like - $L = f(g(h(x)))$ and then we take the derivative and get - $L' = f'(g(h(x))g'(h(x))h'(x)$. The argument being that because we calculate $h(x)$ separately and then substitute it, this is not a closed form.
The second example being the algorithm for finding the smallest prime number larger than an integer.


text:
Q: Fiware cygnus docker installation I have questions regarding docker installation of fiware-cygnus:
What docker image should I use, I found at least 3 of them(not sure if this affect installation)
I have agent.conf on my host, and I was not able to map it to the container. So it could be me but is this location where I should map agent.conf?
I had no problems to map my own grouping_rules.conf but agent.conf I was not able to do it, I run docker images/containers many times never had an issue like this.
/opt/apache-flume/conf/agent.conf

This is the main reason of my problems because file inside of docker-container simply won't change, even if I try to change it the manual moment I restart container it returns to the original state.
3. Do I need to configure cygnu_instance.conf, very confusing for me is the fact that in it mention agent.conf but on the different location, is that location I should map my agent.conf or not.
CONFIG_FOLDER=/usr/cygnus/conf
CONFIG_FILE=/usr/cygnus/conf/agent.conf

These are the main questions/issues I have:
If someone were able to install Cygnus with docker and with personal agent.conf or know where I should look and send me in some direction would help a lot.

A: Not fully sure, but of the 3 I think the one you need to work with Orion Context Broker (i.e. subscribing to Orion so it sends notifications to Cygnus) is cygnus-ngsi.
With regards to configuration, I think that the approach is not editing .conf files inside the docker container on execution. You should inject configuration as environment variables. The ENV marks in the Dockerfile mean configurabe parameters.
I guess that both docker run and docker-compose should allow to set environment variables to the container, but that's a docker generic question not directly related with this question. There should be a lot of literature out there about this :)


text:
Q: data-src not getting replaced with src after jquery ajax call I am binding a div with a response from ajax function like below
BindProductFamilyList: function (str) {
    var _obj= new Object();

    _obj.id= str;

    $.ajax({
        url: 'page.aspx/Bind',
        data: JSON.stringify({ 'obj': _obj}),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        cache: false,
        async: false,
        type: 'POST',
        beforeSend: function () {
            $("#divLoader").fadeIn();
        },
        complete: function () {
        },
        success: function (response) {
            var _strInnerHtml = "";
            $("#div").html(_strInnerHtml);
            // Loop and bind the parameter header
            $.each(response, function (key, value) {
                if (Object.keys(value).length > 0) {
                    $.each(value, function (key, value) {
                        // Loop and bind
                        _strInnerHtml += "
";
                        _strInnerHtml += "";
                        _strInnerHtml += "";
                        _strInnerHtml += "
" + value.name + "
";
                        _strInnerHtml += "";
                        _strInnerHtml += "
";
                    });
                }
                else {

                    _strInnerHtml = "No records.";
                }
            });
            $("#div").html(_strInnerHtml);
            $("#divLoader").fadeOut();

        },
        error: function (xhr, ajaxOptions, thrownError) {
            //alert(xhr.status);
            //alert(thrownError);
        }
    });
}

  $(document).on("change", ".catfilter", function () {
    ns.BindProductFamilyList(ns.GetSelectedId());
});

First time on calling this function, the images are loaded properly. When I call this function on change event of checkbox list. The images are not loading, only the data 64 image is loaded and the actual image from the folder is not loaded. How can I solve this?

A: try adding an img.onLoad event and set the img.src as the result of that event instead....
img.onload(function(){img.src = "imgurl.png"})


text:
Q: How to repeat a json object in angular2? like in angular 1 we can repeat json object in following way :
ng-repeat="state(k,v) in states"

then using {{k}} or {{v}}
But how to do it for angular 2 ?
*ngFor="let state of states"

A: Unfortunately, I haven't seen a simpler method to iterate and get the keys using '*NgFor' than the one here: iteration a json object on Ngfor in angular 2
It's basically creating a custom pipe to set the keys as properties you can access in the loop.
Hope it helps.


text:
Q: Google OAuth 2.0. javascript API doesn't stay "logged in" after page refresh I'm developing an AngularJS application with google+ user authentication. I've taken the package angular-google-plus (an Angular module which handles the login with the Google+ API).
At it's heart, the login will use the gapi object:
gapi.auth.authorize(...)
Everything is working while the page doesn't refresh. For example, I can get the current user from the API with:
gapi.client.oauth2.userinfo.get().execute(function() { ... }) but again, the state wont be kept when I refresh the page.
What do I need to do in order to maintain the "Logged-In" state after the page is refreshed ? it seems the google api "forgets" the state.

A: I feel unfamiliar with your code... Is it really OAuth 2.0?
I think you are talking about Google Sign-In JavaScript client because you are mentioning page refresh.
I believe that you cannot immediately get any information like gapi.client.oauth2.userinfo because there is no code to wait for an instance to be initialized.
Do something like the following with then:
gapi.auth2.init({client_id: "...", ...}).then(function(googleAuth) { // onInit
  console.log(googleAuth.isSignedIn.get());
}, function() { // onError
});


text:
Q: QueryOver and ProjectionLists We are trying to use QueryOver and projects. Basically it works fine. But we are currently struggling with a projection which should contain multiple items. The problem is that we have pallets which can contain pallet items. Pallet items are the base classes for various subclasses. We need to be able to projects only one property of each subclass MagazinePlaceLoadingOverviewData. Any ideas how we could achieve this?
Information: Magazine contains Levels, Levels contains Places, Places can have one Pallet assigned and a pallet can have multiple pallet items on it. Pallet items can be of various subtypes. We tried to get into the subtypes by implementing a visitor pattern on the pallet item but we can't even get the query below working.
        MagazinePlaceLoadingEntity magazineLoadingAlias = null;
        MagazinePlaceSettingsEntity magazinePlaceAlias = null;
        MagazineLevelSettingsEntity magazineLevelAlias = null;
        MagazineSettingsEntity magazineAlias = null;
        MagazinePlaceLoadingOverviewData overviewAlias = null;

        PalletEntity palletAlias = null;
        PalletTypeSettingsEntity palletTypeAlias = null;
        PalletItemEntity palletItemsAlias = null;

        return session.QueryOver(() => magazineLoadingAlias)
                        .JoinAlias(x => x.Pallet, () => palletAlias)
                        .JoinAlias(() => palletAlias.PalletType, () => palletTypeAlias)
                        .JoinQueryOver(x => x.Place, () => magazinePlaceAlias)
                        .JoinQueryOver(x => x.Level, () => magazineLevelAlias)
                        .JoinQueryOver(x => x.Magazine, () => magazineAlias)
                        .Where(x => x.Id == this.magazineId)
                        .Select(
                            Projections.Property(() => magazinePlaceAlias.Id).WithAlias(() => overviewAlias.MagazinePlaceId),
                            Projections.Property(() => magazineLoadingAlias.PalletInProgress).WithAlias(() => overviewAlias.PalletInProgress),
                            Projections.ProjectionList().Add(Projections.Property(() => palletAlias.PalletItems), () => overviewAlias.Items),
                            Projections.Property(() => palletTypeAlias.Classification).WithAlias(() => overviewAlias.PalletTypeClassification))
                        .TransformUsing(Transformers.AliasToBean<MagazinePlaceLoadingOverviewData>())
                        .List<MagazinePlaceLoadingOverviewData>();

This leads to the following exception
System.Data.SqlServerCe.SqlCeException: The column aliases must be unique. [ Name of duplicate alias = y2_ ]
at System.Data.SqlServerCe.SqlCeCommand.ProcessResults(Int32 hr)
at System.Data.SqlServerCe.SqlCeCommand.CompileQueryPlan()
at System.Data.SqlServerCe.SqlCeCommand.ExecuteCommand(CommandBehavior behavior, String method, ResultSetOptions options)
at System.Data.SqlServerCe.SqlCeCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader()
at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd)
at NHibernate.Loader.Loader.GetResultSet(IDbCommand st, Boolean autoDiscoverTypes, Boolean callable, RowSelection selection, ISessionImplementor session)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
NHibernate.Exceptions.GenericADOException: could not execute query
[ SELECT magazinepl3_.Id as y0_, this_.PalletInProgress as y1_, palletalia1_.Id as y2_, pallettype2_.Classification as y2_ FROM "MagazinePlaceLoading" this_ inner join "Pallet" palletalia1_ on this_.PalletId=palletalia1_.Id inner join "PalletTypeSettings" pallettype2_ on palletalia1_.PalletTypeSettingsId=pallettype2_.Id inner join "MagazinePlaceSettings" magazinepl3_ on this_.MagazinePlaceSettingsId=magazinepl3_.Id inner join "MagazineLevelSettings" magazinele4_ on magazinepl3_.MagazineLevelSettingsId=magazinele4_.Id inner join "MagazineSettings" magazineal5_ on magazinele4_.MagazineSettingsId=magazineal5_.Id WHERE magazineal5_.Id = @p0 ]
Positional parameters:  #0>cb9ff95a-58ca-4b2b-9aa6-9f6c008fc0b3
[SQL: SELECT magazinepl3_.Id as y0_, this_.PalletInProgress as y1_, palletalia1_.Id as y2_, pallettype2_.Classification as y2_ FROM "MagazinePlaceLoading" this_ inner join "Pallet" palletalia1_ on this_.PalletId=palletalia1_.Id inner join "PalletTypeSettings" pallettype2_ on palletalia1_.PalletTypeSettingsId=pallettype2_.Id inner join "MagazinePlaceSettings" magazinepl3_ on this_.MagazinePlaceSettingsId=magazinepl3_.Id inner join "MagazineLevelSettings" magazinele4_ on magazinepl3_.MagazineLevelSettingsId=magazinele4_.Id inner join "MagazineSettings" magazineal5_ on magazinele4_.MagazineSettingsId=magazineal5_.Id WHERE magazineal5_.Id = @p0]
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes)
at NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results)
at NHibernate.Impl.CriteriaImpl.List(IList results)
at NHibernate.Impl.CriteriaImpl.List()
at NHibernate.Impl.CriteriaImpl.Subcriteria.List()
at NHibernate.Criterion.QueryOver`1.List()
at NHibernate.Criterion.QueryOver`1.NHibernate.IQueryOver<TRoot>.List<U>()
at .Domain.Queries.Magazines.GetLoadingOverviewByMagazineQuery.Find(ISession session) in GetLoadingOverviewByMagazineQuery.cs: line 41
at .Domain.Queries.QueryTestBase.Execute(IEnumerableQuery`1 query) in QueryTestBase.cs: line 39
at .Domain.Queries.Magazines.GetLoadingOverviewByMagazineQueryTest.Find_ShouldReturnOverviewData() in GetLoadingOverviewByMagazineQueryTest.cs: line 39

A: You can't do this:
Projections.ProjectionList().Add(Projections.Property(() => palletAlias.PalletItems), () => overviewAlias.Items),
AliasToBean Transformer means you are flattening your results set. You can't have a list inside your MagazinePlaceLoadingOverviewData.
You will need to get your list of items as a second query and join them together using Linq To Objects if you want them in that format.


text:
Q: Использование noexcept Для чего используется noexcept в конструкторе перемещения? Насколько я понял, он используется, чтобы вызывать не конструктор перемещения, а копирующий конструктор. Верный ли мои рассуждения?
class String
{
    size_t len;
    char* buffer;
public:
    String(const char* str)
    {
        len = strlen(str);
        buffer = new char[len + 1];
        memcpy(buffer, str, len + 1);

        std::cout << "Call CTR " << str << endl;

    }
    friend std::ostream& operator<< (std::ostream& stream, const String& str);
    ~String()
    {
        delete[] buffer;
    }

    String& operator= (const String& str)
    {
        delete[] buffer;
        if (this == &str)
        {
        }
        this->len = str.len;
        buffer = new char[len + 1];
        memcpy(buffer, str.buffer, len + 1);
        return *this;

        std::cout << "Call COPY " << str << endl;
    }

    char& operator[] (unsigned int index)
    {
        return buffer[index];
    }

    String(const String& str)
        :
        len(str.len)
    {
        buffer = new char[len + 1];
        memcpy(buffer, str.buffer, len + 1);
    }

    String(const String&& str) noexcept
    {

        std::cout << "MOVE СTR\n" << str << endl;
    }

};

std::ostream& operator<< (std::ostream& stream, const String& str)
{
    stream << str.buffer;
    return stream;
}

int main(int argc, char* argv[])
{

    String str = "string";
    String str2 (std::move(str));
    return 0;
 }

Но если использовать либо нет noexcept все равно вызывается этот конструктор.

A: Если move-ctor вашего класса не помечен как noexcept, действительно вместо него будет вызываться конструктор копирования, но в одном достаточно узком случае.
Допустим у вас есть вектор, в который вы добавляете объекты вашего класса. В какой-то момент вместимости вектора (размера выделенной под него памяти) перестает хватать и вектор делает переаллокацию - выделяет новую память с запасом и переносит туда содержимое старого фрагмента памяти. И если у вас кидающий перемещающий конструктор, вместо него вектор вызовет конструктор копирования.
Это сделано для того, чтобы сохранить состояние вектора в случае вылета исключения - если мы копировали объекты, можно просто почистить новую память и старое состояние вектора останется валидным, а в случае перемещения, непонятно, что куда возвращать.
Другие контейнеры стандартной библиотеки следуют тому же правилу

upd
Добавлю что наличие noexcept у методов позволяет компилятору лучше оптимизировать исполняемый файл (хотя к конструкторам копирования/перемещения это отношения не имеет).
Также cpp core guidelines рекомендуют всегда помечать move-ctor noexcept так как кидающий перемещающий конструктор "нарушает ожидания большинства людей": http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-move-noexcept


text:
Q: Why requests is getting same data and returning errors from different urls in python? I have a list of data to scrape here https://docs.google.com/spreadsheets/d/1KMYsjN2ggklFMQ5HPKMbdkVqc04MdjhYGLvku1Js0cc/edit?usp=sharing
So the scraper runs but there are two problems here.

*

*The scraper returns the same data for different url, even though when I checked the urls reponse through web is both different and both are returning 200.
The dictionary ID is a distinct id mapped out to the urls.

scraped_product_name
url
dictionary_id

Hansaplast aqua protect 6s
https://www.blibli.com/p/hansaplast-aqua-protect-6s/ps--RAM-70107-07546?ds=RAM-70107-07546-00001&source=MERCHANT_PAGE&sid=7cb21b003f4516bb&cnc=false&pickupPointCode=PP-3239816&pid=RAM-70107-07546
418

Hansaplast aqua protect 6s
https://www.blibli.com/p/hansaplast-aqua-protect-6s/ps--RAM-70107-07546?ds=RAM-70107-07546-00001&source=MERCHANT_PAGE&sid=7cb21b003f4516bb&cnc=false&pickupPointCode=PP-3239816&pid=RAM-70107-07546
181

*After running a few urls, it returns an error Access Denied where there is no data. I was wondering if this affects the data being returned?However when I tried rerunning it again in another iteration it returns a 200.

Here's my code
from random import randint
import requests

rancherrors=pd.DataFrame()
ranchdf=pd.DataFrame()
for id, input,url in zip(ranch['product_id'],ranch['urls'],ranch['urls2']):

    headers={
        "user-agent" : f"{UserAgent().random}",
        'referer':'https://www.blibli.com/'
        }
    response =requests.get(url,headers=headers,verify=True)
    #catches error
    ####################
    if response.status_code != 200:
        datum={
            'id':id,
            'url':url,
        'date_key':today
        }
        rancherrors=rancherrors.append(pd.DataFrame([datum]))
        print(f'{url} error')

        sleep(randint(5,15))

    else:
    #runs scraper
    ################################
        try:
            price=str(response.json()['data']['price']['listed']).replace(".0","")
            discount=str(response.json()['data']['price']['totalDiscount'])
        except:
            price="0"
            discount="0"
        try:
            unit=str(response.json()['data']['uniqueSellingPoint']).replace("• ","")
        except:
            unit=""

        datranch={
            'product_name':response.json()['data']['name'],
            'normal_price':price,
            'discount':discount,
            'competitor_id':response.json()['data']['ean'],
            'url':input,
            'unit':unit,
            'product_id':id,
            'date_key':today,
            'web':'ranch market'
            }
        ranchdf=ranchdf.append(pd.DataFrame([datranch]))

I use the rancherrors to catch errors and run in loop until no errors appears.
Any help would be greatly appreciated.

A: *

*You have duplicated values in the url2 column in your examples list, and such same data is scraped. Few highlighted duplicates can be seen in below image:

*Don't refresh the User-Agent from the Header at every call. The User-Agent identifies the application, operating system, vendor, and/or version of the requesting user. As you are not using proxies and are making a call from the same IP address, changing these details every second is very suspicious. Try moving the Headers initialization outside your for loop at the start:
...
ranchdf=pd.DataFrame()
headers={
     "user-agent" : f"{UserAgent().random}",
     'referer':'https://www.blibli.com/'
     }
for id, input,url in zip(ranch['product_id'],ranch['urls'],ranch['urls2']):

     response =requests.get(url,headers=headers,verify=True)
...

A chance of being denied will still be there but it should be much better. For better avoiding bans you would need to make use of proxies as well.


text:
Q: I need output ( create colmun) how many cities for every country by using the same query ( with ) WITH city_count_per_country AS
  (SELECT
    country_name,
    count(city_id) AS count

  FROM dim_city

  GROUP BY 1),

average_count AS
   (SELECT
    avg(count) AS avg
  FROM city_count_per_country)

SELECT country_name
FROM city_count_per_country, average_count
WHERE count > average_count.avg

Result:
+-------------------+
| country_name  |   |
+-------------------+ |
+-------------------+
| Germany        |  |
+-------------------+
| France         |  |
+-------------------+
| Colombia       |  |
+-------------------+
| Russia         |  |
+-------------------+
| Australia      |  |
+-------------------+
| United States  |  |
+-------------------+
| Argentina      |  |
+-------------------+
| Brazil         |  |
+-------------------+
| Mexico         |  |
+-------------------+
| Spain          |  |
+-------------------+
| Canada         |  |
+-------------------+
| United Kingdom |  |
+-------------------+
| India          |  |
+-------------------+

A: If you want to show the number of city of a country you can just use count column from city_count_per_country in your final output. It's always better to use proper join syntax. So I have used inner join. Count is a reserved word so it's better not to use it as column name so I have use country_count instead. Please check below query:
WITH city_count_per_country AS
  (SELECT
    country_name,
    count(city_id) AS country_count

  FROM dim_city

  GROUP BY country_name),

average_count AS
   (SELECT
    avg(country_count) AS avg
  FROM city_count_per_country)

SELECT country_name, country_count
FROM city_count_per_country inner join average_count
on country_count> average_count.avg

You can also use window function (if your dbms permits) to calculate average within the same CTE. Please check Query#2.
 create table dim_city (country_name varchar(10),city_id int);
 insert into dim_city values('russia',3);
 insert into dim_city values('russia',2);
 insert into dim_city values('russia',1);
 insert into dim_city values('Germany',12);
 insert into dim_city values('Germany',10);
 insert into dim_city values('bd',20);
 insert into dim_city values('bd',21);
 insert into dim_city values('bd',22);

Query #1:
 WITH city_count_per_country AS
       (SELECT
         country_name,
         count(city_id) AS country_count

       FROM dim_city

       GROUP BY country_name),

     average_count AS
        (SELECT
         avg(country_count) AS avg
       FROM city_count_per_country)

     SELECT country_name, country_count
     FROM city_count_per_country inner join average_count
     on country_count average_count.avg

Output:

country_name
country_count

bd
3

russia
3

Query #2:
 with city_count_per_country as
 (
   SELECT
     country_name,
     count(city_id) AS country_count,avg(count(city_id))over() as average_country_count

   FROM dim_city

   GROUP BY country_name
 )
 select country_name,country_count from city_count_per_country
 where country_count  average_country_count
 GO

Output:

country_name
country_count

bd
3

russia
3

db<fiddle here


text:
Q: Delaying a PayPal payment for more than 90 days So there I was, browsing the PayPal Adaptive Payments API and I encountered Delayed Chained Payments. Looks like exactly what I need to implement a booking system for camping vans: The majority of the payment is supposed to be delayed until ten days after the trip (which gives us some times to solve any grievances).
Yet this part of the API only allows to delay a payment for 90 days, which is not enough for my purpose: People tend to book campers for the summer during winter time, so 180 days is common.
Does anyone know another part of the Paypal API that allows delays that long? Or is there a way to hack this, maybe with some kind of recurring payment?

A: I found no way to extend the 90 day period, even support did not know of a way. But since no one responded yet, I would like to point out my rather boring work-around:
Instead I used the pre-approval process, which allows payments to be subtracted from a user account for up to a year. You simply define a maximum amount of money to be subtracted.
Pros:

*

*Allows for a full year of delayed payments

*Allows multiple payments to be made in that timeframe

*No need for the first recipient to hold all the money (which might get you in trouble with some financial institutions)

Cons:

*

*Is limited to 2000 USD, but this limit can be waived by PayPal (unlike the 90 day limit - at least I was unsuccessful there).

*The approval can be cancelled by the user (though there is a small security-though-obscurity protection: Finding where to cancel this is hard)

Meh:

*

*Like delayed chained payments, pre-approved payments require permission from PayPal


text:
Q: Powershell - include blank spaces I have the below code....
Get-Service -CN . |
ForEach-Object {
write-host -ForegroundColor 9 "Service name $($_.name)"
if($_.DependentServices)
{ write-host -ForegroundColor 3 "`tServices that depend on $($_.name)"
  foreach($s in $_.DependentServices)
   { "`t`t" + $s.name }
} #end if DependentServices
if($_.RequiredServices)
{ Write-host -ForegroundColor 10 "`tServices required by $($_.name)"
  foreach($r in $_.RequiredServices)
   { "`t`t" + $r.name }
} #end if DependentServices
} #end foreach-object $o

This code gives me a list of all services being run on my machine and the various dependencies.
It also highlights the Service Name in RED and the Services Required and Services Dependent in GREEN.  as shown below ...

what I want to do is separate the data output with blank lines after each service so that it looks like the below....

Can anyone advise me on the best way to do this?  Can it be coded in?
I am trying to create a document to show what services we have and what dependencies etc.
All help appreciated.

A: May be just an extra write-host will be enough?
Get-Service -CN . |
ForEach-Object {
write-host -ForegroundColor 9 "Service name $($_.name)"
if($_.DependentServices)
{ write-host -ForegroundColor 3 "`tServices that depend on $($_.name)"
  foreach($s in $_.DependentServices)
   { "`t`t" + $s.name }
} #end if DependentServices
if($_.RequiredServices)
{ Write-host -ForegroundColor 10 "`tServices required by $($_.name)"
  foreach($r in $_.RequiredServices)
   { "`t`t" + $r.name }
} #end if DependentServices
write-host #new line
} #end foreach-object $o


text:
Q: Show $[(P\Rightarrow Q)\land(Q\Rightarrow R)]\Rightarrow(P\Rightarrow R)$ is a tautology using a truth table. Show $[(P\Rightarrow Q)\land(Q\Rightarrow R)]\Rightarrow(P\Rightarrow R)$ is a tautology using a truth table.
I have constructed the following truth table, however, I must have made an error because there are two rows that do not actually match between the hypothesis and conclusion. Could someone point out where the problem is?

$P$
$Q$
$R$
$P\Rightarrow Q$
$Q\Rightarrow R$
$(P\Rightarrow Q)\land(Q\Rightarrow R)$
$(P\Rightarrow R)$
$[(P\Rightarrow Q)\land(Q\Rightarrow R)]\Rightarrow (P\Rightarrow R)$

T
T
T
T
T
T
T
T

T
T
F
T
F
F
F
T

T
F
F
F
T
F
F
T

T
F
T
F
T
F
T
T

F
T
T
T
T
T
T
T

F
F
T
T
T
T
T
T

F
F
F
T
T
T
T
T

F
T
F
T
F
F
T
T

The problem is with my fourth and last row. I where the entries in the last two columns do not align.

A: You were not asked to show that $(P \implies Q) \land (Q \implies R)$ is equivalent to $P \implies R$. Rather, you were asked to show that $((P \implies Q) \land (Q \implies R)) \implies (P \implies R)$ is a tautology. So, you need to make a column for the proposition $((P \implies Q) \land (Q \implies R)) \implies (P \implies R)$ and verify that each entry in the column is T.


text:
Q: MPAndroidChart Scatterchart in ListView I am using the MPAndroidChart library.
I have multiple scattercharts in a ListView.
Every chart contains 365 xvalues (every day of the year).
The yvalues vary from 1 to 5.
The height of the charts is 150dp.
I would like to be able to zoom in, so I can see every single day.
But when I zoom in, the yvalues get out of range of the chart.
Is there a way to keep the yvalues within range of the chart?
I tried it with the next settings:
 holder.chart.setTouchEnabled(true);
    holder.chart.setDragEnabled(true);
    holder.chart.setScaleEnabled(false);
    holder.chart.setScaleMinima(3f, 0f);
    holder.chart.centerViewPort(xIndex, 3);

But when I drag from left to right or right to left, values just disappear from the chart, even when in range.
Has anyone any idea how to accomplish this?

A: This is your issue:
holder.chart.setScaleMinima(3f, 0f);
You are setting the scale value of the y-axis to zero. By doing that, you practically zoom out the chart into infinity. If you do not want to manipulate the zoom/scale of the y-axis, set the y-scale to 1f. Like this:
holder.chart.setScaleMinima(3f, 1f);

A: Try to invalidate the chart after centerViewPort, worked for me.
holder.chart.invalidate();


text:
Q: JUnit & IntelliJ: Could not autowire. No beans of type found I'm trying to run a basic unit test on the code in this GitHub repository found here
The test in MultiplicationServiceTest fails because of the following error:
Caused by:     org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'microservices.book.multiplication.service.MultiplicationService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 28 more

The IDE I'm using is IntelliJ and from some Googling I see that it often reports an error when @Autowire is used in test cases.  The error is affecting the multiplicationService variable in the MultiplicationServiceTest class and I'm unsure why.  I've tried tagging the MultiplicationService interface with @Repository but this doesn't resolve the error.  Any help is appreciated.
MultiplicationServiceTest:
package microservices.book.multiplication.service;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;

import microservices.book.multiplication.domain.Multiplication;
import microservices.book.multiplication.service.MultiplicationService;
import microservices.book.multiplication.service.RandomGeneratorService;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MultiplicationServiceTest {

    @MockBean
    private RandomGeneratorService randomGeneratorService;

    @Autowired
    private MultiplicationService multiplicationService;

    @Test
    public void contextLoads() {

    }

}

MultiplicationService:
package microservices.book.multiplication.service;

import microservices.book.multiplication.domain.Multiplication;

public interface MultiplicationService {

    Multiplication createRandomMultiplication();

}

Multiplication:
package microservices.book.multiplication.domain;

public class Multiplication {

    private int factorA;
    private int factorB;
    private int result;

    public Multiplication(int factorA, int factorB, int result) {
        this.factorA = factorA;
        this.factorB = factorB;
        this.result = result;
    }

}

SocialMultiplicationApplication:
package microservices.book.multiplication;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SocialMultiplicationApplication {

    public static void main(String[] args) {
        SpringApplication.run(SocialMultiplicationApplication.class, args);
    }
}


text:
Q: Wikipedia API Interlanguage Links using WMF Labs I'm working through WMF Labs and using the Wikipedia API to parse out all the page links from a specific page in German then go back and find the english equivalent. My code only works for batches of 5 or less. If I try to run a larger batch like 10 or 15, some of the links that I KNOW have an english equivalent (good old fashioned search, also they show up in the <5 batches) throwback "None" as the english equivalent. Why do all links only work in batches of less than 5?
Here is a link to my code.
https://github.com/empo0270/Interlanguage-links-Wiki/blob/master/translateOutlinks.py

A: The API returns a maximum number of links per query, in this case 500 due to the lllimit=500 in your request. To get the remaining links, you have to follow the instructions for continuing queries to submit additional requests.
Since you're using python, you might want to consider using pywikibot which handles many of these details for you.


text:
Q: In which file is the Ubuntu system path set? I have system path
vickey@tb:~/work/sayonara$ echo $PATH
/usr/local/Trolltech/Qt-4.8.0/bin:/home/vickey/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/vickey/bin:/home/vickey/tunebasket/p2p/
vickey@tb:~/work/sayonara$ cd /usr/local/

I want to get rid of the first entry PERMANENTLY . Where is the system path being set ?

A: /etc/environment
Ref: https://help.ubuntu.com/community/EnvironmentVariables#System-wide_environment_variables

A: You should first start looking at:
/etc/environment

If it is not included there, take a look at:
/etc/profile

The next possible location depends on the shell you are using. All shells also have a default config file located in /etc like /etc/bash.bashrc.


text:
Q: javascript push jquery functions I have some inline jquery what I want to load in the footer after the jquery is loaded.
I do not want to load the jquery in the header. And I do not want to change the inline jquery to a js file because there is also PHP in it.
But I do believe it is possible with javascript to load it in the footer.
In the header you do
var code = [];

So now you have an empty array.
And now I want to push the inline jQuery code in the array.
$(function myFunction(){
    // jQuery methods...
});

So eventually you can do something like this:
code.push(myFunction);

So that I can push all the different jQuery functions and when I put the push code in the footer it will be loaded.
But this does not work for me. The console log says that "myFunction" is not defined...

A: As I understood, you can do it like this:
var code = [];

function _dom_ready() {
    $(function() {
        // do something here...
    })
}

code.push(_dom_ready);

Or something like this:
function click_something() {
    $('div.something').click(function() {
        // event handler here
    });
}

code.push(click_something);

function click_handler_something2() {
    // event handler here
}

function click_something2() {
    $('div.something2').click(click_handler_something2);
}

code.push(click_something2);

Then run all the functions:
for(var f = 0; f < code.length; f++) {
    if(typeof code[f] == 'function') {
        code[f]();
    }
}

A:
$(function myFunction(){
    // jQuery methods...
});

Here you have a function expression which you are passing as an argument to $.
Consequently:

*

*It will be called on the DOM Ready event (because $(a_function) is shorthand for $(document).on('ready', a_function).

*It creates a variable called myFunction inside the scope of that function.

code.push(myFunction); will work, but only inside myFunction, and you probably don't want it there as it will get pushed onto the array repeatedly every time you call it.
You need a function declaration to make the function appear in the current scope.
function myFunction(){
    // jQuery methods...
}

code.push(myFunction);
$(myFunction);


text:
Q: How to look up values in a HashMap, V> without copying? I have a HashMap with Option<String> keys; is it possible to do lookups with a key of type Option<&str>? I know I can use a &str to lookup in a HashMap<String, V> because str implements Borrow<String>.
Do I have to convert to an owned string just to do a lookup?

A: It's slightly less efficient, but you could use Cow here. It avoids the problem with the Borrow trait by instead having a single type that can represent either a reference or an owned value, like so:
use std::borrow::Cow;
use std::collections::HashMap;

fn main() {
    let mut map = HashMap::<Option<Cow<'static, str>>, i32>::new();
    map.insert(None, 5);
    map.insert(Some(Cow::Borrowed("hello")), 10);
    map.insert(Some(Cow::Borrowed("world")), 15);

    // works with None and constant string slices...
    assert_eq!(map.get(&None), Some(&5));
    assert_eq!(map.get(&Some(Cow::Borrowed("hello"))), Some(&10));

    // ...and also works with heap-allocated strings, without copies
    let stack = String::from("world");
    assert_eq!(map.get(&Some(Cow::Borrowed(&stack))), Some(&15));
}


text:
Q: How to Change HTML Tags Using Javascript I have some HTML code that looks like this:
<textarea name="message"></textarea>

And I would like to change it to this:
<textarea maxlength="300" name="message"></textarea>

How can I accomplish this using Javascript? I have tried a lot of different code from a lot of different places, but none of them seem to work. If need be, I will accept CSS code too.

A: Here's how you do it if you aren't using jQuery (highly recommended):
var myelement = document.getElementsByName('message')[0];
myelement.setAttribute('maxlength',300);

Here's the jsFiddle

A: Match the tag element using jquery and then use the .attr() function.

A: Since you're not using jQuery:
<textarea id="text" name="message"></textarea>

var element = document.getElementById("text");
element.setAttribute("maxlength","300");

Example

A: document.querySelector('[name="message"]').setAttribute('maxlength', 300)

A: $('textarea').attr('maxlength', 300);


text:
Q: Use of iFrame to avoid IE oddities I'm working with a team on an ASP.NET MVC C# EF application that needs extensive Help materials.  The Help materials will be stored on a helpdesk site (FreshDesk) so they can be accessed as a Knowledge Base and so we don't have to duplicate the Help materials both there and inside the app.
In a proof of concept test, we have code that will translates href links from different points in the application into urls to the Freshdesk pages, with anchors if needed. The Help material opens in a separate window so people can keep using the app.  Generally that works fine.
Per the requirements it needs to work for Chrome and IE.
Using Chrome, the separate Help window opens nicely from inside the app, and the same window is re-used each time a new Help link is clicked.  If you move the separate Help window it doesn't matter.
Using IE, we ran into a problem where a new window opens each time a new Help link is clicked.  We figured that one out, however, the current solution has some remaining issues.  One is that the solution requires closing the Help window and re-opening it each time.  It reopens in a fixed position, which will be frustrating for users, because they will want to move the Help window.  So now we're capturing the position of the Help window before it closes, and re-using that info when it is re-opened.  It works, sort of, but has more issues.
Here's the problem for me.  I'm concerned that the IE solution is not robust and reliable; and that the more special handling we need to add for IE the more it will run into problems in the field.
An alternative is to make the Help page a separate cshtml page and fetch and display the FreshDesk page in an iFrame.  The desired outcome is that through the cshtml/iFrame the user could arrive at a specific Freshdesk Help page based on the application Help link, and from there if they wanted to they could navigate around the Freshdesk knowledge base using a table of contents and search function, all through the iFrame.
My question is, why would using an iFrame NOT be the better solution for this use case, or, what might go wrong with using an iFrame, compared to the special handling required for IE?

A: Here are some potential issues with an iFrame-style integration:

*

*The FreshDesk application may not support the display of its pages within an iFrame, e.g. if it has anti-clickjacking measures that can't be turned off.

*If you run into any IE issues where the resolution requires compatibility mode to be turned on, you will also have to turn on compatibility mode for your own application.

*Depending on browser settings, the browser may not allow cookies from iFramed content, which could interfere with FreshDesk session management.

*There may be cosmetic issues with the iFrame, e.g. an annoying small whitespace that causes two sets of scrollbars.  You can usually figure out a way around this sort of thing but it is a PITA.

*End users will not be able to bookmark any of the FreshDesk pages, or use the navigation buttons such as back, forward, and history. Also they will not be able to cut and paste the address into an email if they wish to share something with a colleague.

*By concealing the address of the iFramed content, you may make yourself vulnerable to a MITM attack, since the end user can't tell if the content is served over HTTP or HTTPS.

*If the user hits the browser's refresh button, it may reset the iframe content back to its original landing page. This could be very frustrating if your network connections are not 100% reliable.
In my opinion, if you already have a new window solution with IE, and it works, stick with that.  After all, you know what the issues are with your current solution; if you switch to something totally different, you never know if there are going to be even worse problems with it and IE.


text:
Q: C# sum of intergers in array using foreach Please help. Got stuck with this code tried different things but cannot make it work properly. I have a "foreach" loop, where technically it must sum all the integers in the 2D array, however, the answers calculated isn't what it is expected to be. What am i doing wrong? thank you thank you.
    static void Main(string[] args)
    {

        const int ROWS = 2;
        const int COLS = 2;
        const int MAX = 5;

        string input;
        int[,] numbers = new int[ROWS, COLS];

        do
        {
            int total = 0;
            double avg = 0;
            Random rand = new Random();
            for (int rows = 0; rows < ROWS; ++rows)
            {
                for (int cols = 0; cols < COLS; ++cols)
                {
                    numbers[rows, cols] = rand.Next(1, MAX);
                }
                {
                    for (int cols = 0; cols < COLS; ++cols)
                        Console.Write(" {0, 3}", numbers[rows, cols]);
                    Console.WriteLine();
                }

    foreach (int cell in numbers)
                {
                    total += cell;
                }

                avg = total / 4.0;

            } Console.WriteLine("Sum: {0:0,0}   Average: {1:f}", total, avg);

            Console.Write("\nWould you like to generate a new table? Type yes or no... ");
            input = Console.ReadLine().ToLower();

            if (input == "no")
            {
                Console.WriteLine("End of program. Press any key to exit. Goodbye.");
            }
        }

        while (input == "yes");

        Console.ReadKey();

A: So i found the logic error. I moved the "foreach" loop outside of "for" loop and it fixed an error. Thank you for your time and support. Here's the working code:
        static void Main(string[] args)
        {
        const int ROWS = 2;
        const int COLS = 2;
        const int MAX = 5;

        string input;
        int[,] numbers = new int[ROWS, COLS];

        do
        {
            int total = 0;
            double avg = 0;
            Random rand = new Random();
            for (int rows = 0; rows < ROWS; ++rows)
            {
                for (int cols = 0; cols < COLS; ++cols)
                {
                    numbers[rows, cols] = rand.Next(1, MAX);
                }
                {
                    for (int cols = 0; cols < COLS; ++cols)
                        Console.Write(" {0, 3}", numbers[rows, cols]);
                    Console.WriteLine();
                }

            }

                foreach (int cell in numbers)
                {
                    total += cell;
                }

                avg = total / 4.0;
            Console.WriteLine("Sum: {0:0,0}   Average: {1:f}", total, avg);

            Console.Write("\nWould you like to generate a new table? Type yes or no... ");
            input = Console.ReadLine().ToLower();

            if (input == "no")
            {
                Console.WriteLine("End of program. Press any key to exit. Goodbye.");
            }
        }

        while (input == "yes");

        Console.ReadKey();
    }
}

}

A: I think that your foreach is redundant here:
for (int rows = 0; rows < ROWS; ++rows)
{
    for (int cols = 0; cols < COLS; ++cols)
    {
        numbers[rows, cols] = rand.Next(1, MAX);
        total += numbers[rows, cols]; // Sum in the same loop
    }

    for (int cols = 0; cols < COLS; ++cols)
        Console.Write(" {0, 3}", numbers[rows, cols]);
    Console.WriteLine();

    avg = total / 4.0;

}

A: I agree with @QtRoS that your cycle was redundant - you summed up values of all cells twice (for each row).
But I think there is one more error in code (in @QtRoS's answer as well).
If you want to calculate average of all grid cells, you must do this after cycle on rows.
This way:
for (int rows = 0; rows < ROWS; ++rows)
{
    for (int cols = 0; cols < COLS; ++cols)
    {
        numbers[rows, cols] = rand.Next(1, MAX);
        total += numbers[rows, cols]; // Sum in the same loop
    }

    for (int cols = 0; cols < COLS; ++cols)
        Console.Write(" {0, 3}", numbers[rows, cols]);
    Console.WriteLine();
}

avg = total / 4.0;


text:
Q: PHP file search works in WAMP but not in LAMP I wrote a PHP script to find video files and tested it on my local WAMP server. It works there. However, when the script is moved onto my LAMP server, the script is unable to find the same files. It checks if the specified directory exists, so I know it sees the /var/www/videos directory (script is run from /var/www/web).
The LAMP server is being run on VirtualBox, and /var/www/videos is mounted to the directory on my Windows 7 host machine I used during the script's development.
My best guess is something related to permissions, does that sound like the right path?
Script is here: http://pastebin.com/9MTKaUep
--one mistake, the last if statement is the following on my LAMP version:

if (isset($search)):
        $videos = glob_files($search, '../videos');
endif;

Permissions look like the following
-rw-r--r-- 1 root root   177 Feb 21 22:44 index.html
drwxrwxrwx 1 root root 49152 Feb 21 22:53 videos
drwxr-xr-x 3 root root  4096 Feb 21 23:29 web

A: YOu may have to copy that video files folder in to the virtual box