text:
Q: Advice on Math Undergraduate degree I grew up with Portuguese as my first language, both my parents are immigrants without a high school diploma. My dad taught me multiplication over the course of a couple of days at 5 years old but didn't know any mathematics beyond that.  He worked construction since the age of 15, my mom never held down a job, dropped out of high school in Portugal to work on a farm. She speaks broken English.
My elementary school was OK, I got all A's from 2nd grade to 5th grade without much effort.  There was a kid named Ryan that I would tutor that ending up doing well.   6th grade our elementary school got a new teacher, the class average was a D.  I found it impossible to learn from her.  Ryan got lucky with a good teacher for 6th grade.
We were sent to an inner city middle school, I was put in standard class's because of a poor performance in 6th grade.  He was put in honors class's.  75% of the kids in my class's in the 7th and 8th grade were living in project housing, had a parent in prison, or from a single parent home living on the poverty line.  A small group of kids would harass the teachers and disrupt the class room so that 90% of the class was babysitting.
This carried over into high school which was actually worse, a lot of my high school classmates are serving time in prison with a couple for murder convictions. Ryan stayed in honors class's throughout, eventually getting into BU.
I fell so far behind that although I graduated high school on time, I didn't even know how to simplify basic fractions. I didn't know what "x" was in a mathematical context.  I just assumed I was bad at math.  My Algebra 1 teacher taught us nothing we watched movies all day, same with geometry, I was completely lost in Algebra 2.  I would get mostly D's, I failed Chemistry twice, with my second Chemistry teacher saying that I had a strong work ethic.  After working dead end jobs and trying my hand at boxing and music in my early 20's I decided to go to community college after a severe boxing injury.  Boxing gave me a lot of confidence, I did fine at community college for a year and got into state university.  I was soo confidenct that decided to take Calculus without knowing any algebra, geometry, trig, or precalc, or even how to properly manipulate fractions.  My advisor told me I was insane, she told me that I would 100% fail if I took Calculus based on my transcripts.
From sheer willpower and brute force I managed a B in Calculus teaching myself the absolute basics of algebra, geometry, trig, and pre calc along the way and just rote memorizing everything. I just took Calc and nothing else while working a full time 40 hr job.
My guidance councilor was in complete disbelief.  After a talk she recommended that I enroll in the Physics program so I did, she thought I was like the guy from Good Will Hunting. I did ok the first semester but did worse and worse as I went on, I couldn't complete a Physics undergrad without really knowing Algebra or so much of the other high school maths, so I took a year off of school.
I bought an Algebra 1 and 2 textbook, a geometry text book, trig textbook, a high school physics book and chemistry. I worked a job 20 hours a week and thoroughly taught myself all those high school math and science subjects over the course of a year to the point were I would search the internet for a Pre-Calc / Geometry / Trig problem that I couldn't solve but couldn't find any. I was able to solve any math problem I could find on the internet that only required up to high school pre-calc.
I re-enrolled in class's at univeristy, I retook Calc 1 with the hardest professor at the university, I took Classical Mechanics with the hardest physics professor at the university, I also took astronomy and a logic course. I got 100 on every test in all my class's and 120 on my Calc final.   The average grade in the class for Calc was a 55.
I felt like things were finally going to start going my way . . . boy was I wrong.
I discovered that a really poor primary school education and growing up in poverty was only a part of the reason I had done poorly historically in school . . . I also have ADHD.
I did great for a couple of semesters and then started doing poorly again . . . This time I was at my wits end . . I couldn't understand why I was doing poorly again but I've pretty much come to a conclusion.
After reading a bit of some great text books in Real Analysis and Topology I've come to the conclusion that school just isn't for me. It's not  that I'm stupid or bad at math or whatever it's just that lectures are a complete waste of time for me.  My time is 100% best served by reading through well written advanced math texts and learning everything at my own pace from there.
In hindsight, what I should have done when I had finished teaching myself all of middle school and high school mathematics and science extremely thoroughly and rigorously over the course of a year, I should have continued to teach myself all of College Math and College freshman and sophomore Physics from home using quality texts.
After teaching myself all of College math, I could have enrolled back in college and taken all the necessary courses for a BS in mathematics in 2 years after which I likely would have had the opportunity at grad school or at least a good transcript.
My transcript now just looks like a hodgepodge of what the heck was going on with you.
Now in the second part of my Junior year in the math program and in my late 20's I'm getting annoyed that I don't have a career yet.
I'm extremely tempted to take 1 or 2 years off and load up on self teaching math texts, go back and finish with all A's in 1 year, rather than continue doing crappy and finishing in 2 years anyways, getting worse grades and learning less.
Part of me says screw it and take the next 6 to 9 months mastering my Python programming skill set and getting a decent a job so I can finally start a family with my Fiance. Ryan, the guy who I tutored in Elementary school has started a family, makes over 100K working at a big bank as a bank manager.
I just feel so behind . . . part of me regrets not becoming a Plumber out of high school, I'd have bought a house by now and established a family.
Any advice on what to do next?

A: There are a ton of people who dont have a proper career in their late 20's, thats really not uncommon!
You know exactly what your strengths are, which is a pretty important thing when thinking about your career, so I think you will be fine.
I would suggest you find a college to enroll in, where you are not forced to sit through lectures (I know in germany, you dont have to attend at all if you dont want to).
Continue selfteaching the lecture material, pass the tests and when you finally have the degree, you can easily start your career in your early 30's.
Or you continue in academics! Being able to self teach and having interesting in aquiring knowledge is exactly the thing you need for a PhD.
I actually know a good with ADHD who struggled through his math studies but had a fantastic PhD in the end.
I wish you good luck for your future!
Oh and as a side note, as @shaun said, this is not really the right place to ask, try https://academia.stackexchange.com/ next ;-)

A: Thank you for sharing your experience. I believe a lot of people are left feeling inept at math and never realize how ubiquitous the feeling genuinely is. Only to then learn later in life that much of the material is approachable with the right teacher / method of learning.
What you have suffered from is the systemic failures of the American education system. That, and the fact that you had to struggle to sustain your education while having ADHD, is incredibly challenging. I believe many could empathize with your frustrations, most of which I could only imagine carry the sensation that your hardships could have been avoided.
So a couple of notes to (maybe) help you realize you're doing fine:

*

*You're hopefully learning something you're passionate about. In the end, unless you are applying to graduate school, grades don't really matter. If you're feeling like you're wasting time, then taking months off could exacerbate those feelings.

*You cannot compare yourself to the chronology of others. Maybe this Ryan fellow looks at your life with similar anxiousness because they may lack a significant other.

*Being able to learn from lectures is an important skill. Part of grad school is being able to navigate mathematics without a textbook. That is, reading papers and understanding seminars. It sounds like you would absolutely hate grad school, so I wouldn't recommend dwelling on missed opportunities too much.

If you don't feel like you will get much from your education, then leaving to pursue a tech job is valid. But it is incredibly difficult to transition companies when you don't have a competitive degree. Simultaneously, pushing yourself to take classes you don't want to take is never good either.
PS: Depending on where you live, plumbing may or may not be a lucrative industry... I do know of some places where it is, but where I live you would not be able to afford a house on that paycheck alone.
PSS: You should probably stop talking to Ryan. It doesn't seem like a healthy relationship...


text:
Q: Default page when clicked gives error When the default page of a shared library is clicked it throws an error:

"ERROR
An unexpected error has occurred.
Troubleshoot Issues with Windows SharePoint Services"

We are able to access all the other links, only when accessing the default page its throwing this error
The page contains webparts.

A: Check the ULS (SharePoint log files) if you have access to them or the EventVeiwer on the server.
In case you don't, do as follows:
In the URL add this at the back: ?contents=1.
Example: http://www.mysharepointsite.com/default.aspx?contents=1
This will open a page with a list of current webparts on the page.
Delete the webparts and insert them again one by one untill the page fails. Then you'll know which webpart is causing the error.
If the page still throws an error while not having any webparts on it, if you have publishing features activated, it's most likely the pagelayout that the page uses that causes it.
Hope this helps :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I translate "Author Note" in apa6 into german? I want to create a german paper in APA 6 format. Using
\documentclass[a4paper,man,natbib]{apa6}
\usepackage[ngerman]{babel}

works, but the headline for the authors note on the title page remains untranslated. How can I fix this?
My document is
\documentclass[a4paper,man,natbib]{apa6}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}

\title{Der Titel}
\shorttitle{Der Kurztitel}
\author{Hans Peter}
\affiliation{Universität}
\note{19.09.2016}
\authornote{Man erreicht den Autor unter}
\abstract{mein Abstract}
\begin{document}
\maketitle
Text hier
\end{document}

I refer to this headline here:

A: The English terms are happily defined using macros \rheadname et al.
Since these macros are also defined in \begin{document}, the redefinitions are done at the end of the preamble using \AtBeginDocument:
\documentclass[a4paper,man,natbib]{apa6}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}

\title{Der Titel}
\shorttitle{Der Kurztitel}
\author{Hans Peter}
\affiliation{Universität}
\note{19.09.2016}
\authornote{Man erreicht den Autor unter}
\abstract{mein Abstract}

