text:
Q: Dependency Injection in .NET Core 3.1 with multiple implementations I am confused about dependency injection in .NET Core where I have many intercoupled dependencies. I have a class MyClass implementing an interface IMyClass as follows:
public class MyClass : IMyClass
{
     private IClass classA;
     private IClass classB;

     public MyClass (ClassA classA, ClassB classB)
     {
          this.classA = classA;
          this.classB = classB;
     }
     ....
}

The classes ClassA and ClassB are implementations of interface IClass as follows:
public class ClassA : IClass
{
     public ClassA (many other DI)
     {
     }
}

public class ClassB : IClass
{
     private IClass baseClass;

     public ClassB (IClass baseClass, ...)
     {
          this.baseClass = baseClass;
          ....
     }
}

In my startup file, how should I register my dependencies. I have tried the following, which doesn't work:
services.AddSingleton<ClassA>();
services.AddSingleton<IMyClass, MyClass>();

Can someone please explain what is the issue here and the solution to this?

A: you need to add the following in configureservices of Startup.cs:
var factory = ActivatorUtilities.CreateFactory(typeof(ClassB), new Type[] {typeof(IClass)});
services.AddSingleton<ClassB>(sp => factory.Invoke(sp, new object[] {sp.GetService<ClassA>()}) as ClassB); //when calling sp.GetService<ClassA> you can of course pass any implementation of IClass instead of ClassA. Of course you cannot pass ClassB beacause of infinite recursion.

With this solution you are telling the IoC container that you want to register a service for ClassB wich:

*

*will have his dependency of type "IClass" resolved as "ClassA" as it was declared in the IoC container

*will have all other dependencies normally resolved by the IoC container


text:
Q: How to use stopifnot with a list in R Suppose I have a list of vectors. Suppose further that I would like to have a condition based on their length. That is, I would like my function return an error if the lengths of these vectors are not equal.
For example,
x <- c(1:4)
y <- c(1:5)
z <- c(1:4)
k <- list(x, y, z)
I would like to check that their lengths are equal.
stopifnot(length(k[[1]]) == length (k[[2]]) == length(k[[3]]))
How could I generalize this code and make it works for an arbitrary number of elements of the list?

A: We can use lengths with unique
stopifnot(length(unique(lengths(k)))==1)

Error: length(unique(lengths(k))) == 1 is not TRUE

The lengths will get the length of each of the vector in the list as a vector, get the unique and check if the length is equal to 1.  If it is not i.e. stopifnot, give an error

redpajama_set_name: RedPajamaStackExchange


