text:
Q: Child method is undefined for the type Base public class Base {
    public String Method1() {
        System.out.println("Inside Base method 1");
        return "";
    }
}
class Child extends Base {
    static Base o = null;
    public String Method1() {
        System.out.println("Inside Base method 1");
        return "";
    }
    public String Method2() {
        return "Cant be called with base reference";
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Base base = new Child();
        base.Method1();
        base.Method2();***(Error : **The method Method2() is undefined for the type Base**)***
    }
}

As the code suggests I want to know, What actually happens in memory allocation that hides Base from calling extra methods of Child and what it is called
And is there a way of calling methods via Base.
Please help

A: base.Method2() is invalid because Base class has no method with that name, that is the meaning of the error

The method Method2() is undefined for the type Base

since you are doing this:
Base base = new Child();

one option you have is casting, then you can call that method...
Base base = new Child();
base.Method1();
((Child) base).Method2();

A: You need to study more about how polymorphism works.
Your instance is a child, but you use it like a Base. Base knows nothing about his children, he only knows his methods.
Cast the instance to Child to acces their custom methods.
((Child)base).Method2()


text:
Q: Too many nested getContent calls error on button click to create and attach PDF to Record UPDATE:

I have updated my APex code to the following:
public class attachRecPDFToQuote {

    private final Quote q; //Quote object

    //constructor
    public attachRecPDFToQuote(ApexPages.StandardController standardPageController) {
        q = (Quote)standardPageController.getRecord(); //instantiate the Quote object for the current record
    }

    //method called from the Visualforce's action attribute
    public PageReference attachPDF() {
        String skipPDF = ApexPages.currentPage().getParameters().get('doNotSavePDF');
        PageReference pdfPage = Page.SystemRec; //create a page reference to our Visualforce page
        Blob pdfBlob; //create a blob for the PDF content

        if (skipPDF != 'true') {
            pdfPage.getParameters().put('doNotSavePDF','true');

        }

        Attachment attach = new Attachment(parentId = q.Id, Name = 'pdfAttachmentDemo.pdf', body = pdfBlob); //create the attachment object
        insert attach; //insert the attachment

        //redirect the user
        PageReference pageWhereWeWantToGo = new ApexPages.StandardController(q).view(); //we want to redirect the User back to the Quote detail page
        pageWhereWeWantToGo.setRedirect(true); //indicate that the redirect should be performed on the client side
        return pageWhereWeWantToGo; //send the User on their way
    }
}

I am now met with this error:
Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Body]: [Body]
Error is in expression '{!attachPDF}' in component apex:page in page systemrec: Class.attachRecPDFToQuote.attachPDF: line 23, column 1

I am using this reference: here
I want to: Create a button on the 'Quote' object that creates and attaches a PDF of a VisualForce page when selected
The issue I'm having: "Too many nested getContent calls" - infinite loop?
My VisualForce Code:
<apex:page action="{!attachPDF}" extensions="attachRecPDFToQuote" standardController="Quote" standardStyleSheets="false" showHeader="false" sidebar="false" applyHtmlTag="false" applyBodyTag="false" renderAs="pdf">
<apex:stylesheet value="{!$Resource.styleForSystemRec}"/>

    System Recommendation

    48 Fisk Dr.

    Arden, NC

    28704

    (828)684-8441

 SimplyHome Recommendation

 for Independence-Granting Technology

This recommendation was assembled by a dedicated member of the SimplyHome Customer Service team,

using a person-focused approach.

                Recommendation Prepared For:

                Name and Role

                Client Name:

                48 Fisk Dr.

                Arden, NC

                28704

                (828)684-8441

                Recommendation Prepared By:

                SimplyHome

                48 Fisk Dr.

                Arden, NC

                28704

                (828)684-8441

                Site Address:

               48 Fisk Dr.

               Arden, NC

               28704

                Concerns Addressed:

               Wandering and Elopement

               Kitchen/Cooking Safety

               Personal Care

    <apex:outputtext rendered="{IF(CONTAINS({!key},'Cooking'),true, false)}">
             Kitchen/Cooking Safety
            The SimplyHome System can be customized to support individuals during cooking, baking, and meal preparation routines, creating opportunities for independence and learning. Caregivers or staff can be alerted if concerns arise, such as the stove being left on. We may recommend stove sensors, motion sensors in the kitchen or dining areas, and smoke alarm monitors as part of these systems.
            Read more about Cooking Safety here, or meet Pearlie.

    </apex:outputtext>

    Please Note:
    THIS SYSTEM RECOMMENDATION DOES NOT SERVE AS THE QUOTE FOR PRODUCTS AND SERVICES. Once you have decided which items you would like as a part of your customized system design, we will send a formal quote.

My Apex Code:
public class attachRecPDFToQuote {

    private final Quote q; //Quote object

    //constructor
    public attachRecPDFToQuote(ApexPages.StandardController standardPageController) {
        q = (Quote)standardPageController.getRecord(); //instantiate the Quote object for the current record
    }

    //method called from the Visualforce's action attribute
    public PageReference attachPDF() {

        //generate and attach the PDF document
        PageReference pdfPage = Page.SystemRec; //create a page reference to our Visualforce page
        Blob pdfBlob; //create a blob for the PDF content
        if (!Test.isRunningTest()) { //if we are not in testing context
            pdfBlob = pdfPage.getContent(); //generate the pdf blob
        } else { //otherwise, we are in testing context and getContent() gets funky so create the blob manually
            pdfBlob = Blob.valueOf('Some Text for a boring PDF file...');
        }
        Attachment attach = new Attachment(parentId = q.Id, Name = 'pdfAttachmentDemo.pdf', body = pdfBlob); //create the attachment object
        insert attach; //insert the attachment

        //redirect the user
        PageReference pageWhereWeWantToGo = new ApexPages.StandardController(q).view(); //we want to redirect the User back to the Quote detail page
        pageWhereWeWantToGo.setRedirect(true); //indicate that the redirect should be performed on the client side
        return pageWhereWeWantToGo; //send the User on their way
    }
}

A: Main problem is that during execution of getContent, all the actions are called as well. That leads to an infinite loop, so if you open a page, on page load it calls getContent to get data for same page. During execution of that, all actions are executed, and that leads to a recursion.
One of the ways to prevent it - use a URL parameter to let action know when PDF should not be saved at all. Consider the following pseudocode:
public class attachRecPDFToQuote {

    private final Quote q; //Quote object

    //constructor
    public attachRecPDFToQuote(ApexPages.StandardController standardPageController) {
        q = (Quote)standardPageController.getRecord(); //instantiate the Quote object for the current record
    }

    //method called from the Visualforce's action attribute
    public PageReference attachPDF() {
        String skipPDF = ApexPages.currentPage().getParameters().get('doNotSavePDF');
        if (skipPDF != 'true') {
            PageReference pdfPage = Page.SystemRec;
            Blob pdfBlob;
            pdfPage.getParametersMap().put('doNotSavePDF','true');
            /* SAME code as before */
        }
    }
}

A: I was able to solve the issue going a different route and using this article as a guide: [here][1]
My final APEX code was:
public class attachPDFToApplication {
    public Id recId {get;set;}
    Public List<Attachment> existingAttLst {get;set;}
    Public Assessment__c record {get;set;}

    //constructor
    public attachPDFToApplication(ApexPages.StandardController standardPageController) {
        recId = standardPageController.getId();
        record = (Assessment__c)standardPageController.getRecord();
        Datetime apllicationdate = datetime.now();   //field that will create the pdf
        String attName = 'SystemRec - '+ datetime.now() + '.pdf';
        existingAttLst  = new List<Attachment> ([Select id from Attachment where ParentId =: record.Id and Name =: attName limit 1]);
    }

    //method called from the Visualforce's action attribute
    public void attachPDF() {
        if(existingAttLst == null || existingAttLst.size() <1){
            Blob pdfBlob;
            PageReference pdfPage = Page.SystemRec2;

            pdfPage.getParameters().put('id',recId);
            pdfPage.setRedirect(true);
            try{
                pdfBlob = pdfPage.getContentAsPdf();
            }catch(exception e){
                pdfBlob = blob.valueOf('this is from excetion  '+e.getMessage());
                system.debug(e.getMessage());
            }
            system.debug('id==>'+recId );
            Attachment attach = new Attachment(ParentId = recId, Name = 'SystemRec - '+ datetime.now() + '.pdf', body = pdfBlob);
            insert attach;
        } else {
            system.debug('PDF already attached');
        }

    }
}

I had 2 VF pages, one with the content, and one as a wrapper.
VF Page 1 (content):
<apex:page standardcontroller="Assessment__c">
**Content**
</apex:page>

VF Page 2 (wrapper):
<apex:page standardcontroller="Assessment__c" extensions="attachPDFToApplication" action="{!attachPDF}" showHeader="false" applyHtmlTag="false" applyBodyTag="false" standardStylesheets="false" docType="html-5.0"  lightningstylesheets="true">
<apex:include pageName="SystemRec2" />
</apex:page>

Then, I created a button on the appropriate object to pull in the wrapper VF page.
[1]: https://trailblazers.salesforce.com/answers?id=9063A000000puiWQAQ

redpajama_set_name: RedPajamaStackExchange


text:
Q: .NET custom DbContextFactory registration to DI i created my own dbcontextfactory and now i don't know how to correctly register it in di. Can you somebody help me please? IApplicationDbContext is just interfaces with db sets.
I have register ma DbContext as pooled db context factory
builder.Services.AddPooledDbContextFactory<MyContext>(options =>
{
    ....
});

Interface of my db factory
interface IApplicationDbContextFactory
{
    IApplicationDbContext CreateDbContext();
}

Implementation db factory
public class MyContextFactory<TContext> : IApplicationDbContextFactory where TContext : DbContext, IApplicationDbContext
{
    private readonly IDbContextFactory<TContext> _dbContextFactory;

    public MyContextFactory(IDbContextFactory<TContext> dbContextFactory)
    {
        _dbContextFactory = dbContextFactory;
    }

    public IApplicationDbContext CreateDbContext()
    {
        return _dbContextFactory.CreateDbContext();
    }
}

How can i correctly register my factory to di?
Thank you

A: Lifetime for the factory registered by AddPooledDbContextFactory is Singleton. Just register it with builder.Services.AddSingleton<IApplicationDbContextFactory, MyContextFactory<MyContext>>(); (though Scoped and Transient should also work just as fine):
var serviceCollection = new ServiceCollection();
serviceCollection.AddPooledDbContextFactory<SomeContext>(builder => builder.UseSqlite($"Filename={nameof(SomeContext)}.db"));
serviceCollection.AddSingleton<IApplicationDbContextFactory, MyContextFactory<SomeContext>>();
var serviceProvider = serviceCollection.BuildServiceProvider();
var dbContextFactory = serviceProvider.GetRequiredService<IDbContextFactory<SomeContext>>();

using (var scope = serviceProvider.CreateScope())
{
    var applicationDbContextFactory = serviceProvider.GetRequiredService<IApplicationDbContextFactory>();
    var applicationDbContext = applicationDbContextFactory.CreateDbContext();
}

public class SomeContext : DbContext, IApplicationDbContext
{
    public SomeContext(DbContextOptions<SomeContext> options) : base(options)
    {
    }

    public DbSet<MyEntity> Entities { get; set; }
}