\AtBeginDocument{%
  \renewcommand*{\rheadname}{Laufende Kopfzeile}%
  \renewcommand*{\acksname}{Autorhinweis}%
  \renewcommand*{\keywordname}{Schl\"usselw\"orter}%
  \renewcommand*{\notesname}{Fu\ss noten}%
}

\begin{document}
\maketitle
Text hier
\end{document}


text: Q: how to encrypt on sqlite database in flutter application I am using flutter mobile framework .Need to encrypt files in database using sqflite_sqlcipher package. can anyone help me out with a sample program?


text:
Q: How can I find the sender of an unrecognized selector in LLDB? I'm getting an "unrecognized selector" error that is confusing me.
I know that I can "po" the pointer in LLDB to find out about the receiver.  But is there a way to deduce which object is sending this message?
Thanks!

A: The command bt in the debugger will show you a backtrace (stacktrace), which should give you the class that initiated the message somewhere in that output.

A: Backtrace doesn't always help if you're dealing with multiple threads - you end up with the backtrace of the exception handler on the main thread which isn't necessarily the one that cause the error.
However, since you know that the particular selector doesn't exist for a particular class, you can cheat a little by using a category to add the selector to the class, then just stick a breakpoint on it.
For example, for this error:
-[__NSCFDictionary isEqualToString:]: unrecognized selector sent to instance 0x10004fb0

we know that something's trying to call "NSDictionary" with "isEqualToString". So, add this at the end of any file you like, outside any other "@implementation" blocks:
@implementation NSDictionary(debug)
- (BOOL)isEqualToString:(NSString*)theString {
    return FALSE;
}
@end

Stick a breakpoint on this, re-run your code and you will get a genuine stack trace. Don't forget to remove the category once you've found the error!


text:
Q: how to concatenate two strings in iphone In this Code here i am sending Code number and phone number seperatly, i have two textFiedls phone code number field, and phone number field, but i want to concatenate code number and phone number field and send it as full mobile number...
Please help me how to concatenate codenumber and phone number.
self.operatorLbl.text = self.operatorStr;

    self.codeLbl.text = self.codeStr;

    self.phoneNumLbl.text = self.phoneNumStr;

    self.balanceLbl.text = self.balanceStr;

[post orderConfirm: self.operatorLbl.text :self.codeNumLbl.tex :self.phoneNumLbl.text :self.balanceLbl.text];

I'm very very new in this program need your help

A: Here is all way you can do with string
//1st Way
NSString *finalString = [NSString stringWithFormat:@"%@ %@",firstString,secondString];

//2nd Way
NSString *finalString = [firstString stringByAppendingFormat:@" %@",secondString];

//3rd way
NSArray *ary= [NSArray arrayWithObjects:firstString,secondString, nil];
NSString *finalString= [ary componentsJoinedByString:@" "];

A: You can append in different way like this...
First Way
NSString *combinedStr = [NSString stringWithFormat:@"%@ %@", firstStr, secondStr];

Second way
For Immutable String
NSString *firstStr = @"FirstString";
NSString *secondStr = @"SecondString";
NSString *concatinatedString = [firstStr stringByAppendingString:secondStr];

For a Mutable string:
NSMutableString *firstStr = [NSMutableString stringWithString:@"FirstString"];
NSString *secondStr = @"SecondString";
[firstStr appendString:secondStr];

A: you can try this one
    NSString *string1, *string2, *result;

string1 = @"This is ";
string2 = @"my string.";

result = [result stringByAppendingString:string1];
result = [result stringByAppendingString:string2];
OR

result = [result stringByAppendingString:@"This is "];
result = [result stringByAppendingString:@"my string."];

If a = AAA and b = BBB then you will need to write
[a stringByAppendingString:b];

So in your case it will be [codeLbl.text stringByAppendingString:phoneNumLbl.text];
For more information about this method please see  NSString Documentation
If its not helping you please let me know


text:
Q: customize amazons SES - remove amazonses.com I finally got SES to work, but now im confronted with another problem
The email sent leaves amazonses.com in the from and mailed-by fields like thisI am currently on sandbox access
from:    name@myDomain.com via amazonses.com
to:  john@aol.com
date:    Sat, Jun 2, 2012 at 3:30 PM
subject:     Subject message
mailed-by:   amazonses.com

question: how can i remove amazonses.com from these 2 fileds and replace the 'mailed-by' field with my companies email address?

heres my php
function sendMail($to, $subject, $message, $from ) {
    require_once('sdk-1.5.6.2/sdk.class.php');

    $AWS_KEY = "********************";
    $AWS_SECRET_KEY = "****************************************";

    $amazonSes = new AmazonSES(array( "key" => $AWS_KEY, "secret" => $AWS_SECRET_KEY ));

    $response = $amazonSes->send_email(
        $from,
        array('ToAddresses' => array($to)),
        array(
            'Subject.Data' => $subject,
            'Body.Html.Data' => $message,
        )
    );

    if (!$response->isOK()) {
        return false;
    }else {
        return true;
    }
    return false;
}
sendMail('john@aol.com', "Body message", "Subject message", "name@myDomain.com" );

A: The reason you're getting this is by default you're encouraged to use Amazon's own DKIM setup.
In order to remove the 'via amazonses.com' text you'll need to follow instructions similar to these in order to set up your own DKIM keys.
Note that I haven't yet tested this myself.

A: Set the MX and SPF record obtained form amazon ses into your subdomain through which your sending your emails.
eg:
Suppose verified domain on amazon ses is: domain.com
then add the MX and SPF record obtained when you click on verfied domain to the subdomain-  abc.domain.com
It will change your mailed by to abc.domain.com

A: Since july 2012 it is easy to sign outgoing mail via SES itself.
Instructions are easy and straightforward.
p.s.: sorry for nekroposting, but this question is the one that popped up when I tried to do the same thing.

A: I don't believe you can. SES allows only to send from your domain (or other verified address), and it always has the ses stamp.

A: Even if your php mail has From address other than the verified email from SES it will go through the SES but via amazonses will show. But if the From address is the verified email with SES then the via address will not show up. So not to show the via address its better to change the php script of sending mail.

A: You can replace mailed-by with your companie's email address. To do that, you must create a custom MAIL FROM domain which is the domain with subdomain like sub.example.com.
The below is how you create the custom MAIL FROM domain sub.example.com.
Click on the domain example.com.

Then, the detail is shown.

Then, click on MAIL FROM Domain to show Set MAIL FROM Domain button.

Then, clicking on Set MAIL FROM Domain button, the window is open.

Then, put the subdomain "sub" to the field and click on Set MAIL FROM Domain button.

Then, the MX Record and SPF Record are shown. You must add the MX Record and SPF Record to Route 53 in addition to the records of the domain example.com to verify the custom MAIL FROM domain sub.example.com.

Finally, check if the custom MAIL FROM domain sub.example.com is verified under MAIL FROM domain section.

If MAIL FROM domain status is still pending verification, click on retry in blue.

Then, it will be verified.

After the custom MAIL FROM domain is verified, mailed-by is  sub.example.com whether or not you send emails using example.com or sub.example.com and whether or not your account is in the sandbox.


text:
Q: Covariant assignment not working I am trying to generalize the notification of changes to the properties of an object via an IObservable<T> but that's besides the point of the question. The point of the question is: the following assignment I make reports an invalid covariance error:
protected virtual void OnPropertyChanged<T>(
                      string propertyName,
                      T oldValue, T newValue)
{
    IPropertyChangedNotification<Student, object> notification =
        new PropertyChangedNotification<Student, T>(this,
        propertyName, oldValue, newValue);

    ...
}

This reports:

Cannot implicitly convert type
  PropertyChangedNotification<UsingSubjectToWatchProperty.Student, T>
  to  IPropertyChangedNotification<UsingSubjectToWatchProperty.Student,
  object>.  An explicit conversion exists (are you missing a cast?)

Here is the complete code:
class Student
{
    private ISubject<IPropertyChangedNotification<Student, object>> _subject =
       new Subject<IPropertyChangedNotification<Student, object>>();;
    private string _name = null;

    public string Name
    {
        get
        {
            return _name;
        }
        set
        {

            var oldValue = _name;
            _name = value;

            OnPropertyChanged<string>("Name", oldValue, _name);
        }
    }

    protected virtual void OnPropertyChanged<T>(string propertyName, T oldValue, T newValue)
    {
        IPropertyChangedNotification<Student, object> notification =
            new PropertyChangedNotification<Student, T>(this,
            propertyName, oldValue, newValue);

        _subject.OnNext(notification);
    }
}

public class PropertyChangedNotification<TDeclaringType, TPropertyType>
    : IPropertyChangedNotification<TDeclaringType, TPropertyType>
{
    public PropertyChangedNotification(TDeclaringType declaringObject,
        string propertyName,
        TPropertyType oldValue,
        TPropertyType newValue)
    {
        DeclaringObject = declaringObject;
        PropertyName = propertyName;
        OldValue = oldValue;
        NewValue = newValue;
    }

    public TDeclaringType DeclaringObject { get; set; }
    public string PropertyName { get; set; }

    public TPropertyType OldValue { get; protected set; }
    public TPropertyType NewValue { get; protected set; }
}

public interface IPropertyChangedNotification<TDeclaringType, out TPropertyType>
{
    TDeclaringType DeclaringObject { get; set; }
    string PropertyName { get; set; }

    TPropertyType OldValue { get; }
    TPropertyType NewValue { get; }
}

PS: This is not production code. Just practice stuff.

A: Covariance and contravariance are only supported for reference types (to convert a value type to an Object it would need to be boxed).
So you would need to constrain T to class:
void OnPropertyChanged<T>(string propertyName, T oldValue, T newValue)
    where T : class { ... }

Alternatively, you could just use new PropertyChangedNotification<Student, object>().
A third option would be to have an interface without TProperty:
public interface IPropertyChangedNotification<TDeclaringType>
{
    TDeclaringType DeclaringObject { get; set; }
    string PropertyName { get; set; }
}

public interface IPropertyChangedNotification<TDeclaringType, out TPropertyType>
    :  IPropertyChangedNotification<TDeclaringType>
{
    TPropertyType OldValue { get; }
    TPropertyType NewValue { get; }
}

Then use it in the Subject (since you'd have to cast it to a concrete type anyhow when you subscribe):
ISubject<IPropertyChangedNotification<Student>>


text:
Q: Are loops the best way to build a table? I have to build an HTML table that shows data for users versus pages visited. It seems klunky to use for and/or foreach loops, but I can't think of anything better. I'm using PHP, but I would assume that this is language agnostic.

A: Well, if you have multiple rows, with data formatted similarly in each row, I can't think of a way to create a table that avoids using a loop.  That type of thing is basically what loops were invented for.
If you gave us more details on the table you want to build, maybe we can formulate a better method.

A: Avoiding loops is probably not possible, if not in implementation, then it will still happen at machine level.
However, if you want to try stay 'pure' without nasty code, you can at least do:
$tableformat = '

%s

%s

';
$rowformat   = '
%s
';
$cellformat  = '%s	';

$hdata = '';
foreach( $data[0] as $cellname => $cellvalue )
{
   $hdata  .= sprintf( $cellformat, $cellname );
}
$hdata = sprintf( $rowformat, $hdata );
$rdata = "";
foreach( $data as $rownum => $rowvalue )
{
   $row = "";
   foreach( $rowvalue as $colname => $colvalue )
   {
       $row .= sprintf( $cellformat, $colvalue );
   }
   $rdata .= sprintf($rowformat,$row);
}
return sprintf( $tableformat, $hdata, $rdata );

At least that way it might be somewhat maintainable. and you don't have much worry about incomplete strings.
You could also subsitutue some of that code with
   $hdata = "
" . implode( "	", array_keys( $data[0] )) . "
";
   $rdata .= "
" . implode( "	", $rowvalue ) . "
";

Which while being rather concise, will possibly get you in a bit of hot water eventually and it will need recoding.  ( and implode internally runs a loop, so its a lose-lose ).
If you don't mind the over head of extra function calls ( and still running loops ) this could make for more concise code without too many negatives:
 $tableformat = '

%s

%s

';
 $rowformat   = '
%s
';
 $cellformat  = '%s	';

function tr( $cells )
{
   $o = "";
   foreach( $cells as $i => $v )
   {
      $o .= sprintf( $cellformat, $v );
   }
   return sprintf( $rowformat, $o );
}

return sprintf( $tableformat,
               tr( array_keys($data[0])),
               implode("", array_map( 'tr', $data )) );

But beware, thats hard to read, and you keep that up one day you'll wake up with lisp.

A: If you don't use some kind of loop then you need to hardcode the number of rows and columns in your code, which is probably a much worse idea

A: If the data in the table is dynamic then you have to use a loop. Even if you get a component that generates the table for you, internally it will use a loop.

A: I highly recommend the Smarty templating engine for PHP.  This will permit you to move your table (and the associated loop, which is unavoidable) into the template using Smarty syntax, so it will be clearer and more separated from your business logic.  You would be able to replace nearly all the code in your example with a few simple tags in an HTML snippet.  Check out the crash course on the Smarty page for an example of using a table.

A: That depends on your definition of "best". FOR loops will do the job just fine. I'm not a PHP programmer, but in .NET, you can use the Repeater, a sort of template that you can use to declare the table HTML. It has templates for the header, the footer and each item. You bind a data source to the repeater, and it will generate the table HTML for you a bit more elegantly than using FOR loops. I imagine there might be some sort of templating equivalent in PHP.
In the end, though, even the Repeater uses some sort of loop...

A: Why do you want to avoid loops?  If you have a set of items, and you want to display each item, surely looping over the set is the obvious solution?
If you are trying to separate the model from the view, or write more readable code, good; but loops are not inherently bad.

A: I usually use loops and implode for this, in PHP. In a language, which supports functional programming I would do it differently.
function render_table($data) {
  $html = '
';
  $tr = array();
  foreach (array_keys($data[0]) as $key) {
    $tr[] = '' . htmlspecialchars($key) . '	';
  }
  $html .= "\n" . '
' . "\n" . '
' . "\n" . implode("\n", $tr) . '
' . '
';
  $tbody = array();
  foreach ($data as $row) {
    $tr = array();
    foreach ($row as $value) {
      $tr[] = '' . htmlspecialchars($value) . '	';
    }
    $tbody[] = '
' . "\n" . implode("\n", $tr) . '
';
  }
  $html .= "\n" . '
' . "\n" . implode("\n", $tbody) . '
';
  $html .= '
';
  return $html;
}


text:
Q: Anchor tag stripped from URL on form submit Freeform version: 4.07
ExpressionEngine v2.5.3 - Build Date: 20120911
I have a freeform form inside a jQuery tab. When the form is submitted with erros, the anchor for that tab is stripped from the URL. This takes me back to the first tab and not the tab with the form in. Is there a way to redirect the user back to the form tab?
Thanks

  {exp:freeform:form
  form_id="2"
  required="name|email|user_message"
  return="contact_us/thank_you"
  recipients="yes"
  recipient1="Happy Harry|h_harry@somemail.com"
  recipient2="Lazy Larry|lazyl63@somemail.com"
  recipient_template="contact_form"
  notify_user="yes"
  user_email_field="user_email"
  inline_errors="yes"
  }
   {if freeform:general_errors}

There were some error(s) with your submission:

   {freeform:general_errors}

{freeform:error_message}

   {/freeform:general_errors}

   {/if}

     {freeform:label:name}
     {freeform:field:name}
     {if freeform:error:name}{freeform:error:name}{/if}

     {freeform:label:email}
     {freeform:field:email}
     {if freeform:error:email}{freeform:error:email}{/if}

   {freeform:label:user_message}
   {freeform:field:user_message}
   {if freeform:error:user_message}
   {freeform:error:user_message}{/if}
   <input type="hidden" name="subject" value="{title}" id="subject">
   <input type="submit" name="submit" value="Submit" id="submit" class="button">
  {/exp:freeform:form}

A: You should solve this using jQuery by:

*

*Checking for the existence of class error

*If exists: open the tab with the form

*Else: do nothing

Which would be something like:
if ($(".error").length > 0) {
    $("#tabs").tabs("select", "#qaTab");
}

Good luck!


text:
Q: I want to change the font color of a disabled input I want to change the font color of V1. It's a disabled input and I want to make it darker. How can I do this for Chrome?

My HTML code is;
 <mat-form-field appearance="outline" fxFlex="100" fxFlex.gt-xs="30" class="w-100-p"
                        ngClass.gt-xs="pr-4">
                        <mat-label>Versiyon</mat-label>
                        <input matInput formControlName="Revision" type="text">
                    </mat-form-field>

Mind you, it's a reactive form so, my TS code is:
    Revision: new FormControl({ value: "", disabled: true }),

A: You can add this CSS class in your styles.scss file :
For label
.mat-form-field-appearance-outline.mat-form-field-disabled.mat-form-field-label {
  color: rgba(0,0,0,.6)!important;
}

For input value
.mat-form-field-type-mat-native-select.mat-form-field-disabled .mat-form-field-infix::after, .mat-input-element:disabled {
  color: rgba(0,0,0,1)!important;
}


text:
Q: How can I ensure user enters a valid choice? I'm making a simple rock paper scissors program but am unsure how to ensure that the user only enters a valid choice. I need to be able to reprompt them if they don't type some varriant of "rock", "paper", or "scissors" (capitalization doesn't matter) and later "yes" or "no". Suggestions?
import java.util.*;

public class RockPaperScissors {

private int wins = 0;
private int losses = 0;
private int ties = 0;

public static void main(String[] args) {
    // TODO Auto-generated method stub

    RockPaperScissors model = new RockPaperScissors();
    Scanner scan = new Scanner(System.in);

    while (true) {
        System.out.println("Rock, Paper, Scissors... Pick one! (Type Rock, Paper, or Scissors)");
        String playerChoice = scan.next();

        String computerChoice = model.getRandomChoice();

        System.out.println("You chose " + playerChoice + ".");
        System.out.println("The computer chose " + computerChoice + ".");

        RockPaperScissors.GameOutcome outcome = model.getGameOutcome(
                playerChoice, computerChoice);

        if (outcome == RockPaperScissors.GameOutcome.WIN) {
            System.out.println("You won! Congratulations");
        } else if (outcome == RockPaperScissors.GameOutcome.LOSE) {
            System.out.println("You lose! Better luck next time!");
        } else {
            System.out.println("Tie!");
        }

        System.out.print("Do you want to play again? (Yes/No):");

        String answer = scan.next();
        if (answer.equalsIgnoreCase("no")) {
            break;
        }
    }

    System.out.println("Thanks for playing!");
    System.out.println("Wins: " + model.getWins());
    System.out.println("Losses: " + model.getLosses());
    System.out.println("Ties: " + model.getTies());
    scan.close();
}

public static enum GameOutcome {
    WIN, LOSE, TIE;
}

public GameOutcome getGameOutcome(String userChoice, String computerChoice) {

    if (userChoice.equalsIgnoreCase("Rock")) {

        if (computerChoice.equalsIgnoreCase("Paper")) {
            losses++;
            return GameOutcome.LOSE;
        } else if (computerChoice.equalsIgnoreCase("Scissors")) {
            wins++;
            return GameOutcome.WIN;
        }
    } else if (userChoice.equalsIgnoreCase("Paper")) {

        if (computerChoice.equalsIgnoreCase("Scissors")) {
            losses++;
            return GameOutcome.LOSE;
        } else if (computerChoice.equalsIgnoreCase("Rock")) {
            wins++;
            return GameOutcome.WIN;
        }
    } else if (userChoice.equalsIgnoreCase("Scissors")) {
        if (computerChoice.equalsIgnoreCase("Rock")) {
            losses++;
            return GameOutcome.LOSE;
        } else if (computerChoice.equalsIgnoreCase("Paper")) {
            wins++;
            return GameOutcome.WIN;
        }
    }
    ties++;
    return GameOutcome.TIE;
}

public String getRandomChoice() {
    double d = Math.random();

    if (d < .33) {
        return "Rock";
    } else if (d < .66) {
        return "Paper";
    } else {
        return "Scissors";

    }
}

public int getWins() {
    return wins;
}

public int getLosses() {
    return losses;
}

public int getTies() {
    return ties;
}

}

A: Keep the valid choices in a list, loop asking the input from the user until he enter something valid.
List<String> validChoices = Arrays.asList("rock", "paper", "scissors");
Scanner sc = new Scanner(System.in);
String choice = null;
do
{
    System.out.println("Enter a choice (rock|paper|scissors)");
    choice = sc.next().toLowerCase();//Retrieve as lower case
}
while(!validChoices.contains(choice));

A: If I were to play a session of roshambo against the computer, I'd like to be able to make my selection by only typing in the first letter of "Rock" , "Paper" or "Scissors".
Using a rich enum is a natural choice here:
private enum Choice {

    ROCK ("Rock"),
    PAPER ("Paper"),
    SCISSORS ("Scissors");

    private String displayName;

    private static final List<Choice> VALUES =
            Collections.unmodifiableList(Arrays.asList(values()));
          private static final int SIZE = VALUES.size();
    private static final Random RANDOM = new Random();

    private Choice(String dn) {
        displayName = dn;
    }

    /**
     * Returns a random Choice.
     */
    public static Choice getRandomChoice() {
        return VALUES.get(RANDOM.nextInt(SIZE));
    }

    /**
     * Returns a Choice that matches the input string. The input is considered a match if it starts with the same character
     * as the displayname of a Choice. If no match is found, returns null.
     */
    public static Choice fromInput(String input) {

        if (input == null || input.length() == 0) {
            return null;
        }

        for (Choice c : VALUES) {
            if (Character.toLowerCase(c.displayName.charAt(0))
                    == Character.toLowerCase(input.charAt(0))) {
                return c;
            }
        }
        return null;
    }

    /**
     * Returns the text to display to the user, asking for input to #fromInput().
     */
    public static String promptText() {
        StringBuilder sb = new StringBuilder();
        for (Choice c : VALUES) {
            if (sb.length() > 0) {
                sb.append(", ");
            }
            sb.append(c.displayName).append(" (")
                    .append(c.displayName.charAt(0)).append(")");
        }
        sb.append(". Pick one!");
        return sb.toString();
    }
}

Having most of the functionality coded declaratively in the enum, your client code will become much simpler. The enum also handles the computer's random selection (idea from this answer).
 while (true) {

        Choice choice = null;

        while (choice == null) {
            System.out.println(Choice.promptText());
            choice = Choice.fromInput(scan.next());
        }

        String computerChoice = Choice.getRandomChoice().displayName;
 // ...

You could also encapsulate most (if not all) of the logic you have in the getGameOutcome method, into Choice.

A: Somesing like
if (!playerChoise.equalsIgnoreCase("paper") && ...) continue;

Or you can store valid choises in list as shown above, and use foreach loop. But it will be more difficult, becouse you need to check all variants. Maybe something like.
private boolean checkValid(String userChoise, String... variants) {
    for (String s : variants) {
        if (playerChoise.equalsIgnoreCase(s)) return true;
    }
    return false;
}

And call it for both cases:
if (!checkValid(userChoise, "rock", "papper", "scissors")) continue;


text:
Q: Sampling population U to rank elements of another population S I have two sets of locations(lat/long pairs), U and S. I have to count
how many elements of U fall within a 10 mile radius of each location
in S i.e. construct a circle of radius 10 miles at each of the
location in set S and count how many elements of U fall within those
circles. This is to be done so that I can determine the top 100 most
dense locations in S.
Problem is that this count will take a very long time if I brute force
it. I don't have a lot of compute power available to me. U has 100
million entries while S has 1 million entries. It takes about 25 hours
for 1000 locations of S i.e. entire U and only first 1000 entries of
S.
Set U is comprised of data collected over an entire month (30 days). I
plan to take 10,000 samples from each of the day (uniform random
selection) to get a 300,000 subset of U and do the count for all the
entries in S. Now if I take the top 200 locations found in this way,
what is the chance that this set will contain the actual top 100 dense
locations? The reason I want to take 200(or more) locations is to
compensate for sampling and other approximations.
Needless to say I don't have a formal training in statistics. I just
want to use a sample to find a smaller set of locations that might
contain the most dense locations to a high degree of likelihood.
Questions:
Will this work?
How should I estimate the sample size? Is 10,000 samples per day
enough? More samples mean more compute time, so there is a trade-off
here.
What topics should I investigate in the field of statistics to gain
more understanding of how to solve this problem?
Comments:
I am not bothered with overlap of counts at the moment.
I suspect the title question does not make much sense to a statistics savvy reader.


text:
Q: Inertia without gravity Is there inertia in absence of gravity? If I was in a region of space with zero gravity, would I have to apply some force to accelerate a massive body?

A:
Is there inertia in absence of gravity?

Inertia is just another word for mass.
So yes, there is mass in absence of gravity.

If I was in a region of space with zero gravity, would I have to apply some force to accelerate a massive body?

Yes, of course.
This it what Newton's second law says:
$$\vec{F}=m\vec{a}$$
You need a force to accelerate a mass.
This law is independent of gravity.
Gravity is just one possible cause of a force.
But there are many other possible causes for a force.

A: Inertia is a property of mass, and it exists in the absence of gravity and you would have to apply a force to accelerate a body even if the object is massive.

A: Every answer here is wrong. Inertia and gravity are NOT independent, they are two aspects of the same phenomena. You cannot have one without the other (or without mass, which again is another way of looking at the same phenomena).
In your hypothetical scenario, the massive body in question would necessarily have its own gravitational field so there couldn't be 'zero gravity'. If there were no gravitational field then the body could not have mass, in which case it couldn't be accelerated because it would always be traveling at $c$.


text:
Q: How to find out the length of an array? std::string array[] = { "one", "two", "three" };

How do I find out the length of the array in code?

A: You can use std::begin and std::end, if you have C++11 support.:
int len = std::end(array)-std::begin(array);
// or std::distance(std::begin(array, std::end(array));

Alternatively, you write your own template function:
template< class T, size_t N >
size_t size( const T (&)[N] )
{
  return N;
}

size_t len = size(array);

This would work in C++03. If you were to use it in C++11, it would be worth making it a constexpr.

A: Use the sizeof()-operator like in
int size = sizeof(array) / sizeof(array[0]);

or better, use std::vector because it offers std::vector::size().
int myints[] = {16,2,77,29};
std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );

Here is the doc. Consider the range-based example.

A: C++11 provides std::extent which gives you the number of elements along the Nth dimension of an array. By default, N is 0, so it gives you the length of the array:
std::extent<decltype(array)>::value

A: Like this:
int size = sizeof(array)/sizeof(array[0])


text:
Q: Chorded keyboards for programming I am trying to find a chorded keyboard layout that is a good fit for programmers. I do a lot of work in emacs & screen on languages like c, c++, python and node.js so they all have a similar "ends in semicolon" style.
I have found many chorded layouts but no layouts that really focus on programming. Is it possible that the addition of the special characters makes the charset to large to chord?
If I can find one that suits my needs I am making an ergonomic keyboard with trackball that way I can sit in a normal spine position and not put my chair on plywood to match my desk height all day...

A: I can't really tell if this is a question about ergonomics or something else. I'm sure you know that a lot of people who keyboard a lot like Dvorak because of reduced finger movement. Have you tried it.
I use this keyboard for it's physical adjustability but each key is actually 100% programmable, too, so that may get you what you need.
http://www.fentek-ind.com/Comfort-keyboard.htm#.Vti1yPkrIgs


text:
Q: How postgresql return a data set like the follows? Just like the below function. I don't know how to return a set of inside parameter in postgresql?
create or replace function g_i(num int)
returns setof integer
as $$
declare
    i int;
begin
      while i < $1 loop
        select i; -- How to write statements here?
    end loop;
end;
$$ language plpgsql;

A: create or replace function g_i(num int)
returns setof integer
as $$
declare
    i int;
begin
        i := 0;
      while i< $1 loop
        i := i+1;
        return query select i;
    end loop;
end;
$$ language plpgsql;


text:
Q: Eclipse feature to arrange a class file? Eclipse has tons of features, i'm wondering if this one exsists? Or if any shortcut ways of doing it exist?
I want to arrange my class data into Variables, Constructors, Methods in that flow(Top to Bottom)
Further refined I would like to arrange by access level(pub, private, protected) and type - void or methods that return. The same for Vars - access level and type.
Any ideas. I mean I try to keep my code as tidy as possible. But would be nice to kind of format a class that perhaps I havent written that is messy.

A: If you go the preferences screen and then go to Java -> Appearance -> Members Sort Order you can configure the sort order for members.
Next just right click when you have a file open and go to Source -> Sort members

A: Under Preferences choose Java -> Appearance -> Members Sort Order. This allows you to set the order of members within a class when you use the Sort Members action.


text:
Q: Error type 'Null' is not a subtype of type 'Timestamp' I am setting the current date in firebase and trying to retrieve it to use as a reference. But somehow the results vary. Sometimes I'm having a null value but sometimes it's okay. I tried to add a delay command but it is still behaving the same. Please help. Thanks!
        //set current date
        await db.collection(Paths.playersPath).doc(uid).set({
          'currDate': FieldValue.serverTimestamp(),
        }, SetOptions(merge: true));

        DocumentSnapshot<Map<String, dynamic>> documentSnapshot =
            await db.collection(Paths.playersPath).doc(uid).get();

        Timestamp currDate = documentSnapshot.data()!['currDate'];

Edit: I'm not really sure if it is connected but I have 2 methods that call the same logic. One is under a HookWidget which almost always fail and another in StatefulWidget which never have a problem.
Edit: I don't really know why. But when I move the event which update the current date to a Stateful Widget, it is now working. Hopefully someone can clarify this.

A: Can you try this:
db.collection(Paths.playersPath).doc(uid).get().then((value) => value.data()!['currDate']);
You can also try to chain then with db.collection(Paths.playersPath).doc(uid).set if still not working


text:
Q: Eclipse code editor colour schemes Is there an Eclipse equivalent of http://studiostyl.es/ or some other way to set code editor colour schemes.

A: First answer on Google: http://eclipsecolorthemes.org/
So I guess the answer is yes.


text:
Q: Where do you find each of the pouch expansions? Since you get a few through the main story (but not enough for each character), where can you find the rest of the pouch expansions?

A: There are six in total that you can find (one for each party member throughout the game). Here is where you get each of them:

*

*You'll receive this one in the main story during chapter 2 from

 killing Dughall.

*You'll receive this one in the main story during chapter 6 from

 killing Giga Rosa.

*After the story event in the bandit cave in Gormott, you'll find this in a chest.

*
 When you've been to Leftheria, you can skip travel to Godford Isle, turn around and drop onto the moving platform. It will pass by one platform that has a collection node, but when you go farther north you'll find another platform with a chest on it containing the 4th expansion.

*
 At the end of Spirit Crucible Elpys (in the Vault of Heroes area, underneath the staircase), you can find the 5th expansion. This one will require a skill check.

*
 When you can access the Beruf Industry Ward in Mor Ardain (NE, Alba Cavanich) you can ride a moving cargo container to a cliff off to the side. There is a key obtained by doing the quest We Meet Again which is required to access the factory.

source
Why are there 6 instead of 5 (the number of party slots you have)?

 Vandham dies, so just in case you used one on him, you can still get an additional one later.


text:
Q: Position image similarly throughout all resolutions I have kinda complex situation here (at least complex for me). Attached a fiddle to show how I was trying to accomplish this.
I wanted to position the speech bubble in the center of the black line of the yellow image. (shown in fiddle).
Also, when I go down to smaller devices the text flows beneath the speech bubble. (you can re-size the window and see)
All of these must be shown at a 100 vh height meaning, users need not scroll to see the bubble as well as image.
Fiddle Link to show what I was doing

Heading

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

Heading

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

Heading

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

A: Try this code:

.bubble {
  position: relative;
  z-index: 1;
  /*width: 80%;*/
  height: auto;
  /*    margin-left:12.5%;*/
  padding: 5%;
  background: #2e3c6f;
  -webkit-border-radius: 15px;
  -moz-border-radius: 15px;
  border-radius: 15px;
  color:darkgrey;
}

.bubble:after {
  content: '';
  position: absolute;
  border-style: solid;
  border-width: 32px 21px 0;
  border-color: #2e3c6f transparent;
  display: block;
  width: 0;
  z-index: 1;
  margin-left: -10.5px;
  bottom: -32px;
  left: 50%;
}

.about_bg {
  width: 100%;
  height: auto;
}

#about_container {
  height: 100vh;
  margin-top: 2.5%;
}

#row_about_1 {
  height: 80vh;
}

#row_about_2 {
  height: 20vh;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

Heading

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

Heading

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

Heading

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

Solution:
1) To set bubble arrow in center:
--> Added position absolute and left value 50%, then added margin-left 10.5% (it's the half width of arrow)
2) Overlapping content:
--> Set bubble height auto (which was 80% previously), now when you'll resize browser it'll not get disturbed.