text:
Q: When/why did Stack Overflow disallow anonymous questions? I remember a time when anonymous users could post questions without an account on Stack Overflow. IIRC, this is no longer possible.
I don't mind the removal. I DO, however, find it interesting that it was built and then removed. What was the rationale? Are there any blog posts talking about it? Are there any stories from the trenches that lead to the decision?
Why did Stack Overflow drop anonymous content?
I ask because I'm faced with a similar situation and tested wisdom is interesting.
(Again, I don't want this to be a feature debate, but rather a historical recounting).

A: The SE platform optimizes for high-quality answers; for that, the starting point is high-quality questions.  See Optimizing for Pearls, not Sand.  Note that posting an answer is still almost frictionless; anyone can post an answer to a question, even anonymously.
To that end, requiring registration became part of a comprehensive effort to combat a flood of low-quality questions that were plaguing Stack Overflow in late 2011.
See Also
Clarify the "No registration required" message
Encouraging users to create an account (and keep it)

A: When: September, 2011
Why: With a question volume of between 4,000 and 5,000 questions per day, it no longer "made sense"
Source

Programmers (now Software Engineering) followed suit a year later


text:
Q: CakePHP 1.3 query question I am trying to convert working query to CakePHP find. So I fail, try to use Containable behavior and so on, but no luck. Please help me convert this SQL query to CakePHP find:
SELECT COUNT(DISTINCT(da.dealer_id))
    FROM dealer_access_list da, dealers d
    WHERE   da.dealer_id NOT IN (SELECT dealer_id FROM fixture_inventory)
    AND d.disabled = 0
    AND d.do_not_include IS NOT TRUE
    AND da.dealer_id = d.dealer_id

Thank you!
I have problems with joining more that two tables and using SQL special functions. I want to use CakePHP ORM and not plain SQL if possible.

A: Cake used to have the -! syntax for running SQL inside the find, which would have come in handy with your nested query. But with that deprecated, as far as I know, you might have to break it into 2 pieces.
I'm going to put my answer here using two queries, till someone can put up an alternative with the nested query
$dealers  = //get the dealer IDs in the table in the normal way. make sure it's an array of only the IDs

$opts = array(
  'fields' => array(
    'COUNT(DISTINCT(da.dealer_id)) AS count_dealer_id'
   ),
  'conditions' => array(
    'NOT' => array('da.dealer_id' => $dealers),
    'd.disabled' => 0,
    'd.do_not_include IS NOT TRUE',
  )
)
$results = $this->find('all', $opts); //assuming you're in the correct model

As long as you have the associations setup properly in the models, cake will figure out the correct joins and you don't have to worry about it.


text:
Q: Minimising line integral over a scalar field part 2 This is a continuation of this question whose general point is summarised below

Say we want to find a path $y=y(x)$ in the scalar field $S(x,y)$ that finds the extrema of of its line integral.
  Therefore we wish to minimise the integral $$\int_{x_1}^{x_2} S(x,y(x))
  dx $$

The original question involved $S(x,y)=y*x^2$ and the Euler-Lagrange equation returned $x^2=0$ because there was no extrema.
But intuitively $S(x,y)=x^2*y^2$ should have a minimum path for almost any two point.
Applying the Euler-Lagrange:
$$\frac{dS}{dy}-\frac{d}{dx}(\frac{dS}{dx'})=0 $$
$$2*x^2*y-\frac{d}{dx}0=0 $$
$$x^2*y=0 $$
Which means either $x=0$ or $y(x)=0$ which continues to confuse me, as I assumed a minimum would exist. Could somebody please explain to my how the Euler-Lagrange equation behaves for the integrand being independent of the derivative of $y$?


text:
Q: Spring MVC form validation messages not loading I'm trying to define error messages in a resource file, but I can't seem to get them to load so I can use them in my controller.
My servlet-context.xml file:
<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <beans:property name="basename" value="classpath:messages" />
</beans:bean>

My form:
public class LoginForm {
    @NotEmpty
    private String username;
    // getters and setters
}

My messages.properties file (in the root of my source folder, so it gets compiled to the root of my classes folder):
NotEmpty.loginForm.username=test1
NotEmpty.username=test2
NotEmpty.java.lang.String=test3
NotEmpty=test4

My controller:
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@Valid LoginForm form, BindingResult result) {
    if (result.getFieldErrors().size() > 0) {
        FieldError firstError = result.getFieldErrors().get(0);
        System.out.println(firstError.getDefaultMessage());
    }
    // ...
}

However, the output of the getDefaultMessage call is never what I define in my resource file! It is always may not be empty (the default).
I've tried a variety of different entries in my context file but it seems like it's not loading the resource file. What am I doing wrong?

A: According to this documentation, all you need is to put a properties file called ValidationMessages.properties at the root of your project classpath.
You can then add properties with the following format
org.hibernate.validator.constraints.NotEmpty.message=Default message, can not be empty
NotEmpty.ClassName.fieldName=fieldName can not be empty.

where ClassName is the name of your class and fieldName is the name of the field of that class.
You might need to do some configuration to set the correct MessageInterpolator, but I think the default one will do what you need.

A: First idea:
Try to rename property keys from NotEmpty.loginForm.username to NotEmpty (Just to check if messageSource works correctly). If still not working there is
Second idea:
Where do you perform scanning of components?
Assume that you have two spring configurations: applicationContext.xml (or other name) and servlet-context.xml.
If you have such structure <context:component-scan base-package="by.company.app" /> in applicationContext than your controllers have no defined messageSource - so it cannot load customized messages. It is because @Controller bean is in one spring context, MessageSource bean - in another. (To check this you can simple declare @Autowired MessageSource messageSource field in controller and see in debug is it null or not) In that case you can modify component-scan in applicationContext to:
<context:component-scan base-package="by.company.app">
    <context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>

and add following configuration to servlet-context.xml:
<context:component-scan base-package="by" use-default-filters="false">
    <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>

Hope this helps

A: Unfortunately it looks like a MessageSource must be defined and then used in the appropriate Java class. The getDefaultMessage() method doesn't appear able to read from message properties.
In a component-scanned class:
@Autowired
private MessageSource messageSource;
public String getMessage(FieldError field) {
    return messageSource.getMessage(field, null);
}

This will iterate through all possibilities in the message properties files and then--if nothing is found--falls back on the getDefaultMessage() results.
Additionally I updated my servlet-context.xml file to define my messageSource with the basename value of /WEB-INF/classes/messages, as opposed to what I had in my question above.

A: I spent some time to fix this issue, I done a following changes, now it is working fine in Spring 4.0 MVC and Hibernate 4.1.9
1.put messages under source folder.

*

*If ReloadableResourceBundleMessageSource is not working change to

      class="org.springframework.context.support.ResourceBundleMessageSource">

*changes property like  '<'property name="basename" value="messages"/>

*In Message.properties file, the key should be in the following format.
NotEmpty.userForm.userId
userForm-->Model class name.

(If your Model class name is UserForm, then it should
                                     be mentioned as userForm)
    userId--> attribute of userForm class


text:
Q: drawing different parts of a line in different colours How to draw different parts of a line in different colours. In the following code can each part of the line be drawn in different colour
    \documentclass{beamer}
\beamertemplatenavigationsymbolsempty
\usepackage{tikz}
\usepackage{pgfplots}
\begin{document}
\begin{frame}[fragile,t]
\frametitle{}
{
\begin{tikzpicture}
\draw [thick, green] (2.3,1.4) +(-27:2.2cm)-- +(153:2.2cm) +(42:1.88cm) -- +(-138:1.88cm);
\end{tikzpicture}
}
\end{frame}
\end{document}

A: Using edge could perhaps be an option.

\documentclass{beamer}
\beamertemplatenavigationsymbolsempty
\usepackage{pgfplots}
\begin{document}
\begin{frame}[fragile,t]
\frametitle{}
{
\begin{tikzpicture}
\draw [thick, green] (2.3,1.4) +(-27:2.2cm) edge +(153:2.2cm) +(42:1.88cm) edge[blue] +(-138:1.88cm);
\end{tikzpicture}
}
\end{frame}
\end{document}


text:
Q: how to install approxeng on windows 10 I tried writing the command pip install approxeng.input on command prompt and it raised an error that said
The 'linux/input.h' and 'linux/input-event-codes.h' include files
are missing. You will have to install the kernel header files in
order to continue:

    yum install kernel-headers-$(uname -r)
    apt-get install linux-headers-$(uname -r)
    emerge sys-kernel/linux-headers
    pacman -S kernel-headers

can anybody help me understand what I'm supposed to do?


text:
Q: Safari extension builder no "+" sign to add new extension folder I have an extension that I need to build back to safariextz, but there is no + sign to add new extension. In the tutorials there are + signs but they are old tutorials and there is no new information. How do I build extension?

A: *

*In Safari, from the Develop menu, choose Show Extension Builder.

*Choose Continue from the Xcode promotion sheet if shown.

*From the bottom-left of the window, click the + button.


text:
Q: Sending bulk "Weekly Digest" email from Rails 3 application I created a rake task to send emails to my subscribers (registered users).
digest.rake:
desc "Send digest"
task :send_digest => :environment do
   Notifier.digest.deliver #if Time.now.monday?
end

Notifier::digest
 def digest(periodicity = "weekly")

   @from = "biowatts@gmail.com"

   @bcc = ""
     User.where("digest_periodicity LIKE ?", periodicity).each do |u|
       @bcc += u.email_address + ","
     end
   @bcc = Rails.env.production? ? @bcc[0..-1] : "biowatts@gmail.com"

   @message_subject = Rails.env.production? ? "#{periodicity.capitalize} Digest" : "#{periodicity.capitalize} Digest (Test)"

   @public_projects = PowerPlant.where("public = ?", true).order("created_at desc")

   mail(:bcc => @bcc, :subject => @message_subject)

end
This works all fine until I try to deploy.
On my production environment my list of recipients is over 300 emails addresses.
so when I run the proper rake command, instead of sending my email I am getting this message.
$ heroku rake send_digest --app biowatts
> rake aborted!
> 452-4.5.3 Your message has too many recipients. For more information regarding

I am using a smtp.gmail.com
but I also tried to use my godaddy smtp mail server,
but it looks like I am going to face similar issues.
MY QUESTION: How do I send an email periodically to the list of my subscribers?
Note This email is build upon what's in my database ...
hope you can help,
joel

A: Your code is fine. The issue is the rules for gmail. You can't send that many emails at once. If you have ever had a friend's account hacked you will see they send the email to 100 or so recipients and repeat.
Solution:
Have multiple emails and rotate (this is a bad idea because it will trigger other spam defenses from gmail)
Use Constant Contact or some other bulk mailer - Ideal for your situation
Use SendGrid - They will likely drop you as you are "spamming" in their eyes even though you aren't really spamming.


text:
Q: Brumer theorem about ideal class group I am reading chapter 9 in Cassels-Frohlich Algebraic Number Theory, this chapter is about class field tower.
In this chapter the following claim is due to Brumer: There exist a function $c(n)$ \begin{gather*}d^p Cl_k\geq t_k^p-c(n)\end{gather*} where $t_k^p$ is the number of rational primes of ramified primes $q$ such that $p$ divide $e_k(q)$ and $n$ is the degree of $k$.
Remark: when $k$ is not Galois then one take $e_k(q)$ to be $gcd_{\mathfrak{q}|q}e(\mathfrak{q}|q)$, feel free to ignore this and assume $k$ is Galois.
When I looked at Brumer's paper (Ramification and class tower of number fields)  I couldn't find this claim, I found a similar claim: Let $k$ be a Galois number field of degree $n$, and $r$ the number of generators of its class ideal group and supposed $s$ primes are ramified in $k$ then \begin{gather*}\frac{s}{w(n)}-2n\leq r\end{gather*} where $w(n)$ is the number of distinct prime factors of $n$.
I can't understand how these two claims are related, I don't see how the second inequality implies the first and less important the Galois assumption.
Thank you all!


text:
Q: jQuery Callback .load not working on mobile device This code:
$("#sound").load("randomradio.php", function() {
    var r = document.getElementById("radio");
    r.play();
});

randomradio.php dynamically creates a <audio id="radio">...
and it works fine on my PC webbrowser. Just not on mobile devices and I can't figure out why.

A: jQuery should work fine on mobile devices.
jQuery mobile is something else entirely, you don't need it. Perhaps the code is breaking when you viewed on a mobile device? Have you tried looking at your javascript errors? You can see error
You can find these errors in the JavaScript Console. For Chrome you can open it in a couple ways:

*

*Use the keyboard shortcut Command - Option - J (Mac) or Control -Shift -J (Windows/Linux).

*Select View > Developer > JavaScript Console.


text:
Q: ffmpeg/ffprobe show_frames option I recently installed ffmpeg version 0.8.5-4:0.8.5 on my Ubuntu Linux box.
When I execute "ffprobe -show_frames http://test.com/test.mp4" I get the following error:
Unrecognized option 'show_frames'
I have tried installed all sorts of ffmpeg dependent packages to fix this without any success.
Can someone help to resolve this error by telling me what I need to install exactly to fix this?
Thanks

A: You're using a crippled, fake version of "ffprobe" that originates from libav, not FFmpeg:
Ubuntu switched from FFmpeg to libav because the Debian/Ubuntu ffmpeg package maintainer is a libav developer. The intentional usage of the names "ffmpeg" and "ffprobe" for something not from FFmpeg was disappointing, and is misguiding to users and misrepresents the work of the FFmpeg developers. Also see Who can tell me the difference and relation between ffmpeg, libav, and avconv?
This bizarro "ffprobe" does not have the -show_frames option. You have three options:

*

*Compile ffmpeg and/or ffprobe

*Use Jon Severinsson's FFmpeg PPA

*Use a static build of ffmpeg
All three methods will provide a real, working ffprobe. Use the static build if you're lazy.

A: Uninstalled the current version of ffmpeg(This was a static build downloaded from the ffmpeg site: http://ffmpeg.gusari.org/static/32bit/
show_frames option was deprecated in this version.
Download and installed the latest version from:http://www.ffmpeg.org/releases/ffmpeg-1.1.3.tar.bz2


text:
Q: How to resolve "snapd returned status code 400: Bad Request"? I have encountered "snapd returned status code 400: Bad Request" error while installing applications from Synaptic Package Manager in Ubuntu.I tried to use Software Center also but it's not working.

A: I used snap to resolve this issue and it worked.
I have installed skype to check this.
snap find "skype"
Then used the command in the following fashion to install the snap package:
sudo snap install skype --classic
::Snap is universal packaging system launched by Ubuntu.It allows you to use these Snap packaged applications on any Snap supported Linux distributions, not just Ubuntu.::

A: The better way for the installation of your application will be using snap. Whatever application you are installing through synaptic, try it with snap.
Just take the keyword of the application name. As an example, I take visual studio code.
snap is providing the installation of visual studio code. Use these steps in command line.

Step 1: snap find "visual studio code"
Step 2: sudo snap install vscode --classic

Please note that the name "vscode" came from the result of Step 1.
After the execution, the window opens automatically and then you can continue.
I tried installing skype with this, and got it done successfully.
For more details of snap, and its errors, use the link https://youtu.be/tmqBlc7FFgg

A: For Any type of application type the command described above. As i got the same issue while downloading visual studio.
snap find "visual studio code"

Follow this link to get better idea.enter link description here


text:
Q: rails admin join model Hy guys,
Is my first time using rails admin and I have one question how to use join model on rails admin.
I have this models:
class Visitor
  attr_accessible :name
end
class Place
  attr_accessible :name
  has_many :visits
end
class Visit
  attr_accessible :another_field
  belongs_to :visitor
  belongs_to :place
end

and my PlaceConcern is like that:
rails_admin do
  edit do
    group :visits do
      field :another_field
      field :visits do
        searchable :name
      end
    end
  end
end

but that way when I edit/create a tour on my admin panel, when adding a visit, I need to select visitor AND tour. I need a way where the tour will be auto selected (because actually I already have it). How should I configure my concern?

A: You need to configure the inverse_of of your associations.
You can do it on the associations or on the fields like this:
config.model Team do
  field :categories do
    inverse_of :teams
  end
end


text:
Q: Objective-C to Swift Navigation not working I'm translating some code from Objective-C to Swift, but something isn't working. The code below is supposed to switch views and pass a String, however, nothing happens when a cell is tapped. I've embedded both ViewControllers with a NavigationViewController in Storyboard.
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {

        var dvc : TemplateViewController = self.storyboard?.instantiateViewControllerWithIdentifier("TemplateViewController") as TemplateViewController
        dvc.tweet = self.templateList?.objectAtIndex(indexPath.row) as NSString
        self.navigationController?.pushViewController(dvc, animated: true)

}

A: You need to explicitly write some methods in your TemplateViewController. Follow this SO answer
Instantiate and Present a viewController in Swift


text:
Q: Assigning random value to a parameter in a python program I need to assign a default random value in __init__(). For example:
import math
import random
class Test:
    def __init__(self, r = random.randrange(0, math.pow(2,128)-1)):
        self.r = r
        print self.r

If I create 10 instances of Test, they all get the exact same random value. I don't understand why this is happening. I know I can assign the random value inside the __init__(), but I am curious why this is happening. My first guess was that the seed is the current time and objects are being created too close together, and, as a result, get the same random value. I created objects 1 second apart, but still same result.

A: The random.randrange(0, math.pow(2,128)-1) is evaluated when the function is defined, not when it is called.
Use
class Test:
    def __init__(self, r = None):
        if r is None:
            r = random.randrange(0, math.pow(2,128)-1)
        self.r = r
        print self.r

instead.

A: The value of the default parameter is being set at the time the function is created, not when it is called - that's why it's the same every time.
The typical way to deal with this is to set the default parameter to None and test it with an if statement.
import math
import random
class Test:
     def __init__(self, r = None):
             if r is None:
                 r = random.randrange(0, math.pow(2,128)-1)
             self.r = r
             print self.r

A: When you put the expression inside the constructor header (instead of the constructor body) it only gets evaluated once.
Try this in the body:
self.r = random.randrange(0,math.pow(0,128)-1)

A: The reason all your class instances have the same value for the argument is because its default value is determined only once, when the method definition it is part of is compiled as part of the class statement's execution.
Although this is not the use it was designed for, you could use Recipe 20.14 titled Automatic Initialization of Instance Attributes from the somewhat dated Python Cookbook, 2nd Edition to achieve what you want to do.
This is it applied to the sample code in your question:
class AutoAttr(object):
    def __init__(self, name, factory, *args, **kwds):
        self.data = name, factory, args, kwds
    def __get__(self, obj, cls=None):
        name, factory, args, kwds = self.data
        setattr(obj, name, factory(*args, **kwds))
        return getattr(obj, name)

import math
import random

class Test(object):
    r = AutoAttr('r', random.randrange, 0, math.pow(2,128)-1)  # default value
    def __init__(self, r=None):
        if r is not None:  # argument value supplied to override default?
            self.r = r
        print format(self.r, ',d')

for i in xrange(5):
    Test()
Test(42)  # override default random initial value

Sample output:
282,608,676,427,101,189,083,121,399,193,871,110,434
211,475,719,281,604,076,410,306,973,803,289,140,631
86,842,148,927,120,143,765,936,219,265,140,532,918
41,767,122,731,332,110,507,836,985,804,081,250,336
97,993,619,669,833,151,963,441,072,354,430,500,011
42

Here's how it works:
The auto_attr class from the recipe is a called a descriptor. One of them is assigned to a Test class attribute named r. The first time you access this attribute in an instance of Test using self.r, Python notices it's bound to a descriptor and calls its __get__() method with the Test instance as an obj argument.
The descriptor's __get__() method calls the associated factory function and assigns the result to an instance attribute with the same name, so that all further references to that attribute through the instance will get its actual value instead of the Test class's auto_attr descriptor.


text:
Q: A tricky algebraic inequality This is an old inequality but I haven't seen a satisfactory solution yet and am hoping someone here can provide one. There are a couple of brute force solutions but they provide no insight into the inequality and I'd be surprised if there isn't a trick to it:
$$x\frac{(y+z)^2}{(1+yz)^2} + y\frac{(x+z)^2}{(1+xz)^2} + z\frac{(x+y)^2}{(1+xy)^2} \ge \frac{3\sqrt 3}{4}$$
for $xy+yz+zx = 1$, all positive.
My attempt was to try to find a lower bound of the left side in terms of symmetric quantities like $u=x+y+z$ and $w=xyz$, however I haven't had much success despite multiple attempts. For example, the left hand side above can be bounded from below by
$$\sum x\frac{(y+z)^2}{(1+yz)^2} \ge\frac{\left(\sum x(y+z)^2\right)^3}{\left(\sum (y+z)(1-y^2z^2)\right)^2} = \frac{\left(u+3w\right)^3}{\left(u+2u^2w+w\right)^2}$$
but the above has a minimum just a tad less than $3\sqrt 3/4$.
I have also tried a cotangent substitution and breaking the symmetry (i.e. assuming $x\ge y\ge z$) but I didn't get far.
I don't know the origin of the inequality but it's supposed to be competition level so I suspect it has a nice and tricky solution and not just a brute force one. So, I am hoping someone here will find it.

A: We need to prove that
$$\sum_{cyc}\frac{x(y+z)^2}{(xy+xz+2yz)^2}\geq\frac{3}4\sqrt{\frac{3}{xy+xz+yz}}$$ or
$$\sum_{cyc}\frac{\frac{1}{x}\left(\frac{1}{y}+\frac{1}{z}\right)^2}{\left(\frac{1}{xy}+\frac{1}{xz}+\frac{2}{yz}\right)^2}\geq\frac{3}{4}\sqrt{\frac{3}{\frac{1}{xy}+\frac{1}{xz}+\frac{1}{yz}}}$$ or
$$\sum_{cyc}\frac{x(y+z)^2}{(y+z+2x)^2}\geq\frac{3}{4}\sqrt{\frac{3xyz}{x+y+z}}.$$
Now, let $x+y+z=3u$, $xy+xz+yz=3v^2$ and $xyz=w^3.$
Thus, we need to prove that
$$\frac{u(-11w^6+756u^3w^3-126uv^2w^3+972u^4v^2-576u^2v^4)}{(w^3+9uv^2+54u^3)^2}\geq\frac{1}{4}\sqrt{\frac{w^3}{u}}$$ or $f(v^2)\geq0$, where
$$f(v^2)=4u(-11w^6+756u^3w^3-126uv^2w^3+972u^4v^2-576u^2v^4)-$$
$$-(w^3+9uv^2+54u^3)^2\sqrt{\frac{w^3}{u}}.$$
Now, it's obvious that $f''(v^2)<0$, which says that $f$ is a concave function.
But the concave function gets a minimal value for an extreme value of $v^2$,
which happens for equality case of two variables.
Since $f(v^2)\geq0$ is a homogeneous inequality it's enough to assume that $y=z=1$
and we need to prove that
$$\frac{4x}{(2+2x)^2}+\frac{2(x+1)^2}{(x+3)^2}\geq\frac{3}{4}\sqrt{\frac{3x}{x+2}}$$ or
$$(x-1)^2(37x^7+346x^6+1339x^5+2700x^4+2891x^3+1466x^2+309x+128)\geq0.$$
Done!


text:
Q: How to print response headers to console and save content to file? How can I print the response headers to console and save the response content to a file?

I  tried
http GET http://download.sysinternals.com/files/SysinternalsSuite.zip --output sis.zip

But this printed both the headers and content to the file, making it nonsense.

A: It is possible in an updated version, the --output option will print the output into a file, and the --download option will make sure that the headers are print to the console, and only the content to the output file.
Here is an example:
http GET "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Stack%20Overflow" --download --output bla.txt

A: This is what HTTPie does by default:

*

*When the output is not redirected, the whole message is printed to the terminal (headers & body). However, binary data is not printed to the terminal.

*When the output is redirected to a file, then only the body is printed (headers & body). It doesn't matter whether the body is binary or not.

So, the output depends on where it is being printed to. You can overwrite the default context-sensitive behaviour with one of the output options. For example, the following saves the headers as well as the body to a file:
http --output sis.zip --print=hb download.sysinternals.com/files/SysinternalsSuite.zip

HTTPie currently doesn't allow outputing binary data to the terminal.

A: It's not possible. Reported issue https://github.com/jkbr/httpie/issues/97
Update 2013: Fixed. Try
http -h --download http://download.sysinternals.com/files/SysinternalsSuite.zip


text:
Q: System library cannot be found I recently updated my Rstudio to version 3.6.2 and now my system cannot find the stats package in the
system library even though I can see it in my downloaded packages.
library(stats)
Error: package or namespace load failed for 'stats' in inDL(x, as.logical(local), as.logical(now), ...):
unable to load shared object 'C:/Program Files/R/R-3.6.2/library/stats/libs/x64/stats.dll':
LoadLibrary failure:  The specified module could not be found.


text:
Q: Find the earliest date for each product where net income is over $100k Suppose that my SQL table has 4 columns: Product, Date, Net_Income, and Cumulative_Net_Income. I want to add a fifth column that shows the first date, for each product, where cumulative net income crosses $100k.
My initial thought is to create a temporary table using
Select Product,
      min(Date)
From Table
Where Cumulative_Net_Income > '100,000'
Group By Product

This can then be joined back to the original table.
However, Is there a simpler or easier approach where I won't have to create separate tables before joining it back?

A: I didn't know it was possible until I tried it, but conditional aggregation can be combined with window functions to get your result.
"Conditional aggregation" is an informal term that refers to putting a CASE expression inside an aggregation function (like MIN() or SUM()) to selectively include or exclude values from consideration. Window functions are aggregate calculations that are calculated over a range of values as defined by the OVER(...) clause within the final select.  Putting the two together lets us ask for the minimum date where Cumulative_Net_Income exceeds 100000 within the context of each distinct product.
Select *,
    Min(Case When Cumulative_Net_Income > 100000 Then Date End)
        Over(Partition BY PD.Product) AS HundredGrandDate
From ProductData
Order By Product, Date

See this db<>fiddle which include both the above and the approach your originally proposed using a separate min-date calculation joined with the original data. I don't know if one form has any performance advantage over the other.
Using some arbitrary test data, the following result is produced:

Product
Date
Net_Income
Cumulative_Net_Income
HundredGrandDate

aaa
2023-01-01
10000.0000
10000.0000
2023-01-04

aaa
2023-01-02
30000.0000
40000.0000
2023-01-04

aaa
2023-01-03
50000.0000
90000.0000
2023-01-04

aaa
2023-01-04
70000.0000
160000.0000
2023-01-04

aaa
2023-01-05
90000.0000
250000.0000
2023-01-04

bbb
2023-01-01
50000.0000
50000.0000
2023-01-03

bbb
2023-01-02
50000.0000
100000.0000
2023-01-03

bbb
2023-01-03
50000.0000
150000.0000
2023-01-03

bbb
2023-01-04
50000.0000
200000.0000
2023-01-03

ccc
2023-01-01
1000.0000
1000.0000
null

ccc
2023-01-02
1000.0000
2000.0000
null

ccc
2023-01-03
1000.0000
3000.0000
null

ccc
2023-01-04
1000.0000
4000.0000
null

ccc
2023-01-05
1000.0000
5000.0000
null

(In retrospect, I should have called the result column OverHundredGrandDate because of the > condition.)


text:
Q: Splitting large data file in python I output a large array into a text file in python. I then read it in excel to plot the data.
Currently, the file I am writing is too large to read in excel.
I use file open and close functions and write the data in array ( please refer the code):
with open("abc.txt", "w") as file:
    file.write(str(abc_value))
    file.close()

Question: How can I split the data file so that after 1000000 steps (approximately), the file closes and starts writing to another file.
At the end, there should be multiple data files which I can read in excel separately.
Any leads much appreciated!

A: I am not sure what is type(abc_value) originally, but if you can submit in in a form of array this code should work:
counter = 1
for i in range(0, len(abc_value), 1000000):
    with open(f"abc{counter}.txt", "w") as file:
        for val in abc_value[i:i + 1000000]:
            file.write(str(val))
        file.close()
        counter += 1

The main idea is just to split your original data and then create and open deferent files in for loop.
Output files should be "abc1.txt","abc2.txt",...
Hope I understood your question correctly and this answers it.


text:
Q: Filtering with WHERE based on whether a variable is a number I am trying to filter a SELECT statament based on whether a variable is a number or not. The behavior I want is that if the parameter @productId is not a number then I want the WHERE clause to do the following:
WHERE (DTH.TaskId IS NULL OR PDT.PK_Product LIKE @productId)

If @productId is a number I want the following WHERE clause:
WHERE (PDT.PK_Product = @productId)

I thought the following would work:
    WHERE (ISNUMERIC(@productId) = 0 AND DTH.TaskId IS NULL
            OR PDT.PK_Product LIKE @productId)
    AND (ISNUMERIC(@productId) = 1 AND PDT.PK_Product = @productId)

because if ISNUMERIC(@productId) evaluates to 0 it would not use the second part of the statement and if 1 the first.
Edit:
The problem I have is that if productId is numeric (and ISNUMERIC(@productId) evaluates to 1) I am still getting results where DTH.TaskId IS NULL.

A: You need extra parentheses around the OR conditional, since AND takes precedence. You can't use AND between the conditional groups, because @productId can only be numeric or not, not both. You also need to filter out the NOT NULL values from the second conditional. So:
WHERE
(
  ISNUMERIC(@productId) = 0 AND
  (
    DTH.TaskId IS NULL
    OR PDT.PK_Product LIKE @productId
  ) -- <-- these parens are important
)
OR -- <-- this can't be AND - @productId can't be numeric and not numeric
(
  ISNUMERIC(@productId) = 1
  AND DTH.TaskID IS NOT NULL -- <-- this clause is important according to edit
  AND PDT.PK_Product = @productId
);

A: you are close, this should do the trick
WHERE (ISNUMERIC(@productId) = 1 AND PDT.PK_Product = @productId AND DTH.TaskId IS NOT NULL) OR
      (ISNUMERIC(@productId) = 0 AND (DTH.TaskId IS NULL OR PDT.PK_Product LIKE @productId))

A: WHERE 1 =
  CASE ISNUMERIC(@productId)
    WHEN 0 THEN
      CASE WHEN DTH.TaskId IS NULL OR PDT.PK_Product LIKE @productId THEN 1 END
    WHEN 1 THEN
      CASE WHEN DTH.TaskId IS NOT NULL AND PDT.PK_Product = @productId THEN 1 END
  END

A: Looks like you need another set of parenthesis and change the AND to OR
WHERE (ISNUMERIC(@productId) = 0 AND (DTH.TaskId IS NULL
        OR PDT.PK_Product LIKE @productId))
OR (ISNUMERIC(@productId) = 1 AND PDT.PK_Product = @productId AND DTH.TaskId IS NOT NULL)


text:
Q: Postgresql Error: must appear in the GROUP BY clause or be used in an aggregate function Before you guyz mark it as duplicate i tried several solutions given on this very same website but none of them worked.
My query
SELECT
  temp_fk_settlements.sku,
  temp_fk_settlements.order_item_id,
  temp_fk_settlements.order_date,
  sum(temp_fk_settlements.order_item_value),
  sum(temp_fk_settlements.total_marketplace_fee),
  sum(temp_fk_settlements.service_tax),
  sum(temp_fk_settlements.settlement_value),
  sum(temp_fk_settlements.commission),
  sum(temp_fk_settlements.fixed_fee),
  sum(temp_fk_settlements.shipping_fee),
  sum(temp_fk_settlements.reverse_shipping_fee),
  sum(temp_fk_settlements.invoice_amount)
FROM
  temp_fk_returns,
  temp_fk_settlements
WHERE
  temp_fk_settlements.order_item_id = temp_fk_returns.order_item_id and
  temp_fk_returns.return_type = 'customer_return'
GROUP BY
  temp_fk_settlements.order_item_id

My ERROR
ERROR:  column "temp_fk_settlements.sku" must appear in the GROUP BY clause or
 be used in an aggregate function
LINE 2:   temp_fk_settlements.sku,

If i try to remove column temp_fk_settlements.sku it still gives me error on different column. i am stuck as none of the solution works.
i want to group the results based on order_item_id.
My table structure is
temp_fk_settlements:
Create table temp_fk_settlements(
    settlement_reference_no varchar(50),
    order_type char(20),
    fulfillment_type varchar(25),
    sku varchar(25),
    order_id varchar(25),
    order_item_id varchar(25),
    order_date date,
    dispatch_date date,
    delivery_date date,
    cancellation_date date,
    settlement_date date,
    order_status varchar(25),
    quantity integer,
    order_item_value integer,
    refund integer,
    protection_fund integer,
    total_marketplace_fee double precision,
    service_tax double precision,
    settlement_value double precision,
    commission_rate integer,
    commission double precision,
    fee_discount double precision,
    cancellation_fee double precision,
    fixed_fee integer,
    emi_fee double precision,
    total_weight float,
    shipping_fee double precision,
    reverse_shipping_fee double precision,
    shipping_zone char(15),
    token_of_apology double precision,
    pick_and_pack_fee double precision,
    storage_fee double precision,
    removal_fee double precision,
    invoice_id varchar,
    invoice_date date,
    invoice_amount integer,
    sub_category char(25),
    total_offer_amount double precision,
    my_offer_share double precision,
    flipkart_offer_share double precision
)

temp_fk_returns:
CREATE TABLE temp_fk_returns(
    return_id VARCHAR(25),
    order_id VARCHAR(25),
    order_item_id VARCHAR(25),
    product_id VARCHAR(25),
    title VARCHAR(100),
    sku VARCHAR(25),
    quantity INTEGER,
    total_price INTEGER,
    return_requested_on DATE,
    return_initiated_on DATE,
    return_tracking_id VARCHAR(25),
    status VARCHAR(25),
    reason VARCHAR(150),
    sub_reason VARCHAR(150),
    customer_comments VARCHAR,
    return_type VARCHAR(25)
)

A: If you look at the logic of the query, you can see why this error occurs:
SELECT
  temp_fk_settlements.sku,
  temp_fk_settlements.order_item_id,
  temp_fk_settlements.order_date

This says that for each row, you want the sku, order_item_id, and order_date.
GROUP BY
  temp_fk_settlements.order_item_id

This says you want one row for each unique order_item_id, no matter what else is different.
So, if there is more than sku or order_date for the same order_item_id, the database would have no way of knowing which of those values to give you. MySQL would just guess, but Postgres (like most other DB systems) tells you to change your query.
In this case, you probably know that every order_item_id corresponds to a single value of sku and order_date, so you can just add them all to the GROUP BY clause:
GROUP BY
  temp_fk_settlements.sku,
  temp_fk_settlements.order_item_id,
  temp_fk_settlements.order_date

This says that you want one row for each unique combination of these three fields, so it is possible to view all the items in the combination.

A: all not aggregated columns should be in GROUP BY... not just one of...
so either
group by
  temp_fk_settlements.sku,
  temp_fk_settlements.order_item_id,
  temp_fk_settlements.order_date

or
select
string_agg(temp_fk_settlements.sku,',') sku,
temp_fk_settlements.order_item_id,
string_agg(order_date.order_date,',') order_date,
...etc
GROUP BY
  temp_fk_settlements.order_item_id


text:
Q: My Rails app returns 500, but I can't see any details in the logs curl localhost:3000/groups gives
Started GET "/groups" for 193.160.199.32 at 2018-07-05 13:41:04 +0000
Processing by GroupsController#index as */*
Filter chain halted as :authenticate_user rendered or redirected
Completed 500 Internal Server Error in 94ms (Views: 0.1ms)

But why can't I see any more details?
I've set RAILS_ENV=staging
[1] pry(main)> Rails.env
=> "staging"

grep log config/environments/staging.rb
  config.log_level = :debug
  # Prepend all log lines with the following tags.
  config.log_tags = [:request_id]

  config.log_formatter = ::Logger::Formatter.new


text:
Q: Link to textarea I want to to create a link that takes the user to the textarea and allows them to start typing in it instantly. This is my textarea:
<textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea>

Currently, I just link to it by:
Post a comment

But this only takes them to the area of which the textarea is, not inside it so that they can start type. In order to do that, they will obviously need to click on it. I have created a fiddle with my current setup.
I would imagine that there are various solutions to this. I would however request a solution that is centred on compatibility (works on all browsers and particularly phone browsers).

A: Use the .focus() method along with window.location.hash.
click
<textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea>

Use return false or preventDefault() for this to work everywhere. Chrome/stock browser on android doesn't require this. Firefox mobile does.
Here's the fiddle for you to test with. Here's another example fiddle where the submit is visible while typing.

A: You don't need to use JavaScript for this, when normal HTML elements can be used; with that in mind just use a label element, instead of an a, since your requirements are precisely met by the label element:
Post a comment
<textarea id="commentnow" name="comment" cols="45" rows="8" aria-required="true"></textarea>

JS Fiddle demo.
The for attribute of the label must be equal to the id of the element you want to focus on, and associate with, the label.
In response to comment from OP (in comments, below):

Two questions: How about compatibility and how can I make it a button where the text is clickable (cursor changes when hovering)...?

To address compatibility, the label element's been around since HTML 4.01 and I've not come across a browser that doesn't work with it (including IE 7, I can't remember using it with IE 6 though).
To make it appear like a button, just use CSS (in the same way you'd style an a element to appear like a button, for example:
label {
    color: #666;
    display: inline-block;
    padding: 0.3em 0.5em;
    border: 1px solid #aaa;
    background-color: #eee;
    margin: 0.5em;
}

label:hover,
label:active,
label:focus {
    color: #f90;
    box-shadow: 0 0 0.3em #f90;
}

JS Fiddle demo, this isn't a particularly beautiful example, but does show that styling possibilities both exist and are no different than any other element in that regard.

A: Simple try this using jQuery:
Post a comment
<textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea

$(".link").click(function(){
    $("#comment").focus();
    return false;
});


text:
Q: Induced emf with no relative motion When we change the magnetic flux encompassed by a loop, an induced current is produced. We know that the induced current is often explained with either the motion of loop  with respect to the magnetic field or vice versa.
Let's say I have placed a loop underneath an electromagnet producing constant magnetic field. When I suddenly increase the field produced by electromagnet, we can see that the current is induced eventhough both the field and loop aren't in relative motion to each other. What am I missing here?

A: It is the change in magnetic flux that induces an emf.  That change can be due to either motion of a loop or a change in the flux through a stationary loop.

A: "We know that the induced current is often explained with either the motion of loop with respect to the magnetic field or vice versa."
It is not always possible to explain an induced emf like this. You have given, in your second paragraph, a case where you can't. A transformer embodies just such a phenomenon.
Faraday recognised that there were two sorts of electromagnetic induction; those in which an emf is induced in a moving conductor, and those in which there is a change in flux through a stationary loop. We now attribute the emf in the moving conductor to magnetic Lorentz forces ($\mathbf F =q \mathbf v \times \mathbf B$) acting on the charge carriers, which move as the wire moves. In the other case the emf is due to an electric Lorentz force, $\mathbf F =q \mathbf E$) on the (stationary) charge carriers – if there are charge carriers present in the loop.
One of Maxwell's equations relates this electric field to the local magnetic field, $\mathbf B$:
$$\text{curl}\ \mathbf E =\ –\frac{\partial \mathbf B}{\partial t}.$$
This can be integrated over a loop to give $$\oint\mathbf E.d\mathbf l\ =-\int \frac{\partial \mathbf B}{\partial t}.d\mathbf A$$
in which the line integral is around the loop and the area integral is evaluated over any surface bounded by the loop.
Some would say that the changing magnetic field gives rise to the electric field, but I prefer to think of the Maxwell equation as telling us an inherent structural characteristic of a single thing: an electromagnetic field, of which $\mathbf B$ and $\mathbf E$ are two parts.


text:
Q: How to wait until data is loaded in AngularJS? In my app I have some data that I fetch from a service that I then proceed to use in my code to preload a form. However, sometimes the data isn't loaded until after the rest of the code is run, so the form comes up blank. Other times, it's fine and everything loads. I want to make it such that it always loads the form with all fields populated.
The problem is that I have multiple service calls, so how do I make sure that all services have finished loading? Here is my code:
In Reference Data Service (the rest of the GETs pretty much use the same kind of code):
        factory.getAllOffices= function(){
          var deferred = $q.defer();
          $http.get(APP_CONFIG.refURL+"/reference/getAllOffices")
            .success(function(response){
                deferred.resolve(response);
            })
            .error(function(msg, code, headers, config){
                console.log(msg);
                deferred.reject(msg);
            });
        return deferred.promise;
    };

In the controller:
    referenceDataService.getAllOffices().then(function(data){
        $scope.allOffices= data;
    });

    referenceDataService.getAllTypes().then(function(data){
        $scope.allTypes= data;
    });

    referenceDataService.getAllTeams().then(function(data){
        $scope.teamOptions.data = data;
    });

    //Checking to see if form exists.
    $scope.formID= '';

    if(!angular.isUndefinedOrNull($routeParams.id)){
        $scope.formID= $routeParams.id.substring(1);
    }

    if (!($scope.formID== '')){
        addFormService.getForm($scope.formID).then(function(data) {

            var officeIndex=angular.findIndexOf($scope.allOffices, data.officeID);
            var typeIndex=angular.findIndexOf($scope.allTypes, data.typeID);

            $scope.form.name= data.name;
            $scope.report.office= $scope.allOffices[officeIndex];
            $scope.report.type= $scope.allTypes[typeIndex];
            $scope.teamOptions.data = data.teamList;
            $scope.report.teams= data.teams;

            angular.forEach($scope.report.teams, function(id) {
                $scope.teamOptions.grid.rows.map(function (row) {
                    if (row.entity.id == id) {
                        row.setSelected(true);
                    }
                });
            });
        });
    }

Sometimes Offices, Types, and Teams aren't returned before the formID code runs.

A: You can use q.all(), as it accepts an array of promises that will only be resolved when all of the promises have been resolved.
$q.all([
      referenceDataService.getAllTypes(),
      referenceDataService.getAllTeams()
    ]).then(function(data){
      $scope.allTypes = data[0];
      $scope.teamOptions.data = data[1];
 });

You can also choose when to show/hide certain elements using ng-hide/ng-show. You can initialize the page with $scope.showProperty = false; and once your service calls have resolved, switch it: $scope.showProperty = true;.


text:
Q: jQuery import not being found My ajax request is not being processed. I receive the warning when starting my server :
WARNING: No mapping found for HTTP request with URI [/jquery-1.7.js] in DispatcherServlet with name 'dispatcher'. I think this is occuring because the file jquery-1.7.js is not being found.
<jsp:useBean id="message" scope="request" type="java.lang.String"/>
<html>
<head>
  <title>Spring MVC Ajax Demo</title>
  <script type="text/javascript" src="./jquery-1.7.js"></script>
  <script type="text/javascript">
    function doAjax() {
      alert('here')
      $.ajax({

        url: 'time',
        data: ({name : "me"}),
        success: function(data) {
          $('#time').html(data);
        }
      });
    }
  </script>
</head>
<body>
${message}
<button id="demo" onclick="doAjax()" title="Button">Get the time!</button>
<div id="time">
</div>
</body>
</html>

Do I need to amend the dispatcher entry -
<servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>

</servlet>
<servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
</servlet-mapping>

Update - this helped me : Static files in (Java) App Engine not accessible

A: You can either add a <static-files> to appengine-web.xml, including jquery-1.7.js there, or you can get it from google, via
    <script type="text/javascript"
            src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
    </script>


text:
Q: Ensuring a variable is always cached in Spark and never gets evicted I have a non-serializable object and I need that object to be 100% cached in memory all the time. However as spark job requires more execution memory due to load increase it tries to evict the cached object into disk and since the object is not serializable I will get "task not serializable" exception. Is there anyway to force spark to keep my object in cache all the time?

A: This is not the right direction. Even if it's cached, it may also need to be serialized when a remote node is trying to fetch it. If you just want to always cache it in executor side, you can use companion object in Scala or singleton pattern in Java to lazily create them as static objects.


text:
Q: Array within Form collecting multiple values with the same name possible? Good afternoon,
I will first start with the goal I am trying to accomplish and then give a very basic sample of what I need to do.
Goal
Instead of collecting several variables and naming them with keys individually, I have decided to give in and use an array structure to handle all inputs of the same type and rules. Once I have the variables, I will validate against them and if 'ok' store them in a MySQL table. The table will hold consumer information and will need to store multiple rows of the same type of information.
First Pass
I will leave out the validation portion of this question because I feel I need to first understand the basics.
<form action="?" method="POST" name="Form">
Member 1 First Name:<input type="text" name="MemberFirstName[]" />

Member 1 Last Name: <input type="text" name="MemberLastName[]" />

Member 1 Email: <input type="text" name="MemberEmail[]" />

Member 2 First Name:<input type="text" name="MemberFirstName[]" />

Member 2 Last Name: <input type="text" name="MemberLastName[]" />

Member 2 Email: <input type="text" name="MemberEmail[]" />

Member 3 First Name:<input type="text" name="MemberFirstName[]" />

Member 3 Last Name: <input type="text" name="MemberLastName[]" />

Member 3 Email: <input type="text" name="MemberEmail[]" />

<input type="submit" name="submit" value="Continue" />
</form>

I am hoping that each input given for First Name (a required field) will generate a unique key for that particular entry and not overwrite any data entered. Because I am carrying information from page to page (checkout form), I am turning the POST variables into SESSION variables then storing in a mysql database in the end. My hope is to have:
<?php

$conn = mysql_connect("localhost", "username", "password");
mysql_select_db("DBname",$conn);

$sql = "INSERT INTO tablename VALUES ('$_SESSION[Member1FirstName]', '$_SESSION[Member1LastName]', '$_SESSION[Member1Email]', '$_SESSION[Member2FirstName]', '$_SESSION[Member2LastName]', '$_SESSION[Member2Email]', '$_SESSION[Member1FirstName]', '$_SESSION[Member3LastName]', '$_SESSION[Member3Email]')";

$result = mysql_query($sql, $conn) or die(mysql_error());
Header ("Location: completed.php");
?>

Where Member1, Member2, and Member3 values will appear on their own row within the table. I KNOW my code is wrong but I am giving a first shot at the overall business purpose I am trying to achieve and trying to learn how to code the right way.
I am very, very new to programming so any 'baby advice' is greatly appreciated.

A: If you want to need to associate fields in a specific number of sets and still want them in an array then you should put an index in the name. An empty index is only useful when you don't know how many elements the final array will contain.
Member 1 First Name:<input type="text" name="MemberFirstName[1]" />

Member 1 Last Name: <input type="text" name="MemberLastName[1]" />

Member 1 Email: <input type="text" name="MemberEmail[1]" />

A: Depending on your column names the following
INSERT INTO tablename
VALUES ('$_SESSION[Member1FirstName]', '$_SESSION[Member1LastName]', '$_SESSION[Member1Email]'),
       ('$_SESSION[Member2FirstName]', '$_SESSION[Member2LastName]', '$_SESSION[Member2Email]'),
       ('$_SESSION[Member1FirstName]', '$_SESSION[Member3LastName]', '$_SESSION[Member3Email]')"

would work on mysql, see INSERT.
However this is an answer that will lead into much trouble if you do not sanitize the input.
EDIT:
Sanitizing refers to the sql injection attack, where strings passed directly to database may contain constructs that would allow attacker to change database passwords or update or destroy data.
EDIT2:
As for php syntax, I think this question has reasonable answers from which you can learn.


text:
Q: sh: command not found In my Fortran program I want to call the system to run my code (with alias asv20r3). For it I do:
call system ("asv20r3 " //filename)

But I obtain the following message:
sh: asv20r3: command not found

Is it necessary to define something more in order to make the system understand that I want to execute the code via the alias asv20r3?
Thanks!

A: The following FORTRAN90 program has all the answer to your question :
program Test
  print*, 'Printing environment variables : '
  call system("set")
  print*, 'Printing environment aliases : '
  call system("alias")
end program Test

The output of the program speaks for itself : environment variables are inherited; aliases are not.
You can either choose to rely on the content of an environment variable (using call get_environment_variable(...)) or hardcode the path and/or command like someone else suggested.

A: You probably need to supply the path to asv20r3 in the system call

A: your program, asv20r3, needs to be in the $PATH of your system.
if it is in the same directory as where you run your main program, than you must tell your system that by pre-pending a "./" to it, such as "./asv20r3".


text:
Q: Remove last word in cell/string mySQL I have this string in a cell in mySQL:
Sholmsgatan 1253 18 Helborg

Is it possible to delete all text but the last word "Helborg" ?
The word is dynamic so it cannot be static to "Helborg".
Maby i can check for the last whitespace (in front of Helborg) and remove everything in front of it?

A: You can use mysql's string function substring_index, note it uses space as a separator, so it will pick last word from string and update in your column
update demo set title = substring_index(title,' ',-1);

DEMO


text:
Q: Should I avoid querying the database in a foreach loop? I'm sure the answer is yes. But how would I write this differently?
$query = $this->db->get_where('online_ads', array('id' => 20))->row()->size;
$ad_array = json_decode($query, TRUE);
$result = '';

foreach ($ad_array as $a):
    $query = $this->db->get_where('ad_sizes', array('id' => $a))->row();
    $result .= $query->name.' ';
endforeach;

echo $result;

A: Write a query to join online_ads and ad_sizes. Yes, you will have redundant data from the online_ads table, but if ad_sizes has large resultset, the net execution time will be much faster.

A: In situations like this you could better build comma-separated string of ids and then run just one query using IN.
$ids = implode(',', $ad_array);

And execute the following query:
$sql = "SELECT * FROM table WHERE id IN ($ids)";

Another option is to use JOIN queries. In your case I would make a JOIN.


text:
Q: Problem about the equivalent proposition about this congruent equation. Given $c,c',N$, consider the equation
$$
c'\equiv yc\pmod{N}
$$
for some $y$ relative prime to $N$.
In the book I'm reading, it is said that it is equivalent to
$$
(c',N)=(c,N)=d
$$
The necessary direction is easy, and I think in the sufficient direction, we need to prove that in the following numbers:
$$
y_0+i\frac{N}{d},i=0,\cdots,d-1
$$
there is a number relatively prime to $N$, where $y_0$ satisfies
$$
\frac{c'}{d}\equiv y_0\frac{c}{d}\pmod{\frac{N}{d}}
$$
My question is why such $i$ exists?

A: Hint: Let $c=dx, c'=dx'$, where $x, x'$ are coprime to $N$. As such, $c' = dx' = d(x'x^{-1})x = yc \pmod{N}$. It remains to show that $y=x'x^{-1}$ is coprime to $N$.


text:
Q: wall/write command alternative for Docker Linux? I have a use case where I run multiple containers and I want to send messages to specific containers' shells to notify the user working on that shell, over SSH or VS Code or VS Code web.
wall/write commands are popular in Linux but it doesn't seem to work within Docker.
I understand wall or write is used to send messages to those who are logged into the system. who command usually lists all the users currently logged in. In the docker container with code-server running, I am accessing the shell. But who is not able to display that I am logged in. This is why it may not work.
Are there any alternatives? Or is there any way to make it work?


text:
Q: PHP Team development setup Im currently developing a website (PHP,MySQL,Javascript...) and i've been doing great so far. My current setup is a remote LAMP box and Eclipse with the RSE plugin. But now i have to figure out another setup for my team.
  So now im looking for a solution with version control and that would allow us to test the code on said box. Any ideas ?
Thanks!

A: Netbeans (x-platform) and Coda (on Mac) pretty popular if you're looking for an IDE w/ integrated revision control via git, svn, etc.  Git and SVN are both extremely easy to setup, but I'd recommend git as the learning curve is slighter and IMO overall a better revision control system.
Alternatively, you can let everybody use whatever ide they want, force them to learn svn / git from the command line, and focus on standardizing your code approaches (ie frameworks and libraries) instead of your development environment.
I'd go with the latter approach, since diff people will be using diff operating systems and have diff preferences.

A: I recommend running local installs of mamp (or similar) on each user machine. Then use 'git' for version control with a remote host such as codebasehq.com so that you can manage commits over your development team.


text:
Q: Git Branching Model for parallel projects There is very common that on one git repo multiple team works and they have their own development life cycle.
For example, repo1 is shared by two teams p1 and p2 so that created their own branch P1-repo1 and P1-repo2 and these two teams will create independent releases. But at some stage they need to merge their code in repo1.
What will be the best branching model for them?

A: Simply an integration branch, which can be fetch in P1, where the P1-repo1 is merged then push back, after testing, to the central repo.
The P2 project can in turn fetch that same integration branch and merge its own P1-repo2 branch, resolving any conflict, make sure the tests are still passing, and push back.


text:
Q: google cloud function can't be called from postman where unauthenticated is allowed I have the following simple google cloud function:
exports.recordInfo = functions.https.onRequest(async(request, response) => {
      functions.logger.info({
        requestData: request.body.data
      })
      functions.logger.info("Hello logs!", {
        structuredData: true
      });
      response.send("Hello from Firebase!");
    });

I can get it running in the emulator and obtain a local host link, where I can see the response in my browser. I'm unable to test sending request data from postman. The same link just hangs with no response. I've tried using request, request.body, and request.rawBody in both the emulator and the deployed function.
I'm trying to find a platform like postman to send a request containing an object such as:
{
      'data': {
        'objID': 'abc123',
        'objName': 'obj1',
        'objDescription': 'object'
      }
}

The ultimate goal is to record this object as a firestore document in the database, but right now I just want to be able to ensure that I can see and log the object in the cloud function.
The only response that I get when I view the function url is "Hello from Firebase". I am also seeing the "Hello logs!" statement in emulator logs, and in logs associated with the deployed function. I am not seeing the object with the 'structuredData' key in the deployed cloud function logs.

A: I was able to reproduce the issue with a post request to the function URL with the provided data object in the body.
The issue is that you need to use CORS library in order to make the request body accessible, as shown in this example onRequest function, which is referenced in this google documentation on HTTP requests.


text:
Q: What's the difference between dask=parallelized and dask=allowed in xarray's apply_ufunc? In the xarray documentation for the function apply_ufunc it says:
dask: 'forbidden', 'allowed' or 'parallelized', optional

    How to handle applying to objects containing lazy data in the form of dask arrays:

    'forbidden' (default): raise an error if a dask array is encountered.
    'allowed': pass dask arrays directly on to func.
    'parallelized': automatically parallelize func if any of the inputs are a dask array.
                    If used, the output_dtypes argument must also be provided.
                    Multiple output arguments are not yet supported.

and in the documentation's page on Parallel Computing then there is a note:

For the majority of NumPy functions that are already wrapped by dask, it's usually a better idea to use the pre-existing dask.array function, by using either a pre-existing xarray methods or apply_ufunc() with dask='allowed'. Dask can often have a more efficient implementation that makes use of the specialized structure of a problem, unlike the generic speedups offered by dask='parallelized'.

However, I'm still not clear as to what the difference between these two options is. Does allowed still operate on chunks one by one to lower memory usage? Will allowed still parallelize if the applied ufunc only uses dask operations? Why does parallelized require you to give more information about the ufunc outputs (i.e. the arguments output_dtypes, output_sizes) than allowed does?

A: dask='allowed' means that you're applying a function that already knows how to handle dask arrays, e.g., a function written in terms of dask.array operations. In most cases, that does indeed mean that the function will operate on chunks one by one to lower memory usage, and will apply the computation in parallel.
dask='parallelized' requires more information from the user because it creates its own wrapper that allows the provided function to act on dask arrays, by using low-level dask.array functions like atop. With dask='parallelized', you can provide a function that only knows how to handle NumPy arrays, and xarray.apply_ufunc will extend it to handle dask arrays, too.


text:
Q: Wordpress ul dropdown menu: display only some li sub items I created a dropdown menu for my Wordpress website with this PHP statement:
<ul id="menu">
    <?php wp_list_pages('title_li=&depth=0&sort_column=menu_order'); ?>
</ul>

In this jsfiddle you can find the HTML and CSS code: http://jsfiddle.net/N5H4c/
I only want to display the subpages of 'Menu item One' and not those of 'Menu item Three' (see jsfiddle) and of any other menu items. How can I exclude them? Can I implement a general rule or do I have to exclude each with exclude=pageid in the PHP statement?

A: Use the child_of parameter with the ID of the parent page as value, e.g.:
wp_list_pages('title_li=&depth=0&sort_column=menu_order&child_of=3');
http://codex.wordpress.org/Function_Reference/wp_list_pages


text:
Q: AngularJS multi-select using ng-repeat I'm new to AngularJS and JavaScript. I've come up with a way to build a multi-select list, which is working. The ng-model associated with the dropdown is part of a "user" DTO object, specifically a member which contains an array of "groups" the user can belong to. The "master list" of possible groups are read from a database table using a webservice, put in an array and this is what's used to build the dropdown when the page is displayed.
Those elements in the list that are included in the "groups" field of the user object are displayed below the dropdown in a "preview" field.  That's all working - if a user has two selected groups, they come up in that pre-field when the page is populated... but I don't understand why these groups are not highlighted in the dropdown. Sometimes they are...like sometimes when I refresh the page, but most of the time when the page is displayed and populated from the user information, these groups contained in the user are not highlighted in the dropdown.
Here's how the code is set up (again, I'm new to AngularJS/JavaScript and webservices so bear with me).
The HTML code is like this:

    Group Memberships:

        <select name="userGroups" id="userGroups" ng-model="user.userGroups" multiple style="width: 300px;">
            <option ng-repeat="group in approverGroups" value="{{group.name}}" selected >{{group.name}}</option>
        </select>

{{user.userGroups.toString()}}

The JavaScript side looks like this. The "get" is used to read all possible groups from a table, and that populates the dropdown:
    $http({
        method : 'GET',
        url : '/pkgAART/rs/ApproverGroupService/approvergroups',
        data : {
            applicationId : 3
        }
    }).success(function(result) {
        // Create an array from the groups for use
        // in the multi-select UI component for groups
        var arr = [];
        for (var i = 0; i < result.approvergroup.length; i++) {
            var id = result.approvergroup[i].approverGroupId;
            var value = result.approvergroup[i].name;
            var pair = {id : id, name : value };
            arr.push(pair);
        }
        $scope.approverGroups = arr;
    });

Here's a screenshot of the page. This is how it looks:

So again, it works, and "SOMETIMES" when I pull up the page, the items listed in the lower
 box are actually highlighted in the dropdown, but not often. I don't understand how to ensure they come up highlighted. In the picture I manually clicked these elements. But if I refresh the page, sometimes they are and sometimes they are not.

A: I think I figured it out.  Per Peter's suggestion I changed to ng-options for the dropdown, but modified the array that I use as my options to just use the name string.  Here's the HTML

    Group Memberships:

        <select name="userGroups"
                id="userGroups"
                ng-model="user.userGroups"
                multiple="true"
                style="width: 300px;"
                ng-options="group for group in approverGroups">
        </select>

{{user.userGroups.toString()}}

and the js file that builds up the array of strings looks like this:
$http({
    method : 'GET',
    url : '/pkgAART/rs/ApproverGroupService/approvergroups',
    data : {
        applicationId : 3
    }
}).success(function(result) {
// create an array from the groups for use
// in the multi-select UI component for groups
    var arr = [];
    for (var i = 0; i < result.approvergroup.length; i++) {
        var value = result.approvergroup[i].name;
        arr.push(value);
    }
    $scope.approverGroups = arr;
});

It's now showing the multi-select list's items as selected if they are contained in "user.userGroups"
Mark

A: I think I figured it out.
First off, you should use ng-options in the select instead of ng-repeat on <option>. This makes it so the options are bound to the model of the select.
Check out this fiddle: http://jsfiddle.net/mcxqjngm/3/
Here is the relevant select html:

<select
name="userGroups"
id="userGroups"
ng-model="user.userGroups"
multiple="true"
style="width: 300px;"
ng-options="group.name for group in approverGroups track by group.id">
</select>

The button mimics an ajax call. I gotta run, but I can answer questions in a bit.


text:
Q: How to confirm a request by clicking a button I'm creating a laravel app whereby if user send a request you have to confirm by clicking a button. Which is the best method to implement that. Can somebody help me please.

A: If its a form request you can just add to the Button-Element a
onclick="return confirm('Are you sure?')" like so:
<button onclick="return confirm('Are you sure?')"> Send Request </button>

a Popup Window will ask you for confirmation

A: The best way to do this would be using JavaScript.  You can easily achieve this with JQuery.
Have a look at this, I think this is what you need: form confirm before submit


text:
Q: Regarding Transfer of rows between a Datagridview to a Listview How do I transfer selected rows from a Datagridview to a listview?
(Sorry Guys I messed up in asking this previously the wrong way!!)
private void button1_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.SelectedRows)
    {
    lvt = new ListViewItem();
    lvt.SubItems.Add(row.Cells[1].Value.ToString());
    lvt.SubItems.Add(row.Cells[2].Value.ToString());
    lvt.SubItems.Add(row.Cells[3].Value.ToString());
    lvt.SubItems.Add(row.Cells[4].Value.ToString());
    listView1.Items.Add(lvt);
    }
}

A: it's not name, it should be SubItems
    ListViewItem lvItem;
    foreach (DataGridViewRow row in dataGridView1.SelectedRows)
    {

        lvItem = new ListViewItem();
        lvItem.SubItems.Add(row.Cells["ID"].Value.ToString());
        lvItem.SubItems.Add(row.Cells["Item"].Value.ToString());
        lvItem.SubItems.Add(row.Cells["Cost"].Value.ToString());
        lvItem.SubItems.Add(row.Cells["Manufacturer"].Value.ToString());
        lvItem.SubItems.Add(row.Cells["Quanlity"].Value.ToString());
        // ...
    }

or
    foreach (DataGridViewRow row in dataGridView1.SelectedRows)
    {

        lvItem = new ListViewItem(row.Cells["ID"].Value.ToString());
        lvItem.SubItems.Add(row.Cells["Item"].Value.ToString());
        lvItem.SubItems.Add(row.Cells["Cost"].Value.ToString());
        lvItem.SubItems.Add(row.Cells["Manufacturer"].Value.ToString());
        lvItem.SubItems.Add(row.Cells["Quanlity"].Value.ToString());
        // ...
    }


text:
Q: Automating webscraping with Python without Selenium I am beginner in  Python , I need to fetch data for list of codes from website :
https://www.isindb.com/fix-cusip-calculate-cusip-check-digit/
Under Enter Cusip , enter data from list of codes , and then click on Fix and check for result.
I want to automate this using Python but not with Selenium as it would be slow.
I would like to know is this task possible without Selenium. and if possible how should I approach.

A: you can use:
urllib3 and BeautifulSoup
Visit https://urllib3.readthedocs.io/
or
mechanicalsoup
Visit https://mechanicalsoup.readthedocs.io/en/stable/tutorial.html


text:
Q: Manually validate with a custom validator without default constructor I have a custom validation with annotations such as:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniquePropertyValidator.class)
public @interface UniqueProperty {

