text:
Q: How to print the palindrome and prime numbers in an array I'm trying to print the prime and the palindrome numbers from an array. It does not print me anything where am i wrong?!
#include <iostream>
#include <string>
using namespace std;

int main() {
    int x, n, i, num, digit, rev=0;
    int bar[100];
    cout << "Cate numere trebuie sa fie in Array?:";
    cin >> x;
    for (i = 0; i < x; i++) {
        cout << "bar[" << i << "]=";
            cin >> bar[i];
    }
    for (i = 0; i < x; i++) {
        num=bar[i];

        do
        {
            digit = num % 10;
            rev = (rev * 10) + digit;
            num = num / 10;
        } while (num != 0);
    }
    if (num == rev)
        cout << num;

    int y;
    bool prim = true;

    for (y = 2; y <= bar[i] / 2; ++y)
    {
        if (bar[i] % y == 0)
        {
            prim = false;

        }
    }
    if (prim)
        cout << bar[i];

    return 0;
}

A: You have to do the output inside loops. But for example this output is made outside a loop
for (i = 0; i < x; i++) {
    num=bar[i];

    do
    {
        digit = num % 10;
        rev = (rev * 10) + digit;
        num = num / 10;
    } while (num != 0);
}
if (num == rev) // <===
    cout << num;

Moreover the comparison in the if statement above is incorrect. After the do-while loop the value of num is equal to 0. You need to write
if (bar[i] == rev) // <===
    cout << num;

Also the output of prime numbers also is made outside a loop. Moreover you are determining prime numbers incorrectly. For example 1 is a prime number according to your algorithm.
Also within the first loop you have to reinitialize the variable rev to 0.
The program can be written the following way
#include <iostream>

int main()
{
    const size_t N = 100;
    int bar[N];

    cout << "Cate numere trebuie sa fie in Array?: ";

    size_t n = 0;
    std::cin >> n;

    if ( N < n ) n = N;

    for ( size_t i = 0; i < n; i++ )
    {
        std::cout << "bar[" << i << "] = ";
        std::cin >> bar[i];
    }

    std::cout << '\n';

    for ( size_t i = 0; i < n; i++ )
    {
        const int Base = 10;
        int num = bar[i];
        int rev = 0;

        do
        {
            int digit = num % Base;
            rev = rev * Base + digit;
        } while ( num /= Base );

        if ( bar[i] == rev ) std::cout << bar[i] << ' ';
    }

    std::cout << '\n';

    for ( size_t i = 0; i < n; i++ )
    {
        bool prime =  bar[i] % 2 == 0 ?  bar[i] == 2 :  bar[i] != 1;

        for ( int j = 3; prime && j <=  bar[i] / j; j += 2 )
        {
            prime =  bar[i] % j != 0;
        }

        if ( prime ) std::cout <<  bar[i] << ' ';
    }

    std::cout << '\n';

    return 0;
}

Its output might be
Cate numere trebuie sa fie in Array?: 10
bar[0] = 121
bar[1] = 11
bar[2] = 131
bar[3] = 13
bar[4] = 143
bar[5] = 14
bar[6] = 1551
bar[7] = 10
bar[8] = 1234321
bar[9] = 99

121 11 131 1551 1234321 99
11 131 13


text:
Q: Why does the R class not contain the field type? Whenever we want to inflate a view or get a resource we have to cast it in run-time. views, for example, are used like so:
In the past, we would have needed to cast it locally
(RelativeLayout) findViewById(R.id.my_relative_layout_view)

Now, we use generics
findViewById<RelativeLayout>(R.id.my_relative_layout_view)

my question is why doesn't the compiler(or whoever generates the R class) doesn't also keep some kind of a reference to the type of the element(doesn't matter if it's a string or an int or any other type) that way casting problems should not occur

A: We cannot really speculate on that, that would be a design choice.
It might be that they wanted to avoid bloating the APK. Every ID would need a full package name to the class. So would each ID in android.R too. Since R is packaged in every APK.
Solutions
However, if you are using Kotlin, you can even do away with the generics check. Kotlin will determine it automatically.
val view = findViewById(R.id.my_relative_layout_view)
view.method()

Or event simpler, if you use synthetics:
my_relative_layout_view.method()

Also, if you are using data bindings, you can just access it like this:
binding.my_relative_layout_view.method()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Oracle Apex get cookie from an ajax request How can I get the value of a cookie in oracle from a request that was originated with ajax from a non-apex page (inside an apex server)?
I wanted to start by creating a function that returns the value of the login cookie and use that function to return the value to the browser to see that it can be done.
So I created a resource template and handler with the following source: select test() from dual.
The test function is declared as:
create or replace function test return varchar2
is
   c owa_cookie.cookie;
begin
   c := owa_cookie.get('LOGIN_USERNAME_COOKIE');
   return c.vals(1);
end;

When I run select test() from dual from an sql commands window I get the value of the cookie, but when I send a request to the handler with ajax I get the following error:
An error occurred when evaluating the SQL statement associated with this resource. SQL Error Code 6502, Error Message: ORA-06502: PL/SQL: numeric or value error
ORA-06512: at "SYS.OWA_UTIL", line 354
ORA-06512: at "SYS.OWA_COOKIE", line 59
ORA-06512: at "SYS.OWA_COOKIE", line 179
ORA-06512: at "<no need to see this>.TEST", line 5

I've been using the following call (checking the result through the network dev tools)
$.ajax({url: "<handler url here>"})
Update:
The reason I'm using a rest service is because the page that originates the request is not an apex application but it is on the same domain (so it has the same cookies).

A: This is what I think is happening: The cookie is sent as part of the http request header of your apex application call. The rest call is another http request, unrelated to your apex http request and I don't believe the header of that request includes the cookie. So in the database session that is created as part of your rest request the cookie will not exist. You could probably set the header of the rest request yourself to fix this.
--UPDATE--
To check which cookies can be read, create a rest handler of source type pl/sql with the following source:
DECLARE
  l_names owa_cookie.vc_arr;
  l_vals owa_cookie.vc_arr;
  l_num_vals INTEGER;
BEGIN
    owa_cookie.get_all(
        names => l_names,
        vals => l_vals,
        num_vals => l_num_vals);
    APEX_JSON.open_array('cookies');
    FOR r IN 1 .. l_names.COUNT LOOP
    APEX_JSON.open_object; -- {
    APEX_JSON.write('name', l_names(r));
    APEX_JSON.write('value', l_vals(r));
    APEX_JSON.close_object; -- } cookie
    END LOOP;
     APEX_JSON.close_array; -- ] cookies
END;