A: You probably wanted more fluid solution but with media queries you can adjust image size and position bubble from bottom on larger screens. Just add one more step, eg. on screens > 1200px.
To avoid overflowing I would keep min-height of container...

.about-container {
 height: 100vh;
 min-height: 580px;
}

.about-container .wrap {
 position: relative;
 height: 100%;
}

.bubble {
 background: #2e3c6f;
 color: #fff;
 position: absolute !important;
 bottom: 150px;
 left: 0;
 padding: 30px;
 border-radius: 15px;
 z-index: 1;
}

.bubble:after {
 position: absolute;
 content: '';
 top: 100%;
 left: 50%;
 height: 0;
 width: 0;
 border: solid transparent;
 border-top-color: #2e3c6f;
 border-width: 30px;
 margin-left: -30px;
}

p:last-child {
 margin-bottom: 0;
}

.about-img {
 position: absolute;
 bottom: 0;
 left: 0;
 right: 0;
 margin: 0 auto;
 max-width: 320px;
 height: auto;
}

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

Heading

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

Heading

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

Heading

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s


text:
Q: Unable to create oauth client ID (google developer console) I am including sign in via google functionality in my app, for which i had created oauth client id keys for both of my debug and release mode, but since everything was not working properly so, i thought of deleting and re-creating it again, so i deleted both the keys but now when i trying to create the new keys it gives me error  as
 Duplicate fingerprint