    String message() default "sample message";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

here's my validator:
public class UniquePropertyValidator extends JdbcDaoSupport implements ConstraintValidator<UniqueProperty, UniquePropertyClass> {

    @Inject public UniquePropertyValidator(DataSource dataSource) {
        setDataSource(dataSource);
    }

    @Override
    public void initialize(UniqueProperty property) {

    }

    @Override
    public boolean isValid(UniquePropertyClass propertyClass, ConstraintValidatorContext constraintValidatorContext) { return some boolean; }
}

and I am trying to use it as following:
SpringValidatorAdapter adapter = new SpringValidatorAdapter(validator);
BeanPropertyBindingResult result = new BeanPropertyBindingResult(propertyClass, propertyClass.getClass().getName());
adapter.validate(propertyClass, result, UniquePropertyClass.SomeValidationGroup.class);

if (result.hasErrors())
    throw new MethodArgumentNotValidException(null, result);

however I am getting this error:
HV000064: Unable to instantiate ConstraintValidator: class some.package.UniquePropertyValidator.

Now, I am well aware that my validator class does not have a default constructor without any method parameters. However, the following works with the exact annotation and validator:
public someMethod(@Validated(value = UniquePropertyClass.SomeValidationGroup.class) @RequestBody UniquePropertyClass propertyClass)

What I am asking is; is there a way to manually validate without the default constructor.
P.S. The reason why I cannot use @Validated (the working example above) is:
I have a @PathVariable (say id) and before validating @RequestBody UniquePropertyClass propertyClass object, I need to set the id of UniquePropertyClass object before validating it, since I could not find a way to bind the @PathVariable into @RequestBody field and validate on the fly with @Validated. So giving a hint on how to make this work would also be a perfectly acceptable answer.
Thanks!

A: Create default constructor for the UniquePropertyValidator and add @Component annotation. Then just add
@Inject
private DataSource dataSource;

to inject the datasource rather than init it from Constructor. (See more for autowiring objects in validator)
UPDATE you can get the bean from context (see
Spring get current ApplicationContext )


text:
Q: How to delete/erase a specific polygon in openGL? Suppose i have drawn a triangle,a cube,a square using draw_triangle,draw_cube and draw_square function respectively.How can I delete a cube using keypress func.?..If i use glClear(GL_COLOR_BUFFER_BIT) entire screen will be erased..How to delete a specific polygon.?

A:
How to delete a specific polygon.?

Don't render it in next frame.
Once you draw a polygon, there is no polygon, just a bunch of pixels in color buffer + values in depth buffer. So you can't "delete" it, and you can't restore previous state of color/depth buffer. So clear screen, redraw the scene without polygon you didn't want.

A: If you want to clear only a specific part of the screen or any specific image, then redisplay it by using a keyboard interrupt wihout clearing the whole screen.

A: I think the best solution is to have a boolean variable which indicates whether your object must be displayed or not. Thus, only when a key is pressed, you clear the screen and redraw the entire scene.

A: maybe something like that:
Render()
{
 clear_screen();

 setup_camera_and_other_scene_states();

 if (cube) drawCube();

 if (sphere) drawSphere();

 swap_buffers():
}

keyPress()
{
 if (presses_some_key) cube = !cube;
}


text:
Q: Semi-Automatic Classification Plugin - Crush dumped I installed Semi-Automatic Classification Plugin but it doesn't work.
After starting QGIS, program displays a message "Please restart QGIS to executing the Semi-Automatic Classification Plugin. Possible missing dependencies."
Closing the program gets an error "Crush dumped", every time.
I can't uninstall or reinstall this plugin from plugins repositories interface, this also causes "Crush dumped".
I use QGIS 2.14.7 and 2.16.3. Windows 7 Pro 64bit.

A: I have the same problem with ubuntu 17.04 and 17.01 running qgis las palmas. It was solved by installing python-matplotlib  and python-scipy
sudo apt-get install qgis python-matplotlib python-scipy
For QGIS based on Python 3:
sudo apt-get install python3-scipy


text:
Q: Difference between major_compact on a table or on all regions of table Say I have an Hbase table with 10 regions, Which is better approach to run major_compact on the table. To run major_compact on whole table via command:

hbase> major_compact "tableName"

or running major_compact on all regions one after another(after major_compact of one region has completed)-

hbase> major_compact "region1"

This I am asking so to make sure when running live compact there is no impact on production traffic. When running on one region after another, I know that only one region is getting impacted at a time. When we run major_compact on a table, does it also take care of doing it region by region internally or it starts compactions on all the regions together?


text:
Q: FATAL EXCEPTION: main java.lang.VerifyError: net/sqlcipher/database/SQLiteDatabase from SQLCipher I am using SQLCipher as db in my project.My app is running successfully in phones with OS lollipop and above. but having issues from OS 4.4.4 and below. I am using SQLCipher jar files (not the latest one).on application start, I am getting the following error:
04-26 12:50:04.940 18598-18598/packageName E/dalvikvm: Could not find class 'net.sqlcipher.database.SQLiteCompiledSql', referenced from method net.sqlcipher.database.SQLiteDatabase.deallocCachedSqlStatements
04-26 12:50:04.940 18598-18598/packageName E/dalvikvm: Could not find class 'net.sqlcipher.database.SQLiteStatement', referenced from method net.sqlcipher.database.SQLiteDatabase.getPragmaVal
04-26 12:50:04.945 18598-18598/packageName E/dalvikvm: Could not find class 'net.sqlcipher.database.SQLiteDatabase$SyncUpdateInfo', referenced from method net.sqlcipher.database.SQLiteDatabase.markTableSyncable
04-26 12:50:04.955 18598-18627/packageName E/GMPM: Uploading is not possible. App measurement disabled
04-26 12:50:04.955 18598-18598/packageName E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.VerifyError: net/sqlcipher/database/SQLiteDatabase
at packageName.database.PassbookContentProvider.onCreate(PassbookContentProvider.java:538)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1214)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1189)
at android.app.ActivityThread.installProvider(ActivityThread.java:5119)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4725)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4665)
at android.app.ActivityThread.access$1400(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1376)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)