The apex username cookie is not in that list of cookies. I suggest you create your own custom cookie in an after-login process in apex.
I verified that a cookie set with the following code in an apex process is picked up by the rest handler (based on blog https://www.apex-at-work.com/2012/05/apex-simple-cookie-example.html)
begin
owa_util.mime_header('text/html', FALSE);
owa_cookie.send(
name => 'CUSTOM_USER_COOKIE',
value => :APP_USER,
expires => sysdate + 30 );

apex_util.redirect_url (
p_url => 'f?p=&APP_ID.:1:' || :SESSION,
p_reset_htp_buffer => false );
end;

A: To get a cookie from an AJAX request within APEX, you can use the OWA_COOKIE package, but you do not need to define any templates or handlers. It can all be done from within the page (or calling an external procedure from within the page). Below are the steps I used to get the JSESSIONID cookie.
I have built an example application on apex.oracle.com that you can check out.
Page Setup
The page is very simple with just one text box and one button. The button's action is set to Redirect to URL and this is the target:
javascript: apex.server.process("AJAX_TEST", { }, { success: function (pData) { console.log(pData); apex.item("P10_JSESSIONID").setValue(pData); }, dataType: "text", error: function (jqXHR, textStatus, errorThrown) { } }).always(function () {  });

The javascript is calling the AJAX Callback (which is shown below) and storing the output in the P10_JSESSIONID page item as well as logging it to the browser console.

AJAX Callback Setup
The code in the AJAX Callback is very similar to the code you shared. I am getting the cookie then printing it out with HTP.P. This is all that is needed to return the value of the cookie to the page to be used for whatever you'd like. You can also make the code in the AJAX callback call a standalone procedure compiled into the database if you so choose.

Update
I updated my example application so that there will be a dropdown showing all of the cookies, then you can select from the list and click the button to send an AJAX request to get the value of that cookie.


text:
Q: Is it possible to use a snackbar inside a function in flutter? I currently have a password reset page on my app.
The widget call a password reset function when the button is pressed. I have the reset button inside a Builder. I have test a snackbar inside the onPressed and it woks fine . But I want to be able to use the Firebase auth error inside the snackbar if the  password has an error. but when trying to call the snackbar is still get a scaffold context error. my code is below. i am not putting the full widget tree as it is quite long but have put down what i think are the important part. The code to update the password runs fine, so I don't think there is any blocker there.
class _PasswordBuyerState extends State<PasswordBuyer> {

final newpassword = TextEditingController();
final confirmpassword = TextEditingController();
final _PasswordformKey = GlobalKey<FormState>();

void SubmitBuyerPassword(password) async{

 var user = await FirebaseAuth.instance.currentUser();

 user.updatePassword(password).then((_){

   print("Succesfully changed password");

   final snackbar = SnackBar(content: Text("Password changes Successfully"));
   Scaffold.of(context).showSnackBar(snackbar);
 // this is not showing

   Navigator.push(context,MaterialPageRoute(builder: (context) => EditProfileBuyer()));

 }).catchError((error){

   final snackbar = SnackBar(content: Text("Password can't be changed" + error.toString()));

   Scaffold.of(context).showSnackBar(snackbar);  // If the form is valid, display a Snackbar.
 // this is not showing

   print("Password can't be changed" + error.toString());

 });

  }
  @override
  Widget build(BuildContext context) {
return MaterialApp(
  home: Scaffold(

Further down in the code is the Builder with the button:
child:Builder(
builder: (context) => RaisedButton(
onPressed: (){

if (_PasswordformKey.currentState.validate()) {

if(newpassword.text == confirmpassword.text){

print('matching');

setState(() {

final snackbar = SnackBar(content: Text('password changing'));

Scaffold.of(context).showSnackBar(snackbar);
// the above snackbar works when tested

SubmitBuyerPassword(newpassword.text.toString());

});

} else if(newpassword.text != confirmpassword.text){

 print('not matching');

}

};

},

color: Colors.blue[500],

child:  Text('Submit',textAlign: TextAlign.center,style: TextStyle(color:Colors.white),),
                                ),
                              ),

A: See answer above by @Hiwa Jala. use the Flushbar or flash extension.
I personally used Flushbar due to its simplicity.


text:
Q: What does `~` do? I saw ~ here before the path of repository.
chmod a+x ~/bin/repo

What does ~ do here?

A: It is short hand for $HOME or /home/your_current_user
I advise you avoid using it in scripts or with sudo as results can be unexpected.
You can also specify a user with ~user rather than /home/user
Basically save typing, usually works, but can yield unexpected results in scripts.
For the gory details see http://tldp.org/LDP/abs/html/special-chars.html
Those pages cover most anything you want to know about bash and cure insomnia ;p

home directory [tilde]. This corresponds to the $HOME internal
  variable. ~bozo is bozo's home directory, and ls ~bozo lists the
  contents of it. ~/ is the current user's home directory, and ls ~/
  lists the contents of it.

Note "tab completion" also saves typing. start typing part of a path or command and press Tab
cd /hoTabTab
Helpful for commands and long paths other than ~
Again see http://www.tldp.org/LDP/abs/html/tabexpansion.html


text:
Q: Histogram of column counts and row counts with NA data I have data in the form:
Input_SNP   Set_1    Set_2     Set_3     Set_4     Set_5     Set_6
1.09        0.162    NA        2.312     1.876     0.12      0.812
0.687       NA       0.987     1.32      1.11      1.04      NA
NA          1.890    0.923     1.43      0.900     2.02      2.7
2.801       0.642    0.791     0.812     NA        0.31      1.60
1.33        1.33     NA        1.22      0.23      0.18      1.77
2.91        1.00     1.651     NA        1.55      3.20      0.99
2.00        2.31     0.89      1.13      1.25      0.12      1.55

I would like to make a histogram plot of the total number of data in each column except for the Input_SNP column. For example, Set_1 has 6, Set_2 has 5, etc. I would also like to make a histogram plot of the total number of data in each except the top row obviously. How can this be done in R? This is a data frame.

A: You can get the counts of non-missing values in the columns (minus the first) and rows this way:
# Toy data to test
df <- data.frame(X1 = c(1, 1, NA, 3, NA), X2 = c(3, 4, NA, 1, 5), X3 = c(3, 4, 6, 1, 8))

# Now generate vectors of the counts
column.counts <- colSums(!is.na(df[,2:ncol(df)]))
row.counts <- rowSums(!is.na(df))

There are a few ways to make histograms. In base R, you could just call hist(column.counts) and hist(row.counts). In ggplot2, you'd call ggplot(NULL, aes(x=column.counts)) + geom_histogram(). You can look at the help for those functions for details on how to fine-tune them.


text:
Q: How to select a specific row from a table using BeautifulSoup? So I have a question related to a previous question, but I realized I needed to go one level more to get an 11-digit NDC code instead of a 10-digit NDC code. Rather than convert them later, I thought I could just grab them initially. Here is the link to the previous question. Is there a way to parse data from multiple pages from a parent webpage? And what I want to do is to click on the links here (which is the 2nd level btw)

And then grab the 11-digit NDC codes that results on the following page

I am able to write the code to get to the page, but I'm not sure how to select it. The number is in a  tag and then a  tag, but I just want the specific row in the table, so I thought I could get index it like this, but I'm getting a None Type and td throughout my list. Here is my code
import requests
from bs4 import BeautifulSoup
url ='https://ndclist.com/?s=Trospium'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

all_data = []
for a in soup.select('[data-title="NDC"] a[href]'):
    link_url = a['href']
    print('Processin link {}...'.format(link_url))

    soup2 = BeautifulSoup(requests.get(link_url).content, 'html.parser')
    for b in soup2.select('#product-packages a'):
        link_url2 = b['href']
        print('Processing link {}... '.format(link_url2))
        soup3 = BeautifulSoup(requests.get(link_url2).content, 'html.parser')
        for link in soup3.findAll('tr', limit=7)[1]:
            print(link.name)
            all_data.append(link.name)

print('Trospium')
print(all_data)

A: Just minor modifications to your code:
import requests
from bs4 import BeautifulSoup
url ='https://ndclist.com/?s=Trospium'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

all_data = []
for a in soup.select('[data-title="NDC"] a[href]'):
    link_url = a['href']
    print('Processing link {}...'.format(link_url))

    soup2 = BeautifulSoup(requests.get(link_url).content, 'html.parser')
    for b in soup2.select('#product-packages a'):
        link_url2 = b['href']
        print('\tProcessing link {}... '.format(link_url2))
        soup3 = BeautifulSoup(requests.get(link_url2).content, 'html.parser')
        ndc_billing_format = soup3.select_one('td:contains("11-Digit NDC Billing Format") + td').contents[0].strip()
        print('\t\t{}'.format(ndc_billing_format))
        all_data.append(ndc_billing_format)

print('Trospium')
print(all_data)

Prints:
Processing link https://ndclist.com/ndc/0574-0118...
    Processing link https://ndclist.com/ndc/0574-0118/package/0574-0118-30...
        00574011830
Processing link https://ndclist.com/ndc/0574-0145...
    Processing link https://ndclist.com/ndc/0574-0145/package/0574-0145-60...
        00574014560
Processing link https://ndclist.com/ndc/0591-3636...
    Processing link https://ndclist.com/ndc/0591-3636/package/0591-3636-05...
        00591363605
    Processing link https://ndclist.com/ndc/0591-3636/package/0591-3636-30...
        00591363630
    Processing link https://ndclist.com/ndc/0591-3636/package/0591-3636-60...
        00591363660
Processing link https://ndclist.com/ndc/23155-530...
    Processing link https://ndclist.com/ndc/23155-530/package/23155-530-02...
        23155053002
    Processing link https://ndclist.com/ndc/23155-530/package/23155-530-05...
        23155053005
    Processing link https://ndclist.com/ndc/23155-530/package/23155-530-06...
        23155053006
Processing link https://ndclist.com/ndc/42291-846...
    Processing link https://ndclist.com/ndc/42291-846/package/42291-846-60...
        42291084660
Processing link https://ndclist.com/ndc/60429-098...
    Processing link https://ndclist.com/ndc/60429-098/package/60429-098-30...
        60429009830
Processing link https://ndclist.com/ndc/60505-3454...
    Processing link https://ndclist.com/ndc/60505-3454/package/60505-3454-5...
        60505345405
    Processing link https://ndclist.com/ndc/60505-3454/package/60505-3454-6...
        60505345406
    Processing link https://ndclist.com/ndc/60505-3454/package/60505-3454-8...
        60505345408
Processing link https://ndclist.com/ndc/68001-228...
    Processing link https://ndclist.com/ndc/68001-228/package/68001-228-04...
        68001022804
Processing link https://ndclist.com/ndc/68462-461...
    Processing link https://ndclist.com/ndc/68462-461/package/68462-461-05...
        68462046105
    Processing link https://ndclist.com/ndc/68462-461/package/68462-461-30...
        68462046130
    Processing link https://ndclist.com/ndc/68462-461/package/68462-461-60...
        68462046160
Processing link https://ndclist.com/ndc/69097-912...
    Processing link https://ndclist.com/ndc/69097-912/package/69097-912-02...
        69097091202
    Processing link https://ndclist.com/ndc/69097-912/package/69097-912-03...
        69097091203
    Processing link https://ndclist.com/ndc/69097-912/package/69097-912-15...
        69097091215
Processing link https://ndclist.com/ndc/69150-258...
    Processing link https://ndclist.com/ndc/69150-258/package/69150-258-06...
        69150025806
Processing link https://ndclist.com/ndc/76282-336...
    Processing link https://ndclist.com/ndc/76282-336/package/76282-336-60...
        76282033660
Trospium
['00574011830', '00574014560', '00591363605', '00591363630', '00591363660', '23155053002', '23155053005', '23155053006', '42291084660', '60429009830', '60505345405', '60505345406', '60505345408', '68001022804', '68462046105', '68462046130', '68462046160', '69097091202', '69097091203', '69097091215', '69150025806', '76282033660']


text:
Q: Error bars overlap but effect is significant in glmm. What's going on? I have run the following glmm:
mod<-glmer(data=newdata, total_flr_vis ~ treatment + flr_num + (1|individual), family=poisson)
and get this output from summary()
Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) ['glmerMod']
Family: poisson  ( log )
Formula: total_flr_vis ~ treatment + flr_num + (1 | individual)
Data: newdata

 AIC      BIC   logLik deviance df.resid
706.8    718.9   -349.4    698.8      148

Scaled residuals:
Min      1Q  Median      3Q     Max
-3.1461 -0.8155 -0.3522 -0.2022 14.1669

Random effects:
Groups     Name        Variance Std.Dev.
individual (Intercept) 4.066    2.016
Number of obs: 152, groups:  individual, 42

Fixed effects:
            Estimate Std. Error z value Pr(>|z|)
(Intercept) -1.610176   0.432666  -3.722 0.000198 ***
treatmentR  -0.457492   0.121054  -3.779 0.000157 ***
flr_num      0.037063   0.005064   7.319  2.5e-13 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
             (Intr) trtmnR
  treatmentR -0.117
  flr_num    -0.416  0.040

But I get the following plot for treatment using plot(allEffects(mod))

I don't understand why the effects plot shows overlapping error bars while the summary() output tells me that the effect of treatment is significant. Is there a problem with the model, or is it the plot? How can I troubleshoot this?
Here is the residual plot (which I got using plot(mod))

I'm not totally sure how to interpret this plot, but it does not look random to me, thus I suspect that there is something wrong with the model.
I am happy to post data if someone can tell me where to do that.
Any help would be very welcome.


text:
Q: Not able to pass string to formGroup 1.I want to loop through an array
*ngFor="let item of myformNameArray"

Think myformNameArray.length have 3 items
If I console item it will be like
myFormName1
myFormName2
myFormName3

I have already made these form group in my typescript component.
Example
<form [formGroup]="myFormName3">

It will work perfectly!!
But i want to loop :means
<div *ngFor="let item of  myformNameArray">
<form [formGroup]="{{item}}">
</form>
</div>

So when I do,
[formGroup]="{{item}}"

It throws me an error can't assign to object or interpolation
Or
[formGroup]="see(item)"

Where ,
see(item) :string {
return String(item);
}

ERROR TypeError: can't assign to property "validator" on "see(item)": not an object

A: [formGroup] requires a FormGroup Object not string
you need to make array of formgroups instead of string names
TS:
myformArray = [
   this.myFormOne,
   this.myFormTwo,
   this.myFormThree
]

HTML:
<div *ngFor="let item of  myformArray">
    <form [formGroup]="item">
    </form>
</div>

you can also use formArray instead of normal array
TS:
myFormArray = new FormArray([]);

this.myFormArray.push(myFormOne);
this.myFormArray.push(myFormTwo);
this.myFormArray.push(myFormThree);

HTML:
<div *ngFor="let form of myFormArray.controls;">
  <form [formGroup]="form">
    <input formControlName="controlOne" />
    <input formControlName="ControlTwo" />
  </form>
</div>

And also you should not use both square brackets and curly brackets (interpolation) for property binding, use either square brackets or interpolation.
internally angular converts square brackets to interpolation
either do this : [formGroup]="item"
or this : formGroup="{{item}}"
not both


text:
Q: Will ImageMagick SVG to PNG conversion respect blend modes? Does ImageMagick have the capability to handle SVG blend modes? When converting an SVG to PNG, for example?
Using ImageMagick-7.0.8-Q16, Inkscape 0.92.1 r15371
I have a simple SVG with two rectangles, red and blue, and a mix-blend-mode of "exclusion" on the blue. It appears as expected on any browser I've tried (see the MS Edge sshot)
Inkscape will convert the SVG image to a PNG correctly, respecting the mix blend mode style. However, ImageMagick, does not (see results.png). ImageMagick seems to just use "normal" mix-blend-mode (FWIW, IMDisplay shows the same icorrect image, blend mode ignored)
Is there some option that I need to change? Or, if ImageMagick just does not handle SVG blending modes, is there some plan to have it do so in the future?
My command lines are as follows:
inkscape test.svg -e Inkscape.png
magick test.svg IMagick.png

The SVG file contains only:
<svg width='300' height='300' xmlns = 'http://www.w3.org/2000/svg'
     xmlns:xlink='http://www.w3.org/1999/xlink'>
<rect width='100%' height='100%' fill='#dddddd'/>
<rect x='50'  y='50' width='150' height='150' style='fill:red;' />
<rect x='100' y='100' width='150' height='150'
      style='fill:blue;mix-blend-mode:exclusion' />
</svg

A: Looks like ImageMagick is using its internal MVG decoder. Make sure that the delegates.xml file has inkscape instructions for the svg:decode, and such a command works as expected.
Something like:
<delegate decode="svg:decode" stealth="True" command=""inkscape" "%s" --export-file="%s" --export-dpi="%s" --export-background="%s" --export-background-opacity="%s" > "%s" 2>&1"/>

You can verify the correct command is being used with a -verbose option.
magick -verbose test.svg IMagick.png


text:
Q: |DataDirectory| Wrong Project I'm working on some 3 tier architecture project.
I created 1 solution, with 3 different projects: DAL,BLL and Presentation.
The DAL Project App_Data folder contain my mdf file.
In one of my DAL classes, i'm using the following command to connect to my database:
Conn = new SqlConnection("Data Source =.\\SQLExpress; Integrated Security =true; AttachDbFilename = |DataDirectory|\\" + dbName + "; User Instance =true;");

When i'm trying to run it, i see that the |DataDirectory| returns the path of my Presentation Project App_Data folder(which doesn't exist).
How can i change it to my DAL Project App_Data Folder?
Thanks!

A: You can specify the physical path.
However, you probably shouldn't - I know that's not the answer you are looking for but consider what is going to happen when the application is deployed. You will presumably not be deploying the solution but only the compiled presentation project. In this case, it makes more sense to store the database in the presentation project's App_Data folder and leave the reference as it is.

A: Why don't you move the database to your presentation projects App_Data folder?


text:
Q: UIDefaults.getUI() failed: error when loading a JFrame into another project I found this project which works just fine in a standalone run. However when I try to add it to a JPanel in another project (already did this in the exact same project but with a JFrame of my own and worked fine) this error arises:
 UIDefaults.getUI() failed: no ComponentUI class for: doubleslider.MThumbSlider[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=0,maximumSize=,minimumSize=,preferredSize=,isInverted=false,majorTickSpacing=0,minorTickSpacing=0,orientation=HORIZONTAL,paintLabels=false,paintTicks=false,paintTrack=true,snapToTicks=false,snapToValue=true]
    java.lang.Error
        at javax.swing.UIDefaults.getUIError(UIDefaults.java:729)
        at javax.swing.MultiUIDefaults.getUIError(MultiUIDefaults.java:130)
        at javax.swing.UIDefaults.getUI(UIDefaults.java:759)
        at javax.swing.UIManager.getUI(UIManager.java:1002)
        at javax.swing.JSlider.updateUI(JSlider.java:323)
        at doubleslider.MThumbSlider.updateUI(MThumbSlider.java:44)
        at javax.swing.JSlider.<init>(JSlider.java:275)
        at javax.swing.JSlider.<init>(JSlider.java:182)
        at doubleslider.MThumbSlider.<init>(MThumbSlider.java:24)
        at doubleslider.DoubleSlider.<init>(DoubleSlider.java:29)
        at com.einge.scadaremotecontrol.Ventana.<init>(Ventana.java:227)
        at com.einge.scadaremotecontrol.ScadaRemoteControl.<init>(ScadaRemoteControl.java:92)
        at com.einge.scadaremotecontrol.ScadaRemoteControl.main(ScadaRemoteControl.java:197)
    UIDefaults.getUI() failed: no ComponentUI class for: doubleslider.MThumbSlider[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=0,maximumSize=,minimumSize=,preferredSize=,isInverted=false,majorTickSpacing=0,minorTickSpacing=0,orientation=HORIZONTAL,paintLabels=false,paintTicks=false,paintTrack=true,snapToTicks=false,snapToValue=true]
    java.lang.Error
        at javax.swing.UIDefaults.getUIError(UIDefaults.java:729)
        at javax.swing.MultiUIDefaults.getUIError(MultiUIDefaults.java:130)
        at javax.swing.UIDefaults.getUI(UIDefaults.java:759)
        at javax.swing.UIManager.getUI(UIManager.java:1002)
        at javax.swing.JSlider.updateUI(JSlider.java:323)
        at doubleslider.MThumbSlider.updateUI(MThumbSlider.java:44)
        at doubleslider.MThumbSlider.<init>(MThumbSlider.java:26)
        at doubleslider.DoubleSlider.<init>(DoubleSlider.java:29)
        at com.einge.scadaremotecontrol.Ventana.<init>(Ventana.java:227)
        at com.einge.scadaremotecontrol.ScadaRemoteControl.<init>(ScadaRemoteControl.java:92)
        at com.einge.scadaremotecontrol.ScadaRemoteControl.main(ScadaRemoteControl.java:197)

My first guess is that the MultiTumbSlider class is trying to set a different Look&Feel than my JFrame. Any solutions? I couldn't figure this out and I really need two sliders so to have a time Range
Any help will be appretiated!

A: I don't recognize the loading approach used in this very old example; it appear to be based on the current Look & Feel. You might try setting javax.swing.plaf.metal.MetalLookAndFeel explicitly. Going forward, look at Kirill Grouchnikov's How to Write a Custom Swing Component for guidance on modernizing the delegate plumbing.

A: At the book "Java Swing, 2nd Edition", by Marc Loy et. al., at the section "Creating Your Own Component" (Chapter 28: Swing Under the Hood), we have the code line at the main() method:
UIManager.put(JogShuttleUI.UI_CLASS_ID, "BasicJogShuttleUI");

This will inform the UIDefaults, through UIManeger, the class name of the basic UI delegate of the custom component. Note, however, that you must provide the fully qualified class name, since it will be located by the class loading mechanism.
For example, when I'm use
UIManager.put(DiagramUI.UI_CLASS_ID, "BasicDiagramUI");

I get the same error reported by your question. But, when I change it to
UIManager.put(DiagramUI.UI_CLASS_ID, BasicDiagramUI.class.getName());

Things works pretty well. Nice coding!


text: Q: Entity Framework Table-Per-Type inheritance with overlapped (non-disjoint) entities I'm using EF4 with DDD and layers, and I need to implement a Table-Per-Type hierarchy with non-disjoint (overlapped) entities in my data model, a model like this. Anyway i cannot figure out how to do it, and cannot find any example of TPT with overlapped entities. There is any way  I can do this? (sorry for my english).


text:
Q: SQL Server : ExecuteReader doesn't throw error I have the following code running, which should basically just execute a SQL statement against my database and if there is any error, the script should shout "ERROR!"
When I am running the script, with an invalid SQL statement in the test.sql file, the exception is correctly caught by the CATCH clause and "ERROR!" is written.
Test.sql file looks like this:
SELECT * FRRRROM [dbo].[testtable]

But, when I add a comment to the test.sql file, it doesn't throw the "ERROR!"-message anymore.
Test.sql file now looks like this:
-- my comment
SELECT * FRRRROM [dbo].[testtable]

I don't get it why. Any suggestions?
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='myServer';database='myDatabase';trusted_connection=true;MultipleActiveResultSets=True;"
$Connection.Open()

$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection

$sql = Get-Content 'C:\Test\test.sql'

$Command.CommandText = $sql
Try
{
    $Reader = $Command.ExecuteReader()
}
Catch
{
    echo 'ERROR!!!!'
    Exit
}
$Connection.Close()

A: I still would have expected an error but the main difference between your first and second example is you have another line. Get-Content returns a string array. With one line it would be just seen as a string. Easy way to be sure of that is to convert the text into one whole new line delimited string.
$sql = Get-Content 'C:\Test\test.sql' | Out-String

You could use -join or something else like that but I find Out-String is very simple and compatible with all versions of PowerShell.

A: As user Matt mentioned:
The code returns an array to the variable $sql
$sql = Get-Content 'C:\Test\test.sql'
$Command.CommandText = $sql

after adding | Out-String it's working correctly, as returning a string
$Command.CommandText = Get-Content 'C:\Test\test.sql'| Out-String


text:
Q: Text after the end of a nested list doesn't align properly For example, this
1. first item
2. second item
    - first subitem
    - second subitem
   more info about the 2nd item
3. third item

produces this

How do I get "more info about the 2nd item" to appear where it does in the code?

A: The following places "more info" as an independant paragraph inside the second subitem bullet point, in pandoc markdown.
1. first item
2. second item
    - first subitem
    - second subitem

        more info about the 2nd item

3. third item

Output:

first item

second item

first subitem

second subitem

more info about the 2nd item

third item

A: This is a nasty problem which I also cannot seem to solve in an elegant way. However, for compilation to HTML there is a simple workaround: place a
 or
 tag after the last item of your nested list.
1. first item
2. second item
    - first subitem
    - second subitem

   more info about the 2nd item
3. third item

This will trigger the HTML to end the - in this case unordered - nested list before Markdown instructs it to. Luckily, this doesn't break your layout at all, as long as you are mixing unordered (
) and ordered (
) lists. If your nested list is of the same type as its parent this will break your layout*.
If so desired, you can also place a
 element before the first line that does not belong to the nested list anymore, which I find to produce a more visually appealing layout.


text:
Q: Is any real closed extension of $\mathbb R$ characterized up to isomorphism by its ladder? Let $R$ be a real closed field. Recall that the ladder of $R$ is the divisible, ordered abelian group obtained by quotienting $R$ by a certain equivalence relation.
Note that $R$ has trivial ladder iff $R$ is a subfield of $\mathbb R$. If $R$ has trivial ladder and $L$ is a divisible ordered abelian group, let $R\langle\!\langle x^L\rangle \!\rangle$ be the field of Puiseux series. Then $R\langle \!\langle x^L\rangle \!\rangle$ has ladder $L$. Conversely, from any real closed field, we may extract a maximal subfield of $\mathbb R$ and a ladder. I'm wondering whether that's all there is to it, i.e., whether every real closed field is of the form $R\langle\! \langle x^L \rangle\! \rangle$. Let me state this more formally:
Questions: Let $R$ be a real closed field with ladder $L$, and let $R_0 \subseteq R$ be a maximal subfield with trivial ladder.

*

*Is $R$ characterized up to isomorphism by $R_0$ and $L$?

*Is $R$ characterized up to isomorphism over $R_0$ by $L$?

*The relative version: for any extension $R \to S$ of real closed fields such that $R_0 = S_0$, is $S$ characterized up to isomorphism over $R$ by the induced map on ladders?
As indicated in the title question, I'm happy to assume that $R_0 = \mathbb R$ if that simplifies things.
EDIT:  The first two paragraphs of this question were edited from the version to which @EmilJeřábek responded.  In order that that answer can still make sense, the original first two paragraphs appear below.

Let $R$ be a real closed field. Recall that $x,y \in R$ are comparable if there are $m,n \in \mathbb Z$ such that $mx > y$ and $ny > z$. Recall that the ladder of $R$ is the linear order obtained by quotienting by comparability.
Note that $R$ has trivial ladder iff $R$ is a subfield of $\mathbb R$. If $R$ has trivial ladder and $L$ is a linear order, let $R^L$ be the real closure of the purely transcendental extension $R(L)$ with transcendence basis $L$, ordered as in $L$. Then $R^L$ has ladder $L$. Conversely, from any real closed field, we may extract a maximal subfield of $\mathbb R$ and a ladder. I'm wondering whether that's all there is to it, i.e. whether every real closed field is of the form $R^L$.

A: First, the initial claims in the question are false: the ladder of $R^L$ is not $L$. For example, for any $x\in L$, the field $R^L$ contains the element $\sqrt x$, which is not "comparable" to any element of $L$.
Not every linear order is isomorphic to a ladder of a real-closed field; for example, any such ladder is a dense order. In fact, a linear order is isomorphic to a ladder of a real-closed field if and only if it can be expanded to a divisible ordered group. This follows from the fact that any ordered field $(F,\le)$ carries a canonical structure of a valued field, with valuation ring $\{x\in F:\exists n\in\mathbb N\,(-n<x<n)\}$. Then the ladder of $F$ is exactly the underlying order of the value group of $F$. If $F$ is real-closed, its value group is divisible. Conversely, if $L$ is a divisible ordered group, the field of Puiseux series $\mathbb R\langle\!
\langle x^L\rangle\!\rangle$ is a real-closed field with value group $L$.
Now, the answer to all the questions is no, not at all. For instance, if $K$ is a dense subfield of $L$, then $K$ and $L$ have the same ladder; in particular, any real-closed field has the same ladder (in fact, the same value group and the same residue field) as its completion.


text:
Q: How to change a field value to NULL when there is a change in another field using mysql I am a newbie to mysql. Can anyone please help me to sort out this problem,
"I have the following columns emp id,name,leaveto,leavefrom and status in my table. If an employee applies for leave his manager can accept or reject it. If the manager has accepted the leave then the status filed will contain the value as Approved (same for rejected). What I wanted to know is when the employee applies for leave for the second time the leaveto and leavefrom column gets updated but the status field remains the same. "
Is it possible to make the status field to NULL when there is an update in leaveto and leavefrom columns.
This will update the status field (approve/reject) of an employee by comparing his ID and manager ID. If that employee comes under manager "A" then only manager "A" can approve/reject it.
"UPDATE leave_details join managerlogin on managerlogin.manager_id=leave_details.manager_id SET leave_details.leave_status='Approved' where (employee_id='$myemployee_id' and managerlogin.manager_id= '".$_SESSION['mymanager_id']."' )";

A: Yes it is possible to update the value to NULL.
Update tablename set columnname=null where put your condition...

A: You can just
update mytable
set status = null,
    leaveto = ...
where emp_id = 17;

A: Here is the code to set NULL for Satatus
UPDATE mytable SET status = null WHERE empid = '17'

Try it...

Put the condition befor Update
if($_POST['leavefrom'] || $_POST['leaveto'])
{
    $status == "NULL";
}

UPDATE mytable SET status = '$status' WHERE empid = '17'

By using this condition , you can set Null value to Status when leavefrom and leaveto having values.


text:
Q: How to delete NULL items from Canvas? Somehow WPF Canvas has a lot of items which are NULL.
Is there some way to delete/remove it?

A: I am assuming your Canvas has null items because it is bound to a data source that has null items
It would be far better to remove the null items from the data source before binding the data, however if that isn't possible, then try using a Converter that removes null items from the collection to do the binding.
All it really needs to do is loop through the items and check if each one is null. If so, remove it using .RemoveAt(index)
var i = 0;
while(i < list.Items.Count)
{
    if (list.items[i] == null)
        list.RemoveAt(i);
    else
        i++; // don't increase i if you're removing an item
}


text:
Q: Return array with closest numbers from two different arrays EDIT: Here's a rephrase of the question for clarity (apologies for confusion):
QUESTION : Given an array limits and an array punct_arr where both are sorted, return an output array of values separation_index where separation_index[i] is the closest value in punct_arr to limits[i]. It follows that separation_index will be of the same size as limits.

So, say I have two arrays:
limits = [280, 560]
punct_arr = [5, 99, 151, 159, 255, 352, 462, 502, 519, 531, 556, 602]
Expected Outcome: [255, 556]
The outcome should always be the same length as the limits array.
Here's what I got so far:
    for (var limit = 0; limit < limits.length; limit++) {
        for (var punct = 0; punct < punct_arr.length; punct++) {
            if (Math.abs(punct_arr[punct - 1] - limits[limit]) < (Math.abs(punct_arr[punct] - limits[limit])) && (Math.abs(punct_arr[punct] - limits[limit]) < (Math.abs(punct_arr[punct] - limits[limit + 1])))) {
                separation_index.push(punct_arr[punct-1]);
            }
        }
    }

Thanks in advance!

A: Here's a decomposed approach where we start writing at a high-level and define auxiliary helper functions along the way -

function closest (limits, inputs) {
  return limits.map(v => closest1(v, inputs))
}

function closest1 (one, many) {
  return many.reduce((r, v) =>
    delta(r, one) < delta(v, one) ? r : v,
    -Infinity
  )
}

function delta (a, b) {
  return Math.abs(a - b)
}

const limits = [280, 560]

const inputs = [5, 99, 151, 159, 255, 352, 462, 502, 519, 531, 556, 602]

console.log(closest(limits, inputs))

[ 255, 556 ]

A: Here's one way. I just adjusted a bit your code.

const limits = [280, 560]

const punct_arr = [5, 99, 151, 159, 255, 352, 462, 502, 519, 531, 556, 602]

function closestLimits(limits, arr) {
  const diff = []
  const separation_index = []
  let closest
  for (var limit = 0; limit < limits.length; limit++) {
    diff.length = 0
    for (var punct = 0; punct < arr.length; punct++) {
      var m = Math.abs(arr[punct] - limits[limit]);
      diff.push(m)
      if (m <= Math.min(...diff)) {
        smallest = arr[punct]
      }
    }
    separation_index.push(smallest);
  }
  return separation_index
}
console.log(closestLimits(limits, punct_arr))


text:
Q: How to throw and catch a BehaviorSubject Observable error I have an observable
bs = new BehaviorSubject<BS>(new BS());

onObsChange(): Observable<BS> {
    return this.bs.asObservable();
}

then I subscribe to the observable
this.sessionService.onBSChange().subscribe(
            data => self.user = data.user,
            error => console.log(error)
        );

I can get data in the subscription callback but don't know how to catch or throw errors with observables/behavior subjects.
this.bs.next(newValue);     // data => ...

How can I throw an error with observable bs that will be caught in the onBSChange() subscription?

A: You can simply call error on the subject:
this.bs.error(err);


text:
Q: Can Spring Security support multiple entry points? I mean need different:

*

*Login URL

*Login out url

*session time url

*authentication provider

*error page

*css

for different entry point.
Is this possible?

A: From 3.1.0 (which is currently beta) it will support multiple <http> elements in the namespace.
So short answer:
In 3.1.x yes.
In 3.0.5.RELEASE no.
Longer aswer:
Here is additional info, check the links in the comments also.

I had a similar problem once, since I had multiple entry points.
A good way IMO would be to make a new login page which decides which login page to redirect to or even calls the logic of the other entry points. Then you can point spring to the new page.
I'm pretty sure this can be done inside the filter chain, but I wouldn't recommend it since you will need a lot of manual coding and bean definitions. Generally I don't think 3.0.5 was designed for multiple entry points.

A: With multiple <http../> elements, you can achieve most of what you want but the authentication manager is going to be common and that means authentication providers are going to be common. See the issue faced by @David Parks in the post Spring Security 3.1.0.RC1: With multiple  elements why can I only register one authentication manager?.
You can see my answers to similar questions such as Configuring Spring Security 3.x to have multiple entry points and Authenticate user using external webservice in grails to develop custom code to execute entry point specific authentication providers. This can be implemented in 3.0.5 as well.
You can implement solution in 3.0.5 without multiple <http../> elements but you will be need to develop custom code to handle logout and error pages.

A: There is org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint
since 3.0.2.
It might help.


text:
Q: Xamarin changing text and color of a label within a listview I have a label inside a list view which is binded to a datetime property
Instead of showing the datetime value I need to show the hour interval from current time and, if it is less than one hour the text needs to be painted red.
I can accomplish that using a converter but not both rules at the same time. I mean changing color AND text.
Should I use two converters or combine a converter with a trigger or can I do it in one place?
Thanks

A: Why can't you use multiple converter here? I think you can and should. One for the text and one for the text color. Both properties needs a binding to the same view model property.


text:
Q: update_attribute not doing anything after first_or_create if record does not exist previously I do a first_or_create statement, followed by a update_attributes:
hangout = Hangout.where(tour: tour, guide: current_user).first_or_create
hangout.update_attributes(priority: current_user.priority)

If the record already existed, it updates the priority. If it doesn't exist previously, there is no update. Why?
Thanks!

A: update_attributes (aka update) returns a boolean indicating if there was an error, if you do not check it - use bang-version update! so that exception will not be ignored.
Most probably record does not get created due to validation. Also when you're updating new record just after create - better use first_or_create(priority: current_user.priority) or first_or_initialize(with subsequent update) to spare extra DB write.

A:   def update_attributes!(attributes)
    self.attributes = attributes
    save!
  end

update attribute with bang call the save with bang.
def save!(*args, &block)
  create_or_update(*args, &block) || raise(RecordNotSaved.new("Failed to save the record", self))
end

Inside the save! RecordNotSave error will be raise if it cannot save the record.
so you can customize the error handing from your code.
begin
    hangout.update_attributes!(priority: current_user.priority)
rescue RecordNotSaved => e
    #do the exception handling here
end


text:
Q: The truth or truth? "We always like boys who speak the truth"
This sentence is written in my grammar book. I don't understand how is it correct. As far as I was told, articles are omitted before abstract noun unless it is used in particular sense or qualified by an adjective, adjectival clause or phrase.

A: The example from the grammar book is correct and breaks no rules of the English language.
'Truth' can be:

*

*An abstract noun equal in meaning to 'veracity', 'honesty'

What we live by in our community is truth and justice.

*A regular noun equal to 'fact'

You need to learn these scientific truths.

*A noun equal in meaning to 'reality', 'what happened'

I will tell you the truth (about sth).
See: https://www.lexico.com/definition/truth
More detailed take on the issue here: https://www.merriam-webster.com/dictionary/truth

A: Standard usage and common practice show that this is correct, despite what you may have been taught from a grammarian standpoint. Most English native speakers don't know the grammar of their own language, as it is not usually taught in schools so thoroughly as in other countries.
"The truth, the whole truth and nothing but the truth"is a standard phrase for example in court rooms, and I for one am not about to tell the judge that something is not quite right.


text:
Q: Transform data stored in a TIFF file to a CSV with latitude/longitude and data? I've obtained a population density map from the European commission's Global Human Settlement Layer. The download contained a .tif file and .tif.ovr file sharing the same name. Their specifications say about the file "Values are expressed as decimals (Float)
representing the absolute number of inhabitants of the cell."
I need to convert this data to a format where it is listed, in plain text, the latitude, longitude, and that float value from earlier for every cell (csv would probably work best).
So what would be the best way to go about this conversion?
Sorry if this is rather basic or vague as I'm new to this field.

A: If you have the gdal utilities installed, you can do this at the command line, using gdal_translate to convert to XYZ format. This is a flavour of CSV using spaces to separate the three columns:
Initial file:
$ file /tmp/r.tif
/tmp/r.tif: TIFF image data....

Convert:
$ gdal_translate -of XYZ /tmp/r.tif /tmp/r.xyz
Input file size is 360, 180
0...10...20...30...40...50...60...70...80...90...100 - done.

Looks like:
$ head /tmp/r.xyz
-179.5 89.5 0.493539184331893921
-178.5 89.5 0.505515038967132568
-177.5 89.5 0.181563228368759155
-176.5 89.5 0.76950681209564209

Using the TIF from here: http://cidportal.jrc.ec.europa.eu/ftp/jrc-opendata/GHSL/GHS_POP_GPW4_GLOBE_R2015A/GHS_POP_GPW42015_GLOBE_R2015A_54009_1k/V1-0/ the output is in the coordinate system of the raster, which in this case is a Mollweide world projection, the first few lines looking like this:
-17619094.5474435315 8750529.46186848916 0
-17618094.5474435315 8750529.46186848916 0
-17617094.5474435315 8750529.46186848916 0
-17616094.5474435315 8750529.46186848916 0

To convert this to lat-long, use cs2cs and specify the coordinate system:
cs2cs  -f %.6f +proj=moll +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs < out.csv | out_ll.csv

The first few lines of out_ll.csv are:
-2147483648d-2147483648'-nan"E  -2147483648d-2147483648'-nan"N 0.000
-2147483648d-2147483648'-nan"E  -2147483648d-2147483648'-nan"N 0.000
-2147483648d-2147483648'-nan"E  -2147483648d-2147483648'-nan"N 0.000
-2147483648d-2147483648'-nan"E  -2147483648d-2147483648'-nan"N 0.000
-2147483648d-2147483648'-nan"E  -2147483648d-2147483648'-nan"N 0.000

this is basically junk because the Mollweide projection turns the globe into an oval, and the raster is rectangular, so there's a load of non-projectable cells in the corners. Further on it gets okay, looking a bit like this (I put in some fake population data in my test to check it was working):
-177.413720 83.630801 30.000000
-177.372595 83.630801 40.000000
-177.331471 83.630801 20.000000
-177.290347 83.630801 40.000000
-177.249223 83.630801 50.000000
-177.208098 83.630801 60.000000

Note this is no longer a regular grid in lat-long.
I've not tested this on the whole raster because its 540 million points and I'm not even sure that's the file you want because you didn't point to a specific example...


text:
Q: Storing ArrayBuffer in mongodb with mongoose I am trying to store the book's array buffer in MongoDB with the help of mongoose. I am getting some error related to validation I hope you guys can help me.
Here is my back-end:
This is my schema
...
const UserSchema = new mongoose.Schema({
    book: {
        type: Buffer,
    },
});
...

router:
...
router.post("/api/book", auth, async (req, res) => {
    try {
        const { user } = req;
        user.book = req.body.book;
        await user.save();
        res.send({ success: true });
    } catch (error) {
        console.log(error.name, error.message);
        res.send({ success: false, error });
    }
});
...

Here is my front-end:
This is the place where I did a post request
...
getBook = async (book) => {
        console.log(book);
        if (book) {
            try {
                const res = await axios.post(
                    "/api/book",
                    { book },
                    {
                        headers: {
                            Authorization:
                                "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlYTJlOWJlZmI0OTVhMDZhZTkzZjZmNyIsImlhdCI6MTU4NzczNDk3NH0.fzoJcHbkVhkgYZZgYP0N1XNdqf6uowAVrekntuulOu0",
                        },
                    }
                );
            } catch (error) {
                console.log(error.name, error.message);
            }
        }

...

this is the place where o get the book and converted it into array buffer and passed it to above code
...
handleOnChange = (event) => {
        if (event.target.files[0].type === "application/epub+zip") {
            let reader = new FileReader();
            reader.readAsArrayBuffer(event.target.files[0]);

            reader.onload = () => {
                this.props.getBook(reader.result);
            };
        } else {
            alert("Only .epub Files are supported");
        }
    };
...

and here is my error at server side
ValidationError User validation failed: book: Cast to Buffer failed for value "{}" at path "book"
POST /api/book 200 198.131 ms - 533

I think it is because I am using the wrong data type in the mongoose schema


text:
Q: Check if an input is anywhere in a list So I have this code below:
It works by accepting a user input that is in an external list file, but I would like it to accept an input from the user, and then check if that input is anywhere in the external file. Right now, it only accepts the first line as the first user, then the other lines. I want it to accept the input, even if it isn't the first line of the code.
with open("users.txt") as f:
    lines = set("users.txt")
    x = input("First Player, please enter a valid username and password (In the form: Username , Password): ")
    for lines in f:
        if (x) in ("users.txt"):
             lines2 = [line.rstrip("\n") for line in open("users.txt")]
             y = input("Second Player, please enter a valid username and password (In the form: Username , Password): ")
             for lines in f:
                if (y) in ("users.txt"):

I've tried simple code, up to more complex code such as:
if (y in lines for y in lines)

A: You are working with the name of the file rather than the contents of the file.
with open("users.txt") as f:
    allowed_names = set(line.strip() for line in f)

x = input("First player name, password")
p1_name, p1_password = x.split(",")

y = input("Second player name, password")
p2_name, p2_password = y.split(",")

if p1_name in allowed_names:
    ...

if p2_name in allowed_names:
    ...


text:
Q: How to parse 00:00.00000 to TimeSpan? I try to parse string via c#:
  var tm = TimeSpan.ParseExact(00:00.00000, "hh:mm.sssss", CultureInfo.InvariantCulture);

and then get TotalMilliseconds, but i get FormatException.
How to do that?


text:
Q: pass a wildcard as IN parameter to stored procedure Is it possible to pass a wildcard character as an IN parameter when calling a stored procedure (jsp with MySQL)
If I have (in my stored procedure)-
CREATE DEFINER=`root`@`localhost` PROCEDURE `duration`(IN varassetid varchar(25), IN vardtmin datetime, IN vardtmax datetime)

This works fine if calling with -
CALL duration(1157, '2015-06-29 11:47:28', '2015-07-02 11:47:28');

But not with -
CALL duration('%', '2015-06-29 11:47:28', '2015-07-02 11:47:28');

or with any other wildcard character combination.
I do not want to have to change the stored procedure if possible.
Thoughts appreciated


text:
Q: How to enumerate Stream results I have a Stream, that yields Strings like this:
'apple'
'orange'
'banana'

When I listen to the Stream, I want to assign numbers to the results from 1 to n (Stream lenght) in the order they were yielded like this:
1: 'apple'
2: 'orange'
3: 'banana'

What is the best way to do that?

As there is no enumerate() function like in Python, my attempts so far are pretty bad:
inside Stream definition
int n = 0
await for (var nextString in originStream) {
  ++n;
  yield [n, nextString];
}

when stream is called
myStream.transform(enumerateFunc)

List enumerateFunc(String myStr){
  return [n, myStr];
}

I got a suggestion to create a class for this. But I don't want to create a class for simply assing numbers to Stream events in the order they happenned.
Is there a better way to do this?

A: As @julemand101 suggested, a pretty viable option is to create a class for this purpose and yield the class instead of List:
Stream<String> fruits() async* {
  int n = 1;
  await for (final String fruit in fruitChannel) {
    yield Enumerated(n, fruit);
    n++;
  }
}


text:
Q: How to calculate average of adjacent rows? I got a DF with peoples salary data and their job. One row is one person. I need to calculate the average salary of 3 people on the same job and make a new DF out of it. The 3 people need to be on the same job and their wages need to be adjacent if the DF is sorted from highest to lowest salary. The average salary of the person themselves and the ones above and below them in the DF if they have the same job. The people with the highest and lowest salary in a job are excluded as they have nobody above or below them.
This is a sample of the data i have

Job     salary
IT       5000
IT       4500
IT       4000
IT       4000
Sales    4500
Sales    4500
Sales    4000
Sales    3000
Sales    2500
HR       3000
HR       2500
HR       2300

This is what i would like to get (if the average salary went to decimal places i rounded it. But in the R DF there is no need to do it. Decimal places are ok.

Job    salary
IT      4500
IT      4167
Sales   4333
Sales   3833
Sales   3167
HR      2600

I'm stuck as i can't figure out how to calculate the average of the 3 people on the same job and exclude the top and bottom. Hope you can help.
Thank you

A: You want a rolling average by group. This can be done with zoo::rollmean coupled with dplyr::group_by.
library(dplyr)
library(zoo)

dat %>%
  group_by(Job) %>%
  summarise(mean = rollmean(salary, 3, align = "right"))

  Job    mean
  <fct> <dbl>
1 IT    4500
2 IT    4167.
3 Sales 4333.
4 Sales 3833.
5 Sales 3167.
6 HR    2600

A: Here are some base R options
> with(df,stack(tapply(salary, Job, function(x) rowMeans(embed(x, 3)))))
    values   ind
1 2600.000    HR
2 4500.000    IT
3 4166.667    IT
4 4333.333 Sales
5 3833.333 Sales
6 3166.667 Sales

> aggregate(salary ~ ., df, function(x) rowMeans(embed(x, 3)))
    Job                       salary
1    HR                         2600
2    IT           4500.000, 4166.667
3 Sales 4333.333, 3833.333, 3166.667


text:
Q: ImportError: No module named social_django.middleware.in import_module __import__(name) Hello I am trying to execute a project that is made in django 1.10.8 and pyhon 2.7 and the python_social_auth library. When I try to execute the project I get the following error.I hope you can help me
manage.py runserver
Unhandled exception in thread started by <function wrapper at 0x7f4b908eb488>
Traceback (most recent call last):
  File "/home/mauricio/.local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "/home/mauricio/.local/lib/python2.7/site-packages/channels/management/commands/runserver.py", line 39, in inner_run
    http_consumer=self.get_consumer(*args, **options),
  File "/home/mauricio/.local/lib/python2.7/site-packages/channels/management/commands/runserver.py", line 134, in get_consumer
    return StaticFilesConsumer()
  File "/home/mauricio/.local/lib/python2.7/site-packages/channels/handler.py", line 327, in __init__
    self.handler = self.handler_class()
  File "/home/mauricio/.local/lib/python2.7/site-packages/channels/staticfiles.py", line 18, in __init__
    super(StaticFilesHandler, self).__init__()
  File "/home/mauricio/.local/lib/python2.7/site-packages/channels/handler.py", line 177, in __init__
    self.load_middleware()
  File "/home/mauricio/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 80, in load_middleware
    middleware = import_string(middleware_path)
  File "/home/mauricio/.local/lib/python2.7/site-packages/django/utils/module_loading.py", line 20, in import_string
    module = import_module(module_path)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named social_django.middleware

A: Try this
The Python executable you use to run the application doesn't have social_django installed. You can verify this by running these commands:
python manage.py shell
import social_django
This will give you an error, for the same reason.
You can install it with:
pip install social-auth-app-django


text:
Q: android, retain and restore Fragment state after replace I have an activity hosting 2 fragments, and I don't use viewpager. The way I do is like below. When I move from Fragment1 to Fragment2, I see  onSaveInstanceState of Fragment1 is called. However, when I move from Fragment2 back to Fragment1, onCreate() and onCreateView() are called with savedInstanceState as null.
I already try setRetainState(true) in onCreate() of fragments. What am I missing? Thanks.
P.S: SO has a question that's marked duplicate Saving Fragment's state after replacing Fragment but the original question doesn't exist any more.
switch (event.option) {
            case 1:
                getSupportActionBar().show();
                if (frag1 == null)
                    frag1 = new Fragment1();
                fragmentManager.beginTransaction().replace(R.id.v4_main_content, frag1).commit();
                break;
            case 2:
                getSupportActionBar().hide();
                if (frag2 == null)
                    frag2 = new Fragment2();
                fragmentManager.beginTransaction().replace(R.id.v4_main_content, frag2).commit();
                break;
}

Update: code as required in the comment, the function in Fragment1()
@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // Save near location
        outState.putParcelable(KEY_NEAR_LOCATION, mNearLocation);
        outState.putLong(KEY_SELECTED_TIME_IN_MILLIS, mSelectedTimeInMillis);

    }

A: I know I'm late with response, but maybe it will help the others looking for answer to this question. When you have one activity with multiple fragments, onDestroy in fragment is not called. In result of this fragment is not destroyed as long as activity is not destroyed. But, when you replace fragment2 and you add it to backstack, then you come back to fragment1, in fragment2 will be called method onDestroyView. So, to save a state of fragment2 you need to do this inside onDestroyView, for example:
Bundle savedState;

public onCreateView(...){
 ..........
     if(savedState != null){
          String hello = savedState.getString("hello");
     }
 ..........
}
@Override
public void onDestroyView(){
     super.onDestroyView();
     savedState.putString("hello", "Say hello");
}

That's all. I hope it will help.


text:
Q: Is it possible?(c++) Write pointer to string,delete pointer,and load pointer from string?

A: It's possible, but it won't do what you think it will do. Saving entire object as a string is called serialization - see Boost.Serialization (or Protocol Buffers, as suggested in comments) if you need that.

A: It's possible to do those operations, but they won't have the effect you're (probably) after.
Writing the pointer to string will only store the pointer value, i.e. the address of the pointed-to object. This is a string of more or less constant length, like 0x7f2b93c91780 (on a 64-bit system). Naturally, this doesn't capture any of the state of the actual object.
When you use delete on the pointer, the memory pointed at will be returned to the system; it's no longer yours to use. The pointer itself is not deleted, the operation only affects the memory being pointed at. Also, the pointer's value doesn't actually change when you use delete on it. Thus, there's no difference if you now re-load it by reading it in from a string stored somewhere else: it's still pointing at memory you no longer own, and thus can't read or write without invoking undefined behavior.
Like PiotrLegnica suggested, you need to serialize the entire object into a string, and then re-create the object from the serialized version (de-serialize it).


text:
Q: Supporting IPv6 with ELB I have created:

*

*An EC2 instance with IPv6 and IPv4 support, running Ubuntu 16.04 and Apache 2.4

*A dualstack internet-facing application ELB, with the above EC2 instance in its target group

Accessing the website through the ELB's DNS name works fine under IPv4. But testing IPv6 with different online test providers I get a "web server is unreachable : Connection timed out" error.
Here are the inbound rules for both the ELB and EC2 security group:

Not sure what I did wrong?

A: are security groups also open for ipv6 that are attached to the ELB?


text:
Q: Why is this community so well-behaved compared to other online forums? I have seen online communities over the years, and the amount of foul language is really high. People are not polite to each other and flame wars are common.
Why is this community is so well-behaved? I don't see the moderators cleaning up the site, which means this is just the users being well-behaved. Do you have any idea why this is only happening on Stack Exchange?

A: When people can vote on what you do, and those votes have consequences, that goes a long way toward encouraging proper behavior.
Beyond basic peer voting, which is huge, we also have four (!) tiers of moderation:

*

*15+ rep users can flag things as offensive or spam

*2,000+ rep users can edit anything you write

*3,000+ rep users can vote to close your question

*10,000+ rep users have visibility into system hotspots, flags, and can vote to delete content

We also have a policy of "be nice" and "try to post useful content" which is outlined in the /faq
There are also some professional connection, in that your public track record here can be used to show potential employers that you're a good communicator who is willing to help others in the community.
Also, on language, see Are expletives (cursing, swear words or vulgar language) allowed on SE sites?

A: Yeah, Fork you too!
It could be because Stack Overflow has thousands of members with (limited) moderation powers.
It could also be because Stack Overflow draws another part of the public than e.g. a forum about some favourite boyband.
And, of course, because this site has so many active members at any given moment plus some smart algorithms to detect possible abuse, and thus abusive behaviour can be stopped real fast.
Plus, we have Meta Stack Overflow, where we can complain about anything that troubles us at Stack Overflow.
Still, peer pressure isn't enough to stop misbehaviour. Consider those Soccer Hooligans who misbehave during lots of all kinds of events, but mostly soccer sport events. Basically, these hooligans are just regular people and there are probably a few at Stack Overflow and Meta Stack Overflow. But they organise themselves in groups for organized misbehaviour. There are online groups of forum hooligans who tend to misbehave at dozens of forums and the only reason why they're not harassing Stack Overflow could be the moderation done by all members. Or maybe Stack Overflow just isn't interesting enough as a target.
Because, strange as it sounds, Stack Overflow might not be interesting enough for online hooligans to misbehave. :-)

A: I think it could be because downvoting someone works so much better than telling them to "F**-off".
I think downvotes actually represents quite nicely what intentional swearing (e.g. swearing to tell someone to shut up) in type means. A downvote is actually more effective than swearing cause it affects the recipient's reputation (and it shows you really meant it since it annoyed you so much that you were willing to take a downvoter-penalty yourself), while a curse can be ignored and upset innocent bystanders...
Sure you could "accidentally" utter "bad words" when actually talking. But you don't sit down and "accidentally type" a swear word.
-- Personally when I see a question or answer with lots of downvotes, its almost as if I can hear several people screaming "shut up!" or similar... ;)

A: When Stack Overflow started out, it was fairly small, and everyone were happy little smurfs.

Then one day Gargamel showed up.

With his foul language he tried to destroy EVERYTHING.
This made Smurfette cry and get very upset.

So.... Papa Smurf, decided certain word are never to be uttered in Smurf village and using his magnificent reality distortion field smrufed the words out of existence.

A: This is a somewhat task-centered collection of sites, unlike some, and that probably promotes civility.  There are also consequences and people who will enforce the mores, and a sense of community.  Finally, of course, there are plenty of people who can moderate in various ways, so this isn't like an unmoderated group.

A: Regarding questions and answers, it is hard to imagine a scenario where a swear is necessary in prose to communicate the point more effectively (excluding things like quotes containing swears and questions about swears or terms containing swears).
First, including swears is going to make a question or answer unnecessarily offensive to some readers.  Rephrasing the question to exclude them makes the question more approachable.
Secondly, setting aside the distraction of being offensive, the question or answer is going to be better without the swears, as they are just unnecessary fluff.  This is similar to thank yous, greetings, etc. — a question doesn't communicate its content better with them present, so they should be removed.
Part of the responsibility of the Stack Exchange community is to ensure questions and answers are of high quality.  This means omitting or editing out unnecessary and distracting prose, both of which swears fall into.

A: 'cos "offensive" flags attract... the management

(edit: relevant YouTube videos for those of us who had no idea what this was)

A: Confession time, I swear. I do curse at the computer for not loading fast enough, I curse at other people's code when it's awful, I curse at my own code when I realize how foolish I've been.
I do not curse at other people when they ask questions or respond to my, or other people's, questions. This is impolite and completely unacceptable.
So what is the fascination with, or the exclusive reliance upon, swears to communicate?
Seriously...

A: Because even users with 15+ rep can flag posts as:

Offensive, Abusive, or Hate Speech

And 6 flags get an automatic closure/deletion so, even if there weren't the greater moderation powers available to higher rep users, with the numbers of users on SO questions that fall foul of the rules and guidelines don't tend to last very long.


text:
Q: Select in a primary key interval SQL At school We saw you can select this way:
SELECT *
FROM BLALBLA
WHERE id=1 AND id = 2 AND id=3 AND id=4

But how can we do :
SELECT
FROM BLABLA
WHERE id = 1 to 4

Thank you
goldiman

A: There are several ways
1) if id field is integer.
SELECT *
FROM BLALBLA
WHERE id between 1 and 4