The fingerprint you specified is already used by an Android OAuth2 client ID in this project or another project

but i had deleted both the key's, i had tried all the solution that are already present in stack overflow, like going into the old console portal etc. but none is helping me out,please help me with the issue

A: Did you try to go to your API console and UNDELETE your old projects? When you delete a project in the API console, the oauth IDs associated with it seems to not get deleted with it. I undeleted every single one and went through them and removed all associated APIs. Once I cleared out the past projects, I re-deleted them and added the oauth again to my new/safe project and it was OK.
Your problem seems to be little different, so you can look for different solutions here, as it's a common problem:
https://code.google.com/p/google-plus-platform/issues/detail?id=554


text:
Q: Short-story about a boy's obsession with a video game about war I have been searching for so long now for the title of a short-story I read in the late 1990s, I think. Possibly early 2000s. The plot goes along something like this. There is a boy, I think he may have just recently graduated from college. He starts to play a computer game. It is a war game that he has to program the correct amount of weapons to use to be able to win the war.
He becomes obsessed with the game as he just can't work out what the answer could be and he tries a multitude of numbers. I think he has a girlfriend that ends up walking out on him due to his obsession. His world falls apart around him because of the game (it may or may not actually be real but I could be confusing that with Ender's Game). It turns out that the correct answer is zero because there are (surprise surprise) no winners in war.
I thought this was a Stephen King short story but I have trawled through the list of every SK short story ever written and I cannot find it anything that even closely resembles this one. It's not the movie/book WarGame.