app/build.gradle:
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'

android {
  compileSdkVersion 23
  buildToolsVersion "23.0.2"

  def isSMSAuthEnabled = "false"

  defaultConfig {
    applicationId "packageName"
    minSdkVersion 16
    targetSdkVersion 22
    versionCode 6
    versionName "v3.0"

    multiDexEnabled true
  }
  buildTypes {
    debug {
      resValue "bool", "enableSMSAuth", isSMSAuthEnabled
    }

    release {
      minifyEnabled true
      resValue "bool", "enableSMSAuth", isSMSAuthEnabled
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
  dexOptions {
    javaMaxHeapSize "4g"
  }
  packagingOptions {
    exclude 'META-INF/services/javax.annotation.processing.Processor'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
  }
}

dependencies {
  testCompile 'junit:junit:4.12'
  compile files('libs/PDFjet.jar')
  compile files('libs/guava-r09.jar')
  compile files('libs/sqlcipher.jar')

  compile('de.keyboardsurfer.android.widget:crouton:1.8.5@aar') {
    exclude group: 'com.google.android', module: 'support-v4'
  }

  // sqlcipher
  //  compile 'net.zetetic:android-database-sqlcipher:3.3.1-2@aar'

  compile('com.mikepenz:materialdrawer:5.1.2@aar') {
    transitive = true
  }

  // Because RxAndroid releases are few and far between, it is recommended to
  // explicitly depend on RxJava's latest version for bug fixes and new features.

  compile 'com.android.support:appcompat-v7:23.2.1'
  compile 'com.android.support:design:23.2.1'
  compile 'com.google.code.gson:gson:2.4'
  compile 'com.github.castorflex.smoothprogressbar:library-circular:1.0.2'
  compile 'com.shamanland:fab:0.0.6'
  compile 'com.android.support:recyclerview-v7:23.2.1'
  compile 'com.android.support:cardview-v7:23.2.1'
  compile 'com.squareup.retrofit:retrofit:1.9.0'
  compile 'com.squareup.okhttp:okhttp:2.4.0'
  compile 'com.squareup.okhttp:okhttp-urlconnection:2.4.0'
  compile 'de.hdodenhof:circleimageview:2.0.0'
  compile 'com.flipboard:bottomsheet-core:1.5.0'
  compile 'com.flipboard:bottomsheet-commons:1.5.0'
  compile 'com.github.PhilJay:MPAndroidChart:v2.2.2'
  compile 'io.reactivex:rxandroid:1.1.0'
  compile 'io.reactivex:rxjava:1.1.0'
  compile 'com.bignerdranch.android:expandablerecyclerview:2.0.4'
  compile 'com.borax12.materialdaterangepicker:library:1.6'
  compile 'com.google.android.gms:play-services:8.4.0'
}

contentProvider.java
 @Override public boolean onCreate() {
    String password = null;
    SQLiteDatabase db = null;

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
    try {
      if (mOpenHelper == null) mOpenHelper = new BOBDatabaseOpenHelper(getContext());
      SQLiteDatabase.loadLibs(getContext());

      if (preferences.contains(Constants.OLD_USER_PIN_SET)) {
        if (preferences.contains(Constants.REKEY) && preferences.getBoolean(Constants.REKEY,
            true)) {
          password = getPassword();
        } else {
          password = getOldPassword();
        }
      } else {
        password = getPassword();
      }
      if (password != null) db = mOpenHelper.getWritableDatabase(password);
    } catch (SQLiteException e) {
      e.printStackTrace();
    }
    return db != null;
  }

error is occurring at this position in the code
SQLiteDatabase.loadLibs(getContext());

I have done enough research but couldn't solve the issue. please help me.thanks.

A: In my case it wasn't practical to remove multidex, but found a solution using gradle's multiDexKeepFile property. This nudges the specified classes to be inluded in the first dex when you're breaching the 64K method limit.
In app/build.gradle, point to a multiDexKeepFile:
// Enabling multidex support.
multiDexEnabled true
multiDexKeepFile file('multidex.keep')

And in the keep file, specify the classes you need to be included in the first dex, in my case my content provider and sqlcipher's SQLiteDatabase:
com/myapp/android/database/provider/MyContentProvider.class
net/sqlcipher/database/SQLiteDatabase.class

This stopped the crashing from happening on both a physical S3 mini and a Nexus 4 virtual device (both api 16, both crashed before the fix).

A: It sounds as if the native libraries may not be included within your build. The easiest solution maybe for you to just use the AAR distribution we make available:
compile 'net.zetetic:android-database-sqlcipher:3.4.0@aar'

A: Finally, after lots of research, I got the solution for my problem. The problem started when I added
compile 'com.google.android.gms:play-services:8.4.0'

for maps in my project. which wasnt necessary. when I added this I got an error saying method count exceeded 64K limit. so I added
`multiDexEnabled true`

in my app/build.gradle
still got some more errors. when I searched I had to add
 dexOptions {
    javaMaxHeapSize "4g"
  }

into app/build.gradle.
and there was no more error in phones with lollipop and above OS.
but for others I am getting the above problem.
so I fixed it by changing
compile 'com.google.android.gms:play-services:8.4.0'

to
 compile 'com.google.android.gms:play-services-location:8.4.0'
 compile 'com.google.android.gms:play-services-maps:8.4.0'
 compile 'com.google.android.gms:play-services-appindexing:8.4.0'

so the methods didnt exceeded 64K limit. and the problem got solved. thanks everyone for your time.

A: If you can delete:
multiDexEnabled true


text:
Q: How to multiply fractions passed down as a tuple def mult(num):
    #num='(1,2)(3,4)'
    numn=int(num[1])
    denom=int(num[3])
    numn1=int(num[6])
    denom1=int(num[8])
    numnetor=numn*numn1
    denominetor=denom * denom1
    ans=str(numnetor)+'/'+ str(denominetor)
    return ans
askUser=input("Enter Fraction:")
print(mult(askUser))

I tried to do it this way but when I input double digit number it crashes What can I do?

A: Python already has support for fractions in the standard library.
If your fraction is in string form:
from fractions import Fraction
f = Fraction(askUser)

If your fraction is in tuple form:
f = Fraction(*fraction_tuple)

The resulting Fraction objects can be used in standard arithmetic as if they were numbers.

A: Expressing my doubt that you will actually need to process strings of compound tuples, the solution you are looking for is raw_input (instead of input), and ast (which is what input does).
Now, when the two tuples are understood separately, the program may now process numbers with more than two digits.
import ast

def mult(num):
    sep_indx = num.find(')(')
    assert sep_indx > -1

    tuple1, tuple2 = num[:sep_indx+1], num[sep_indx+1:]
    tuple1 = ast.literal_eval(tuple1)
    tuple2 = ast.literal_eval(tuple2)

    numn=int(tuple1[0])
    denom=int(tuple1[1])
    numn1=int(tuple2[0])
    denom1=int(tuple2[1])
    numnetor=numn*numn1
    denominetor=denom * denom1
    ans=str(numnetor)+'/'+ str(denominetor)
    return ans

askUser=raw_input("Enter Fraction:")
print(mult(askUser))

#Enter Fraction:(1,20)(3,40)
#3/800

Do note that your program will still have problems with division by zero errors, issue with extra spaces, and any non-integer numbers entered by the user. I am leaving these to you.


text:
Q: netsuite transactionLine.isClosed and Transaction.voided- orders In TransactionLine, there is a field called isClosed.  What does that mean for sales orders, work orders, and purchase orders?  I am hoping there is a sort of generic meaning for these 3 transaction types.
When is it set to "T"?  I think I see it being set to "T" when we fulfill a sales order (for instance), but I am just not sure.  I know it is still "F" when I delete the line entirely.  Also, I know in the UI for purchase orders, there is a way to close individual lines.  I have not looked at work orders yet, but sales orders does not have that ability in the UI.  That is part of why I am confused.
On a related note, what about the Voided field inside the Transaction, and how does it relate to sales, work, and purchase orders?  What sets it to "T"?  Maybe it is because our customer is still setting up their first instance of NetSuite and learning things, but we currently have no "Voided = 'T'".
We need to know what isClosed and Voided mean, as we need to maybe read those flags into our system and do different things based on the value of those flags.  To me they seem closely related, so that is why I am asking about both of them.


text:
Q: i want to update data image using codeigniter Severity: Notice
Message: Trying to get property 'gambar' of non-object
Filename: admin/CarouselController.php
Line Number: 42
Controller
    public function edit_carousel(){//update carousel
    $id= $this->input->post('id_carousel');
    $data = $this->modelcarousel->getDataById($id)->row();
    $gambar = './assets/foto/carousel/'.$data->gambar;

    if (is_readable($gambar) && unlink($gambar)) {
        $config['upload_path']          = './assets/foto/carousel';
        $config['allowed_types']        = 'gif|jpg|png|jpeg';
        $config['max_size']             = 2048;
        $config['max_width']            = 10000000;
        $config['max_height']           = 10000000;

      $this->load->library('upload', $config);
      $this->upload->initialize($config);
      if (!$this->upload->do_upload('gambar')) {
          $error = array('error' => $this->upload->display_errors());
      }else{
        $gambar = $this->upload->data();

        $data = array(
                'gambar' => $gambar,
                'headline' => $this->input->post('headline'),
                'deskripsi' => $this->input->post('deskripsi'),
                'status' => $this->input->post('status'),
                'tanggal_post' => $this->input->post('tanggal_post')
            );
        $update = $this->modelcarousel->update_carousel($id,$data);
        if ($update) {
            redirect('carousel');
        }else{
            echo 'Gagal';
        }
      }
    }
}

Model
function update_carousel($id,$data){//update carausel
    $this->db->where('id_carousel',$id);
    return $this->db->update('tb_carousel',$data);
}
function getDataById($id){
    $this->db->where('id_carousel',$id);
    return $this->db->get('tb_carousel');
}

database:
id_carousel
gambar
headline
deskripsi
status
tanggal_post

A: You can try with this
 if (is_readable($gambar)) {
            $media_files = $gamba;
            $this->load->library('upload');

            // Get file data
            $type = explode("/", $gamba['type']);
            $cMediaType = $type[0];
            $cMediaName = $gamba['name'];
}

Your controller Code

A: Change this line of code:
$this->load->library('upload', $config);
To this (do not send the second parameter)
$this->load->library('upload');


text:
Q: getting "ClassNotFoundException" or "HTTP Status 404 – Not Found" when running jsp or servlet //index.jsp file
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

    <form action="IndexServlet" >
        <input type="text" name="username">
        <input type="submit">
    </form>

</body>
</html>

//servlet file
import java.io.IOException;
import java.io.PrintWriter;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class Index extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        PrintWriter out = resp.getWriter();
        out.println("Hi There!");
    }
}