SELECT *
FROM BLALBLA
WHERE id => 1 AND id =< 4

SELECT *
FROM BLALBLA
WHERE id IN (1,2,3,4)

2) if id is varchar
SELECT *
FROM BLALBLA
WHERE id IN ('1','2','3','4')

A: SELECT * FROM BLABLA WHERE id => 1 AND id =< 4

A: Jarlh found the answer
"id between 1 and 4 –  jarlh 53 secs ago"
Thank you


text:
Q: HTML CSS: Fixed Element, Adjust height to TOP I have a DIV in fixed position on bottom of page.
Problem: if Elements in this Div Box are Wrapped (responsive), the div box is growing its height to bottom, so Im not able to see the other elements.
Hence, I try to adjust the height of the div Element according to "TOP".
  EG: [+++++++++++++++++++++++++++]     <- WideScreen  [Elements]
        ----------------------------------

Problem:  [+++++++++            //Small Screen: Wrapping [Elements]
         ---------------      <- Window ends here
          +++++++++           <- not visible anymore
          +++++++++      ]

    How its should be:
         [+++++++++
          +++++++++
          +++++++++  ]
         ----------------     //Div adjust height to TOP

How isit possible?
Edit:

 Elements

Thanks alot!

A: Don't use margin-top: calc(100vh - 245px); (erase it), but only bottom: 0 for a footer-type fixed element like this. You can  use height: 245px if you want (apparently that's the height you wanted), but you don't have to. If not, the height will depend on the contents and padding settings of the element.