text:
Q: Superslides resizes images to big I seem to run into an issue that didnt excist before today with some code. While the jquery script of superslides works normally fine, we got a message today that our site looked weird, so I went and checked it. It seems the resizing of the images in our superslides slider are all of the sudden done wrong and it causes the images to move out of its area and not hidden in the overflow.
It assigns a wrong height variable to the height of the image, except when i resize it in width, than it fixes. Whenever I resize in height, it fails again.
So I wondered what happened, and checked if there were modifications done. None happened, and I checked on the test server where I run a different version of the website, and I know should work fine, but it had the same problem. I cross checked browser to see if it was a browser problem, no luck.
Now after some deducting and testing I figured it has to do with the variable stated as following.
.... some code ..... <-- line 117 in jquery.superslides.js
} else {
      $('body').css({
        margin: 0
      });

      that.$el.css({
        position: 'relative',
        overflow: 'hidden',
        width: '100%',
        height: that.height
      });

For some odd reason, that (which is technically a this since its defined as  var that  = this;) doesn't calculate the height of div but just spits out a number I cant even figure out. The same happens to the image, so my question is, where does it go wrong?
I removed the superslides temporarly from my site, but the issue is at hand as well on our test domain and on my personal testing space, for some odd reason, since it worked all perfectly just a few days ago.
See it at hand here: http://test.thewebfanatics.com/jellyweb

A: Superslides uses by default $(window).height() which fails in your case.
Either you could inject another object that has the correct size OR you could just fix $(window).height() as read here:

With no doctype tag, Chrome reports the same value for both calls.
Adding a strict doctype like <!DOCTYPE html> causes the values to work as advertised.


text:
Q: Ubuntu issues after updating Ruby I'm trying to install beef framework on my Ubuntu 14.04.
I'm getting the error :
Gem::InstallError: public_suffix requires Ruby version >= 2.0.
An error occurred while installing public_suffix (2.0.5), and
Bundler cannot continue.
Make sure that `gem install public_suffix -v '2.0.5'` succeeds before
bundling.

I've tried to install ruby 2.4.0 and it worked and i used it using rvm :
root@XBuffer:/usr/share/beef-xss# rvm use ruby-2.4.0rvm
Using /usr/local/rvm/gems/ruby-2.4.0

But I'm still getting the same error while using bundle install
I've tried even to manually install public_suffix :
root@XBuffer:/usr/share/beef-xss# gem install public_suffix -v '2.0.5'
Successfully installed public_suffix-2.0.5
Parsing documentation for public_suffix-2.0.5
Done installing documentation for public_suffix after 0 seconds
1 gem installed

But I still get the same exact error.
I'm really stuck at this and I've tried a lot of other solutions based on some researches.


text:
Q: Manipulate regex variable after a pattern match Search Regex expression is:
_(01|02|03|04)_

Replace expression is:
_$1_

Result is:
_01_/_02_/_03_/_04_ (depending on the match)

How do I manipulate the variable so it strips away the 0 to return a single digit:
_1_/_2_/_3_/_4_

?

A: Make the match be: 0(1|2|3|4) and the replacement be $1.


text:
Q: R - How to apply terms from training document-term-matrix (dtm) to test dtm (both unigrams and bigrams)? I am training a simple text classification method on 1,000 training examples and would like to make predictions on unseen test data (about 500,000 observations).
The script is working fine, when I work only with unigrams. However, I am not sure how to use control = list(dictionary=Terms(dtm_train_unigram)) when working with unigrams and bigrams as I have two separate document-term-matrices (one for unigrams, one for bigrams, see below):
  UnigramTokenizer <- function(x) unlist(lapply(NLP::ngrams(words(x), 1), paste, collapse = " "), use.names = FALSE)
  dtm_train_unigram <- DocumentTermMatrix(processed_dataset, control = list(tokenize = UnigramTokenizer, wordLengths=c(3,20), bounds = list(global = c(4,Inf))))

  BigramTokenizer <- function(x) unlist(lapply(NLP::ngrams(words(x), 2), paste, collapse = " "), use.names = FALSE)
  dtm_train_bigram <- DocumentTermMatrix(processed_dataset, control = list(tokenize = BigramTokenizer, wordLengths=c(6,20), bounds = list(global = c(7,Inf))))

To ensure that the test set has the same terms as the training set, I use the following function:
corpus_test <- VCorpus(VectorSource(test_set))
dtm_test <- DocumentTermMatrix(corpus_test, control = list(dictionary=Terms(dtm_train_unigram), wordLengths = c(3,20)))

How do I feed the terms of both the dtm_train_unigram and the dtm_train_bigram to the dtm_test?

*

*Can I combine dtm_train_unigram and dtm_train_bigram to a single dtm after creating them separately (as currently done)?

*Can I simplify my two-step Tokenizer function so I only create a single
dtm with unigrams and bigrams in the first place?

Thank you!

A: Answering your questions:
Official documentation of tm states the following for combining things.:

Combine several corpora into a single one, combine multiple documents
  into a corpus, combine multiple term-document matrices into a single
  one, or combine multiple term frequency vectors into a single
  term-document matrix.

which in your case would be the answer to 1:
my_dtms <- c(dtm_train_unigram, dtm_train_bigram)

But it does result in doubling the number of documents which is actually not the case.
So we come to point 2, you can create a tokenizer from the NLP package that handles more than just 1 instance of n-gram:
my_tokenizer <- function(x) unlist(lapply(NLP::ngrams(words(x), 1:2), paste, collapse = " "), use.names = FALSE)

note the vector 1:2 ngram function. Change this to 1:3 for 1, 2, 3 grams or 2:3 for just 2 and 3 grams.


text:
Q: Use regex to add empty groups I'm a beginner python programmer. I'm trying to use a regular expression to build groups to append to a list. I'm not sure whether what I want to do can be covered with a single regex, or if I need to pass the text through more than one regex.
Test data:
yada yada 0.003 40 40.00
yadayada ya 55
yaaaaaaya 100.0000 4
My regex:
(\w+ *\w* *\w*) (\d*\.*\d*) *(\d*\.*\d*) *(\d*\.*\d*)\n

The groups that I get:
'yada yada','0.003','40','40.00'
'yadayada ya','55',empty,empty
'yaaaaaaya','100.0000','4',empty
BUT the groups that I want are:
'yada yada','0.003','40','40.00'
'yadayada ya',empty,empty,'55'
'yaaaaaaya',empty,'100.0000','4'
Is it possible to change the regex to introduce empty (\d*.*\d*) groups into those lines that have less than 3 of those groups? So that the number groups are "right-justified"?
I tried to add ? to the end of the first two (\d*) groups, but get the same empty groups.

A: The simplest way to perform what you are colloquially describing as "right-justifying" the matches, i. e. prioritize the matching of later optional subexpressions, is to reverse the "greediness" of the optional components. In Python regex, this is accomplished by adding ? to each quantified element:
(\w+ *\w* *\w*) (\d*?\.*?\d*?) *?(\d*?\.*?\d*?) *?(\d*?\.*?\d*?)\n

Note that your expression is quite liberal and will not validate certain poorly-formed input. If this works for you, great, otherwise you may want to consider sticking certain parts in optional groups, such as (| \d+(?:\.\d+)?) to lazily match a space and number, for example (the construct (|x) is equivalent to ((?:x)??)).
Edit: As Tim pointed out, the shortcomings of this regex entail more than just permissiveness and could invoke catastrophic backtracking if the input is even slightly malformed. I'd recommend something a little more precise if you plan to stick with this method:
(\w+(?: \w+){0,2}) (|\d+(?:\.\d+)?) ?(|\d+(?:\.\d+)?) ?(|\d+(?:\.\d+)?)\n

It can still match malformed input but at least it's a bit tighter now.

A: Your regex has several problems, one of which is a high risk of catastrophic backtracking because there is an exponentially growing number of permutations that the regex engine needs to test in non-matching cases. Another problematic thing is that \w will also match digits, so the first group may contain numbers you didn't want it to contain.
Furthermore, for such a "dynamically growing" regex, you'd need a "match continuation" feature like the \G or \K anchors, but Python does not support those.
The best way would be to .split() the string into substrings, then check each substring if it contains a number (for example by trying to convert it to a float) and behave accordingly.
Added bonus: You have a readable Python script instead of a very complicated regex.


text:
Q: Adding, Subtracting and Multiplying form input values Based on this post from here, JQuery multiply input values of table rows, i used the same form field names and added Tax field and Discount field.

            <input name="txtEmmail" class="val1"  />

            <input name="txtEmmail" class="val2"/>

            0.00

            <input name="txttax" class="val1"  />%

            0.00

This tax needs to be multiplied, like if i enter 10 (%)
var $tax = ($val1 * 1) * ($total * 1)/100;
$('.multTax', this).text($tax);

and then out put that as a tax amount
I changed the txttax class value as val3 and added the jquery like above
again, I need to subtract the discount, I tried all possible ways, but no luck.
this is the function (Edited)
$(document).ready(function () {
   $(".txtMult input").keyup(multInputs);
   function multInputs() {
       var mult = 0;
       $("tr.txtMult").each(function () {
           var $val1 = $('.val1', this).val();
           var $val2 = $('.val2', this).val();
           var $val3 = $('.val3', this).val();
           var $total = ($val1 * 1) * ($val2 * 1);
           var $tax = ($val1 * 1) * ($total * 1)/100;
           $('.multTotal', this).text($total);
           $('.multTax', this).text($tax);
           mult += $total;
       });
       $("#grandTotal").text(mult);
   }
});

Please advise. (spent the whole day)

A: jsFiddle solution
HTML

        <input name="txtEmmail" class="val1"  />

        <input name="txtEmmail" class="val2"/>

        0.00

        <input name="txttax" class="val3"  />%

        0.00

JS
    $(document).ready(function () {

   $("input").keyup(multInputs);
   function multInputs() {
       var mult = 0;
       $("tr.txtMult").not('.odd').each(function () {
           var $val1 = $('.val1', this).val();
           var $val2 = $('.val2', this).val();
           var $val3 = $('.val3', $(this).next()).val();

           var $total = $val1 * $val2;
           var $tax = $val3 * ($total / 100);

           $('.multTotal', this).text($total);
           $('.multTax', $(this).next()).text($tax);

           mult += $total - $tax;
       });

       $("#grandTotal").text(mult);
   }
});


text:
Q: Download an old version of Google App Engine SDK Where can I find for download an old GAE SDK, say 1.9.15 ? I need to find out coverage and maybe use 3rd party API, which do not work well with the recent version.

A: It depends if the respective SDK is still officially supported or not. Both kinds are available in the appengine-sdks GCS bucket.
No longer supported SDKs (like the 1.9.15 one you're seeking) are available in the deprecated folder. Note that they may be under a subdirectory named as the version number without the dots, i.e. 1915 for 1.9.15).
Still supported SDK versions are available in the featured folder.


text:
Q: How get the color format in Opencv? In C++, how can I get the color format (RGB or BGR for example), from an object cv::Mat or cv::IplImage?

A: The image type is not part of the image specification in OpenCV.
The user needs to know and track the actual color format.
In most cases, this is not a problem since ultimately the format of the source of the image is known.
As a rule of thumb, most RGB image sources (webcams, files etc.) are represented as BGR, but you should check your particular domain.


text:
Q: Replace css when element is visible I have a right arrow that when clicked shows the hidden left arrow. There is text centered between the two arrows so the margin changes on the centered text when both arrows are visible so I removed the css styling on #completeList and am trying to add the css with JQuery. Here is the code that I am trying:
$('#completeList').css('margin-left', '44%');
if ($('#leftArrow').is(':visible')) {
$('#completeList').css('margin-left', '32%');
}

The shortened html is:

The problem I am having is the 44% margin-left is not changing to the 32% margin-left when $('#leftArrow') is visible.
Is the jQuery i used a viable solution or should I be looking for another way?

A: You can try positioning the arrows absolutely. This removes the arrows from the context of the surrounding elements and allows them to be positioned relative to the parent
 without affecting the adjacent text.
p {
    position: relative;
    padding: 0 20px; /* Leave enough space for an arrow on each side*/
}
#leftArrow,
#rightArrow {
    position: absolute; /* position the arrows absolutely */
}
#leftArrow {
    left: 0;
}
#rightArrow {
    right: 0;
}