enter image description here
I want to print "Hi There!" when hitting submit from jsp file. but when I do I either get a 404 or 500 error
//////////////////////////
HTTP Status 404 – Not Found
Type Status Report
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Apache Tomcat/10.0.27
//////////////////////////
HTTP Status 500 – Internal Server Error
Type Exception Report

Message Error instantiating servlet class [com.bootcamp.IndexServlet]

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

jakarta.servlet.ServletException: Error instantiating servlet class [com.bootcamp.IndexServlet]
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:356)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:870)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1762)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.base/java.lang.Thread.run(Thread.java:833)
Root Cause

java.lang.ClassNotFoundException: com.bootcamp.IndexServlet

A: Okay, so I think a .class file is missing. I created a new project where the class file is visible and it worked
not sure how it's working. lol
enter image description here
I've read about the articles here:
Tomcat: the origin server did not find a current representation for the target resource or is not willing to disclose that one exists
Unable to instantiate a servlet, getting class not found exception
Eclipse doesn't compile java files into classes


text:
Q: Separating AngularJs and Django into individual Apps? I am building a web application using AngularJs and our web server is built in Python Django Rest Framework.
I would like to have the two projects separated and not coupled.
In my current setup the client side web application is served as a NodeJs application while the Node server is being used only as a proxy server to the Django web server APIs.
This setup works, but it doesn't feel right to use NodeJs when all the logic is in the Django server. Also, some of the features we have involve file upload and this makes it even smellier when I upload a file to the node server and then resend it to the Django server.
What are your thoughts on using NodeJs only as a static file server that proxies the requests to different servers, and what other options use cases are there to connect an AngularJs application that is being served as a stand alone app (maybe by NginX) to a Django web server (CORS issues).

A: You can separate the Front-end and Back-end application, actually that's good practice from my view. But you can serve both application in single ip address and different port nos in Apache/Nginx. The server will do static file serve and caching. Cors you can do by Django. You don't need one more server to render the templates.


text:
Q: Instagram-API with python I recently started using the instagram-API in python. I built successfully some programs, and then I searched a way to create an Instagram account through the api - but I couldn't find.
Is there a way to create an instargram account from the api (python), and then send the login details (user,pass) and the token, secret token to the user?
Thanks, and have a nice day.

A: Check out the documentation and you'll quickly discern that their API isn't designed to allow for third-party, programmatic user account creation.
The only way to create an account with Instagram is by downloading their iOS or Android app and following the account creation process that way.
From an end user perspective, what would be the use case for granting a third party application all the sensitive personal data required to create an Instagram account? Because an end user can only upload media to their account via the app, why wouldn't someone just want to sign up when they download the app?