A: Sorry, already found my answer :D
position: fixed; overflow: hidden; bottom: 0;


text:
Q: A combination of winforms' controls as a prefab? In our winforms application we often have a situation where the same panel is used in different forms. Right now I simply copy the code and the designer elements from form to form but that is obviously a terrible practice.
So I thought of making a class that could be easily added to a different form as a "component". The only problem is to be able to prototype and maintain this panel in the visual designer in such a way that if I want to change the panel's appearance in the future it gets changed for every class instance I created.
For instance I have a panel that provides search functionality:

Alongside with the code for click/textChanged events. I want to encapsulate it in a class, which I would be able to instantiate and initialize in any form's constructor to instantly add these controls (alongside events) into that form. Now it is not necessary for me to see the controls in the designer of the recepient form, however, I need to be able to see them in the designer somewhere in order to modify them if I would ever require that.
And if I do modify the appearance somehow (for instance add an extra button) these controls instantly change across the entire project, everywhere I instantiated the class.
I do know that all this can easily be done just creating a new form and encapsulating everything in it, I just wonder if it can be done for a group of controls instead.

A: You just described the perfect use of a User Control. It's easy to use and direct.
First Add a user COntrol to the project:

Then add the desired controls on the user control:

Build the project and you will see the UserControl on the toolbox:

Add them to the form as a standard control:

If you change the code for the user control (in this case adding a button click handler) uit will affect all the intances of that user control:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    TextBox1.Text = "Button Clicked"
End Sub

Note: If you have the Control in another project on the same solution, make sure you build that project too if you make any change.


text:
Q: Drag and Drop into a textbox I have a list of people on the left hand side of a page, this list is populated by PHP.
Each person is in their own div (this can be changed but I thought div's may be easier to work with). I want to be able to drag any one of these people onto a textbox, thus entering their name into that textbox.
Also to make it more awkward, I don't really want to be using jQuery or prototype. Or any of the others really.
Edit:
Sorry let me rephrase the question...
How would I check to see if something has been dragged on top of a textbox? And how would I get the ID of that element?
What I don't know is how to check if something has been dragged on top of the textbox (input box, not text area, but that's no big issue.)
I know there would never be a magical param like onDragOnto="" but hopefully that will show you what I mean

A: Without more details, I can't really provide a better answer.
How about clicking within the DIV element resulting in a Javascript event to be fired which causes the element's text to be selected?  Then, you can drag this text into a multiline textarea.
Now, with the information from the edit:
You'd register a onmousedown event with each DIV that you have.
On the names:

Jane

On the textarea/textbox:
<textarea onmouseover="return onMouseOver(event);"></textarea>