A: You don't spell #completeList the same in both your statements.
$('#completeList').css('margin-left', '44%');
if ($('#leftArrow').is(':visible')) {
$('#completList').css('margin-left', '32%');
}

Try this:
$('#completeList').css('margin-left', '32%');


text:
Q: Getting values from database , then putting it in new Array with JS I'm new here , so basically what i'm trying to do , i need to take the values from database and put those values in one Array, see below my PHP:
    <?php
$db = mysqli_connect('localhost', 'krissko0o', 'krisko0o', 'KISP');
$sql = "SELECT * FROM products ORDER BY productName ASC";
$rsd = mysqli_query($db, $sql);
while($rs = mysqli_fetch_assoc($rsd)) {
    $id = $rs['id'];
    $productName = $rs['productName'];
    $quantity = $rs['quantity'];
    $litres = $rs['litres'];
    $type = $rs['type'];
    $singlePrice = $rs['singlePrice'];
}
?>

My array:
var arrValues = new Array('<?php echo $id; ?>~~~~~~~~<?php print $productName; ?> - <?php print $litres; ?>~~~~~~~~~~~~~~~~~~~~~~~~~~<?php print $quantity; ?>~~<?php print $type; ?>~~~~~~~~<?php print $singlePrice; ?>');

in this case the output code i want to receive is something like:
var arrValues = new Array('0001~~~~~~Кока Кола - 0.25 l.~~~~~~~~~~~~~~~~~~~~~~~~~~24~~каса~~~~~~~~0.71','0003~~~~~~Кока Кола - 0.5 l.РЕТ~~~~~~~~~~~~~~~~~~~~~~~~12~~стек~~~~~~~~1.09','0033~~~~~~Спрайт - 0.5 l.РЕТ~~~~~~~~~~~~~~~~~~~~~~~~~~~12~~стек~~~~~~~~1.09','0043~~~~~~Швепс Тоник - 0.5 l.РЕТ [недост.]~~~~~~~~~~~~12~~стек~~~~~~~~1.09','0053~~~~~~Сода Кинли - 0.5 l.РЕТ~~~~~~~~~~~~~~~~~~~~~~~12~~стек~~~~~~~~0.78','0112~~~~~~Ред Бул - 0.355 l.~~~~~~~~~~~~~~~~~~~~~~~~~~~24~~стек~~~~~~~~2.93','0305~~~~~~Капи Праскова Бут. - 0.25 l.~~~~~~~~~~~~~~~~~24~~каса~~~~~~~~0.79','0320~~~~~~Капи Ябълка Бут. - 0.25 l.~~~~~~~~~~~~~~~~~~~24~~каса~~~~~~~~0.79','0328~~~~~~Капи Банан - 1 l.*6 [недост.]~~~~~~~~~~~~~~~~6~~~стек~~~~~~~~2.27','0355~~~~~~Капи Вишна Бут. - 0.25 l.~~~~~~~~~~~~~~~~~~~~24~~каса~~~~~~~~0.79','1000~~~~~~Загорка РЕТРО БУТ. - 0.5 l.~~~~~~~~~~~~~~~~~~20~~каса~~~~~~~~1.08','1061~~~~~~Каменица св. БУТ. - 0.5 l.~~~~~~~~~~~~~~~~~~~20~~каса~~~~~~~~1.04','1068~~~~~~Наливно пиво Каменица - 30 l.~~~~~~~~~~~~~~~~30~~кег~~~~~~~~~2.17','1079~~~~~~Stella Artois БУТ. - 0.5 l.~~~~~~~~~~~~~~~~~~20~~каса~~~~~~~~1.37','10851~~~~~Шуменско БОМБИЧКА - 0.33l~~~~~~~~~~~~~~~~~~~~20~~каса~~~~~~~~0.70','1161~~~~~~Старопрамен БУТ. - 0.5 l.~~~~~~~~~~~~~~~~~~~~20~~каса~~~~~~~~1.17','4695~~~~~~Мента Карнобат- 0.7 l.~~~~~~~~~~~~~~~~~~~~~~~1~~~бр.~~~~~~~~~6.01','9188~~~~~~Нестий Праскова - 0.5 l.~~~~~~~~~~~~~~~~~~~~~12~~стек~~~~~~~~0.94','91881~~~~~Нестий Лимон - 0.5 l.~~~~~~~~~~~~~~~~~~~~~~~~12~~стек~~~~~~~~0.94');

but instead , i'm getting this one:
var arrValues = new Array('11~~~~~~~~Бъз лимон - 0~~~~~~~~~~~~~~~~~~~~~~~~~~2~~~~~~~~~~0');
var arrValues = new Array('7~~~~~~~~Вишна - 0~~~~~~~~~~~~~~~~~~~~~~~~~~2~~~~~~~~~~0');
var arrValues = new Array('24~~~~~~~~Вишна - 0~~~~~~~~~~~~~~~~~~~~~~~~~~3~~~~~~~~~~0');
var arrValues = new Array('33~~~~~~~~Вишна - 0~~~~~~~~~~~~~~~~~~~~~~~~~~0~~~~~~~~~~0');
var arrValues = new Array('18~~~~~~~~Газирана вода - 0~~~~~~~~~~~~~~~~~~~~~~~~~~2~~~~~~~~~~0');
var arrValues = new Array('34~~~~~~~~Газирана вода - 0~~~~~~~~~~~~~~~~~~~~~~~~~~0~~~~~~~~~~0');
var arrValues = new Array('8~~~~~~~~Горски плод - 0~~~~~~~~~~~~~~~~~~~~~~~~~~2~~~~~~~~~~0');
var arrValues = new Array('25~~~~~~~~Горски плод - 0~~~~~~~~~~~~~~~~~~~~~~~~~~3~~~~~~~~~~0');
var arrValues = new Array('17~~~~~~~~Грейпфрут - 0~~~~~~~~~~~~~~~~~~~~~~~~~~2~~~~~~~~~~0');
var arrValues = new Array('12~~~~~~~~Грозде - 0~~~~~~~~~~~~~~~~~~~~~~~~~~2~~~~~~~~~~0');
var arrValues = new Array('10~~~~~~~~Див лимон - 0~~~~~~~~~~~~~~~~~~~~~~~~~~2~~~~~~~~~~0');
var arrValues = new Array('15~~~~~~~~Дюля - 0~~~~~~~~~~~~~~~~~~~~~~~~~~2~~~~~~~~~~0');
var arrValues = new Array('27~~~~~~~~Дюля - 0~~~~~~~~~~~~~~~~~~~~~~~~~~3~~~~~~~~~~0');
var arrValues = new Array('2~~~~~~~~Жълта лимонада - 0~~~~~~~~~~~~~~~~~~~~~~~~~~2~~~~~~~~~~0');
var arrValues = new Array('19~~~~~~~~Жълта лимонада - 0~~~~~~~~~~~~~~~~~~~~~~~~~~3~~~~~~~~~~0');
var arrValues = new Array('28~~~~~~~~Жълта лимонада - 0~~~~~~~~~~~~~~~~~~~~~~~~~~0~~~~~~~~~~0');
var arrValues = new Array('51~~~~~~~~Жълта лимонада - 2л~~~~~~~~~~~~~~~~~~~~~~~~~~24~~Стек~~~~~~~~0.25');

Any help with that please ? :) :D

A: I don't know what the code pieces 2-3 are or where they come from nor what you will do with that array, but i think in php you could do the following for getting the data in an array:
<?php
    $db = mysqli_connect('localhost', 'krissko0o', 'krisko0o', 'KISP');
    $sql = "SELECT * FROM products ORDER BY productName ASC";
    $rsd = mysqli_query($db, $sql);
    $arrValues = array();                               //will become a multidimensional array
    while($rs = mysqli_fetch_assoc($rsd)) {
        $tempArray = array(                             //one array per dataset
            "id" => $rs['id'],
            "productName" => $rs['productName'],
            "quantity" => $rs['quantity'],
            "litres" => $rs['litres'],
            "type" => $rs['type'],
            "singlePrice" => $rs['singlePrice']
        );
        array_push($arrValues, $tempArray);             //insert the dataset in the multidimensional array
    }
?>

If you want to get the data from php to js, it would be helpful to know on which way you want to get the data there (echo it in a script tag or send it as a response to an ajax request?)
Second part after the reply on my call back question in the comments
then of course you don't need a php array, just a long string:
<?php
    $db = mysqli_connect('localhost', 'krissko0o', 'krisko0o', 'KISP');
    $sql = "SELECT * FROM products ORDER BY productName ASC";
    $rsd = mysqli_query($db, $sql);
    $arrValues = '';
    while($rs = mysqli_fetch_assoc($rsd)) {
        $arrValues .= '"' .
            $rs['id'] . '~~~~~~~~' .
            $rs['productName'] . ' - ' .
            $rs['quantity'] . '~~~~~~~~~~~~~~~~~~~~~~~~~~' .
            $rs['litres'] . '~~' .
            $rs['type'] . '~~~~~~~~' .
            $rs['singlePrice'] .
        '", ';
    }
    echo '<script> var arrValues = [' . $arrValues . ']; </script>';