interface IApplicationDbContextFactory
{
    IApplicationDbContext CreateDbContext();
}

public interface IApplicationDbContext
{
}

public class MyContextFactory<TContext> : IApplicationDbContextFactory where TContext : DbContext, IApplicationDbContext
{
    private readonly IDbContextFactory<TContext> _dbContextFactory;

    public MyContextFactory(IDbContextFactory<TContext> dbContextFactory)
    {
        _dbContextFactory = dbContextFactory;
    }

    public IApplicationDbContext CreateDbContext()
    {
        return _dbContextFactory.CreateDbContext();
    }
}


text:
Q: Есть ли преимущества в использовании числа вместо типа bool в Posgresql? Несколько раз встречал в таблицах базы, относящейся к веб-приложению на Java, столбцы, играющие роль флага, но имеющие не привычный тип bool, а smallint который принимает значения 0 или 1 вместо false и true соответственно.
Какие преимущества такого способа? Интересуют соображения, как и в рамках работы БД, так и возможного влияния на архитектуру веб-приложения.

A:
Вопрос довольно обширный, и на него вряд ли можно ответить полностью.
Мой личный опыт говорит, что були часто имеют привычку становиться
перечислениями.  Сначала у вас просто ON
и OFF.  Потом подбегает манагер и говорит, что надо
различать неустановленный режим, и появляется UNSET.
С этим ещё можно справиться через NULL, но потом тот же
манагер добавляет вам режим по расписанию (SCHEDULED),
автоматический режим (AUTO), какой-нибудь режим клоуна,
и проч.  Поэтому многие при проработке архитектур и API
предпочитают вместо булей сразу иметь перечисления, в том числе
в качестве INTEGERов в базе.


text:
Q: How to pattern match on a boolean equality on strings and simultaneously gain the desired propositional equality in a proof in Coq? I'm getting stuck trying to prove the substi_correct theorem in SF because I don't know how to split on boolean equality and simultaneously assert this as propositional equality.
Theorem substi_correct : forall s x t t',
  [x:=s]t = t' <-> substi s x t t'.