And a script:

This is a very crude way to do things, but I hope this gives you the principles that you're looking for.  If you want to force the elements to move rather than just using text drag-and-drop, then things get more hairy.  To handle that, you'll need to use CSS and modify the coordinates.


text:
Q: Get view height and element height offset without using window or DOM I'd like to get the view height without using window or document.
I'd also like to get the distance between the top of an element and the top of the view height without using document at all!
I am using Angular 4 to set the height of elements based on where it is. It works right now but I'm being told that using the DOM is not very safe. I have my element hooked up using ViewChild right now. Any advice on how to accomplish this using anything other than window or document?
Preferably there is a way to do it using nativeElement


text:
Q: Is there a way to check if a SIM card is inserted in a Notebook? We would like to do a statistic, over all notebooks, to check if they have a SIM card inserted.
Is there a way to check this?
I played already around with netsh, but maybe is there an easy query, just for checking if a SIM is inserted.

A: How does this do, I am not that good at this, but maybe:
$comPortNumber = Get-WMIObject win32_potsmodem | where-object {$_.DeviceID -like "*05C6*"} | foreach {$_.AttachedTo}

# 05C6 is the Vendor ID for Qualcomm, AttachedTo returns the Com port number

if (!$comPortNumber) { Return "No Gobi Card Detected!" }
else {

    $port = New-Object System.IO.Ports.SerialPort
    $port.PortName = $comPortNumber
    $port.BaudRate = "9600"
    $port.Parity = "None"
    $port.DataBits = 8
    $port.StopBits = 1
    $port.ReadTimeout = 9000 # 9 seconds
    $port.DtrEnable = "true"
    $port.open() #opens serial connection

    Start-Sleep 2 # wait 2 seconds until device is ready

    $port.Write("AT$")
    $port.Write("QCGSN `r") #writes your content to the serial connection

    try
    {
        while($myinput = $port.ReadLine())
    {
        $myinput
        }
        }

        catch [TimeoutException]

        {
    # Put handling code here
    }

    finally
    {
    # Put the clean up code here
    }

    $port.Close() #closes serial connection
}