?>


text:
Q: How to estimate False Discovery Rate from p-value distribution? I have learned many models and I calculated p-values for the cross-validation errors. I want to select significant models based on the false discovery rate (FDR). How can I estimate the FDR from p-value distribution?

A: Generally speaking, the false discovery rate correction requires ranking your p-values and then computing a critical value (based on the false discovery rate) that you can compare to your p-values. This website gives a very concrete example: here.
If you're using R, then it's even easier to do the adjustment. The following code is a quick example:
pvals <- c(0.04, 0.03, 0.06, 0.01, 0.02, 0.003)
p.adjust(p = pvals, method = "BH")

In the above code, the object pvals is a list of the p-values that you obtained from your analyses. The function p.adjust provides several different options for adjusting p-values based on multiple observations. In this case, the false discovery rate adjustment can be done by specifying method = "BH" for Benjamin-Hochberg or method = "fdr" for false discovery rate (note: they are the exact same procedure and will give the exact same results).


text:
Q: Angular service return observable from callback function I'm using Angular 8.
In my service, I'm using a library which accepts callback function and gives value in the callback function.
My service method is
raw(qrInfo, res?): Observable<string> {

  return manager.getData(res.width, (res1) => {
    return of<string>(res1);
  });
}

I want to subscribe to this raw() method and get the result of res1 in the controller
constructor(
  private myS: MyService
) {}

data() {
  this.myS.raw(info, op).subscribe(res => {
    console.log(res);                              // Get value here
  }
}

But this is not working. How can I return observable from callback function?

A: You can create a new Observable inside your raw() method by following this  documentation to emit the callback result into your Observable.
raw(qrInfo, res?): Observable<string> {
  /** Returns the freshly created Observable **/
  return Observable.create(function(observer) {
    /** Call your method with the callback **/
    manager.getData(res.width, (res1) => {
      /** Emit the callback response to the Observable **/
      observer.next(of<string>res1)
      /** Complete the Observable to close it **/
      observer.complete();
    });
  });
}

A: You could create a Subject inside the MyService and then subscribe to it from your component.
managerData$ = new Subject<any>();

raw(qrInfo, res?): Observable<string> {

  manager.getData(res.width, (res1) => {
    this.managerData$.next(res1);
  });
}

And then in component:
constructor(
  private myS: MyService
) {
    this.myS.managerData$.subscribe((res) => { ... } );
  }

data() {
  this.myS.raw(info, op);
}

NOTE: If you need to unsubscribe from it, you can do it like this:
private managerDataSubscription: Subscription;

constructor(
  private myS: MyService
) {
    this.managerDataSubscription = this.myS.managerData$.subscribe((res) => { ... } );
  }

And then you can call this.managerDataSubscription.unsubscribe(); where ever you need (in ngOnDestroy for example)


text:
Q: C++11 regex_error - why? (code: 2) Why does this C++11 code throw a regex_error?
string s{R"((http)(s)?(:\/\/)(www\.)?([^ ]*))"};
regex r{s}; // throws regex_error

I've been looking all over the internet for correct escaping and I've tried multiple combinations, but I think my escaping is correct. What am I doing wrong?

A: GCC apparently does not really support regular expressions yet.
See the status page: http://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html
As suggested by comments, you may be best off using boost for now. Clang with libc++ already has regexes too.


text:
Q: nestJs FileInterceptor and DTO I want to create upload with swagger,use DTO and save the binary in my MongoDB
My DTO is:
import { ApiProperty } from '@nestjs/swagger';
import { Expose } from 'class-transformer';
import { IsNotEmpty, IsOptional } from 'class-validator';

export class GatewayDto {

  @ApiProperty({ default: 'foo' })
  @IsNotEmpty()
  @Expose()
  name: string;

  @ApiProperty({default: 'XXXX:YYYY'})
  @IsNotEmpty()
  @Expose()
  token: string;

  @ApiProperty({default: '123'})
  @IsNotEmpty()
  @Expose()
  channelId: string;

  @ApiProperty({ default: true })
  @IsNotEmpty()
  @Expose()
  public: string;

  @Expose()
  @IsNotEmpty()
  logo: any;

}

my controller is:

 @Post('/')
    @ApiConsumes('multipart/form-data')
    @ApiBody({
        schema: {
            type: 'object',
            properties: {
                name: {
                    type: 'string',
                    default: 'foo'
                },
                token: {
                    type: 'string',
                    default: '11:22'
                },
                channelId: {
                    type: 'string',
                    default: '1234'
                },
                public: {
                    type: 'string',
                    default: 'true'
                },
                logo: {
                    type: 'string',
                    format: 'binary',
                },
            },
        },
    })
    @UseInterceptors(FileInterceptor('logo'))
    @HttpCode(HttpStatus.CREATED)
    @ApiCreatedResponse(GatewayConfigSwagger.API_CREATE_GATEWAY)
    //@Serialize(GatewayDto)
    public async create(
        @UploadedFile('file') file,
        @Body() data: GatewayDto,
        @Request() request
    ) {
        console.log(data);

        if (file) {
            data['logo'] = file.buffer;
        }
        //return this.gatewayService.create(request.user.userId._id, data);
    }

When I create my request, I get this error:
"logo should not be empty"
My curl is:
curl -X 'POST' \
  'http://localhost:3001/api/v1/gateways' \
  -H 'accept: application/json' \
  -H 'Authorization: Bearer xxx \
  -H 'Content-Type: multipart/form-data' \
  -F 'name=foo' \
  -F 'token=11:22' \
  -F 'channelId=1234' \
  -F 'public=true' \
  -F 'logo=@image.png;type=image/png'

If I remove the logo field from DTO I'm able to store my image.
I tried to create a interceptor according to this answer File uploading along with other data in Swagger NestJs

import { BadGatewayException, CallHandler, ExecutionContext, Injectable, NestInterceptor, UnauthorizedException } from "@nestjs/common";
import { catchError, map, Observable, throwError } from "rxjs";

export interface Response<T> {
    statusCode: number;
    data: T;
}

@Injectable()
export class FileExtender implements NestInterceptor {
    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
      const req = context.switchToHttp().getRequest();
      console.log(req.body)

      return next.handle();
    }
  }

and my req.body doesn't have logo field
UPDATE
I updated my interceptor with
import { BadGatewayException, CallHandler, ExecutionContext, Injectable, NestInterceptor, UnauthorizedException } from "@nestjs/common";
import { catchError, map, Observable, throwError } from "rxjs";

export interface Response<T> {
    statusCode: number;
    data: T;
}

@Injectable()
export class FileExtender implements NestInterceptor {
    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
      const req = context.switchToHttp().getRequest();

      req.body['logo'] = req.file.buffer;
      console.log(req.body)

      return next.handle();
    }
  }

Now it works, but is it the best practice?

A: Try using the @IsOptional validator on the logo property in the DTO file. It is used to mark nullable fields. Validation will pass if it is null or undefined and will be enforced as per other validators otherwise. Application logic must handle this accordingly.
You can take a look at all available validators here. You can combine any number of them on any DTO class property.


text:
Q: Enumerating the shell with Next > 1 All sample codes anywhere on the net just don't question the habit of passing 1 as the first argument to an enumeration interface Next() call. Yet the documentation clearly promises that more than one items can be obtained in one call. As it can be seen in this code fragment, doing so would tremendously speed up the process of counting the files in a folder (actually, the fundamentally similar WPD interface works that way).
string FolderPath = @"::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\<Phone-USB-ID>\Internal storage\Pictures\Test";
SHCreateItemFromParsingName(FolderPath, IntPtr.Zero, typeof(IShellItem).GUID, out IShellItem item);
item.BindToHandler(IntPtr.Zero, BHID_SFObject, typeof(IShellFolder).GUID, out IShellFolder folder);
folder.EnumObjects(IntPtr.Zero, SHCONTF_FOLDERS | SHCONTF_NONFOLDERS, out IEnumIDList list);
uint count = 0;
try {
  do {
    //var ObjectIDs = new ObjectIDLargeArray();
    //var pidl = Marshal.AllocHGlobal(Marshal.SizeOf(ObjectIDs));
    //Marshal.StructureToPtr(ObjectIDs, pidl, true);
    //var pidl = Marshal.AllocCoTaskMem(100 * IntPtr.Size);
    int hr = list.Next(100, out var pidl, out uint fetched); // <<<<<
    if (hr == 0)
      count += fetched;
    if (fetched == 0)
      break;

    //Marshal.FreeHGlobal(pidl);
    Marshal.FreeCoTaskMem(pidl);
  }
  while (true);
}
catch (Exception e) {
  Console.WriteLine(e);
}

[StructLayout(LayoutKind.Sequential)]
internal class ObjectIDLargeArray {
  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)]
  public IntPtr[] IDs;
}

The documentation and the usage on the web is not entirely clear about whether the caller has to allocate the buffer for the IDs returned but as can be seen from the code, I tried all approaches, both a specific array and an allocated block of memory. For very small values like 2 and 3, the shell might simply return garbage in fetched. For anything larger, an access violation exception.
Just to put it into a perspective of why it's important: with a newly connected phone, no previous caching, counting the files in a folder of 500 pictures takes about 15 (!) seconds. The second time with data already cached, 3 to 4. Needless to say, even the second is unacceptable for a mere file count but 15 seconds are absolutely stupid. With the otherwise mediocre speeds of WPD but with a 100-step count, a few hundred ms at most.

A: Solved courtesy of the new C# 7.2 feature, in parameters:
internal interface IEnumIDList {
  [PreserveSig]
  [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
  HResult Next(uint celt, in IntPtr rgelt, out uint pceltFetched);
}

That makes it play all right with both the preallocated array and the single value case. It's not really that much faster, unfortunately...


text:
Q: How do I change the text of a span element in JavaScript? Basically, I can use this method only for image. The question is how can I use this method for text types.
Image Method:

A: There are several issues with your code.

*

*you are not initializing your text array, but attempting to fill it with data

*you are not filling the text of the a tag, but trying to change it's source.
this will work just fine:
Text Here

jsFiddle

A: Here's a thought, try  not using jQuery for every little thing.