Proof.
  intros.
  split.
  + generalize dependent t'.
    induction t; intros.
    - simpl in H.
      subst.
      case (eqb_string x0 s0).
      * constructor. (*Doesn't work*)

The proof goal is as follows, without the needed H : x0 = s0 so that I can proceed.
  s : tm
  x0, s0 : string
  ============================
  substi s x0 (var s0) s

In the Maps.v chapter we prove, in addition to a false case,
Theorem eqb_string_true_iff : forall x y : string,
    eqb_string x y = true <-> x = y.

but how can I use then when pattern matching on (eqb_string x0 s0) so that I can proceed?  Am I supposed to use this as a lemma in the proof or is there an easier way to proceed?

A: You can use the variant of the destruct tactic with the eqn: clause to add a hypothesis remembering which case you're in:
  destruct (eqb_string x0 s0) eqn:Ex0s0  (* <-- You can pick any name for the equation here *)
  - (* Ex0s0 : eqb_string x0 s0 = true *)
    apply eqb_string_true_iff in Ex0s0.
    ...
  - (* Ex0s0 : eqb_string x0 s0 = false *)
    apply eqb_string_false_iff in Ex0s0.
    ...


text:
Q: Split sorted list into two lists I'm trying to split a sorted integer list into two lists. The first list would have all ints under n and the second all ints over n. Note that n does not have to be in the original list.
I can easily do this with:
under = []
over  = []
for x in sorted_list:
    if x < n:
        under.append(x)
    else
        over.append(x)

But it just seems like it should be possible to do this in a more elegant way knowing that the list is sorted. takewhile and dropwhile from itertools sound like the solution but then I would be iterating over the list twice.
Functionally, the best I can do is this:
i = 0
while sorted_list[i] < n:
    i += 1

under = sorted_list[:i]
over = sorted_list[i:]

But I'm not even sure if it is actually better than just iterating over the list twice and it is definitely not more elegant.
I guess I'm looking for a way to get the list returned by takewhile and the remaining list, perhaps, in a pair.

A: The correct solution here is the bisect module. Use bisect.bisect to find the index to the right of n (or the index where it would be inserted if it's missing), then slice around that point:
 import bisect # At top of file

 split_idx = bisect.bisect(sorted_list, n)
 under = sorted_list[:split_idx]
 over = sorted_list[split_idx:]

While any solution is going to be O(n) (you do have to copy the elements after all), the comparisons are typically more expensive than simple pointer copies (and associated reference count updates), and bisect reduces the comparison work on a sorted list to O(log n), so this will typically (on larger inputs) beat simply iterating and copying element by element until you find the split point.
Use bisect.bisect_left (which finds the leftmost index of n) instead of bisect.bisect (equivalent to bisect.bisect_right) if you want n to end up in over instead of under.

A: I would use following approach, where I find the index and use slicing to create under and over:
sorted_list = [1,2,4,5,6,7,8]
n=6

idx = sorted_list.index(n)
under = sorted_list[:idx]
over = sorted_list[idx:]

print(under)
print(over)

Output (same as with your code):
[1, 2, 4, 5]
[6, 7, 8]

Edit: As I understood the question wrong here is an adapted solution to find the nearest index:
import numpy as np

sorted_list = [1,2,4,5,6,7,8]
n=3

idx = np.searchsorted(sorted_list, n)
under = sorted_list[:idx]
over = sorted_list[idx:]

print(under)
print(over)

Output:
[1, 2]
[4, 5, 6, 7, 8]


text:
Q: JQuery .closest("tr") is not working http://jsfiddle.net/yjxq7bae/1/
I am trying to select the checkbox prop in the input tag. The id and name of the input tag are reused, so I have to use the <nobr> text to scale the dom and get the value.

        <nobr>Confirmation Sent</nobr>

          <input id="ctl00_m_g_ed53ee23_de9d_4105_ba24_00e2a21cef5e_ctl00_ctl05_ctl50_ctl00_ctl00_ctl04_ctl00_ctl00_BooleanField" type="checkbox" name="ctl00$m$g_ed53ee23_de9d_4105_ba24_00e2a21cef5e$ctl00$ctl05$ctl50$ctl00$ctl00$ctl04$ctl00$ctl00$BooleanField" checked="checked" />

Click Here

I have tried every conceivable way. If you will notice .closest() fails once I go up one more from the
 element. The fiddle demonstrates this on load by first changing the css of h3, and then attempting to hide the td.
var mop = $('nobr').filter(function () {
    return $(this).text() === 'Confirmation Sent'
}).closest("tr").find("input[type=checkbox]").prop('checked');
alert(typeof mop);

$('nobr:contains(Confirmation Sent)').closest("h3").css("background", "yellow");
$('nobr:contains(Confirmation Sent)').closest("h3").closest("td").hide();

$('div').on("click ", function (event) {
    var toast = $('nobr').filter(function () {
        return $(this).text() === 'Confirmation Sent'
    }).closest("tr").find("input[type='checkbox']").prop('checked');
    alert(typeof toast);
});

A: The problem is that you don't have correct syntax for a table. You're missing the
 and
 tags around your rows.
Since it's not a valid table, the browser throws away your
 and  tags:

If you wrap your HTML in a
 your javascript works as intended.


text:
Q: What tools do I need to port packages to powerpc? I'm relatively new to coding and building apps, and I wan to contribute to PowerPC Linux via packages.  So I'm trying to port apps and tools over to then package them for the platform and try to package them for different distro's such as ubuntu and void.  But, as it stands with running Ubuntu Mate 16.04, basically everything is out of date (LLVM, Clang, ETC) so I'm having to build stuff by hand to get other stuff built, which atm is Firefox 61.
No problem!  But, what all tools should I acquire?  And I have the system as up to date as I can make it by the way, the tools are just out of date.  I have the code for LLVM, clang, and associated tools, but I don't know what other tools I may need in the future (If I have Clang do I need GCC?  If an app calls for GCC in the build process can I bump it to clang instead?  What tools do I need for python?  Or rust?  What are your general recommendations for languages I should be up to date with?).
For note, I'm building on-platform via a powerbook G4 A1138.  Its a little slow, but its not that bad over all.  I know I could cross compile, but something doesn't sound right about building on X86 for powerpc. Like I'm gimping the platform by doing that.
Anyways, all the info I can get would be helpful!  Thanks!

A: There is a clang-5.0 and clang-6.0 for powerpc in the Ubuntu repository.
The PPA for Ubuntu Toolchain Uploads (restricted)" team has very recent toolchaing for powerpc on 16.04 too.


text:
Q: Equal strings are not equal in Perl Please help me to understand one strange problem in equality of strings.
This is the code I'm talking about:
my $test=undef;
foreach my $List (@o_descrL) {
  if (!($test)) {
    $test = defined($o_noreg)
      ? $descr_d eq $List
      : $descr_d =~ /$List/i;
      printf("$descr_d = $List\t\t==> $test\n");
   }
}

Unfortunately I didn't write it but I have to understand it. $List is always "SQL Server (C4)", $descr_d is changing according to actual item in array. Part of the printed output is here:
Power = SQL Server (C4)         ==>
SQL Server (C4) = SQL Server (C4)               ==>
SNMP Service = SQL Server (C4)          ==>
Network Connections = SQL Server (C4)           ==>

As you can see, strings in the second line of the output are equal. So why isn't $test true?

EDIT: I've printed some more output and found out that when $descr_d eq $List, it equals, but not if $descr_d =~ $List. Could you please explain what is actually putting to the $test variable? I don't understand what does defined() ? : mean in here.

EDIT2: For a string "SQL Server Agent" the script works just fine, there is a problem only when (C4) is attached. Quite strange, isn't it?

A: When a string is interpolated as a regex, it isn't matched literally, but interpreted as a regex. This is useful to build complex regexes, e.g.
my @animals = qw/ cat dog goldfish /;
my $animal_re = join "|", @animals;

say "The $thing is an animal" if $thing =~ /$animal_re/i;

In the string $animal_re, the | is treated as a regex metacharacter.
Other metacharacters are e.g. (...), which is a capture group. This is present in your $List. That is, your regex is actually looking for the string SQL Server C4 and capturing the C4 when successful.
To deactivate metacharacters, you can quote them like
/\Q$metachars\E/

In your case:
$test = defined($o_noreg)
      ? $descr_d eq $List
      : $descr_d =~ /\Q$List/i;

As an aside, Perl's default false value is the empty string. Your output may be more readable if you force it to a number, e.g via $test += 0. It might also be helpful to print out the strings enclosed in quotes:
print qq("$descr_d" = "$List"\t==> $test\n);

Re: your edit
The conditional operator is common in C-like languages. It consists of three parts:
COND ? EXPR_A : EXPR_B

If the condition COND is true, the expression EXPR_A is evaluated; otherwise, EXPR_B is. In your code, the value of the expression that was evaluated is assigned to $test.
The defined builtin tests whether the value the scalar holds is undef. If that is the case, it returns a false value, or 1 otherwise. This is used for some configuration here: When $o_noreg is set to any value except undef, default string comparison will be used. If it is undef, the regex will be executed.
Re: edit 2
No it isn't strange: SQL Server (C4) contains the ( and ) metacharacters, whereas SQL Server Agent contains no metacharacters whatsoever.


text:
Q: How to handle lots of ports with AWS Network load balancer? I have an application that has to answer to lots of ports (hundreds).
With an AWS Network Loadbalancer, is it necessary to create one target group by port ?
I can only set one port when creating target group.
Maybe there is no limit in number of target groups associated or related to a load balancer, but what I fear is the time needed to change all thoses target groups, when I need to add or remove EC2 instances of this application.
Is there another way to manage all these ports, with a managed loadbalancer ?


text:
Q: Evaluating $\;\lim_{x \rightarrow 1^{-} } \frac{e^{1/(x^2 -1)}}{x-1}$ Consider the limit
$$ \lim_{x \rightarrow 1^{-}  } \frac{e^{1/(x^2 -1)}}{x-1}$$
I tried to apply the L'Hospital rule. But  don't work. It complicates the computations. I also tried to solve the exercise without L'Hospital. But I am getting anywhere. Could someone help me with the exercise?
Thanks in advance

A: Write $f(x) = \frac{e^{\frac{1}{x^2-1}}}{x - 1}$. Two easy things that anyone can do when confronted by a problem like this are

*

*Plot the function $f(x)$.

*Plug in some specific values of $x$, say $f(0.9)$ and $f(0.99)$.

A plot makes it clear that the limit is $0$:

While plugging in specific values gives $f(0.9) = -0.052 \dots$ and $f(0.99) = -1.5 \times 10^{-23}$, so we see that in fact $f$ approaches $0$ very rapidly as $x \to 1^{-}$.
Thinking a bit about the functional form of $f(x)$, it's not hard to see why: as $x \to 1^{-}$ we have $\frac{1}{x^2 - 1} \to - \infty$ so $e^{\frac{1}{x^2 - 1}} \to 0$ very rapidly, much faster than $x - 1$ does, and in fact much faster than any power of $x - 1$ does.
To actually prove it I think it's a little simpler to take the logarithm of $- f(x)$. So, we want to show that
$$\lim_{x \to 1^{-}} \ln (-f(x)) = \lim_{x \to 1^{-}} \left( \frac{1}{x^2 - 1} - \log (1 - x) \right) = - \infty.$$
To see this, note that for $x \in (0, 1]$ we have $x + 1 \ge 1$ which gives $\frac{1}{x^2 - 1} = \frac{1}{(x - 1)(x + 1)} \le \frac{1}{x - 1}$, so an upper bound for the above is
$$\ln (-f(x)) \le \frac{1}{x - 1} - \log (1 - x) = - \left( \frac{1}{1 - x} - \log \frac{1}{1 - x} \right).$$
This suggests the substitution $u = \log \frac{1}{1 - x}$. As $x \to 1^{-}$ we have $u \to \infty$, and the above upper bound becomes $- (e^u - u)$, so we've reduced to showing that
$$\lim_{u \to \infty} (e^u - u) = \infty.$$
This is easy enough to just prove directly and I encourage you to just try it directly from the definition. You can use, for example, the inequality $e^u \ge 1 + u + \frac{u^2}{2}$.

A: My strategy is to simplify expressions as much as possible before attacking the problem.
We have
$$\frac{e^{1/(x^2 -1)}}{x-1}=
\frac{e^{1/(x^2 -1)}}{x^2-1}(x+1)$$
The factor $x+1$ tends to $2.$ It suffices to examine the first ratio.
Let $t=(1-x^2)^{-1}.$ Then $x\to 1^{-}$ implies $t\to \infty.$ We have
$$\frac{e^{1/(x^2-1)}}{x^2-1}=-te^{-t}$$ Next  $$\lim_{t\to\infty}{t\over e^t}=0\quad (*)$$ Hence the final answer is $0.$
Remark Basing on $e^t\ge 1+t>t$ we get $$e^t=(e^{t/2})^2> {t^2\over 4}$$ This can be used for getting $(*)$ avoiding de l'Hôpital rule.


text:
Q: A Class has been compiled by a more recent version of the Java Runtime Good afternoon,
when running a server with Ant, this is the error I get.
Exception in thread "main" java.lang.UnsupportedClassVersionError: es/deusto/ingenieria/sd05/easybooking/server/data/Airline has been compiled by a more recent version of the Java Runtime (class file version 57.0), this version of the Java Runtime only recognizes class file versions up to 56.0

However, when typing javac -version, it says that I'm using the latest Java version (13). I tried to compile it with Java 13, 12 or 11, and none worked. Any ideas on how to fix it?


text:
Q: Cannot resolve symbol 'encrypt' in nimbus-jose-jwt library I am trying to generate an encrypted JWT in Android using 'nimbus-jose-jwt' library. But when I call the method 'encrypt()' of library, I get the error 'Cannot resolve symbol 'encrypt', even though the source code of library has the method 'encrypt()' for the object I specified.
This is my code:
 public class EncryptedJWTGenerator {

 public EncryptedJWTGenerator() throws NoSuchAlgorithmException, JOSEException {
    }

    JWEAlgorithm alg = JWEAlgorithm.RSA_OAEP_256;
    EncryptionMethod enc = EncryptionMethod.A128CBC_HS256;

    KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
    //rsaGen.initialize(2048);
    KeyPair rsaKeyPair = rsaGen.generateKeyPair();
    RSAPublicKey rsaPublicKey = (RSAPublicKey)rsaKeyPair.getPublic();

    // Generate the preset Content Encryption (CEK) key
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

    SecretKey cek = keyGenerator.generateKey();

    // Encrypt the JWE with the RSA public key + specified AES CEK
    JWEObject jweObject = new JWEObject(new JWEHeader(alg, enc), new Payload("Hello, world!"));

    jweObject.encrypt(new RSAEncrypter(rsaPublicKey, cek)); //**ERROR IN THIS LINE**

    String jweString = jweObject.serialize();

}

I have been trying to resolve this for hours, but not successful yet. Please suggest a solution.

A: There are two bugs in the code:

*

*First, a typo: the closing bracket in the 3rd line must be removed.

*Secondly, the KeyGenerator must be initialized as follows when generating the CEK:
keyGenerator.init(EncryptionMethod.A128CBC_HS256.cekBitLength());

With these changes the code works on my machine (API28/P).


text:
Q: Use gradient methods for maximum likelihood estimation of Gaussian mixture I have some questions concerning estimating maximum likelihood of Gaussian mixture model.

*

*As I have read around some material, they usually use EM algorithm for maximizing the complete likelihood function (with hidden variables). If without introducing hidden variables, can I optimize directly the incomplete likelihood function? That is I consider $\Theta = \left( \pi, \theta \right)$ are the mixing proportion vector and the parameters vector, respectively, and then I compute the gradient of likelihood $\nabla L(\Theta)$ and run gradient methods.

*What is the benefits of introducing hidden variables and is there any reasons people tend to use EM over gradient methods?

A: Indeed, since the likelihood function
$$\prod_{i=1}^n \sum_{j=1}^k p_j \varphi(x_i;\mu_j,\sigma_j)$$
is available in closed form, a regular maximisation algorithm like the gradient methods could be applied to this function. Unfortunately, they cannot work because the likelihood is not regular enough for them to find the global maximum:

*

*there are several equivalent local modes;

*it may happen that the likelihood is unbounded at the boundaries of the parameter space.

The EM algorithm also ends up in a local mode, hence shares some of these drawbacks but it is usually fast and can be repeated with different starting points to find a global mode.


text:
Q: initWithCoder for loading xib example I was reading about initializing the archived objects from a XIB file and found that
- (id)initWithCoder:(NSCoder *)aDecoder

is a way of doing it. But I am not able to get a hang around this. Can someone show me an simple example of how to do this?
Thanks a ton

A: The NSCoder class is used to archive/unarchive (marshal/unmarshal, serialize/deserialize) of objects.
This is a method to write objects on streams (like files, sockets) and being able to retrieve them later or in a different place.
I would suggest you to read Archiving
You also need to define the following method as follows:
- (void)encodeWithCoder:(NSCoder *)enCoder
{
    [super encodeWithCoder:enCoder];

    [enCoder encodeObject:instanceVariable forKey:INSTANCEVARIABLE_KEY];

    // Similarly for the other instance variables.
    ....
}

And in the initWithCoder method initialize as follows:
- (id)initWithCoder:(NSCoder *)aDecoder
{
    if(self = [super initWithCoder:aDecoder]) {
        self.instanceVariable = [aDecoder decodeObjectForKey:INSTANCEVARIABLE_KEY];

       // similarly for other instance variables
       ....
}
    return self;
}

You can initialize the object standard way i.e
CustomObject *customObject = [[CustomObject alloc] init];

Example taken from this answer

A: You can use it in following way:
.h file
@interface Score : NSObject {
    NSString *Username;
    NSString *TotalPoints;
    NSString *LifeRemains;
    NSString *ScoreDate;
}

@property (nonatomic, retain) NSString *Username;
@property (nonatomic, retain) NSString *TotalPoints;
@property (nonatomic, retain) NSString *LifeRemains;
@property (nonatomic, retain) NSString *ScoreDate;

in .m file
@synthesize Username, TotalPoints, LifeRemains, ScoreDate;

- (void)encodeWithCoder:(NSCoder *)encoder
{
//Encode properties, other class variables, etc
[encoder encodeObject:self.Username forKey:kScoreUsername];
[encoder encodeObject:self.TotalPoints forKey:kScoreTotalPoints];
[encoder encodeObject:self.LifeRemains forKey:kScoreLifeRemains];
[encoder encodeObject:self.ScoreDate forKey:kScoreDate];
}

- (id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if( self != nil )
{
    //decode properties, other class vars
    self.Username = [decoder decodeObjectForKey:kScoreUsername];
    self.TotalPoints = [decoder decodeObjectForKey:kScoreTotalPoints];
    self.LifeRemains = [decoder decodeObjectForKey:kScoreLifeRemains];
    self.ScoreDate = [decoder decodeObjectForKey:kScoreDate];
}
return self;
}

Happy Coding...


text:
Q: count and say using recursion in C++ Given 'n', the problem is to generate the nth sequence of Count and Say.
Here is the problem description.
I was trying to solve this through recursion:
Edit:
Basically iterating through the string and counting consecutive 1s,2s(or whatever) and appending (count+that number we counted)(it's a string, by the way) to the main string which is to be returned ultimately.
And the link works now.
string gofind(int N){
    if(N==1) return "1";
    else{
        string temp = gofind(N-1);
        ostringstream str1;
        string* t  = &(temp);
        int count;
        string n;
        while(*t!="\0"){
            count=1;
            while(*t==*(t+1)) {
                count++;
                t++;
            }
            str1<<count;//basically to convert int to str
            string geek = str1.str();
            n.append(geek+*t);
            t++;
        }
        return n;
    }
}

This throws up an exception during runtime "bad_alloc".There are probably a lot of things wrong in this code.
Could somebody point out what? And what could be the correct recursive solution.

A: This is not a correct way to iterate through a string:
string* t  = &(temp); // Please no!
while(*t!="\0"){

This gives you a pointer to where the string stores its control block, i.e. information like its size etc. - this is not where the character data is. Also, you are treating this pointer as if there was an array of stringss there, not an array of characters (it is neither).
You can iterate through the string by simply indexing it:
for (int i = 0; i < temp.size() - 1; ++i)
{
  count = 1;
  while ((i+1 < temp.size()) && (temp[i] == temp[i+1]))
  {
    count++;
    i++;
  }
}

I think you can work out the full solution from here.

A: string gofind(int N){
    if(N==1) return "1";
    if(N==2) return "11";
    else{
        string temp = gofind(N-1);
        int count;
        string n;
        for (int i=0;i<temp.size();i++){
            count=1;
            while((temp[i]==temp[i+1])&&(i<temp.size()-1)){
                i++;
                count++;
            }
            ostringstream str1;//all of  this to
            str1<<count;//basically to convert
            string geek = str1.str();//int to str
            n.append(geek+temp[i]);
        }
        return n;
    }
}

This is the corrected code ,by the way.

A: #include<bits/stdc++.h>
using namespace std;
void func(string s,int p){
if((s.substr(1)).length()==0){
    return;
}
if(s[0]==s[1]){
    p=p+1;
    func(s.substr(1),p);
}
if(s[0]!=s[1]){
    cout<<p<<s[0];
    func(s.substr(1),p=1);
}
if((s.substr(1)).length()==1){
    cout<<p<<s[1];
}

}
int main(){
string s;
cin>>s;
func(s,1);
return 0;

}


text:
Q: Current flow in PWM brushed DC motor drive I am driving a brushed DC motor (Cytron gear motor) using a gate driver (SN754410) to do PWM motor speed control.

My expectation
I expected a triangular current wave, ramp up when PWM on, ramp down when PWM off. Like this (with sine speed modulation):

My observations
However, instead I observed the following:

*

*Measured across 1 ohm resistor

*80% PWM duty cycle

*Motor under load.

*Frequencies: 24-500 kHz

*PWM in purple, current in red (1V => 1A)

24 kHz

200 kHz

500 kHz

Questions

*

*Why are there such big current spikes?

*Should I expect this, and will it reduce the chip lifespan?

*What should I do to suppress it? (I have put decoupling capacitors in, like the reference circuit. It made no significant difference.)


text:
Q: R - finding roots for a cartesian product of function parameters Given a function f(x,c,d) of x that also depends on some parameters c and d. I would like to find the zeroes for a cartesian product of certain values c_1,...,c_n and d_1,...,d_m of the parameters, i.e. an x_ij such that f(x_ij,c_i,d_j)=0 for i=1,...,n and j=1,...,m. Although not that crucial I am applying a Newton-Raphson algorithm for the root finding:
newton.raphson <- function(f, a, b, tol = 1e-5, n = 1000){
                  require(numDeriv) # Package for computing f'(x)
                  x0 <- a # Set start value to supplied lower bound
                  k <- n # Initialize for iteration results
                  # Check the upper and lower bounds to see if approximations result in 0
                  fa <- f(a)
                  if (fa == 0.0){
                      return(a)
                   }
                  fb <- f(b)
                  if (fb == 0.0) {
                     return(b)
                  }
                  for (i in 1:n) {
                    dx <- genD(func = f, x = x0)$D[1] # First-order derivative f'(x0)
                    x1 <- x0 - (f(x0) / dx) # Calculate next value x1
                    k[i] <- x1 # Store x1
                    # Once the difference between x0 and x1 becomes sufficiently small, output the results.
                    if (abs(x1 - x0) < tol) {
                          root.approx <- tail(k, n=1)
                          res <- list('root approximation' = root.approx, 'iterations' = k)
                          return(res)
                     }
                     # If Newton-Raphson has not yet reached convergence set x1 as x0 and continue
                     x0 <- x1
                   }
                     print('Too many iterations in method')
                   }

The actual function that I am interest is more complicated, but the following example illustrates my problem.
  test.function <- function(x=1,c=1,d=1){
                   return(c*d-x)
                   }

Then for any given c_i and d_j I can easily calculate the zero by
  newton.raphson(function(x) test.function(x,c=c_i,d=d_j),0,1)[1]

which here is obviously just the product c_i*d_j.
Now I tried to define a function that finds for two given vectors (c_1,...,c_n) and (d_1,...,d_m) the zeroes for all combinations. For this, I tried to define
zeroes <- function(ci=1,dj=1){
           x<-newton.raphson(function(x) test.function(x,c=ci,d=dj),0,1)[1]
           return(as.numeric(x))
          }

and then use the outer-function, e.g.
 outer(c(1,2),c(1,2,3),FUN=zeroes)

Unfortunately, this did not work. I got an error message
  Error during wrapup: dims [product 6] do not match the length of object [1]

There might be also a much better solution to my problem. I am happy for any input.


text:
Q: Java JNIEnv Segmentation Fault I'm in the process of doing some Java<->.NET interop code using a native library between them, so far things are going fairly well.
However for some reason I cannot run any methods under JNIEnv.
System::String^ JNIStringToNet(JNIEnv * env, jstring js)
{
    const char *buf = env->GetStringUTFChars(js, 0); // segfault

Now I can pass variables back and forth and do all other kinds of communication, so I'm figuring I haven't initialized this correctly or something.
I'm loading it like this:
this.Lib = (LibHandler)Native.loadLibrary(this.Name, LibHandler.class);

(I prefer Native.loadLibrary because it seems to allow me to do more with it easier, such as class sharing between multiple libraries and unhooking and rehooking it from the JVM on the fly).
Edit:
Seriously any method:
std::cout << "Getting version:" << std::endl;
std::cout << env->GetVersion() << std::endl;

Getting version:
(segfault)
Any ideas on wht JNIEnv would segfault for every method? This should be set up by the JVM, correct?
Edit 2:
This is a Java application that is calling a C++ library that will interface with a .NET library (so it's a CLR compiled C++ library, if that makes any difference), to limit any external factors I'm not even calling the .NET DLL but just converting strings that come in back out (or well... trying).
So for example from Java:
this.Lib = (LibHandler)Native.loadLibrary(this.Name, LibHandler.class);
this.Lib.myCPPMethod(); // Segmentation fault during this call, JVM crashes.

Curious if it was the CLR that was causing it: Disabled clr compilation and stripped everything out that was CLR related, still does it.
Edit 3:
Got it to dump:
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000000000000000, pid=1596, tid=7248
#
# JRE version: 6.0_23-b05
# Java VM: Java HotSpot(TM) 64-Bit Server VM (19.0-b09 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# C  0x0000000000000000

So yeah, looks like the JVM isn't giving me memory access for some reason.
Edit 4:
Actual call:
JNIEXPORT jstring JNICALL Query(JNIEnv * env, jobject jobj, jstring start, jstring end)
{
    std::cout << "Getting version:" << std::endl;
    jint j = env->GetVersion();
    return jstring("test");
}

Edit 5:
Works with System.loadLibrary:
JNIEXPORT void JNICALL Java_LibTest_T(JNIEnv *env, jobject jobj)
{
    std::cout << "Getting version:" << std::endl;
    jint j = env->GetVersion();
    std::cout << j << std::endl;
}

Output:
java -Djava.library.path="(dir)\lib\64" EntryPoint
Getting version:
65542

Ack! I mean some headway, but I can't unload libraries from the JVM that are loaded in System.loadLibrary can I?
I basically need to be able to unhook these libraries from the JVM and swap them out, on top of that they all need to "share" a single class and be able to be bound to the class at runtime... which is kinda why I went with Native.loadLibrary.
Currently I do this:
Load the DLL:
this.Lib = (LibHandler)Native.loadLibrary(this.Name, LibHandler.class);

Unhook it:
this.Lib = null;
Runtime.getRuntime().gc(); // Force the JVM to drop it immediately.

Class I load them all into:
public interface LibHandler extends Library{
    void T();
}

Any way to work similarly with System.loadLibrary?
Edit 6:
Feel free to call me dumb, I'm using JNA, NOT JNI, which is completely different and a huge source of my problems.... is there a way to do this with JNI? Or can I get JNIEnv to register with JNA somehow? I'm guessing I can drop JNI from the C++ library and straight up use wstrings?
I'll get back with this tomorrow.

A: Well I feel bad.
Native.loadLibrary == JNA.
System.loadLibrary == JNI.
The purpose of JNA is to not require any real knowledge of the JVM environment, so you can run native libraries as is, so instead of jstring you can use char*...


text:
Q: C# - convert strings such as "uniqueidentifier", "timestamp", "image", "money", "sql_variant" etc. into .net data-types How to convert strings such as "uniqueidentifier", "timestamp", "image", "money", "sql_variant" etc. into respective .net data-types?
I need to query a table to find out its contained fields and then accumulate those into a list List<Column>. Column is a class written by me. So I need this mechanism.

A: Run a query with the target columns using ExecuteReader to get a SqlDataReader, then use GetFieldType (returns the .NET datatype) and GetDataTypeName (returns the corresponding SQL server type name). The actual type mapping is done internally to the SqlClient- you could use reflection to access it, and hope it doesn't change between .NET versions, but I wouldn't recommend it.

A: Simply work out what you want the types to be (which may vary by your database) and use a dictionary:
static reaodnly Dictionary<string, Type> NameToTypeMap =
new Dictionary<string, Type>
{
    { "uniqueidentifier", typeof(Guid) },
    { "timestamp", typeof(DateTimeOffset) },
    { "image", typeof(byte[]) },
    // etc
};

Note that this is assuming you're using C# 3, as it uses a collection initializer. Let me know if you're not using C# 3.
EDIT: Here's the C# 2 code:
static Dictionary<string, Type> NameToTypeMap = GetTypeMap();

private static Dictionary<string, Type> GetTypeMap()
{
    Dictionary<string, Type> ret = new Dictionary<string, Type>();
    ret["uniqueidentifier"] = typeof(Guid);
    ret["timestamp"] = typeof(DateTimeOffset);
    ret["image"] = typeof(byte[]);
    // etc
    return ret;
}


text:
Q: Make hover CSS dropdowns clickable with JavaScript or jquery I have a website layout currently using a css hover dropdown menu:
http://jsfiddle.net/egvvh5yq/
So far this is fully functional for me, however, I would like to make the drop down click activated.  When clicked, the menu stays dropped down until clicked out of, or onto a new category. The Hover state also remains.
I have not been able to achieve this yet, jsfiddle below:
http://jsfiddle.net/mcLh5gch/5/
I can achieve a simple dropdown with one link using javascript below, but not with the formatting I would like (rows and columns in dropdown).

CSS:
.click-nav {margin:10px auto;width:171px; font-family:Arial, Helvetica, sans-serif;}
.click-nav ul {position:relative;font-weight:200;}
.click-nav ul li {position:left;list-style:none;cursor:pointer;}
.click-nav ul li ul {position:absolute;left:0;right:0;}
.click-nav ul .clicker {position:relative;color:#696969; text-align: center;width:171px;height:75px;line-height:75px;padding:0px;
background: linear-gradient(white, white 50%, #90383b 50%, #90383b );
background-size: 100% 202%;
}
#mainmenu { transition: all 0.2s ease;animation: down-bump 0.4s ease;}
.click-nav ul .clicker:hover {background-position: 100% 100%;animation: up-bump 0.4s ease; color:#FFF}
.click-nav ul .active {background-position: 100% 100%;color:#FFF}
.click-nav ul li a {display:block;background:#FFF;color:#333;text-decoration:none;padding:8px;width:155px;}
#sub:hover{background:#90383b; color:#FFF}

/* Fallbacks */
.click-nav .no-js ul {display:none;}
.click-nav .no-js:hover ul {display:block;}

HTML:

  Box 1

Space 1

Space 2

Space 3

Space 4

Space 5

Space 6

Space 7

Space 8

Space 9

All and all I am asking for help to achieve a click dropdown with the hover menu I have now.  My attempt can be reviewed, but it is difficult for me to pin down whats wrong.  I'm new at this!

A: Use the .on() function for this type of events.
Check it out:
   $(function() {
    // Clickable Dropdown
    $('.click-nav > ul').toggleClass('no-js js');
    $('.click-nav .js ul').hide();
    $('.click-nav .js').click(function(e) {
        $('.click-nav .js ul').slideToggle(200);
        $('.clicker').toggleClass('active');
        e.stopPropagation();
    });

   $(".greybox").on("click", "li", function(){
        alert("Item Clicked");
       /*
        if ($('.click-nav .js ul').is(':visible')) {
            alert('test');
            $('.click-nav .js ul', this).slideUp(slow);
            $('.clicker').removeClass('active');
        }*/
   });

});


text:
Q: How can I get the next closest integer out of 2 integers? Let's say I have an int pick = 3 and I also have an int minus = 0 and int plus = 7.
How can I get the number closest to my int pick number?
So in this case the distance from int pick to int minus would be 3 and the distance from int pick to int plus would be 4, so I want int minus to be chosen.
All of the ints are changable values, I just chose some numbers to show as an example, is there a loop or if-statement that could solve this?

A: You could use a ternary or if expression here:
public static int nearest(int minus, int plus, int pick) {
    return Math.abs(minus - pick) < Math.abs(plus - pick) ? minus : plus;
}

System.out.println(nearest(0, 7, 3));  // 0
System.out.println(nearest(0, 4, 3));  // 4


text:
Q: store results of a loop in a shell variable in sh I have a couple of nested loops that generate identical data over multiple iterations.
I would like to instead save this data from one of the inner loops in a shell variable.
Is there an easy way to redirect output from a loop into a variable, without modifying the loop itself?

A: A loop (for, while, or until) is a command just like any other. You can capture its output using command substitution.
$ foo=$(for x in 1 2 3; do echo "Number $x"; done)
$ echo "$foo"
Number 1
Number 2
Number 3

However, if you mean redirect like you would redirect to a file:
for x in 1 2 3; do
    echo "Number $x"
done > somefile.txt
foo=$(cat somefile.txt)

then things get a little trickier. You can't write directly to a variable, but arguably the simplest workaround is the above, which first writes the output to a file, then reads the file back into a variable.


text:
Q: Making sense of mod_tiles /[TileSetName]/Z/X/Y.png tile serving I am trying to understand this part of mod_tile documentation about tile serving:
Apache serves the files as if they were present under /[TileSetName]/Z/X/Y.png with the path being converted automatically.

To be sure, I have little experience with Apache. So, I kind of have to make sense of this. Does this mean that if mod_tile is running, I can open use Python with pillow to open a png-file in lets say "/tilename/17/51.5072/0.1276" to get a map of London at zoom-level 17 using tiles with TileSetName=tilename?
Or, do I have to send a get request to localhost "http://localhost/tilename/17/51.5072/0.1276"?
And how do I adjust the size of the PNG?

A: You do have to use http://localhost/tilename/17/51.5072/0.1276 as there are no real file under "tilename/17/51.5072/0.1276" on the machine path. The explanation is from the project doc itself (https://github.com/openstreetmap/mod_tile#details-about-mod_tile-tile-serving)

To avoid problems with directories becoming too large and to avoid too many tiny files. They store the rendered tiles in "meta tiles" in a special hashed directory structure. These combine 8x8 actual tiles into a single metatile file. This is a more efficient use of disk space and inodes.

The metatiles are then stored in the following directory structure: /[base_dir]/[TileSetName]/[Z]/[xxxxyyyy]/[xxxxyyyy]/[xxxxyyyy]/[xxxxyyyy]/[xxxxyyyy].meta

Imagining you choose to open the metatiles to get png from it (using provided utility like convert_meta) if you don't do the call to Apache first, you will no have the required metatiles.
For the output quality, "on the paper", you should be able to play with Mapnik options e.g https://github.com/mapnik/mapnik/wiki/Image-IO#png-output-options  but to be honest, I never changed them so not sure about it, in particular with the abstract level of mml if you are using official OpenStreetMap style.


text:
Q: Billing agreement description not showing full text in paypal sandbox checkout page I have a paypal checkout page where in order summary i am displaying some text inside Billing agreement description. Text is displaying correctly but it's not showing full text length.

This is what i want to display.
$nvpstr = $nvpstr . "&L_BILLINGAGREEMENTDESCRIPTION0=".urlencode("Your account will NOT be charged at this time. This verification is for security purposes only to prevent fraudulent use. Following your Free Trial period, you agree to pay a monthly fee of $fds/month per location for unlimited offer posting. Additional options that you select, i.e. paid offer positions, will be billed every 2-4 days. Thank you for joining fasdfdsa!");

A: Per the SetExpressCheckout documentation, the L_BILLINGAGREEMENTDESCRIPTION parameter only accepts 127 characters.

Description of goods or services associated with the billing
  agreement. This field is required for each recurring payment billing
  agreement. PayPal recommends that the description contain a brief
  summary of the billing agreement terms and conditions. For example,
  buyer is billed at "9.99 per month for 2 years". Character length and
  limitations: 127 single-byte alphanumeric characters.

That description is meant to be short and sweet.  Any details like this that you need to provide should be done on your site prior to sending the user to PayPal for payment.


text:
Q: Complex list comparisons in python I want to do a complex list comparison with python. I want to see if listB contains all of the items from listA and if they are in the same order. But I do not care if listB has extra items or interleaved items.
Examples:
listA = ['A','B','C','D','E']
listB = [':','A','*','B','C','D','E','`']

A, B, C, D, and E all appear in listB and are presented in the same order even though A and B have an item in between them and items at the start and end of listB.
Extra complicated:
listA = ['A','B','C','D','E']
listB = ['A','*','C','B','C','D','E']

A, B, C, D, and E all appear in listB and are presented in the same order even though A and B have two items in between them and one of those items happens to be something we are searching for. But since we are looking if A -> B is sequential and B -> C is sequential the fact that we also have C -> B -> C shouldn't matter.
So,
listA = ['A','B','C','D','E']
listB = [':','A','*','B','C','D','E','`']

Would be True
listA = ['A','B','C','D','E']
listB = ['A','*','C','B','C','D','E']

Would be True
But something like:
listA = ['A','B','C','D','E']
listB = ['A','B','C','D','F']

or even
listB = ['A','B','C','D']

Would be False
If it get a False answer, I'd ideally like to be able to point to where the break in sequence happened -- i.e. E is missing.

A: Simple solution using a nested loop. Walk over listA and search the elements in listB in order. Should you fail at any point -> this is not a substring:

def check(listA, listB):
    start = 0
    for a in listA:
        for i in range(start, len(listB)):
            if a == listB[i]:
                start = i+1
                break
        else:  # triggered only if no break
            # print(f'{a} not found after position {start}')
            return False
    return True

check('ABCDE', 'A*CBCDE')
# True

check('ABCDEF', 'A*CBCDE')
# False

check ('', '')
# True

check('ABA', 'ABBA')
# True

NB. Using strings here for clarity, but this works for any iterable.
To get information on the non-found item, you can uncomment the print.
Example:
check('ABCA', 'ABBA')

C not found after position 2
# False

A: Recursive Solution
def is_contained(a, b):
    # Base case
    if not a or not b:
        return True if not a else False

    # if first letters match check remaining, else check b remaining
    return is_contained(a[1:], b[1:]) if a[0] == b[0] else is_contained(a, b[1:])

Test
print(is_contained(['A','B','C','D','E'], ['A','*','C','B','C','D','E']))  # True
print(is_contained(['A','B','C','D','E'], ['A','B','C','D','F']))          # False

A: As always Python comes with batteries included, use SequenceMatcher.get_matching_blocks for a one-line solution:
from difflib import SequenceMatcher

def check(lstA, lstB):
    sm = SequenceMatcher(isjunk=lambda x: x not in set(lstA), a=lstA, b=lstB)
    return sum(block.size for block in sm.get_matching_blocks()) == len(lstA)

print(check(['A', 'B', 'C', 'D', 'E'], [':', 'A', '*', 'B', 'C', 'D', 'E', '`']))
print(check(['A', 'B', 'C', 'D', 'E'], ['A', '*', 'C', 'B', 'C', 'D', 'E']))
print(check(['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'F']))

Output
True
True
False

Notice that this also works for any sequence, like strings:
print(check('ABCDE', 'A*CBCDE'))
print(check('ABCDEF', 'A*CBCDE'))
print(check('', ''))
print(check('ABA', 'ABBA'))

Output (for strings)
True
False
True
True

SequenceMatcher will even give information on how to transform one sequence into the other:
listA = ['A', 'B', 'C', 'D', 'E']
listB = [':', 'A', '*', 'B', 'C', 'D', 'E', '`']
s = SequenceMatcher(None, listA, listB)
for tag, i1, i2, j1, j2 in s.get_opcodes():
    print('{:7}   a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format(tag, i1, i2, j1, j2, listA[i1:i2], listB[j1:j2]))

Output
insert    a[0:0] --> b[0:1]       [] --> [':']
equal     a[0:1] --> b[1:2]    ['A'] --> ['A']
insert    a[1:1] --> b[2:3]       [] --> ['*']
equal     a[1:5] --> b[3:7] ['B', 'C', 'D', 'E'] --> ['B', 'C', 'D', 'E']
insert    a[5:5] --> b[7:8]       [] --> ['`']


text:
Q: What is .DS_Store file in windows I found a file with .DS_Store extension in one of my drives. How did it get there?
My Operating System is Windows 7 64-bit and to the best of my knowledge I never accessed an Apple computer nor was accessed by one.

A: That file is a proprietary Mac/OSX system file that holds attributes/meta-data about the folder it resides in.
These often appear in file shares that are accessed over the network by a Mac user; but that's not the only way you can get them.  You may have gotten it in an archive (ie: a Zip file perhaps) you picked up someplace, which was originally created on a Mac.
I run into these all the time in archives we get from our graphic designers.
You're safe to just delete it.
More info: http://en.wikipedia.org/wiki/.DS_Store
For additional information on preventing them, perhaps check out these SU questions and answers (and others like them):

*

*How to prevent Mac OS X creating .DS_Store files on non Mac (HFS) Volumes?

*Any programs for getting rid of .DS_Store files?


text:
Q: Could not login to azure instance created using a managed data disk I created a virtual machine using the following command in azure cli.
az vm create --resource-group Test_Group --location eastus --name myVM2 --os-type linux --attach-os-disk disk1

I installed grub on disk1 and all necessary things for booting.I am facing an issue in connecting to the instance using ssh.


text:
Q: How to write type converter for a List in room database I have two entities 'tableOne' and 'tableTwo'
@Entity(tableName = "tableOne")
data class TableOne(
    @field:Json(name = "id") @PrimaryKey val id: Int,
    @field:Json(name = "image") @ColumnInfo(name = "image") val image: List<Image>?
) {
    constructor() : this(0, null)
}

@Entity(tableName = "tableTwo")
data class TableTwo(
    @field:Json(name = "id") @PrimaryKey val id: Int,
    @field:Json(name = "image") @ColumnInfo(name = "image") val image: List<Image>?
) {
    constructor() : this(0, null)
}

Now I have the 'Image' table which will be having the foreign key to the above two tables.
@Entity(
tableName = "Image",
foreignKeys = [ForeignKey(
    entity = TableOne::class,
    parentColumns = arrayOf("id"),
    childColumns = arrayOf("parent_id"),
    onDelete = ForeignKey.CASCADE,
    onUpdate = ForeignKey.CASCADE
), ForeignKey(
    entity = TableTwo::class,
    parentColumns = arrayOf("id"),
    childColumns = arrayOf("parent_id"),
    onDelete = ForeignKey.CASCADE,
    onUpdate = ForeignKey.CASCADE
)]
)
data class Image(
    @PrimaryKey
    @ColumnInfo(name = "id") var id: Int = System.currentTimeMillis().toInt(),
    @ColumnInfo(name = "parent_id") val parentId: Int,
    @field:Json(name = "url") @ColumnInfo(name = "url") val url: String?
) {
constructor() : this(0, 0, null)
}

I got an error when I ran the app.
error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.

How can we write type converter for List instead of converting to Json? Is this the way or do we need to add anything else?
    @TypeConverter
    @JvmStatic
    internal fun fromListOfImages(images: List<Image>): Image? {
        var img: Image? = null
        for (image in images) {
            img = image
        }
        return img
    }

    @TypeConverter
    @JvmStatic
    internal fun toListOfImages(image: Image): List<Image> {
        val images: ArrayList<Image> = ArrayList()
        images.add(image)
        return images
    }

A: The correct way to write converter for your use case is
    @TypeConverter
@JvmStatic
internal fun fromListOfImages(images: List<Image>): String {
    return Gson().toJson(images)
}

@TypeConverter
@JvmStatic
internal fun toListOfImages(image: String): List<Image> {
    val listType = object : TypeToken<List<Image>>() {}.type
    return Gson().fromJson<List<Image>>(image, listType)   }


text:
Q: Scatterplot with trajectory across datasets I am using ggplot2 in R to create scatterplots. I have (x,y) datasets for two different conditions as follows:
    x1           y1           x2             y2
1   1.00000000  150.36247   0.50000000  133.27397
2   1.00000000  129.62707   0.50000000  120.79893
3   1.00000000  79.94730    0.62500000  78.98120
4   1.00000000  79.78723    0.62500000  81.93014
5   1.00000000  133.47697   0.72727273  192.86557

I would like to plot (x1,y1) and (x2, y2) on the same plot, and draw a trajectory line connecting the two points, for each row in the dataset. For example, in the sample data above, there would be a line connecting (1,150) to (0.5, 133) (the data from row 1) and a separate line connecting (1,129) and (0.5, 120) (the data from row 2) and so on. Ideally, I would also like to make each line a different color.
I tried following the instructions below to create the trajectories but the grouping in my dataset is by columns rather than by rows: Scatterplot with developmental trajectories, and Making a trajectory plot using R
Currently, my script just generates two scatterplots on the same graph but there is no connection between data points of the same row:
scatter2<-ggplot(data = df, aes(x=x1, y=y1))
+ geom_point(aes(x=x1, y=y1), color="red")
+ geom_point(aes(x=x2, y=y2), color="blue")

Any help you can provide would be greatly appreciated! Thank you!

A: This can be achieved by using geom_segment(). You can find more information here: http://docs.ggplot2.org/current/geom_segment.html.
I suppose here, you would do something like
scatter2<-ggplot(data = df, aes(x=x1, y=y1))
  + geom_point(aes(x=x1, y=y1), color="red")
  + geom_point(aes(x=x2, y=y2), color="blue")
  + geom_segment(aes(x=x1, y=y1, xend=x2, yend=y2))

A: DF <- read.table(text="    x1           y1           x2             y2
1   1.00000000  150.36247   0.50000000  133.27397
2   1.00000000  129.62707   0.50000000  120.79893
3   1.00000000  79.94730    0.62500000  78.98120
4   1.00000000  79.78723    0.62500000  81.93014
5   1.00000000  133.47697   0.72727273  192.86557", header=TRUE)

Tidy up your data:
DF$id <- seq_len(nrow(DF))
library(reshape2)
DF <- melt(DF, id.var="id")
DF$var <- substr(DF$variable, 1, 1)
DF$group <- substr(DF$variable, 2, 2)
DF$variable <- NULL
DF <- dcast(DF, group + id ~ var)

Plot:
library(ggplot2)
ggplot(DF, aes(x=x, y=y)) +
  geom_point(aes(shape=group), size=5) +
  geom_line(aes(colour=factor(id)))


text:
Q: Java : Json with duplicate keys to map using Jackson I have a json file with same key but different values as follows,
{
    "domains" : {
        "A" : {
            "name" : "a",
            "type" : "a1"
        },
        "B"  :{
            "name" : "r",
            "type" : "g1"
         },
        "A" : {
           "name" : "b",
           "type" : "b1"
        }
    }
}

which is coming from external system.
How to convert the json to java map object and access the different values of the key: A
I am using something like below,
map = mapper.readValue(json, new TypeReference<HashMap<String,String>>(){});

which returns a map with unique keys. But I need a map object to hold all the data from json file.
Anyway to achieve this?

A: I agree with comments by @fge.
But if you really insists on solving this, you could sub-class HashMap (or any other Map), override its put method, and handle duplicates using whatever mechanism you want. Just make sure your Map has a no-arguments constructor.
Guava may also have a datatype that would allow retaining duplicates (Multimap?). If so, you will want to use Jackson's Guava module: https://github.com/FasterXML/jackson-datatype-guava

A: Answering since a related question was marked duplicate but seems to address the reverse problem where JSON with duplicate keys needs to be created. So that is Java Model -> JSON with duplicate keys.
Simplest way I found was to implement a custom serializer.
public class CustomSerializer extends StdSerializer<ModelToSerialize> {

    public CustomSerializer(Class<ModelToSerialize> t) {
        super(t);
    }

    @Override
    public void serialize(ModelToSerialize value, com.fasterxml.jackson.core.JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartObject();
        gen.writeStringField("DuplicateJsonKey", value.getDup1());
        gen.writeStringField("DuplicateJsonKey", value.getDup2());
        // Map all other values on value that you want to be present in the JSON
        gen.writeEndObject();
    }
}

And then when you go to serialize:
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(ModelToSerialize.class, new CustomSerializer(ModelToSerialize.class));
objectMapper.registerModule(simpleModule);
String sr = objectMapper.writeValueAsString(modelToSerialize);


text:
Q: Can Hibernate update a single property? I have a hibernate class with more than one property, I have heard that NHibernate tracks properties in files and only updates those properties that have changed. Is there similar functionality in Hibernate?
I have tried to get it to work using just a simple class load - then set one property - then flush changes. However this without fail updates all the properties in the class.

A: You need to set the dynamic-update property to true via annotation or in the class mapping which would exclude unmodified properties in the Hibernate's SQL update statement. You can find a good reference here. By default, the dynamic-update is set to false so as to be backward compatible as it is somewhat new feature introduced.

A: You can get Entity from db first then update ... try this example..
public final void updateEntity(EntityName entity){

  //get entity from db by id
  EntityName dbEntity = session.get(EntityName.class, item.getProductId());

   //set property
  dbEntity.setStatus(entity.getStatus());

  //and update
  session.update(dbEntity);

}

A: You can use the @DynamicUpdate annotation at the entity level, as shown here.


text:
Q: Cannot connect to laravel-websocket CORS issue I deployed my laravel application in GCP.  I also set up SSL on my application https://myapp.com. It was working fine connecting to the pusher server.  Then I switched to laravel-web sockets.  I modified the same code in my /var/www/myapp with the following:
.env
PUSHER_APP_ID=sample_id
PUSHER_APP_KEY=sample_key
PUSHER_APP_SECRET=samples_secret

config/broadcasting.php
'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'useTLS' => false,
                'host' => '127.0.0.1',
                'port' => 6001,
                'scheme' => 'http'
            ],
            'client_options' => [
                // Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html
            ],

resources/js/bootstrap.js
window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    wsHost: 127.0.0.1,
    wsPort: 6001,
    forceTLS: false,
    disableStats: true
});

Then I run it with
php artisan Webockets:serve

Then I go to my app https://myapp.com and got these errors.  I am not able to connect to my WebSocket:
wss://myapp.com/app/sample_key?protocol=7&client=js&version=7.0.6&flash=false
Finished

And a series of
WebSocket connection to 'wss://myapp.com/app/sample_key?protocol=7&client=js&version=7.0.6&flash=false' failed:

Access to XMLHttpRequest at 'https://sockjs-ap1.pusher.com/pusher/app/sample_key/856/8g5crt3n/xhr_streaming?protocol=7&client=js&version=7.0.6&t=1649947314189&n=1' from origin 'https://myapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

POST https://sockjs-ap1.pusher.com/pusher/app/sample_key/856/8g5crt3n/xhr_streaming?protocol=7&client=js&version=7.0.6&t=1649947314189&n=1 net::ERR_FAILED

A: First, if you're using Laravel Sail (Docker), you might check if you open your websocket port in docker-compose.yml.
services:
    laravel.test:
        #...
        ports:
            - '${APP_PORT:-80}:80'
            - '${VITE_PORT:-5173}:${VITE_PORT:-5173}'
            - '6001:6001' #websocket port added here

If it doesn't work, you can also remove the cluster option for Echo (not necessary for laravel-websockets) and add a wss option with the same port.
window.Echo = new Echo({
    broadcaster: 'pusher',
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    wsHost: window.location.hostname,
    wsPort: 6001,
    wssPort: 6001,
    forceTLS: false,
    disableStats: true,
});


text:
Q: WebRTC Video/Audio stream, but Audio is not playing I am working on an Electron app with React.js that sets up some peer connections through webRTC. Everything looks good with the connections and the peers receive the stream, but the video on the peers end does no play the audio. Perhaps I'm just not understanding how getUserMedia works, but I thought setting constraints true for audio and video was enough.
Relavent HTML (Peer)
<video ref="video" autoplay></video>

A few snippets of the code getting the stream
// constraints
this.constraints = {
    video: true,
    audio: true,
};

this.sdpConstraints = {
    'mandatory': {
        'OfferToReceiveAudio': this.constraints.audio,
        'OfferToReceiveVideo': this.constraints.video
    }
};

...
// getting/setting local video
setupLocalMedia(){
    navigator.mediaDevices.getUserMedia(self.constraints)
    .then(function(stream){
        self.localVideo.src = window.URL.createObjectURL(stream);
        self.stream = stream;
        window.stream = stream;
     }).catch(self.errorHandler);
}

// adding the stream to the peer
peerConnection.onaddstream = function(event){
    peerVideo.src = window.URL.createObjectURL(event.stream);
};

Again, all the connections are working just fine, and the video is streaming as expected, but no audio. Consoling the stream shows that the audio channel is enabled. Any ideas?


text:
Q: How to catch panic when HTTP client make request to unavailable url? I need to make request to some URLs. It is possible, that someone of them is unavailable. It is OK for me, and I want just ignore these URLs.
My problem is I cannot catch error, which is occurs. I get a error message:
2018/01/13 18:46:24 Get http://fakesite.com: dial tcp [::1]:8084: connectex: No connection could be made because the target machine actively refused it.

My sample code is:
package main

import (
    "fmt"
    "log"
    "net/http"
    "io/ioutil"
)

func main() {
    c := make(chan string, 1)

    go func() {
        defer func() {
            if r := recover(); r != nil {
                fmt.Println("try to catch error1", r)
            }
        }()

        resp, err := http.Get("http://fakesite.com")
        if err != nil {
            log.Fatal(err)
            c <- ""
            return
        }

        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Fatal(err)
            c <- ""
            return
        }

        c <- string(body)
    }()

    defer func() {
        if r := recover(); r != nil {
            fmt.Println("try to catch error2", r)
        }
    }()

    msg := <-c
    fmt.Println(msg)
}

A: The problem is:
log.Fatal(err)

This function performs two things. Firstly, it logs. But this function exits too.
// Fatal is equivalent to Print() followed by a call to os.Exit(1).
func Fatal(v ...interface{}) {
    std.Output(2, fmt.Sprint(v...))
    os.Exit(1)
}


text:
Q: Android: Extending a custom abstract Activity I created an abstract Activity which extends the android.app.Activity. Then I created an activity extending my abstract one. [1]
Everything is fine with ant, but eclipse showed an error in the manifest saying that my activiy did not exists, so I regenerate the class files and the error in the manifest is gone. But now eclipse shows an error at the root of my project and don't want to compile.
I precise that the activity is working fine in a device builded with ant. I tried to "Fix Project Properties" as well. I can't declare the abstract activity because of it's abstract.
Anybody already saw this bug ?
Thanks
[1] Here is a little schematic
android.app.Activity ->  abstract ActivityNet -> MyActivity

A: This is a common bug/behaviour of Eclipse.
To eliminate it click on the "Problems" icon (right bottom corner but it depends on your prospective)
Right click on the error line and then delete it.
The error should be gone away now


text:
Q: Todo list in react - how would you move an item completed I am very new to coding and I am trying to work on a Todo list.
Once I click on an item, I would like to have the option to mark it complete and move it to the "Completed Items" column...
Here is how it looks code wise so far :
in my App.js

  function markAsCompleted(event) {
      event.preventDefault()
    // ask if an item is complete
    // if it is, move it to completed items

    }

<li className = 'activities' onClick={markAsCompleted}
                key = {a.text}  >
                    <FaPaintBrush onClick={ (i) => toggleColor (a) }/>
                     <div
                     style = {{color: a.color }}>
                      Activity: {a.data.text},
                      Type: {a.data.area}
               </div>
               </li>

Here is my completed items component, for now not displaying anything else than a title

function CompletedItems (props) {

      return (

        <label>
        Completed items

        </label>

    );
  }
  export default CompletedItems;

Here is how it looks on the Localhost :)
Local host
Thank you so much for your help!
Julie


text:
Q: How to use MouseListener and MouseMotionListener in java3D to rotate 3D object? I m making desktop app in java swing. i made 3D image from my 2D image using PointArray[]. now i want to rotate image using MouseListener and MouseMotionListener.I used MouseRotate object to rotate myImage, but it not works well for that, MouseRotate rotate image with origin(0,0,0). but i want to rotate image using center point of image. means rotate image using center point not origin point. So, How can i do that?

A: Hmm, it's hard to tell without code, but I think you can just set up a transformation matrix and rotate it with that. Assuming the image is facing the front of the screen, you can try something like this:
public void mouseDragged(MouseEvent e)
{
    int dx = e.getX() - x; //x should be a global variable
    int dy = e.getY() - y; //same applies here
    x = e.getX(); //to set x for the next update loop
    y = e.getY();
    double rotation = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
    Transform3D transform = new Transform3D();
    Matrix3d matrix = new Matrix3d();
    transformG.getTransform(transform); //assuming the TransformGroup your image is in is transformG
    transform.getRotationScale(matrix);
    transform.rotZ(rotation);
    transformG.setTransform(transform);
}

You can set up the rotation amount differently if you want, but this should give you an idea


text:
Q: Porting module to newer Linux kernel: Cannot allocate memory I have a quite big driver module that I am trying to compile for a recent Linux kernel (3.4.4). I can successfully compile and insmod the same module with a 2.6.27.25 kernel.
GCC version are also different, 4.7.0 vs 4.3.0. Note that this module is quite complicated and I cannot simply go through all the code and all the makefiles.
When "inserting" the module I get a Cannot allocate memory with the following traces:
vmap allocation for size 30248960 failed: use vmalloc=<size> to increase size.
vmalloc: allocation failure: 30243566 bytes
insmod: page allocation failure: order:0, mode:0xd2
Pid: 5840, comm: insmod Tainted: G           O 3.4.4-5.fc17.i686 #1
Call Trace:
 [<c092702a>] ? printk+0x2d/0x2f
 [<c04eff8d>] warn_alloc_failed+0xad/0xf0
 [<c05178d9>] __vmalloc_node_range+0x169/0x1d0
 [<c0517994>] __vmalloc_node+0x54/0x60
 [<c0490825>] ? sys_init_module+0x65/0x1d80
 [<c0517a60>] vmalloc+0x30/0x40
 [<c0490825>] ? sys_init_module+0x65/0x1d80
 [<c0490825>] sys_init_module+0x65/0x1d80
 [<c050cda6>] ? handle_mm_fault+0xf6/0x1d0
 [<c0932b30>] ? spurious_fault+0xae/0xae
 [<c0932ce7>] ? do_page_fault+0x1b7/0x450
 [<c093665f>] sysenter_do_call+0x12/0x28
-- clip --

The obvious answer seems to be that the module is allocating too much memory, however:

*

*I have no problem with the old kernel version, what ever size this module is

*if I prune some part of this module to get a much lower memory consumption, I will get always the same error message with the new kernel

*I can unload a lot of other modules, but it has no impact (and is it anyway relevant? is there a global limit with Linux regarding the total memory usage by modules)

I am therefore suspecting a problem with the new kernel not directly related to limited memory.
The new kernel is complaining about a vmalloc() of 30,000 KB, but with the old kernel, an lsmod gives me a size of 4,800 KB. Should these figures be directly related? Is it possible that something went wrong during the build and that it is just too much RAM being requested? When I compile the sections size of both .ko, I do not see big differences.
So I am trying to understand where the problem is from. When I check the dumped stack, I am unable to find the matching piece of code. It seems that the faulty vmalloc() is done by sys_init_module(), which is init_module() from kernel/module.c. But the code does not match. When I check the object code from my .ko, the init_module() code also does not match.
I am more or less blocked as I do not know the kernel well enough, and all the build system and the module loading is quite tough to understand. The error occurs before the module is loaded, as I suspect that some functions are missing and insmod does not report these errors at this point.

A: I believe the allocation is done in layout_and_allocate, which is called by load_module. Both are static function, so they may be inlined, and therefore not on the stack.
So it's not an allocation done by your code, but an allocation done by Linux in order to load your code.
If your old kernel is 4.8MB and the new one is 30MB, it can explain why it fails.
So the question is why is it so large.
The size may be due to the amount of code (not likely that it has grown so much) or statically allocated data.
A likely explanation is that you have a large statically allocated array, whose size is defined in Linux. If the size has grown significantly, your array would grow.
A guess - an array whose size is NR_CPUS.
You should be able to use commands such as nm or objdump to find such an array. I'm not sure how exactly to do it however.

A: The problem was actually due to the debug sections in the module. The old kernel was able to ignore these sections, but the new one was counting them in the total size to allocate. However, when enabling the pr_debug() traces from module.c at loading time, these sections were not dumped with the others.
How to get rid of them and solve the problem:
objcopy -R .debug_aranges \
    -R .debug_info \
    -R .debug_abbrev \
    -R .debug_line \
    -R .debug_frame \
    -R .debug_str \
    -R .debug_loc \
    -R .debug_ranges \
    orignal.ko new.ko

It is also possible that the specific build files for this project were adding debug information "tailored" for the old kernel version, but when trying with a dummy module, I find exactly the same kind of debug sections appended, so I would rather suspect some policy change regarding module management in the kernel or in Fedora.
Any information regarding these changes are welcome.


text:
Q: PHP Instagram клиент Сейчас занимаюсь созданием парсера инстаграмм-профилей, и все хорошо работает, т.к. есть много данных по адресу
https://www.instagram.com/ ник пользователя /?__a=1
Но есть проблема: приватные профили. Гуглил много, повсюду только способы выставлять посты и сторис, но ни слова о подписке на другие профили и их просмотр.
Есть ли какой-то способ войти в инстаграмм, следить за приватными профилями и качать посты через API?

A: Нашел очень хорошую библиотеку - raiym/instagram-php-scraper
++ phpfastcashe/phpfastcashe
Работает отлично и стабильно, инстаграм думает, что пользователь сидит с телефона. Вхожу через свой профиль, все приватные каналы теперь доступны


text:
Q: Should I call escape_javascript when displaying data fetched from the database I have a field that is xss_sanatised in the model level before being saved in the database. When I wish to display this should I again escape_javascript it before rendering it in the view?
Like should my query be like
User.all.pluck(:id, :name).map { id: id, name: escape_javascipt(name)}
instead of
User.all.pluck(:id, :name).map { id: id, name: name }
When I directly injected  in the database it actually executed in the UI.
Although I'd not be able to write that value to the database without directly writing SQL Queries.
So Should I use escape_javascript for all fields or not?
Edit
This is rendered in the UI as a dropdown list using select2

jQuery('#input').select2({
    multiple: false,
    data: <%=tech.to_json.html_safe%>,
    initSelection : function (element, callback) {
        callback(<%= esc.to_json.html_safe %>);
    }
});

A: I think you're getting confused here simply because you're bypassing your own application's sanitisation rules - by directly writing to the database.
By default, you should never "trust" user input. It should always be considered potentially-malicious.
One reason you may choose to trust it, is if it's supplied by internal users (e.g. yourself!).
Or, another reason you may choose to trust it is if you've sanitised it before persisting it - i.e. you have explicitly blocked any potentially-malicious input.
Assuming your "xss_sanatised" input is safe (which I cannot confirm, since you didn't share the code), then you can trust user input as safe. Therefore it's fine to display directly in the browser.
However, if you force unsafe input into the database manually by "directly writing SQL Queries", then naturally the above assumption that "input is safe" becomes invalid. But this is an "impossible" scenario, so isn't something I'd particularly worry about.
If you really want to be doubly-extra-safe about this, then you could re-sanitise input before rendering it. But this is most likely overkill, in my opinion. (You should only need to sanitise it once, either way!)

escape_javascript is a separate method, that has nothing to do with user input sanitisation. This is irrelevant to the problem you are describing.
If you need to call escape_javascript on a value, then go for it. But again, since you didn't share the view rendering code, I cannot advise whether it's actually needed.


text:
Q: Is the CLR incompatible with Java (as a language)? I have wondered for a while about the feasibility of having Java run on the CLR.
After seeing a previous question here, I realize that there are quite a few differences between the Sun Java platform and the .NET runtime that would make cross-compiling impossible in all but the most trivial cases.
That being said, isn't IL a Turing-complete language?  Couldn't you write a JVM in IL?  Of course, the answer is yes, but why even go that far?
My question is:
Is the CLR (as a platform) incompatible with Java as a language (not a platform)?
How much of Java would have to be contorted or broken in order to make it fit?

Surely, this could be compiled for the CLR + .NET:
import System.*;

public class HelloWorldExample
{
    public static void main(String args[])
    {
        Console.WriteLine("Hello World !");
    }
}

Clarification:
What I'm getting at, is that I want to know what language features of java are incompatible with their CLR counterparts.
For example, I think that Generics are somehow in-congruent.  I believe that it is as similar story with exceptions.

A: The CLR was designed with the assumption that people would have to be able to transition to .Net from Java by being able to compile their Java source code largely unmodified. Thus, things in Java you might consider to be problematic in a runtime (like covariant arrays) are included as features in the CLR.
The J# project implements enough of the Java standard library that most Java apps will compile with minimal changes. Note that J# can load JVM bytecodes for compatibility, but J# source always compiles to CLR bytecodes.

A: A quick search reveals IKVM and the in-progress project Ja.NET.
That said, I could see value in going the other way.

A: Yes, but given that Java is much more widely used and more standard... wouldn't you want it the other way around, i.e. compile C# to Java bytecode? The answer of course is that it is possible to write a Java compiler that will emit bytecode for CLR or a C# compiler that will emit Java bytecode. The trickiness, though, is that you would need to provide a custom implementation of the  standard library / libraries that would defer to the library or libraries for that platform. And given the size of both APIs that would be a fairly significant undertaking. This would probably require a fairly large team to get it done in a reasonable amount of time. I would suggest starting an opensource project if you intend to do that, although given that C#/CLR is a Microsoft-ism, I'm not sure how much enthusiam can be generated.


text:
Q: java.lang.NumberFormatException: null at java.lang.Integer.parseInt Code in the below link: https://github.com/dheenupriya/Gpay
At first.. I login, then I get the mainPage.jsp and I click transactions and I can view transactions and click Main Page button and I move back to mainPage.jsp and then when I click logout in mainpage.jsp, I move to index.jsp. Now my problem is.. when I click back, i go to mainPage.jsp and from there when I click linkbankaccount.jsp, I able to go to session_expired.jsp as session==null... but when I click other links like view balance or transaction_history.jsp... I get HTTP 500 internal server error... don't know y...
The page I get when I click logout and go back to mainpage and click linkbankaccount.jsp

The page I get when I click other links like transactions, view balance

A: Because you have removed the userId after logged out.
Logout .java Line#11
session.removeAttribute("userId");
and then you got a null when you go back to histoy:
Transaction_history.java Line#42
String s_user_id = (String)session.getAttribute("userId");


text:
Q: JavaPoet: Creating two enums in the same file In Java you can create a single file and it may contain more than one enum\class, for example something like this:
Filename: Recorder.java

public enum Recorder {
  RECORDER_A, RECORDER_B;
};

enum Feature {
  FEATURE_A, FEATURE_B;
};

I'm able to create the "Recorder" enum using JavaPoet, but I can't figure out how to create the 2nd one... notice - they are not nested!
Thank you for any input :-)

A: This is not possible in JavaPoet because it has caused certain problems with certain build tools. Work around by creating separate files for each top-level type.


text:
Q: value of NULL after inserting value I use the following code:
library(data.table)
SRC2 <- read.table(header=TRUE, text='"sequenceID" "transactionID" "eventID" "items"  "Exist"
"1" 42207993       1577          1        "OV50"     1
"2" 42207993       6048          2        "OV11"     0
"3" 42207993       1597          3        "OV148"    1
"4" 57237976       12423         1        "OV46"     0
"5" 57237976       12589         2        "OV197"    1')

setDT(SRC2)
SRC2$Exist<- as.integer(SRC2$Exist)

i1 <- SRC2[, Co:= as.character(round(sum(Exist)/.N, 2)) , sequenceID][, .I[1:(.N-1)], sequenceID]$v1

When I try to find the content of i1:
> i1
NULL

Why do I get the value NULL instead of the required value: 1 2 4? How can I get the required values?
Finally I would like to use the following command:
 SRC2[i1, Co:= '']

And because i1 is NULL I get the following:
> SRC2[i1, Co:= '']
Null data.table (0 rows and 0 cols)

A: You wrote v1 instead of V1.
So this works:
i1 <- SRC2[, Co:= as.character(round(sum(Exist)/.N, 2)) ,
           sequenceID][, .I[1:(.N-1)], sequenceID]$V1


text:
Q: Mouse.WheelScrollLines Property in C# So I made a custom Scroll Bar in C# but I would like to add Windows Properties to it. the problem is, I cant seem to get the Microsoft.VisualBasic.Devices namespace to work in C#. any ideas on how to fix this.
Simply put the IDE does not identify it as a namespace. it does however identify MicroSoft.VisualBasic. here is what I want to do but in C#.

A: Try to add a reference MicroSoft.VisualBasic :
Project > Add Reference ... in the .NET tab select Microsoft.VisualBasic.


text:
Q: How does a string gets displayed 'after' pressing ENTER even though std::cout was used for/after each character in the given code? It's a program which reads the input character by character, and prints it in the same way. The conceptual doubt I'm having here is that how is the complete string being displayed only on pressing ENTER key, even though std::cout was used on every iteration of taking each character input?
int main()
{
 char c;
 while(1)
 {
     c = cin.get();
     if(cin.eof())
         break;
     else cout << c;
 }
 return 0;
}

A: Lets examine your code:
#include <iostream>
using namespace std;

int main()
{
    char c;
    while (1)
    {
        c = cin.get();
        if (cin.eof())
            break;
        else cout << c;
    }
    return 0;
}

In our first line, we make a char. Then we enter a while loop. cin.get() waits until the user hits enter, then flushes and puts the input into a buffer. cin.get() then returns the first char in the buffer, and removes the char it returned. if (cin.eof()) does not execute, because we did not put a EOF yet. On the next loops, cin.get() grabs the remaining chars in the buffer, and when the buffer is empty, waits for the user to enter more input and hit enter.
std::cin is buffered, so you will not get input instantly.
Also, read on Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?.


text:
Q: TikZ scaling problem I tried
\begin{tikzpicture}[scale=0.5]

as indicated in the manual but it had no effect.
Is there an alternative to achieve the desired effect?
Is there a guide to the acceptable values for scale -?


text:
Q: An entire function $g$ such that $|g(z^2)| \leq e^{|z|}$ and $g(m) = 0 \quad \forall m \in \mathbb{Z}$ is identically $0$ I have been trying to solve the following exercise from a collection of old complex analysis qualifier exams.

Suppose that $g$ is an entire function that satisfies the inequality $|g(z^2)| \leq e^{|z|}$. Also suppose that $g(m) = 0 \quad \forall m \in \mathbb{Z}$. Then prove that $g(z) \equiv 0$ (i. e. that $g$ is identically $0$).

So what I think is that the inequality by putting $z^{1/2}$ gives me $|g(z)| \leq e^{|z|^{1/2}}$ and this means that the entire function $g$ is of finite order and its order $\lambda = \lambda(g) \leq \frac{1}{2}$. Then I have been looking at the basic theorems for finite order entire functions but I don't really see if one of them would be helpful here.
So my question is how can I solve this problem? Is it really helpful to look at the theorems for finite order entire functions?

A: Since $\mid g(z) \mid \leq exp(\mid z \mid^{\frac{1}{2}})$, $g$ has growth order $\leq \frac{1}{2}$ by definition, as you correctly remark.
If $g$ were not the zero function and if $(z_k)_k$ were some enumeration of its non-zero zeros, we would have for all $s\gt \frac{1}{2}$ (Stein-Shakarchi, Theorem 2.1, page 138)
$$  \sum_k    \frac{1}{\mid z_k \mid ^s }         \lt \infty   $$   In particular, taking $s=1$ and realizing that the positive integers are among the zeros $z_k$ according to the statement of the exercise, we would get
$$\sum_{n=1} ^\infty    \frac{1}{n } \leq  \sum_k    \frac{1}{\mid z_k \mid  }         \lt \infty   $$
Since the harmonic series actually diverges ( $\sum_{n=1} ^\infty    \frac{1}{n }=\infty $ ) this is  false and we must have  $g=0$.
N.B. The basic heuristic of growth order of an entire  function is that the faster the  function grows, the more zeros it has.
A baby case is that of a polynomial: if its degree is  $n$ it grows like $\mid z\mid^n $and has $n$ zeros.


text:
Q: Copy members of one struct to another C# I want to copy members of one struct (GR) to another larger struct (FR)
    public struct gr
    {
        public double O,C,L;
        public bool isLastFRH, isLastFRL;
    }
    public gr GR;

    // Here I assign values to GR and then I want to copy all these values to FR

    public struct fr
    {
        public double O,C,L;
        public bool isLastFRH, isLastFRL;
        // it has more variables.
    }
    public fr FR;

Is it possible to be done without going one by one:
    FR.O = GR.O; // and so on...

Thank you

A: You cannot subclass a struct in C#, so your best option is to create a new struct that uses the struct you want to copy. The GR property is a struct so it will be a copy of whatever you set it with.
In your fr class add the gr member:
public struct fr
{
   public gr GR;
   //add your unique props..
}

Now you can create fr and just set the GR property, it will copy.
var gr1 = new gr() {  //set all your properties.. };
var fr1 = new fr() { GR = gr1, ... //set all your fr specific props here };

A: Try using automapper, it allows you to create mappings easily. see details
var config = new MapperConfiguration(cfg => cfg.CreateMap<gr, fr>());

var mapper = new Mapper(config);
Fr model = mapper.Map<Fr>(gr);


text:
Q: Can I remove store_id from cached image path? I have a multi-store shop where product images are the same in all store views. As a consequence I have lots of thumbnails - duplicates of each other, e.g.:
media/catalog/product/cache/5/small_image/300x/9df78eab33525d08d6e5fb8d27136e95/b/a/bag.jpg
media/catalog/product/cache/5/small_image/600x/9df78eab33525d08d6e5fb8d27136e95/b/a/bag.jpg
media/catalog/product/cache/2/small_image/300x/9df78eab33525d08d6e5fb8d27136e95/b/a/bag.jpg
media/catalog/product/cache/2/small_image/600x/9df78eab33525d08d6e5fb8d27136e95/b/a/bag.jpg
media/catalog/product/cache/11/small_image/300x/9df78eab33525d08d6e5fb8d27136e95/b/a/bag.jpg
media/catalog/product/cache/11/small_image/600x/9df78eab33525d08d6e5fb8d27136e95/b/a/bag.jpg
media/catalog/product/cache/4/small_image/300x/9df78eab33525d08d6e5fb8d27136e95/b/a/bag.jpg
media/catalog/product/cache/4/small_image/600x/9df78eab33525d08d6e5fb8d27136e95/b/a/bag.jpg

If I extend Mage_Catalog_Model_Product_Image and simply comment out the store_id from setBaseFile($file) function, e.g.:
    // build new filename (most important params)
    $path = array(
        Mage::getSingleton('catalog/product_media_config')->getBaseMediaPath(),
        'cache',
        //Mage::app()->getStore()->getId(),
        $path[] = $this->getDestinationSubdir()
    );

Will there be any unintended consequences from doing this, and, will it work?

A: Yes you can safely do this in your situation. Please refer to my answer in this question: How to store cache in centralised ID folder in magento?