text:
Q: How to share code as open source? I have a little program that I wrote for a local group to handle a somewhat complicated scheduling issue for scheduling multiple meetings in multiple locations that change weekly according to certain criteria.  It's a niche need, but I wouldn't be surprised if there are other groups that could use software like this.  In fact, we've had requests from others for directions on starting a group like this, and if their groups get as big, they might also want special software to help with scheduling.  I plan to continue developing the program and eventually make it an online web app, but a very simple alpha version is completed as a console app.
I'd like to make it available as open source, but I have no idea what kind of process I should go through first.  Right now, all I have is Java code, not even unit-tested thoroughly.  I haven't shown the code to anyone else.  There is no documentation.  I don't know where I would put the code so others could access it.  I don't know anything about licensing it.  I don't know what kind of support people will expect from me if I release it as open source.  I have no idea what else I should worry about.
Can someone outline for me (or post an article(s) that outlines) the process of taking open source software from "coded" to "completed / available"?  I really don't want to embarrass myself by doing things weirdly.

A: With Java, you probably want:

*

*A build script (perhaps written in Ant) to build (javac), test (java and junit), document (javadoc) and package (jar) your application/lib

*Some unittests to make sure the thing works ok (this can evolve later on, but the framework is good to have)

*Some comments that are suitable for JavaDoc (if developers are your intended audience),

And, for any project:

*

*a README file saying what the project is about

*a LICENSE file explaining how to copy

*Some list of changes, versions, etc (evolvable)

*Quick-start compile/install guide (what dependencies and os:es do you require)

*Some actual documentation, faq and usage examples (for the end-user)

*Also, AUTHORS/HACKING files are common, listing everyone that's been involved (important for copyright) and HACKING describes how to contribute.

Names of files may vary, and some put all this in HTML somewhere, but this is the typical setup.
I recommend looking at a few good open-source projects to see how they do, then just copy and adapt their method to your own. :)
The most important thing is to get it out there, then you are likely to get some feedback if there are others that think your project is interesting.

A: Pick a license from the Open Source Initiative list.  If you want anybody to be able to do whatever with your code, use something like BSD.  If you want anybody who uses it to keep it open source, and have to provide the source code, use the Gnu GPL.  For somebody new to this, I'd suggest one of those two licenses.
Add the license to the code, and put it on some sort of open source repository.

A: The Free Software Foundation website would probably be the best source for learning about what you need to do in order to open source your code. For making it available to other people try one of the following:

*

*Bitbucket

*GitHub

*Google Code

*Launchpad