 var el = document.getElementById("randomx");
var image = new Array();
image[0] = "TEXT1";
image[1] = "TEXT2";
image[2] = "TEXT3";
image[3] = "TEXT4";
var size = image.length
var x = Math.floor(size * Math.random())

el.src = image[x];       //set source
el.innerHTML = image[x]; //set link text


text:
Q: Evaulate and print keyboard input as a double This code is not working. For every year it prints amount as 0.00 instead of the result of the calculation
unsigned int counter;
double amount;
double principal;
double rate;
double year;

puts("Enter the principal, interest rate as a decimal and time in years, in that order:");
scanf("%f%f%f", &principal, &rate, &year);

for(counter = 1; counter <= year; ++counter){
    amount = principal * pow(1 + rate, counter);
    printf("Amount at the end of year %u is %.2f\n", counter, amount);

But when I make principal, rate and year of type float, it prints the correct values.
Why does changing the type to float work but double does not?

A: In printf %f is the correct format specifier for a double. since there is no format for a float, because if you try to pass a float to printf, it'll be promoted to double before printf receives it.
in scanf ,if you use %f means you want to read a float and %lf means you want to read a double. since your variables are double ,you should use %lf ,or it will cause undefined behavior ,because of wrong format specifier.

A: The printf/scanf format specifier "%f" expects a float.  But you are using double values. So use the correct format specifier, I suggest you look it up in the printf/scanf documentation.


text:
Q: nodejs control json name I've a function that gets 2 values name and value and now I'd like to turn them into a JSON, so for example lets say ive this function
function addin(name,val)

and then i'll call it
addin("age","28") -> this will return -> {age: 28}
addin("name","Roni") -> {name: Roni}

I've tried many things to find out how to make it done, Im getting many data so I tried this
var full_js = { };

    _.forEach(data, function(val,name) {

        full_js.name = val;
        console.log(JSON.stringify(full_js));

    });

again it can be any value and any name both of them are Random Strings.
but its not working, I get it as {"name": "Roni"} and {"name": "55"}.
thanks for the help.

A: use a different notation:
function addin(name, val) {
    var full_js = {};
    full_js[name] = val;

    return JSON.stringify(full_js);
}

Ex:

at the moment you are always assigning the value to the name key, instead of the dynamic name key, keep in mind that the key will always be the string representation of the variable used.
for example, addin({}, 'rony'), will return {"[object Object]":"test"}


text:
Q: MySQL Junction Table as Foreign Key? I have several tables: company, customer, company_has_customer, and transaction.
company_has_customer is a many-to-many junction table using the PKs of company and customer as its PK.
In almost all situations throughout the database, both the company and customer are used to identify a record (e.g. in the transaction table).
My question is whether I should create the foreign key in the transaction table to point to company_has_customer or to the two tables (company, customer) individually?
I believe it would be best for referential integrity to send those FKs through company_has_customer to ensure that transaction records are only inserted if there is a relationship between the company and the customer.  Are there any standards or conventions to support my hunch?
My second question is doing the lookup from transaction to the customer table if the FK is actually going through the company_has_customer table.  There would still be an index, but should I always have to join through the company_has_customer table?

A: It depends on what you want to enforce. If a transaction can take place between a customer and a company that is not in company_has_customer the individual foreign keys are preferable. If a transaction only can take place between a customer and a company that is in company_has_customer it is better to have a foreign key to that table.

A: I would suggest to use transaction table as warehouse table.because sometime two many references also cause low performance in getting data.
but if you are not in a production db situation which populate db with bulk data in seconds you can use those references and customers pk is important in transaction table.
your second part of question is look up from transaction to customer have nothing to do with company_has_customer this table is used when you want to know the customer belongs to which company.


text:
Q: How to change Ember-Data PUT request expected server response I am using
DEBUG: -------------------------------
DEBUG: Ember             : 1.12.1
DEBUG: Ember Data        : 1.13.4
DEBUG: jQuery            : 2.1.4
DEBUG: -------------------------------

My server API replies to PUT request with just an ID of updated object, example of this response:
{
  data:[123],
  meta{total:1},
  errors:[]
}

How to change ember-data configuration to allow such an object?
AFAIK ember-data expects whole sent object in a response.
Thanks
Resolution:
import DS from "ember-data";
export default DS.Store.extend({

    /**
     * @tampered _super
     * @param internalModel
     * @param dataArg
     */
    didSaveRecord: function (internalModel, dataArg) {
        var data;
        if (dataArg && dataArg.data && dataArg.data.id && dataArg.data.id !== 'undefined' && Ember.typeOf(dataArg.data.id) !== 'undefined') {
            data = dataArg.data;
        }
        if (data) {
            // normalize relationship IDs into records
            this._backburner.schedule("normalizeRelationships", this, "_setupRelationships", internalModel, internalModel.type, data);
            this.updateId(internalModel, data);
        }

        //We first make sure the primary data has been updated
        //TODO try to move notification to the user to the end of the runloop
        internalModel.adapterDidCommit(data);
    },

});

A: What serializer are you using? With JSON API you could try something along the lines of:
export default DS.JSONAPISerializer.extend({

  normalizeUpdateRecordResponse(store, clazz, payload) {
    payload.data = {
      id: payload.data[0]
    }
    return payload;
  }
})

There's more info here: http://emberjs.com/blog/2015/06/18/ember-data-1-13-released.html


text:
Q: Explanation of heterogeneity Following is the output of meta-analysis of five fictitious studies:
      OR           95%-CI %W(fixed) %W(random)
1 0.7037 [0.3963; 1.2495]      2.15      10.29
2 0.6047 [0.5166; 0.7079]     29.95      24.79
3 0.9097 [0.8001; 1.0343]     38.59      25.78
4 0.9696 [0.8285; 1.1348]     25.02      24.80
5 0.5872 [0.3831; 0.9000]      4.30      14.34

Number of studies combined: k=5

                         OR           95%-CI       z  p.value
Fixed effect model   0.8151 [0.7513; 0.8842] -4.9196 < 0.0001
Random effects model 0.7639 [0.6060; 0.9631] -2.2785   0.0227

Quantifying heterogeneity:
tau^2 = 0.0499; H = 2.44 [1.62; 3.68]; I^2 = 83.2% [61.8%; 92.6%]

Test of heterogeneity:
     Q d.f.  p.value
 23.81    4 < 0.0001

Details on meta-analytical method:
- Mantel-Haenszel method
- DerSimonian-Laird estimator for tau^2

How can you explain in layman terms what is heterogeneity and how above output is interpreted in terms of heterogeneity? What are acceptable values of $I^2$ and $\tau^2$? What is the meaning of p value <0.05 here?
Thanks for your help.


text:
Q: update cloudera quickstart vm to use java7 I'm new to Hadoop and I use the cloudera quickstart vm (Version: Cloudera Standard 4.7.2) to get familiar with Hadoop. I have made a java MRJ compiled to java 1.7, the cloudera vm runs on java 1.6, so I get an "Unsupported major.minor version 51.0" error. The MRJ needs to be java 1.7, therefor my question is, how can I get the cloudera vm to use java 1.7?
I have basic Linux skills (ubuntu), the cloudera vm runs on centos. I have already try'd to find a how to on google. Bud cant find what I need.

A: Cloudera Quickstart CDH 5.3 is now available which runs om java 1.7

A: I downloaded the latest 4.x VM from Cloudera, the file name says 4.7 but it actually contained 4.8.3 (at the time of my download):
https://downloads.cloudera.com/demo_vm/vmware/cloudera-quickstart-vm-4.7.0-0-vmware.7z
It contained /usr/java/jdk1.6.0_31. I installed jdk1.7.0_80 alongside it.
I then tried:

*

*changing the symlink /usr/java/default

*editing /etc/default/bigtop-utils as per http://www.cloudera.com/content/cloudera/en/documentation/cdh4/latest/CDH4-Installation-Guide/cdh4ig_topic_29_1.html

*moving /usr/java/jdk1.6.0_31 somewhere else and then making /usr/java/jdk1.6.0_31 a symlink to the new JDK

The last one is a dirty hack but it's the only one that worked for me.
There is probably a better way to do it though : )


text:
Q: Java Android apache poi error 'functionMetadata.txt' not found on release file In my android application, I use poi apache to create an excel file.
I got the library from this link.
In file build.gradle include the library:
dependencies {
  ...
  files('libs/poishadow-all.jar')
  ...
}

When I check a debug file I do not get an error.
But when I check a release file I get the next error:

resource 'functionMetadata.txt' not found

I noticed that this is somehow related to the following code:
float resSum = 15.12478;
cell.setCellFormula("ROUND(" + resSum + ", 2)");

The program crash in the line cell.setCellFormula("...formula...")
Thanks for helping.


text:
Q: Getting area of pentagon with some values missing I have a problem how to get the area from the picture.
Some ideas I got are not good enough to get the correct value of the whole element.

A: Hint: Draw straight lines between the upper left corner and the midline, and upper right corner and the midline. Now you have two rectangles and two triangles. Can you compute their areas?

A: You don't have enough data to compute the area (if 13.62 denotes the lenght of the basis as it seems on the OP figure). The area depends on the « balance » between the left and the right sides of the house. And this seems unknown from your picture.

A: Hint: You know the width is $13.62$, and the maximum height it reaches is $1.65$, so it must fit within a rectangle of those dimensions.

A: I asked someone and this answer will satisfy me


text:
Q: Process list of object by type I have a requirement to create a Sync method.
1) On input it takes SyncRequest object.
class SyncRequest{
    public List<SyncObj> Objects{get;set;}
}
class SyncObj{
    public Type Type{get;set;}
    public object Object{get;set;}
}

2) Based on type of each object i need to use different service to proceed and the different repository to persist the data.
I.e. if i got the 3 objects with types User, User, Task. I will group them by type, and then Proceed with UserService and TaskService.

I'm trying to architect my web.api with Onion Architecture. Where DataAccess, Core, Services are separated of each other. And i want avoid swich or if's, in my code.
All ideas i came up was ugly. For example Dicitionary<Type, Service>, and manual casting.
I feel that Ninject might have really beatifull answer on my problem, with some factory functionality, but i can't come up with it.
Can anyone describe how this pattern should work. Or how this pattern calls, where to read.

A: Since all you've got is a Type one way or another you're going to have to use Reflection. The other question is how you're accessing the DI container (ninject kernel).
You can do something like this:
public interface IHandler<T>
{
    void Handle(T obj);
}

public void UserService : IHandler<User> {...}

Bind<IHandler<User>>().To<UserService>();

which you would then use like this:
foreach(var syncObj in syncRequest.Objects)
{
    Type handlerType = typeof(IHandler<>).MakeGeneric(syncObj.Type);
    MethodInfo handleMethod = handlerType.GetMethod("Handle");

    object handler = kernel.Get(handlerType);

    handleMethod.Invoke(handler, new object[] { syncObj.Object });
}

As you see you'll need access to the container somehow to create the specific type. You can have it injected as IResolutionRoot.
To adhere to the Onion Layering you'll have to move the code that uses the kernel to the composition root and give it an interface...
Since you seem to know about onion layering i won't go into more detail :)


text:
Q: Django: Heroku buildpacks error? My Django App is being rejected by Heroku.
It says: App not compatible with buildpack. And gives a url for more info.
After visiting this URL and applying the "solution":
heroku buildpacks:set heroku/python

The problem continues. Had you similar problems?
This is my app (just Django):
https://github.com/OmarGonD/direlim27

EDIT 1:
These are my files after Heroku preparation (with Procfile, etc).