*SourceForge
There are plenty more, but these seems like the most popular. (I use GitHub.)
People expect the program/library to work. They expect it to have some sort of documentation. And, as with all software ventures, they expect you to be open to bug reports and patches.
Then, you will need to put effort (or find someone who will) and just do it™.

A: Have been reading comments - Wanted to point out that what ppl expect depends on the state of the project. EG: For a production release ppl will expect good documentation. If it's marked "Alpha" then people will be more forgiving of documentation that consists of a text file you wrote in 30 mins.
My advice is pick a license, mark it as Alpha to set ppl's expectations, then just make it public somewhere and start. Try and interest the other groups and take feedback from them on what needs improving.
I'm not saying it'll take of and be a success instantly, it's just that you can spend to long fretting over the small details and that blocks you from the important stuff. Go for it, and good luck :-)

A: Stick it on a public hosting site such a Codeplex, Github, Bitbucket, Google Code and put your preferred licence in the source code (or seperate text file) - job done!


text:
Q: Image losing its draggability after being dropped I have a div full of text and outside that, an img element. (http://jsfiddle.net/EjP5y/2/) I've made  the image draggable and the div droppable. On the drop event I style the image to have a float:left and add some padding and margins, and then preappend it to the div, so it drops nicely into the div with the div text wrapping around it.
$('#clown').draggable();

$('#content').droppable({accept : '#clown', drop : cell_drop});

function cell_drop(e, ui) {
    ui.draggable.css({float   : 'left',
                  padding : '10px',
                  margin  : '10px',
                  top     : '0',
                  left    :'0'
                  })
            .prependTo($(this));

}
Now, once the image is in the div I'd like to be able to drag it and have the div text flow around the image as the image moves.  The image is draggable, so it seems like I should be able to do this, but it acts like the image lost its draggability when it was dropped into the div, even though Firebug still shows that it has class='ui-draggable'.
Also according to http://jqueryui.com/droppable/ draggables should remain draggables after being dropped.
Does anyone understand what's going on here?  How can I drag the image after it's been dropped in the div and have the div text flow dynamically around the moving image?
Thanks


text:
Q: Net Core 2.0 - JWT Bearer not protecting routes I followed the tutorial to configure JWT with Identity on Net Core 2.0 : https://medium.com/@lugrugzo/asp-net-core-2-0-webapi-jwt-authentication-with-identity-mysql-3698eeba6ff8
Author clearly states that there is need to add [Authorize] to protect endpoints,
but I want to protect all endpoint unless explicitly specified [AllowAnonymous].
I read other tutorials about JWT Bearer and they look exactly the same but authors saying that it should request authorization by default...
This is my Startup.cs
 // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // ===== Add DbContext ======
            var connectionString = Configuration.GetConnectionString("dbContext");
            services.AddEntityFrameworkNpgsql().AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(connectionString));

        // ===== Add Identity ========
        services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        // ===== Add JWT =====
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
        services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            })
            .AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata = false;
                cfg.SaveToken = true;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer = Configuration.GetSection("jwt")["issuer"],
                    ValidAudience = Configuration.GetSection("jwt")["audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("jwt")["key"])),
                    ClockSkew = TimeSpan.Zero // remove delay of token when expire
                };
            });

        services.AddMvc();

        // Register the Swagger generator, defining one or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ApplicationDbContext dbContext)
    {
        if (env.IsDevelopment())
        {

            app.UseDeveloperExceptionPage();
        }

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });

        app.UseAuthentication();
        app.UseMvc();

        dbContext.Database.EnsureCreated();
    }
}

Can't find anything in docs looking differently so I would know what I have to change...
I can call any route without the token in headers.
Has anyone an idea?

A: You should be able to use filters like this:
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Authorization;
{...}
services.AddMvc(config =>
{
   var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
   config.Filters.Add(new AuthorizeFilter(policy));
});


text:
Q: Placing a third subfigure at the center in latex I am trying to figure out how to place three images in a triangular order in latex.

Subfigure 3 is not aligned at the center.
I have the following:
\begin{figure}[!h]
\begin{subfigure}{.5\textwidth}
  \centering
  \includegraphics[width=.8\linewidth]{Images/5_Res/bloodstream1.png}
  \caption{Case 1}
  \label{fig:BC}
\end{subfigure}%
\begin{subfigure}{.5\textwidth}
  \centering
  \includegraphics[width=.8\linewidth]{Images/5_Res/bloodstream2.png}
  \caption{Case 2}
  \label{fig:DC}
\end{subfigure}
\begin{subfigure}{.5\textwidth}
  \centering
  \includegraphics[width=.8\linewidth]{Images/5_Res/bloodstream3.png}
  \caption{Case 3}
  \label{fig:EC}
\end{subfigure}%
\caption{Different types of blood vessels}
\label{comparison-blood-vessels}
\end{figure}

I tried removing the \centering in the subfigure 3 but could not achieve it properly.

A: I would write your figure code as follows:
\documentclass{article}
\usepackage[demo]{graphicx}
\usepackage[belowskip=1ex]{subcaption}

\begin{document}
\begin{figure}[!h]
    \centering   %
\setkeys{Gin}{width=\linewidth}
\begin{subfigure}{.4\textwidth}
  \includegraphics{Images/5_Res/bloodstream1.png}
  \caption{Case 1}
  \label{fig:BC}
\end{subfigure}
\hfil
\begin{subfigure}{.4\textwidth}
  \includegraphics{Images/5_Res/bloodstream2.png}
  \caption{Case 2}
  \label{fig:DC}
\end{subfigure}

\begin{subfigure}{.4\textwidth}
  \includegraphics{Images/5_Res/bloodstream3.png}
  \caption{Case 3}
  \label{fig:EC}
\end{subfigure}%
\caption{Different types of blood vessels}
\label{comparison-blood-vessels}
\end{figure}

\end{document}

A you can see to your code fragment are added:

*

*keys Gin for shorter code

*after \begin{figure} command \centering`

*between first and second row with images is empty line

*width of subfigure is reduced to desired width of images. Consequently all \centering in subfigure` are (can be) omitted


text:
Q: Angular bootstrap - accordion shows content when closed This seems pretty straight forward but I don't understand why this accordion menu is always showing the content, before the header is clicked. I'm stuck using version 0.13.0 for now.
<accordion close-others="true">
<accordion-group heading="{{ config.vin }}" ng-model="config.vin" ng-repeat="config in vm.accessor.customConfigs track by config.vin">

hello
 // always visible
</accordion-group>
</accordion>


text:
Q: Javascript simple Form Validation not working I have been trying to figure this simple code out. I have it down to where the IF Firstname is empty or == 1, it will ALERT, but the final IF statement is always ringing true and doesn't alert false or true. Any ideas?
function validateForm()
{
    var firstname=document.getElementById('firstname').value.trim();

var count=0;
if (firstname.length==0)
 { alert("EMPTY");
  document.getElementById("err_firstname").innerHTML="
*This is a required field";
  } else  {
   count++;
   alert("COUNTED");
   document.getElementById("err_firstname").innerHTML="";
  }

  if (count==1)
      {
   return true;
  alert("true");
   } else {
   document.getElementById("err_allerrors").innerHTML="
*There is required information missing. Please enter all required data.";
      return false;
             alert("false");

     }
    //Verified
}

A: return before alert() is the problem


text:
Q: Are folders always part of ArcGIS Server REST API service name? I'm using an ArcGIS REST map service, and my question is how do I construct the URL to the service?
Specifically, what relationship is there between the Service Name, the Test Server, and the folder directory structure?
This is the relevant information to the service I am trying to use:

Service Name: Louisville/LOJIC_LandRecords_Louisville
Folder: Louisville Test Server url:
http://sampleserver1.arcgisonline.com/ArcGIS/rest/services

The server send me for the folders:
{"currentVersion" : 100,
  "folders" : [
    ...
    "Fire",
    ...
  ],
  "services" : [
    {"name" : "Geometry", "type" : "GeometryServer"}
  ]
}

and for the service:
{"currentVersion" : 100,
  "folders" : [],
  "services" : [
    {"name" : "Fire/Sheep", "type" : "MapServer"},
    {"name" : "Fire/Sheep", "type" : "FeatureServer"}
  ]
}

You can see, the folder is part of the service name, is this always so? What is, if there is more then one level of folders?

A: Yes. For example, if you were to use the REST service in a GIS, web GIS, or mobile GIS you would reference to the service you are using as:
http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Louisville/LOJIC_LandRecords_Louisville/MapServer
EDIT | UPDATE
Original question:
I'm using ArcGis as Rest Service.
My question is are allways the folders part of service name?

service name: Louisville/LOJIC_LandRecords_Louisville
folder: Louisville
test server url: http://sampleserver1.arcgisonline.com/ArcGIS/rest/services

Thanks for help!

Marcel

The way the original question was worded did not lend to any clarity about what you were asking, which is why it was edited. The way it was originally structured I was under the impression that you needed to know about how to structure the directory path in a URL request, and I'm afraid that I misinterpreted your question. On your second question, you provided no references to the services or directories. Using the ArcGIS Server you listed in this original question:
Here is the default services directory for all services on this instance of ArcGIS Server: http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/. For this particular directory, the service looks like this:
{"currentVersion" : 10.01,
   "folders" : [
     "Demographics",
     "Elevation",
     "Locators",
     "Louisville",
     "Network",
     "Petroleum",
     "PublicSafety",
     "Specialty",
     "TaxParcel",
     "WaterTemplate"
   ],
   "services" : [
     {"name" : "Geometry", "type" : "GeometryServer"}
   ]
}

So in this example, say we choose the Demographics folder. This is the REST response for that directory:
{"currentVersion" : 10.01,
  "folders" : [],
  "services" : [
    {"name" : "Demographics/ESRI_Census_USA", "type" : "MapServer"},
    {"name" : "Demographics/ESRI_Population_World", "type" : "GPServer"},
    {"name" : "Demographics/ESRI_Population_World", "type" : "MapServer"}
  ]
}

So as you can see, the answer to your question is yes; the folder name is concatenated to the services name. For more information you should read the Using ArcGIS Services Directory and check out the ArcGIS Server REST API. For more information on RESTful web services as a whole, see the wikipedia entry. I hope this helps answer your question.

A: If the service is located in a folder, the folder name is always part of the service. If the service is located at the root directory of the server, it is not part of the service name. ArcGIS Server only supports one level of folders, so there cannot be any sub-directories (see here).
For example:
Service at server root, service name "bar":
  "bar"
Service in folder "foo", service name "bar": "foo/bar"