text:
Q: How can I solve this? 'int' object is not iterable I'm making an Online shop using Django and trying to add quantity of each product from cart and it throws the error under :
'int' object is not iterable
I know that it should be integer in this code(this is my views.py):
def add_cart(request) :
    pnum = request.GET.get("pnum")
    cart = Order.objects.get(prod_num_id = pnum)
    cart.save()  # save 호출
    return redirect( "add_cart_pro" )

def add_cart_pro(request):
    memid = request.session.get( "memid" )
    cart = Order.objects.filter(order_id_id = memid)
    member = Sign.objects.get(user_id = memid)
    pnum = request.GET.get("pnum")
    template = loader.get_template("cart_view.html")
    count = 0
    for add in cart :
        count += add.quan + 1
    context = {
        "memid":memid,
        "cart":count,
        "member":member,
        "pnum":pnum,
        }
    return HttpResponse( template.render( context, request ) )

def minus_cart(request):
    pnum = request.GET.get("pnum")
    cart = Order.objects.get(prod_num_id = pnum)
    cart.save()  # save 호출
    return redirect( "minus_cart_pro" )

def minus_cart_pro(request):
    memid = request.session.get( "memid" )
    cart = Order.objects.filter(order_id_id = memid)
    member = Sign.objects.get(user_id = memid)
    pnum = request.GET.get("pnum")
    template = loader.get_template("cart_view.html")
    count = 0
    for add in cart :
        count -= add.quan - 1
    context = {
        "memid":memid,
        "cart":count,
        "member":member,
        "pnum":pnum,
        }
    return HttpResponse( template.render( context, request ) )

so I changed like this :
count = 0
for add in cart :
    count -= add.quan - 1

the error shows that I have an error at my last line.
return HttpResponse( template.render( context, request ) )
and this is my template :
   {% if memid %}

MyPage

Logout

   {{ memid }} 님 안녕하세요
>  {% endif %}
   {% if not memid %}

MyPage

Login

   {% endif %}

how can I solve this?
+) this is my traceback:
File "C:\Python36\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\BigData\Workspace\project2\order\views.py", line 107, in add_cart_pro
    return HttpResponse( template.render( context, request ) )
  File "C:\Python36\lib\site-packages\django\template\backends\django.py", line 61, in render
    return self.template.render(context)
  File "C:\Python36\lib\site-packages\django\template\base.py", line 170, in render
    return self._render(context)
  File "C:\Python36\lib\site-packages\django\template\base.py", line 162, in _render
    return self.nodelist.render(context)
  File "C:\Python36\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Python36\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Python36\lib\site-packages\django\template\loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "C:\Python36\lib\site-packages\django\template\base.py", line 162, in _render
    return self.nodelist.render(context)
  File "C:\Python36\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Python36\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Python36\lib\site-packages\django\template\loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "C:\Python36\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Python36\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Python36\lib\site-packages\django\template\defaulttags.py", line 167, in render
    values = list(values)

Exception Type: TypeError at /order/add_cart_pro
Exception Value: 'int' object is not iterable


text:
Q: Oracle impdp error when importing data I get this error ORA-02289: sequence does not exist when I try to import a schema to my database, could you give me some recommendation?
Import Command:
impdp '"sys/mmm as sysdba"' directory=BACK_IMPORT dumpfile=0502190800%U.dmp
logfile=impdp_MBD.log SCHEMAS=MSCHEM PARALLEL=7 encryption_password=0qazw

Export Command:
expdp '"sys/mmm as sysdba"' encryption=all encryption_password=0qazw
encryption_algorithm=aes256 COMPRESSION=ALL DIRECTORY=BACK_EXPORT
COMPRESSION_ALGORITHM=BASIC LOGTIME=ALL CONTENT=ALL flashback_time=systimestamp
DUMPFILE=$name% U.dmp LOGFILE=$name.log PARALLEL=7 SCHEMAS=MSCHEM,IOOUT,ZHIST;

A: You are importing MSCHEM schema. Please check in source database that one of TABLE/Procedure/Package using a sequence that exist in another schema. If so, don't worry just recreate it. you can find this sequence name in import log also.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Movie from iTunes: We've determined that your purchase does not meet the conditions for a refund My toddler bought a random movie on Apple TV by accident (even a foreign language).
I tried to use a form to get a refund (Ask Different how-to):
how do you cancel a pending purchase in iTunes
which gives me this output after a millisecond:

We've determined that your purchase does not meet the conditions for a
  refund.

I also tried this Request a refund for an App Store or iTunes Store purchase
I don't wish to use phone support. Is it possible to use other process/form?

A: I had this issue once before and if I recall correctly, I was able to use the support chat on apple.com to resolve the issue. Give it a try.


text:
Q: cannot change default email address in PHP So I created new email from my cpanel and I'm trying to use it for registration verification.
I tried editing "php.ini" it didn't work then I used this code and its still not working its sending message from default email.
ini_set('SMTP', "mail.website.com");
ini_set("smtp_port","25");
ini_set('sendmail_from', 'verify@website.com');

sorry I'm new to web development and i have no idea what im doing wrong

A: The sendmail_from setting can be ignored under various circumstances. Try sending the address with each individual email manually:
mail('receiver@domain.com', 'Subject', 'Text', 'From: verify@website.com');


text:
Q: Data leak from the form object I am trying the form validation for updating password. Expected Behaviour: if Test#123 is submitted in the form it should validate the password (Atleast 1 Upper, 1 lower, 1 special character and minimum 8charcters length)be sent as Test#123 .
Actual Behaviour
Test#123 is submitted in the form, validations are working fine but # is getting lost and only Test123  is being sent to the validator. I don't know why! please look at the screenshot here Click here .
Here is the code, please view this and suggest me where I went wrong.
Controller code:

@RequestMapping(value = "/update-password", method = RequestMethod.POST)
    public String updatePassword(final UpdatePasswordForm updatePasswordForm, final BindingResult result,
                                 final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException
    {
        passwordValidator.validate(updatePasswordForm, result);

        if (result.hasErrors())
        {
            redirectAttributes.addAttribute("hasPwdError", true);
            publishResult(redirectAttributes, "updatePasswordForm", result);
            addFlashMessage(redirectAttributes, ERROR_MESSAGES_HOLDER, "form.global.error");
        }
        else
        {
            try
            {
                redirectAttributes.addAttribute("hasPwdError", false);
                customerFacade.changePassword(updatePasswordForm.getCurrentPassword(), updatePasswordForm.getNewPassword());
                addFlashMessage(redirectAttributes, CONF_MESSAGES_HOLDER, "text.account.confirmation.password.updated", null);
            }
            catch (final PasswordMismatchException localException)
            {
                publishResult(redirectAttributes, "updatePasswordForm", result);
                result.rejectValue("currentPassword", "profile.currentPassword.invalid", new Object[] {},
                        "profile.currentPassword.invalid");
            }
        }
        return REDIRECT_TO_PROFILE_PAGE;
    }

Validator.java:

public class PasswordValidator extends PasswordValidator
{
    public static final Pattern specailCharPattern = Pattern.compile("[^a-z0-9A-Z]", Pattern.CASE_INSENSITIVE);
    public static final Pattern UpperCasePattern = Pattern.compile("[A-Z]");
    public static final Pattern lowerCasePattern = Pattern.compile("[a-z]");
    public static final Pattern digitPattern = Pattern.compile("[0-9]");
    public static final Pattern spacePattern = Pattern.compile("\\s");
    @Override
    public void validate(final Object object, final Errors errors)
    {
        final UpdatePasswordForm passwordForm = (UpdatePasswordForm) object;
        final String newPasswd = passwordForm.getNewPassword();
        final String checkPasswd = passwordForm.getCheckNewPassword();
        final String currPasswd = passwordForm.getCurrentPassword();

        if (StringUtils.isEmpty(currPasswd))
        {
            errors.rejectValue("currentPassword", "profile.currentPassword.invalid");
        }

        if (StringUtils.isEmpty(newPasswd))
        {
            errors.rejectValue("newPassword", "updatePwd.pwd.invalid");
        }
        else if (StringUtils.isEmpty(checkPasswd))
        {
            errors.rejectValue("checkNewPassword", "updatePwd.pwd.invalid");
        }
        else if(currPasswd.equals(newPasswd)){
            errors.rejectValue("newPassword", "updatePwd.same");
        }
        else if(newPasswd.equals(checkPasswd)){
            String test=newPasswd;
            if((newPasswd.length() < 8 || newPasswd.length() >=255 )|| (checkPasswd.length() < 8 || newPasswd.length() >=255 )){ errors.rejectValue("newPassword", "register.pwd.length"); }
            if(!specailCharPattern.matcher(test.replaceAll("\\s", "")).find()){errors.rejectValue("newPassword", "register.pwd.specialchar");}
            if(!UpperCasePattern.matcher(newPasswd).find()){errors.rejectValue("newPassword", "register.pwd.uppercase");}
            if(!lowerCasePattern.matcher(newPasswd).find()){errors.rejectValue("newPassword", "register.pwd.lowercase");}
            if(!digitPattern.matcher(newPasswd).find()){errors.rejectValue("newPassword", "register.pwd.digit");}
            if(spacePattern.matcher(newPasswd).find()){errors.rejectValue("newPassword", "register.pwd.space");}
        }
        else{
            errors.rejectValue("newPassword","validation.checkPwd.equals");
        }

    }
}
/**
 * Form object for updating the password.
 */
UpdatePasswordForm.java

public class UpdatePasswordForm
{
    private String currentPassword;
    private String newPassword;
    private String checkNewPassword;

    public String getCurrentPassword()
    {
        return currentPassword;
    }

    public void setCurrentPassword(final String currentPassword)
    {
        this.currentPassword = currentPassword;
    }

    public String getNewPassword()
    {
        return newPassword;
    }

    public void setNewPassword(final String newPassword)
    {
        this.newPassword = newPassword;
    }

    public String getCheckNewPassword()
    {
        return checkNewPassword;
    }

    public void setCheckNewPassword(final String checkNewPassword)
    {
        this.checkNewPassword = checkNewPassword;
    }
}


text:
Q: What function space do $u(x)=\sin(x)$ and v$(x)=e^{-2x}$ belong to? I'm trying to follow notes, a question is presented in the middle of the notes that isn't answered.
$u(x)=0$ when $-1\leq x<0$
$u(x)=x^2$ when $0\leq x \leq 1$
The $u(x)$ function belongs to $C^1[-1,1]$. What space do $u(x) = \sin x$ and $v(x) = e^{-2x}$ belong to?

A: If the question is what's the largest $n \in \{0,1,2,\ldots\}\cup\{\infty\}$ such that $u \in C^n\lbrack-1,1\rbrack$ where $u(x) = \sin x$ or $u(x) = e^{-2x}$, then the answer (in both cases) is $n = \infty$. In fact we know that $u,v:\mathbb{R}\to\mathbb{R}$ given by $u(x) = \sin x$ and $v(x) = e^{-2x}$ are both infinitely differentiable on $\mathbb{R}$, which is a stronger assertion.


text:
Q: A column called Status in MySQL I've been using MySQL and I need a column called "Status" in a table.
I know this word "Status" is a keyword in MySQL, and I would like to know if I will have problems with it if I write SQL statements like:
select t.Id, t.Name, t.Status from Table t

Or in triggers:
Set new.Status = 1;

if (new.Status <> old.Status) then
  /* do something */
end if

Or should I rename it for another word?

A: I would never recommend to use keywords as column names, but it should not be a problem if you enclose it in [] like [Status].

A: TL;DR: Avoid keyword identifiers and rename them if you can, quote them meticulously otherwise.

You're correct that STATUS is a keyword, likely owing to SHOW STATUS.
If renaming the column isn't much of a chore for you, changing the name is the best choice. That way, you avoid running into problems later or save people trouble who use your database structure.
If you want to keep it however (because "status" is such a handy name), it's perfectly okay. While purists rant, it ensures clean code because you have to use backticks (`) or ANSI quotes (i.e. ") according to the manual on quoting identifiers.
SELECT `t`.`Status` FROM `Table` t -- properly quoted

SELECT t.status FROM `Table` t -- multi-part identifier

SELECT STATUS FROM `Table` t -- will still work, but tease any pedant

Of course this kind of identifier quoting works in procedural logic as well (like in trigger scripts).

A: Status can be its own column if you wrap it, in MySQL, with ``.
SELECT `t`.`Status`. FROM `t`

But for the sake of avoiding confusion later on, it may be better for you to distinguish it in some other way.

A: You should use `` around then in mysql and in sql you should use []

A: rename your column, end of discussion


text:
Q: Goutte can't click link I am not sure what is going on here, I am using Goutte for crawling, trying to crawl all the exploits on exploitdb, but apparently I am not able to click 1 specific link. Here is the code:
<?php

    require_once 'goutte.phar';

     use Goutte\Client;

     $client = new Client();

function crawler_metasploit(){

          global $client;

          $crawler = $client->request('GET','https://www.exploit-db.com/search/?order_by=date&order=desc&pg=1&action=search');

          $exploits =  $crawler->filterXPath('//table[@class="exploit_list bootstrap-wrapper"]//tr[position()=14]/
                                             td[@class="description"]/a[@href]')->each(function ($nodes) {
                     return  $nodes->text();
                         });

          foreach ($exploits as $exploit){

            //$exploit = trim(preg_replace("/[\r\n]+/", " ", $exploit));

            print "
".$exploit."
";

            if ($exploit == 'VideoCharge Express 3.16.3.04 - BOF Exploit'){

                print 'same';

            }
          else {

            print '
diff
';
            print '
VideoCharge Express 3.16.3.04 - BOF Exploit
';
            print $exploit;
          }

            $crawler2 = $client->click($crawler->selectLink($exploit)->link());

                      $code = $crawler2->filterXPath('//table[@class="exploit_list"]//tr[position()=1]/td[position()=2]/a')->each(function ($nodes) {
                     return  $nodes->text();
                         });

          print "
".$code[0]."
";

          if ($code[0] != ""){

            print "there is cve";

          }

            print 'hi';

      }

     }

     crawler_metasploit();
?>

The output is "diff", apparently the string is the same than when I copy paste it directly from the website but it's not, that only happens with this specific string, I have used this function too:
$exploit = trim(preg_replace("/[\r\n]+/", " ", $exploit));

but no success.
What could be happening?


text:
Q: Why doesn't locking a cell in a protected worksheet in Excel prevent selection? I'm working on a protected Excel spreadsheet and ran into a problem with cells that I've programmatically locked that are still selectable.  I can't click on them directly to select them, but if I select the cell to the lower right of a locked cell and then shift-click the one to the upper left, all 9 cells (including the 'locked' one) are selected. I can also click-drag to select the 9 cells.  I'm using the following VBA code to protect and set the selection criteria:
Worksheets("Sheet1").Protect UserInterfaceOnly:=True
Worksheets("Sheet1").EnableSelection = xlUnlockedCells

I've tried the two commands in the reverse order and get the same results.
I've also used the Excel cell formatting / protection menus to do the same thing and get the same results.
Am I missing something obvious or is there some other programmatic way to mark a cell so that it can't be selected later on?

A: I think you'll need to create some code in the Worksheet_SelectionChange event that checks whether your protected cells are included in the new selection and, if so, selects some other cell (perhaps the next unprotected one to the right or below).
I haven't reviewed the code, but a cursory search for "Worksheet_SelectionChange protected cells selection" brought up http://www.vbaexpress.com/kb/getarticle.php?kb_id=383.

A: You not missing anything, this is simply Excel maintaining the shape of the selection in preference to the protection status of the cells.
The cells are still protected, but can be copied.
Using the Worksheet_SelectionChange event will allow you to run code to redirect the selection of protected cells to another cell.  This code needs to be stored in the sheet you are trying to protect.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim Selectedrange As Range
    Dim ProtectedRange As Range
    Dim ws As Worksheet

    Application.EnableEvents = False

    Set ProtectedRange = ActiveSheet.Range("A1:A10")

    Set Selectedrange = Intersect(Target, ProtectedRange)

    If Selectedrange Is Nothing Then
        Exit Sub
    Else
        ActiveSheet.Range("B1").Select
    End If

    Application.EnableEvents = True

End Sub

If you just want to stop the user copying out the formulas then just add a line to your code to set 'Formula Hidden' to true.  If the protected cells are copied, only the values will be copied.
Worksheets("Sheet1").Range("A1:A10").Locked = True
Worksheets("Sheet1").Range("A1:A10").FormulaHidden = True
Worksheets("Sheet1").Protect UserInterfaceOnly:=True, Password:="123"
Worksheets("Sheet1").EnableSelection = xlUnlockedCells

An alternate is to move your protected data into another sheet and set it visibilty to 'very hidden', so that it is no longer visible through the UI.  The values in the 'very hidden' sheet can still be accessed via formula.
Worksheets("Sheet2").Visible = xlVeryHidden


text:
Q: Store result of view as a variable and then call it in same query Is something like this possible in SQL server?
DECLARE @SQL int
SET @SQL = (CREATE VIEW AS SELECT *
        FROM .....
        JOIN.....)

EXEC @SQL

SELECT * FROM

@SQL

LEFT JOIN.....
ON....

I want to join on the result of a view.
And then to actually select the variables such as
join ..... on @SQL.No = ......

A: Your code doesn't make sense.  Why would you want to create a view using dynamic SQL?  You can just create a view as:
CREATE VIEW my_view AS
    SELECT *
    FROM ..... JOIN
         .....;

You can then use the view in a query:
select . . .
from my_view join
     . . .

No dynamic SQL is required.
If you want a "temporary view" for a query, you can use a CTE or subquery.

A: Try this :
DECLARE @SQL nvarchar(max) ,
        @viewName nvarchar(50) = 'MyView'

SET @SQL = ('CREATE VIEW ' +@viewName  +'AS SELECT *
            FROM .....
            JOIN.....')

 EXEC sp_executeSQL @SQL

 SET @SQL = ('
 SELECT * FROM ' +  @viewName +'
 LEFT JOIN.....
 ON.... ')

 EXEC sp_executeSQL @sql


text:
Q: How do differential 2-forms give us bilinear forms on tangent spaces? Suppose $\omega$ is a 2-form on a manifold $M$. So, by definition,  $\omega$ is a section $M \to \bigwedge^2 T^*M$ where $\bigwedge^2 T^* M :=\sum_{p \in M} \bigwedge^2 (T_pM)^*$.
It seems to be a commonly used fact that $\omega$ can be interpreted as a bilinear form $\omega : T_pM \times T_pM \to \mathbb R$ on each tangent space. I know this is because there is an isomorphism $\bigwedge^2 V^* \to (\bigwedge^2 V)^*$ for any vector space $V$. I've seen several sources refer to this isomorphism as "natural," which usually means we don't need to chose a basis to construct it.
So how do we construct this isomorphism? Any other explantions/intuition are welcome.

A: *

*The wedge-product $\wedge$ is the anti-symmetric subspace of the tensor-product $\otimes$. I.e. for any two vector spaces $V,W$, the wedge product $V\wedge W$ is a subspace of $V\otimes W$. and for vectors $v\in V, w\in W$ one can define
$$v\wedge w = v\otimes w - w\otimes v$$
(though there might be a factor of $1/2$ depending on your literature. Thanks @Ted-Shifrin)

*There is an isomorphism between $(V\otimes W)^*$ and $V^*\otimes W^*$, which you can simply write as $$(\alpha\otimes\beta)(v\otimes w)=\alpha(v)\cdot \beta(w)$$ and extending by linearity, where "$\cdot$" is just multiplication of real/complex numbers.

*writing this down for the wedge-product case becomes $$(\alpha\wedge\beta)(v\otimes w)=\alpha(v)\beta(w)-\beta(v)\alpha(w)$$
which you can also write as $(\alpha\otimes\beta)(v,w)$


text:
Q: Verilog: connect modules port without instantiating a new wire Is there a way to connect two modules port without instantiating a new wire?
little example:
module comparator(max,min,in0,in1);

    input[7:0] in0,in1;
    output[7:0] max,min;

    wire[7:0] in0;
    wire[7:0] in1;
    wire[7:0] max;
    wire[7:0] min;

    assign max = (in0>in1) ? in0 : in1;
    assign min = (in0<in1) ? in0 : in1;

endmodule

I want to connect 2 comparator modules without using a new wire, is there some kind of implicit connection? i really need a way to do such thing in order to do this net:

there are to many wire between the modules.

A: I'm guessing you want one module that instantiates the module comparator many times in a way that looks like your diagram. You'll need to an array (two dimensional in my solution) were the width controlled by a parameter for the best flexibility. Inside a generate block use for-loops and if-else statements to make the connections. My solution uses slice of an array e.g. +:.
This follows IEEE Std (1800-2009), should also be true for IEEE Std (1800-2005).
module comparator_list #(parameter int SIZE=10) (input logic [7:0] in [SIZE-1:0], output logic [7:0] out [SIZE-1:0]);
    generate
        if (SIZE==1) begin : pass_through
            always_comb out = in;
        end : pass_through
        else if (SIZE==2) begin : simple
            comparator c0 ( .max(out[0]), .min(out[1]), .in0(in[0]), .in1(in[1]) );
        end : simple
        else if (SIZE%2==1) begin : odd_list
            logic [7:0] in_buf [SIZE:0];
            logic [7:0] out_buf [SIZE:0];
            always_comb begin : link_in
                foreach(in[idx]) in_buf[idx] = in[idx];
                in_buf[SIZE] = 8'h00; // force last entry to 'h0 if unasigned, 'h80 if signed
            end : link_in
            always_comb begin : link_out
                foreach(out[idx]) out[idx] = out_buf[idx];
                // Note: out_buf[SIZE] is don't care
            end : link_out
            comparator_list #(SIZE+1) cl (.in(in_buf), .out(out_buf));
        end : odd_list
        else begin : even_list
            logic [(SIZE/2)*8-1:0] top [SIZE+1];
            logic [(SIZE/2)*8-1:0] bot [SIZE+1];

            for(genvar idx=0; idx<SIZE/2; idx+=1) begin : map
                always_comb {top[0][idx*8+:8],bot[0][idx*8+:8]} = {in[2*idx],in[2*idx+1]};
                always_comb {out[2*idx],out[2*idx+1]} = {top[SIZE][idx*8+:8],bot[SIZE][idx*8+:8]};
            end : map

            for(genvar stage=0; stage<SIZE; stage++) begin : link
                if(stage%2==0) begin : even
                    comparator c0[SIZE/2-1:0] (
                        .max(top[stage+1][0+:(SIZE/2)*8]), .in0(top[stage][0+:(SIZE/2)*8]),
                        .min(bot[stage+1][0+:(SIZE/2)*8]), .in1(bot[stage][0+:(SIZE/2)*8]) );
                end : even
                else begin : odd
                    assign top[stage+1][7:0] = top[stage][7:0];
                    comparator c1[SIZE/2-2:0] (
                        .max(bot[stage+1][0+:(SIZE/2-1)*8]),
                        .min(top[stage+1][8+:(SIZE/2-1)*8]),
                        .in0(bot[stage][0+:(SIZE/2-1)*8]),
                        .in1(top[stage][8+:(SIZE/2-1)*8])
                    );
                    assign bot[stage+1][(SIZE/2-1)*8+:8] = bot[stage][(SIZE/2-1)*8+:8];
                end : odd
            end : link
        end : even_list
    endgenerate
endmodule : comparator_list

A: The IEEE Std (1364-2001) introduced the generate construct to allow for connecting multiple instances together.
The IEEE Std (1800-2005) introduced the "dot-star" (.*) syntax, also known as implicit port connections, to reduce wiring.  If you are using modern tools, they should support this SystemVerilog syntax.


text:
Q: Reset figure numbers in sphinx but only for html When building the sphinx documentation with HTML, the figure numbers appear in a global scope, i.e. the figures of a given page start with say Figure 42 although Figure 42 is the first figure on that page and all the other figures before appear on other pages. While this is definitely desirable for Latex, it is somewhat strange in HTML.
I am using sphinx 1.1 with numfig as proposed in Referencing figures with numbers in Sphinx and reStructuredText, in particular the pip package sphinx_numfig. Python version is 2.7 but I guess that doesn't matter.
How can I reset the figure number per rst file but only when the documentation is generated as HTML?


text:
Q: Can't adjust row with tkinter treeview I was making a treeview for my programm (tkinter). But I can't adjust the row.
Here is my code:
from tkinter import *
import tkinter as tk
from tkinter import ttk
st=ttk.Style()
st.configure('MyStyle.Treeview', rowheight=100)
trv=ttk.Treeview(frame1,style='MyStyle.Treeview',column=(1,2,3,4), show="headings", height=6)
trv.pack(side=LEFT, expand=YES, fill=BOTH)

Thank u

A: I found the solution.
I used in my script a theme for my treeview (ttk.Style.theme_use()) which hid my code
After removing it it works
In fact I changed the order


text:
Q: How to modify this sample code from Crypto++ for RSA to work as it should? I'm a noob with Crypto++, still trying to understand all the pipeline stuff etc...
The first trivial problem I have is that SavePrivateKey isn't found in the library by the compiler but when I look it up on Wiki Crypto++ the link is broken and I can't find what to #include...
The second problem is that I'd like to access the privkey and pubkey generate by the first snippet as strings in X.509/PKCS#8 format in order to manipulate them but it's not clear to me how to do that.
The last problem is that I haven't understood how to input the keys to the decrypt function as a string.
Thank you in advance if you can help me
#include <cryptopp/files.h>
#include <cryptopp/modes.h>
#include <cryptopp/osrng.h>
#include <cryptopp/rsa.h>
#include <cryptopp/sha.h>
#include "cryptopp/filters.h"
#include "cryptopp/hex.h"
#include "cryptopp/cryptlib.h"
#include <typeinfo>

    int main() {

// Generate keys
AutoSeededRandomPool rng;

InvertibleRSAFunction params;
params.GenerateRandomWithKeySize(rng, 3072);

RSA::PrivateKey privateKey(params);
RSA::PublicKey publicKey(params);

std::string plain="RSA Encryption", cipher, recovered;

// Encryption
RSAES_OAEP_SHA_Encryptor e(publicKey);

StringSource ss1(plain, true,new PK_EncryptorFilter(rng, e, new StringSink(cipher))); // StringSource

// Decryption
RSAES_OAEP_SHA_Decryptor d(privateKey);

StringSource ss2(cipher, true, new PK_DecryptorFilter(rng, d, new StringSink(recovered))); // StringSource

SavePrivateKey("rsa-private.key", privateKey);
SavePublicKey("rsa-public.key", publicKey);

std::cout << "Recovered plain text" << std::endl;
std::cout<<rsaPrivate<<std::endl<<rsaPublic<<std::endl;

    return 0;
}


text:
Q: Best way to refactor this static class in c#? See this example static class below.
public static class BackgroundTaskExecuter
{
    public static void MethodA()
    {
        using (var service = IocManager.Instance.ResolveAsDisposable<IServiceA>())
        {
            service.Object.MethodA();
        }
    }

    public static void MethodB()
    {
        using (var service = IocManager.Instance.ResolveAsDisposable<IServiceB>())
        {
            service.Object.MethodB();
        }
    }

    public static void MethodC()
    {
        using (var service = IocManager.Instance.ResolveAsDisposable<IServiceC>())
        {
            service.Object.MethodC();
        }
    }
}

As you can see, I have three methods. MethodA, MethodB, and MethodC that correspond with three different interfaces IServiceA, IServiceB, and IServiceC
The reason I am doing this is because I am using Hangfire.io with aspnetboilerplate framework and in Hangfire, a background task does not have HttpContext from the normal Dependency Injection. Creating a static class that wraps my calls where I resolve manually seems to get around this.
Usage looks like this:
BackgroundJob.Enqueue(() => BackgroundTaskExecuter.MethodA());

For now, I only have one or two background tasks in my web app, but conceivably I may have a lot more in the future and while it's maintainable now, it will get ugly eventually if I keep this approach.
Is there a better way to do this / refactor this? A factory pattern or anything like that perhaps?
Thanks.

A: I would make the static wrapper generic and simple.  Let it expose a single method which resolves the service and consumes it via the using statement, allowing for the caller to invoke the instance passed into the Action<T>.
Source
public static class BackgroundTaskExecuter
{
    public static void ResolveAndConsume<T>(Action<T> consumeService)
    {
        // Consider applying constraint to the <T> to
        // match the constraint of ResolveAsDisposable<T>
        using (var service = IocManager.Instance.ResolveAsDisposable<T>())
        {
            consumeService(service);
        }
    }
}

Example Usage
BackgroundJob.Enqueue(() =>
    BackgroundTaskExecuter.ResolveAndConsume<IServiceA>(serviceA => serviceA.MethodA()));

With the above you could then resolve and consume an implementation of the service and call its functionality as desired.


text:
Q: Too many arguments to function call I am getting this error. I'll admit that I don't know anything about using Xcode. I received this code and was told that it would work. Everything was fine aside from two errors. The specific code segments are:
objc_msgSend(obj, legacySelector, arguments, dict);

and
objc_msgSend(obj, normalSelector, command);

The full code follows:
#include <objc/message.h>
#import "CDV.h"
#import "CDVCommandQueue.h"
#import "CDVViewController.h"

@implementation CDVCommandQueue

@synthesize currentlyExecuting = _currentlyExecuting;

- (id)initWithViewController:(CDVViewController*)viewController
{
    self = [super init];
    if (self != nil) {
        _viewController = viewController;
        _queue = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)resetRequestId
{
    _lastCommandQueueFlushRequestId = 0;
}

- (void)enqueCommandBatch:(NSString*)batchJSON
{
    if ([batchJSON length] > 0) {
        [_queue addObject:batchJSON];
        [self executePending];
    }
}

- (void)maybeFetchCommandsFromJs:(NSNumber*)requestId
{
    // Use the request ID to determine if we've already flushed for this request.
    // This is required only because the NSURLProtocol enqueues the same request
    // multiple times.
    if ([requestId integerValue] > _lastCommandQueueFlushRequestId) {
        _lastCommandQueueFlushRequestId = [requestId integerValue];
        [self fetchCommandsFromJs];
    }
}

- (void)fetchCommandsFromJs
{
    // Grab all the queued commands from the JS side.
    NSString* queuedCommandsJSON = [_viewController.webView stringByEvaluatingJavaScriptFromString:
        @"cordova.require('cordova/exec').nativeFetchMessages()"];

    [self enqueCommandBatch:queuedCommandsJSON];
}

- (void)executePending
{
    // Make us re-entrant-safe.
    if (_currentlyExecuting) {
        return;
    }
    @try {
        _currentlyExecuting = YES;

        for (NSUInteger i = 0; i < [_queue count]; ++i) {
            // Parse the returned JSON array.
            NSArray* commandBatch = [[_queue objectAtIndex:i] cdvjk_mutableObjectFromJSONString];

            // Iterate over and execute all of the commands.
            for (NSArray* jsonEntry in commandBatch) {
                CDVInvokedUrlCommand* command = [CDVInvokedUrlCommand commandFromJson:jsonEntry];
                if (![_viewController execute:command]) {
#ifdef DEBUG
                        NSString* commandJson = [jsonEntry cdvjk_JSONString];
                        static NSUInteger maxLogLength = 1024;
                        NSString* commandString = ([commandJson length] > maxLogLength) ?
                        [NSString stringWithFormat:@"%@[...]", [commandJson substringToIndex:maxLogLength]] :
                        commandJson;

                        DLog(@"FAILED pluginJSON = %@", commandString);
#endif
                }
            }
        }

        [_queue removeAllObjects];
    } @finally
    {
        _currentlyExecuting = NO;
    }
}

- (BOOL)execute:(CDVInvokedUrlCommand*)command
{
    if ((command.className == nil) || (command.methodName == nil)) {
        NSLog(@"ERROR: Classname and/or methodName not found for command.");
        return NO;
    }

    // Fetch an instance of this class
    CDVPlugin* obj = [_viewController getCommandInstance:command.className];

    if (!([obj isKindOfClass:[CDVPlugin class]])) { // still allow deprecated class, until 1.0 release
        NSLog(@"ERROR: Plugin '%@' not found, or is not a CDVPlugin. Check your plugin mapping in Cordova.plist.", command.className);
        return NO;
    }
    BOOL retVal = YES;

    // Find the proper selector to call.
    NSString* methodName = [NSString stringWithFormat:@"%@:", command.methodName];
    NSString* methodNameWithDict = [NSString stringWithFormat:@"%@:withDict:", command.methodName];
    SEL normalSelector = NSSelectorFromString(methodName);
    SEL legacySelector = NSSelectorFromString(methodNameWithDict);
    // Test for the legacy selector first in case they both exist.
    if ([obj respondsToSelector:legacySelector]) {
        NSMutableArray* arguments = nil;
        NSMutableDictionary* dict = nil;
        [command legacyArguments:&arguments andDict:&dict];
        //[obj performSelector:legacySelector withObject:arguments withObject:dict];
        objc_msgSend(obj, legacySelector, arguments, dict);
    } else if ([obj respondsToSelector:normalSelector]) {
        //[obj performSelector:normalSelector withObject:command];
        objc_msgSend(obj, normalSelector, command);
    } else {
        // There's no method to call, so throw an error.
        NSLog(@"ERROR: Method '%@' not defined in Plugin '%@'", methodName, command.className);
        retVal = NO;
    }
    return retVal;
}

@end


text:
Q: Error on Logout: undefined method 'invalidate_token' I'm building authentication on a Rails 5 API, and I'm having issues with the logout piece.  I'm hitting the /logout route and receive a 500 error reading NoMethodError: undefined method 'invalidate_token' for nil:NilClass>, and it then references my sessions_controller.  My sessions_controller references an invalidate_token method in the logout method that's declared in the Users model, and I'm stumped as to why the error is undefined in the controller when I have defined it in the model.
sessions_controller:
class SessionsController < ApiController
  skip_before_action :require_login, only: [:create], raise: false

  def create
    if (user = User.validate_login(params[:username], params[:password]))
      allow_token_to_be_used_only_once_for(user)
      send_token_for_valid_login_of(user)
    else
      render_unauthorized('Error creating the session with provided credentials')
    end
  end

  def destroy
    logout
    head :ok
  end

  private

  def send_token_for_valid_login_of(user)
    render json: { token: user.auth_token }
  end

  def allow_token_to_be_used_only_once_for(user)
    user.regenerate_auth_token
  end

  def logout
    @current_user.invalidate_token
  end
end

Users model
class User < ApplicationRecord
  # validate unique username and email
  validates_uniqueness_of :username, :email
  has_secure_password
  has_secure_token :auth_token

  # clear token value, used to logout
  def invalidate_token
    self.update_columns(auth_token: nil)
  end

  def self.validate_login(username, password)
    user = User.find_by(username: username)
    if user && user.authenticate(password)
      user
    end
  end
end

API Controller:
class ApiController < ApplicationController
  def require_login
    authenticate_token || render_unauthorized('Access Denied: Unauthorized Access')
  end

  def current_user
    @current_user ||= authenticate_token
  end

  protected

  def render_unauthorized(message)
    errors = { errors: [detail: message] }
    render json: errors, status: :unauthorized
  end

  private

  def authenticate_token
    authenticate_with_http_token do |token|
      User.find_by(auth_token: token)
    end
  end
end

Ideally, this should get past the logout method so it can render a 200 and actually invalidate the logged in users token.

A: It is complaining that @current_user is nil so before using the invalidate_token on @current_user make sure @current_user is not nil.
I guess you are using current_user method in the application_controller that returns the @current_user so replace
 def logout
   @current_user.invalidate_token
 end

with
 def logout
   current_user.invalidate_token
 end

A: You are doing a find_by when fetching the user record in authenticate_token.  If no record is found, nil is returned.
Either you got bad data, or your header is not valid.

A: It is because your current_user is nil.You have to send auth_token while making request for logout. With this auth_token you have to get the user, so that you can update that user for -- nil auth_token. If user not found then you have to handle the exception for this case, because your are requesting with invalid auth_token or user might not be present in your database.
Also you need to correct this
def logout
  current_user.invalidate_token
end


text:
Q: Пропадает панель задач во время записи экрана В Linux Mint 17.3 во время записи экрана (recordmydesktop) и при показе экрана через скайп прекращает отображаться панель задач. При завершении записи/показа появляется снова.
Как это исправить?

A: Проблема конкретно циннамона, только багрепорт - циннамнон считает часть "экранозаписывателей" полноэкранными приложениями, в следствии чего прячет панель.


text:
Q: PHP: Create a iv. Not working I have write a code to encrypt a data with mcrypt. When I create a IV it works BUT when I decrypt it the decrypted text isn't the same as before and it gives me this error:
Warning: mcrypt_decrypt(): The IV parameter must be as long as the blocksize

Here is my code when I create a IV:
$iv = mcrypt_create_iv(mcrypt_get_iv_size($algo, $type), MCRYPT_RAND);

The problem is also that it gives a string with unreadable characters.
Here is my code when encrypting:
trim(base64_encode(mcrypt_encrypt($algo, $pass,
                                  $data, $type, $iv)));

And here is for decrypting:
trim(mcrypt_decrypt($algo, $pass,
                    base64_decode($data), $type, $iv));

The question: Why can't it decrypt so I get the plaintext and why it gives me a error.
EDIT:
When I use a EMPTY IV, it works and I get the plaintext, but it still gives me error:
Warning: mcrypt_xxxxxx(): The IV parameter must be as long as the blocksize

A:
I have write a code to encrypt a data with mcrypt.

This never bodes well. (Emphasis mine.)

When I create a IV it works BUT when I decrypt it the decrypted text isn't the same as before and it gives me this error:
Warning: mcrypt_decrypt(): The IV parameter must be as long as the blocksize

Here is my code when I create a IV:
$iv = mcrypt_create_iv(mcrypt_get_iv_size($algo, $type), MCRYPT_RAND);

Do you know what MCRYPT_RAND means? It means rand(), an insecure random number generator.
Every algorithm that requires an initialization vector (IV) has the following security requirements:

*

*Initialization vectors must never repeat.

*Initialization vectors must be unpredictable.

MCRYPT_RAND fails at both counts: There are only 2^32 possible outputs from rand() and it's predictable.

The question: Why can't it decrypt so I get the plaintext and why it gives me a error.

The simplest answer is mcrypt sucks and you should use something else. My recommendations are here.


text:
Q: Later version of GEOS on pypi I am trying to install GEOS 3.3.3 on my workstation. When I look at pypi (https://pypi.org/search/?q=geos), I only see versions up to 0.2.1. Do I need to install it from somewhere else?

A: If you are needing to setup GEOS for a python environment, you should check out Anaconda's python distribution environment.  They provide pre-built GEOS for many platforms.   https://anaconda.org/search?q=geos
see https://www.anaconda.com/distribution/


text:
Q: Android Studio Number Picker I want to use a NumberPicker in Android Studio but instead of numbers I want to set a string array. I found a similar question but the problem is: I have more than 10000 strings and Android Studio doesn't work with more than ?(I don't know) items. What can I do?

A: Copy-pasting from the Spinner sample, this is pretty straight forward, if you have the array:
Spinner spinner = (Spinner) findViewById(R.id.yourSpinnerId);
ArrayAdapter<String> adapter = new ArrayAdapter(
     yourContextRef // If this is in an activity, then simply this
     , android.R.layout.simple_spinner_item // the layout of an item
     , yourStringArray // Your string array
);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);


text:
Q: Accesing DOM elements with PHP Simple DOM I want to extract data from YMCA local schedule, table with data is under div="scheduler_here". For this project I'm using  PHP Simple HTML DOM Parser. But it's not showing any data.
<?php
// Include the library
include('simple_html_dom.php');

// Retrieve the DOM from a given URL
$html = file_get_html('http://www.activelifeadmin.com/newyork/websearch/public/index/weekview?sched=Group%20Exercise%20Schedule,Large%20Pool,Small%20Pool&branch_ids=38#/');

// Find the DIV tag with an id of "myId"
foreach($html->find('div[scheduler_here]') as $e)
    echo $e->innertext . '<br>';
?>

Output PHP
YMCA Website

A: You need to get by id attribute:
foreach($html->find('div[id=scheduler_here]') as $e)


text:
Q: Php catch exception I'm trying to catch an error
        try
        {
            $outcome            =   $bet->getElementsByTagName("Outcome");
            $line1              =   $outcome->item(0)->getElementsByTagName("OptionalValue1")->item(0)->nodeValue;
            $line2              =   $outcome->item(2)->getElementsByTagName("OptionalValue1")->item(0)->nodeValue;
            $aOdds["line"]      =   ($line1 == 0) ? -$line2 : $line1;

            $aOdds["q1"]        =   $outcome->item(0)->getAttribute("odds");
            $aOdds["qx"]        =   $outcome->item(1)->getAttribute("odds");
            $aOdds["q2"]        =   $outcome->item(2)->getAttribute("odds");
        }
        catch (Exception $e)
        {
            $outcome            =   $bet->getElementsByTagName("Outcome");
            $line1              =   $outcome->item(0)->getElementsByTagName("OptionalValue1")->item(0)->nodeValue;
            $line2              =   $outcome->item(1)->getElementsByTagName("OptionalValue1")->item(0)->nodeValue;
            $aOdds["line"]      =   ($line1 == 0) ? -$line2 : $line1;

            $aOdds["q1"]        =   $outcome->item(0)->getAttribute("odds");
            $aOdds["qx"]        =   0;
            $aOdds["q2"]        =   $outcome->item(1)->getAttribute("odds");
        }

Some data comes with 2 same tag and the others with 3 and I want to catch if there not exist the 3. tag, but the error catching not really work.

A: You can throw your own exception in the try block
if (some condition) {
  throw new Exception("Error message");
}

A: You should read a little more about the concept of exceptions. Here are a few links that you might find useful:
http://www.w3schools.com/php/php_exception.asp
http://ciaweb.net/pear-exception-use-guidelines.html
http://php.net/manual/en/language.exceptions.php

A: Are you sure that, in the try block code, an error will throw an exception?
The try statment is able to catch the exception which is threw by this php code:
throw new Exception('exception raised');

Please have a look here, in the Note pane.


text:
Q: geting data from firebase in flutter im trying to get data from firebase
the main page show the data correctly based on the length
but the details page is not the data of the first index is duplicated to the on the other pages
this is the main page and it shows different data correctly

but the first details page keep duplicate it self
this is the detail page code
import 'package:carousel_slider/carousel_slider.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:online_shop/api/summer_list_api.dart';
import 'package:online_shop/core/services/summer_notifier.dart';
import 'package:online_shop/model/Summer_d_model.dart';
import 'package:online_shop/pages/home_page.dart';
import 'package:online_shop/view/widgets/costum_button.dart';
import 'package:online_shop/view/widgets/costum_text.dart';
import 'package:online_shop/view/widgets/nav.dart';
import 'package:provider/provider.dart';

class DetalsPage extends StatefulWidget {
  DetalsPage({Key? key}) : super(key: key);

  @override
  _DetalsPage createState() => _DetalsPage();
}

class _DetalsPage extends State<DetalsPage> {
  late Future Summers;

  @override
  void initState() {
    Summers = getsummerinfo(SummerNotifier());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    SummerNotifier summerNotifier = Provider.of<SummerNotifier>(context);

    return Scaffold(
      body: ListView.builder(
        itemCount: 1,
        scrollDirection: Axis.vertical,
        itemBuilder: (context, index) {
          return Column(
            children: [
              Container(
                child: Stack(
                  children: [
                    Image.network(
                      summerNotifier.summerList[index].Imag,
                      width: 400,
                      fit: BoxFit.fitWidth,
                    ),
                    Container(
                        margin: const EdgeInsets.only(top: 40, left: 5),
                        child: IconButton(
                            onPressed: () {
                              Navigator.push(context,
                                  MaterialPageRoute(builder: (context) {
                                return Nav();
                              }));
                            },
                            icon: Icon(Icons.arrow_back_ios))),
                    Container(
                      height: 575,
                      margin: const EdgeInsets.only(top: 230),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(20)),
                      child: Padding(
                        padding: const EdgeInsets.only(top: 5, bottom: 5),
                        child: ListView.builder(
                          itemCount: 1,
                          scrollDirection: Axis.vertical,
                          itemBuilder: (context, index) {
                            return Column(
                              children: [
                                Padding(
                                  padding: const EdgeInsets.only(
                                    left: 10,
                                  ),
                                  child: CoustumText(
                                    text: summerNotifier.summerList[index].name,
                                    size: 30,
                                    color: Colors.black,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                const SizedBox(
                                  height: 10,
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(
                                      left: 10, right: 10),
                                  child: CoustumText(
                                    text: summerNotifier
                                        .summerList[index].sub_info,
                                    size: 16,
                                    color: Colors.black,
                                  ),
                                ),
                                const SizedBox(height: 20),
                                Padding(
                                  padding: const EdgeInsets.only(left: 10),
                                  child: CoustumText(
                                    text: "some of the place photos:",
                                    size: 18,
                                    color: Colors.black,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                                const SizedBox(
                                  height: 10,
                                ),
                                FutureBuilder(
                                    future: Summers,
                                    builder: (context, snapshot) {
                                      switch (snapshot.connectionState) {
                                        case ConnectionState.none:
                                          return Text("there is issu ");
                                        case ConnectionState.waiting:
                                          return CircularProgressIndicator();

                                        default:
                                          if (snapshot.hasError) {
                                            return Text("Error");
                                          }
                                      }
                                      return CarouselSlider(
                                        items: summerNotifier
                                            .summerList[index].sub_img
                                            ?.map((items) => Container(
                                                  height: 200,
                                                  child: Image.network(
                                                    items,
                                                    fit: BoxFit.cover,
                                                  ),
                                                ))
                                            .toList(),
                                        options:
                                            CarouselOptions(autoPlay: false),
                                      );
                                    }),
                                const SizedBox(
                                  height: 20,
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(left: 10),
                                  child: CoustumText(
                                    text: "trip informations:",
                                    size: 20,
                                    color: Colors.black,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                                const SizedBox(
                                  height: 10,
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(
                                      left: 10, right: 10),
                                  child: Container(
                                    child: CoustumText(
                                      text:
                                          "The trip is for 7 days and 8 nights and ther will be a program for spinding the time,every day ther will be a new place to discover so relax and lets the journy start.",
                                      size: 16,
                                      color: Colors.black,
                                    ),
                                  ),
                                ),
                                const SizedBox(
                                  height: 20,
                                ),
                                Container(
                                  child: Padding(
                                    padding: const EdgeInsets.only(
                                        left: 10, right: 10),
                                    child: Column(
                                      children: [
                                        CoustumText(
                                          text: "Contact informations:",
                                          size: 20,
                                          color: Colors.black,
                                          fontWeight: FontWeight.w600,
                                        ),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          children: [
                                            Row(
                                              children: const [
                                                Icon(
                                                  Icons.phone,
                                                  size: 20,
                                                ),
                                                SizedBox(
                                                  width: 5,
                                                ),
                                                CoustumText(
                                                    text: "85746385",
                                                    size: 16,
                                                    color: Colors.black),
                                              ],
                                            ),
                                            Row(
                                              children: const [
                                                Icon(
                                                  Icons.facebook_rounded,
                                                  color: Colors.blueAccent,
                                                  size: 30,
                                                ),
                                                SizedBox(
                                                  width: 5,
                                                ),
                                                CoustumText(
                                                    text: "Flay_fun",
                                                    size: 16,
                                                    color: Colors.black),
                                              ],
                                            ),
                                          ],
                                        ),
                                        const SizedBox(
                                          height: 5,
                                        ),
                                        Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          children: [
                                            Row(
                                              children: const [
                                                Icon(
                                                  Icons.phone,
                                                  size: 20,
                                                ),
                                                SizedBox(
                                                  width: 5,
                                                ),
                                                CoustumText(
                                                    text: "85208579",
                                                    size: 16,
                                                    color: Colors.black),
                                              ],
                                            ),
                                            Row(
                                              children: const [
                                                Icon(
                                                  Icons.email_rounded,
                                                  color: Colors.blueAccent,
                                                  size: 30,
                                                ),
                                                SizedBox(
                                                  width: 5,
                                                ),
                                                CoustumText(
                                                    text: "Flayfun@gmail.com",
                                                    size: 16,
                                                    color: Colors.black),
                                              ],
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                                const SizedBox(
                                  height: 20,
                                ),
                                Container(
                                  width: 200,
                                  child: CoustumButton(
                                    text: "book now \$200",
                                    onPressed: () {},
                                    size: 20,
                                  ),
                                ),
                              ],
                            );
                          },
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}

this is the method to get the data
// ignore_for_file: unused_local_variable, non_constant_identifier_names

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:online_shop/core/services/summer_notifier.dart';
import 'package:online_shop/model/Summer_d_model.dart';

Future  getsummerinfo  (SummerNotifier summerNotifier) async {
  QuerySnapshot snapshot =
      await FirebaseFirestore.instance.collection("Summer_D").get();

  List<Summer_d> _summerList = [];

  snapshot.docs.forEach((docs) {
    Summer_d summer_d = Summer_d.fromMap(docs.data() as Map<String, dynamic>);
    _summerList.add(summer_d);
  });
  summerNotifier.summerList = _summerList;

}

this is the other one
// ignore_for_file: unused_local_variable, non_constant_identifier_names

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:online_shop/core/services/summer_notifier.dart';
import 'package:online_shop/model/Summer_d_model.dart';

Future  getsummerinfo  (SummerNotifier summerNotifier) async {
  QuerySnapshot snapshot =
      await FirebaseFirestore.instance.collection("Summer_D").get();

  List<Summer_d> _summerList = [];

  snapshot.docs.forEach((docs) {
    Summer_d summer_d = Summer_d.fromMap(docs.data() as Map<String, dynamic>);
    _summerList.add(summer_d);
  });
  summerNotifier.summerList = _summerList;

}

this is the models
// ignore_for_file: camel_case_types

 class Summer_d {
  late String Imag;
  late String info;
  late String name;
  late int price;
  late String sub_info;
  late List<dynamic>? sub_img;

  Summer_d.fromMap(Map<String,dynamic>data){
    Imag = data["Imag"];
    info = data ["info"];
    name = data ["name"];
    price = data["price"];
    sub_info = data ["sub_info"];
    sub_img = data ["sub_img"];

  }
}

A: You're hardcoding the itemCount in the ListView.builder, and then in the ListView.builder, in its itemBuilder method,  you're saying summerNotifier.summerList[index]. The index will always be zero.

@override
  Widget build(BuildContext context) {
    SummerNotifier summerNotifier = Provider.of<SummerNotifier>(context);

    return Scaffold(
      body: ListView.builder(
        itemCount: 1, // hard-coding this to 1
        scrollDirection: Axis.vertical,
        itemBuilder: (context, index) {
           // here the index will always be zero,
           // since above you specified itemCount = 1
           summerNotifier.summerList[index]

        }
      )
    );
}

I'd actually use the SummerNotifier service you have to hold on to the selected item reference and then in the Details page I get it from the service and populate the details of that item. Or in your case, the index of the selected item.
I believe that's your issue.


text:
Q: Default Content before Route Resolution I'm re-working a website that has a very nested interface requiring several child views. Think of a shopping site, with paging, results and filters. What I'd like to do is render default content for said children views while the results are being resolved from the back-end. However, I can't find a way to insert default content past the first <ui-view>, which of course, makes sense.
To get around this, we are currently using $broadcast in the child state controllers. We moved the resolution out of the resolve event into the controller, which is working, but requires us to make all of our directives use $broadcast as well, or they don't work since the data isn't loaded before they are. It also seems like a very inelegant solution to the issue.
What's weird, is that when I move the resolve function into a child view, neither the parent nor it's siblings views load before the results child view loads. I can't understand that whereas I can understand children views not loading before the parent is resolved.
Is there a way we can work around this? Building in broadcasting into all aspects of our code base seems like an extremely poor practice. Is there a way to show children default content before the parent is resolved, or even render child states' views before their controllers are instantiated?

A: Use ng-cloak class:
https://docs.angularjs.org/api/ng/directive/ngCloak

The ngCloak directive is used to prevent the Angular html template from being briefly displayed by the browser in its raw (uncompiled) form while your application is loading. Use this directive to avoid the undesirable flicker effect caused by the html template display.


text:
Q: What do you mean by Newtonian space? What do you mean by Newtonian space? When you see this question, most of you might be thinking that I am trying to crack a joke or something..but no. This was a genuine doubt which one of my friends raised when we were discussing about NLOM on Whatsapp. He asked this question after I answered his query on what an inertial frame was..I wanted to clarify whether Newtonian space and inertial frame are the same or not..

A: In terms of its geometric characteristics Newtonian space is 3D Euclidean spaces as said by G. Smith.
Besides that Newton had an interesting philosophical viewpoint regarding the nature of space. He thought that there was a "relative space", the one our senses and instruments could detect, and an "absolute space", an underlying physical object that acted like a scenario for all the physical processes to occur. When you measure the size of something you are measuring the difference in position between two extremes but you are not measuring the actual position of anything, just its relation to other positions. Newton thought that all our experience of the universe was based on the relative position of things, all measurements of positions are refered to another position to whom is relatively distant or not.
Scientific method tells that anything that can't be shown by evidence (by collecting data from observations) can be assumed to be non existent since something that no interaction reveals has no physical consequences and thus is indistinguishible from non existent. Newton realized that if our perception and our observations regarding space only accounted for relative positions, absolute space was just a belief that needed to be adressed with evidence separatedly, and that there were at the time no actual experiments showing this absolute space to really exist. Maybe space is just that, the inter-relations of positions but there are no actual positions in absolute terms.
Thus he devised some thought experiments (the most famous of which is the Newton's Bucket) to prove there was also an absolute space.
Today we think that absolute space indeed does not exist at all. But Newton's thought experiments are intriguin from that perspective. Trying to make Newton's experiments compatible with the ideo of no absolute space been there has led to a paradoxical conclusion by Ernst Mach: that matter comunicates across the universe by some means to generate some relative standard for mechanics to work.
It's difficult to adress all of this for me, I don't speak english very well and there might be tricky things in the debate that I didn't mention, but if you are interested in the topic these are excellent resources:

*

*https://plato.stanford.edu/entries/spacetime-theories/

*https://plato.stanford.edu/entries/newton-stm/

*https://en.wikipedia.org/wiki/Bucket_argument

*https://en.wikipedia.org/wiki/Mach%27s_principle


text:
Q: Php Sql Server Stored Procedure ALTER PROCEDURE [dbo].[uspProcessProfessionalPinRenewal]
 @processtype INT ,
 @SinglePinNumber NVARCHAR(12) = NULL,
 @operatorID INT,
 @returnMessage NVARCHAR(35) OUTPUT

 AS

.....
$sqlExecSP   = "{CALL uspProcessProfessionalPinRenewal(?,?,?,?)}";
           //$sqlExecSP   = "{CALL uspStudentGrading(?, ?, ?)}";

            // Prepare stored procedure call with three parameters
            $sth = $db->getPdo()->prepare($sqlExecSP);

            $processtype=1;
            $SinglePinNumber=$pin;
            $operatorID=Auth::user()->BusinessEntityID;
            $retMessage="";

            // Bind parameter 1 as IN parameter
            // Be sure *not* to set a length to indicate it's an IN parameter

            $sth->bindParam(1, $processtype, PDO::PARAM_INT);
            $sth->bindParam(2, $SinglePinNumber, PDO::PARAM_STR,12);
            $sth->bindParam(3, $operatorID, PDO::PARAM_INT);
            $sth->bindParam(4, $retMessage, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 35);

            // $sth->bindParam(4, $indexnumber, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 50);

           // dd($programcatid . ', ' . $programtypeid . ', ' . $voucherpin . ', ' . $applicationref);

            // Call the stored procedure

            // print "Executing stored procedure...\n";
            $res = $sth->execute();

Above is the header of my stored procedure and my php code to call it
But I get the error
SQLSTATE[22018]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Conversion failed when converting the nvarchar value '17GS08664006' to data type int.
Please help

A: going through the stored procedure I realized i was assigning a string to an integer. Thanks a lot


text:
Q: Adding a title in Custom Graph in Facebook I using a custom graph api for publishing a story. While publishing the story the API always picks up the "One to One - Without Object Title" and not "One to One". I need to pick the "One to One" as it has an option to update the "level.title".
Question

*

*How to make my code to pick "One to One"

*How to correct my post to have "
James Jack cleared a level 1 in Puzzle Game - Ball Mania" Instead of "James Jack cleared a level in Puzzle Game - Ball Mania"

Code
    // Create an object
    ShareOpenGraphObject object = new ShareOpenGraphObject.Builder()
            .putString("og:type", "puzzlegameballmania:level")
            .putString("og:title", "Puzzle Game - Ball Mania")
            .putString("og:image", "http://i67.tinypic.com/svl2qt.png")
            .putString("og:url", "https://play.google.com/store/apps/details?id=memory.game.collection.free")
            .putString("og:description", "Color of the balls matters more. Lets break the goal and go higher !")
            .putString("puzzlegameballmania:level:title", "LEVEL 1")
            .build();

    // Create an action
    ShareOpenGraphAction action = new ShareOpenGraphAction.Builder()
            .setActionType("puzzlegameballmania:clear")
            .putObject("puzzlegameballmania:level", object)
            .build();

    // Create the content
    ShareOpenGraphContent content = new ShareOpenGraphContent.Builder()
            .setPreviewPropertyName("puzzlegameballmania:level")
            .setAction(action)
            .build();

    ShareDialog.show(AndroidLauncher.this, content);


text:
Q: Selenium: Dynamically loaded page causes automatic scrolling to fail I'm using Selenium for Python to navigate a dynamic webpage (link).
I would like to automatically scroll down to a y-point on the page. I have tried various ways to code this, which seem to work on other pages, but not on this particular webpage.
Some examples of my efforts that don't seem to work for Firefox with Selenium:
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://en.boerse-frankfurt.de/etp/Deka-Oekom-Euro-Nachhaltigkeit-UCITS-ETF-DE000ETFL474")

By scrolling to a y-position:
driver.execute_script("window.scrollTo(0, 1400);")

Or by finding an element:
try:
    find_scrollpoint = driver.find_element_by_xpath("//*[@id='main-wrapper']/div[10]/div/div[1]/div[1]")
except:
    pass
else:
    scrollpoint = find_scrollpoint.location["y"]
    driver.execute_script("window.scrollTo(0, scrollpoint);")

Questions:
What could be some unusual circumstances on webpages such as this, where this very typical scrollTo code may fail?
What can possibly be done to mitigate it? Perhaps keypresses to scroll down – but it would still have to know when to stop pressing down.

A: It is just quite a dynamic page. I would wait for this specific element to be visible and then scroll into it's view. This works for me:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Firefox()
driver.get("http://en.boerse-frankfurt.de/etp/Deka-Oekom-Euro-Nachhaltigkeit-UCITS-ETF-DE000ETFL474")

wait = WebDriverWait(driver, 10)
elm = wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@id='main-wrapper']/div[10]/div/div[1]/div[1]")))

driver.execute_script("arguments[0].scrollIntoView();", elm)


text:
Q: How to use multiple group_concat with count,order by and group by in mysql I have a table t1
id  |   Date      | name
1   | 22-06-2017  | a
2   | 22-06-2017  | a
3   | 22-06-2017  | a
4   | 22-06-2017  | b
5   | 21-06-2017  | a
6   | 20-06-2017  | b
7   | 20-06-2017  | b
8   | 19-06-2017  | a
9   | 19-06-2017  | b
10  | 18-06-2017  | a

I want a result of last 10 days from current date(22-06-2017) with each name and get the count of all ten day in single row. if there is no date present so it will show 0 count and they should be like 10th day in 1st place, 9th day in 2nd place and so on in row

count                |  name
0,0,0,0,0,1,1,0,1,3  | a
0,0,0,0,0,0,1,2,0,1  | b

can somebody please help me to write this query. its very helpful for me


text:
Q: pscp exclude a directory pscp -r   ../mydir/  xxx@example.com:/var/www/html/xxx/

copies everything under mydir, is there a way to exclude one subdirectory under mydir?

A: Not with the scp command itself.
However ... install cygwin, and then ...
find . \! -name to_exclude -print | cpio -o | ssh where-ever "cd dest;cpio -i -"


text:
Q: CSS module `:hover .child` not working I have the following scss:
.skillBox {
  position: relative;
  border-radius: 10px;
  border: 1px solid #ccc;
  box-shadow: 0 2px 20px #ccc;
  padding: 1em;

  &:hover {
    padding: 3em;
    .d-none {
      display: inline-block !important;
    }
  }

  &:hover .d-none {
    display: inline-block !important;
  }
}

On hover, I get the padding:3em but both the nested, and inline child rule didn't work, ie .d-none class wasn't overridden.
What's the right way of writing the rule with CSS module?
I'm trying out CSS module with CRA and custom-react-scripts with sass and modules turned on (REACT_APP_SASS_MODULES=true).
Or perhaps I should use styled components instead? Was trying to figure out which one to go for for react apps.

A: you can try this code to solve your problem
.skillBox {
  position: relative;
  border-radius: 10px;
  border: 1px solid #ccc;
  box-shadow: 0 2px 20px #ccc;
  padding: 3em;
  background: red;
  &:hover {
    &.d-none {
      background: black;
      color: #fff;
      padding: 20px;
    }
  }
}

.d-none {
  background: green;
  color: #fff;
  padding: 20px;
}

  Parrent

Childred

Exmaple :: https://codepen.io/anon/pen/yqQNJXCodePen

A: There's nothing wrong with your CSS. See the demo below.
.skillBox {
  position: relative;
  border-radius: 10px;
  border: 1px solid #ccc;
  box-shadow: 0 2px 20px #ccc;
  padding: 1em;

  .d-none{
    display: none;
  }

  &:hover {
    padding: 3em;
    .d-none {
      display: inline-block;
    }
  }
}

https://codepen.io/paulcredmond/pen/djQoow

A: In case if element with skillbox and d-none class are siblings below is the css for that
.skillBox {
  position: relative;
  border-radius: 10px;
  border: 1px solid #ccc;
  box-shadow: 0 2px 20px #ccc;
  padding: 1em;

  &:hover {
    padding: 3em;
  }
}

.dnone {
  display: none;
}

.skillBox:hover ~ .dnone {
  display: inline-block;
}

http://jsbin.com/hixamotuku/edit?html,css,output

A: So I realise CSS Modules created a customised classname for .d-none and applying that classname worked.
So I changed the classname altogether making it an entirely new class that overrides .d-none.
.skillBox {
  position: relative;
  border-radius: 10px;
  border: 1px solid #ccc;
  box-shadow: 0 2px 20px #ccc;
  padding: 1em;

  &:hover {
    .dNone {
      display: inline-block !important;
    }
  }
}

And applying by adding them as an array then joining them together:


text:
Q: How to read data from a file having unicode in Java? I have a tsv file and it contains Unicode data like "Pär Lagerkvist's received Nobel Prize in Physics."
But while reading it in Java I am receiving output like
"P�r Lagerkvist's received Nobel Prize in Physics."
I am using the following piece of code for the file reading
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
while ((st = br.readLine()) != null) {
    System.out.println(st);
}

A: I assume you are using Intellij Idea. This case, set console encoding
-Dfile.encoding=UTF-8
On Windows, edit idea.exe.vmoptions file and add the above line.
See this for details.


text:
Q: I don't want my ls command in my script to print results on screen I run "ls -lX" over files umbrella31_*.xvg. I run a command that searches the number on the fifth column of the ls command output, that is larger let's say than 20000. It looks like this:
ls -lX umbrella31_*log |  awk '{if($5 >=20000) {print}}' | wc -l

and outputs a number (the number of lines for which the number in column 5 is > 20000).
When I include the above command in a script:
#!/bin/bash -x

ls -lX umbrella31_*log |  awk '{if($5 >=20000) {print}}' | wc -l

and run it, I get in the screen the result of "ls" printed as well (which I don't want). How can I get my script behave like my on-screen command, and print only the desired number of lines?

A: Updated Answer
After posting script used in the question it was discovered:
#!/bin/bash -x

was used where the -x option outputs all commands to the terminal.
Removing the -x solved the original problem.

Original Answer
You're missing the argument flag indicator so this:
ls lX umbrella31_*log |  awk '{if($5 >=20000) {print}}' | wc -l

should be this instead:
ls -lX umbrella31_*log |  awk '{if($5 >=20000) {print}}' | wc -l

On my system looking for bash scripts it works like so:
$ ls -lX *.sh
-rwxrwxr-x 1 rick rick 4183 Jul  1 10:48 aptfileparse.sh
-rwxrwxr-x 1 rick rick  339 Jul 24 17:26 checkrunning.sh
-rwxrwxr-x 1 rick rick  506 Jul 15 17:54 Downloads.sh
-rwxrwxr-x 1 rick rick   78 Jul  6 11:28 runall.sh

$ ls -lX *.sh | awk '{if($5 >=200) {print}}' | wc -l
3

A: Your script will print each of the commands in your pipeline to the terminal because you are running it with the -x flag. Fromman bash:
   -x        Print commands and their arguments as they are executed.

However, your approach using ls and wc is not the best way to count files.

To find file that is >= 20000 you can use find:
find -type f -maxdepth 1 -name 'umbrella31_*log' -size +19999c -ls

(because of how find interpreters + sign (greater than rounded up) you get n+1, therefore the odd -size n)
count output:
(when we count files we just print a newline because we dont really need an output)
wc -l < <(find -maxdepth 1 -type f -name 'umbrella31_*log' -size +19999c -printf \\n)

-maxdepth n  Descend  at  most levels (a non-negative integer) levels of directories below the starting-points.
-size n  File uses n units of space, rounding up.
-ls  List current file in ls -dils format on standard output.


text:
Q: ASP.NET 4.0 MVC2 routing on IIS 6 ASP.NET 4.0 MVC2 routing on IIS 6 is not working for me with all the methods used for 3.5
Works fine as long as I build in 3.5 but building in 4.0 and setting the server to use 4.0 I loose my routing. Anyone seen this and been able to resolve it?

A: Have you checked to make sure that ASP.NET 4.0 is allowed in the web service extensions after upgrading to .NET 4.0 on the server?
See this question.


text:
Q: In the context of python and cpython, is a ".c.src" file a c source code file? how to compile this kind of file? this question comes from this post.
digging numpy.linalg.eig leads to a umath_linalg.c.src file.
in the context of python and cpython, is a ".c.src" file a c source code file? how to compile this umath_linalg.c.src file?


text:
Q: Get a object from json based on a specific value I have a json string. I need to get a specific object based on an id value. Suppose I entered 2, then I want {"id":"2","name":"def"} as the result. I want this to be done in java class.
[
{"id":"1",
"name":"abc"},
{"id":"2",
"name":"def"}
]

A: Put the Objects in the Array for better manipulation..!!!
JSONObject data = new JSONObject(YOUR_JSON);
JSONArray data_Values=data.getJSONArray(values);
int n=2;// Entered ID
for(int i=0;i<=data_Values.length();i++)
{
    if(n==data_Values.getInt("id"))
    {
        id=data_Values.getInt("id");
        name=data_Values.getString("name");
    }
}

JSON Data
    {
      "Values": [
        {
          "id": "1",
          "name": "ABC"
        },
        {
          "id": "2",
          "name": "EFG"
        },
        {
          "id": "3",
          "name": "HIJ"
        }
      ]
    }


text:
Q: How can I make user info card via pure FlexBox This is my design:
enter image description here
How can I make it using Flexbox?

A: While flexbox is a great modern way to create layouts, it doesn't make sense in this case. You would be adding unnecessary styling. You can easily do this with a table.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

            Name
            Data

            Name
            Data

            Name
            Data

            Name
            Data

If you must use flexbox, try the following. If you don't need to specify the width of the items yourself, a good idea is to use flex-grow: 1 instead of width:50%. This resizes it to fit the container.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

1

2

1

2

1

2

1

2

A: This may not be the cleanest one, but at least it works using flexbox!
The styling:
.container {
        display: flex;
        background-color: #f0f0f0;
        width: 340px;
        padding: 3px;
        justify-content: space-between;
    }
    .secondary-container:nth-child(1) {
        color: rgb(165, 165, 165);
    }
    .secondary-container:nth-child(2) {
        color: rgb(0, 0, 0);
        align-self: center;
    }

The HTML code:

User ID:

Email:

Country:

Device ID:

Registered:

Last Updated:

339754133048101

kelly.walkingshaw@gmail.com

Armenia

d16bc5be-02c2-4f82-81

2016-11-03 / 21:26

2020-09-03 / 11:58

Good luck on your project! ~E


text:
Q: How do I give permission for wsgi to operate in my directory? Apache and wsgi now have permissions problems accessing the directory in which my Django project is stored.  I think I need to get back to having wsgi run as user (or maybe just group) kevin.
I had this working, and I don't know what I did to stop it working, but now I get an permissions error as soon as I get past logging into my app.  Unfortunately, I don't have the apache config under version control.  I'm pretty sure that's where the problem is because restoring a backup of the project from when it was working didn't change anything, but tweaking permissions on the database and the root directory of the project has altered the particulars of the error message.  I wasn't going to give o+w to the whole works, nor did I feel like giving an ACL to every single file or directory.
Background: apache 2 as delivered with Ubuntu 16.04 LTS.  Django 1.11.  Python 3.5.  libsqlite3.0 3.11.0
I thought that what I had in the tail of /etc/apache2/apache2.conf took care of this, in particular the line
WSGIProcessGroup kevin

because all the files and directories are owned by kevin.kevin, and my evidence seems to indicate that when it was working, it did so because it was running with at least effective group 'kevin' and not the current 'www-data'.
The whole tail of stuff I added to apache2.conf for this project now looks like this:
# KOSMANOR:
# In accordance with https://www.mindchasers.com/dev/apache-install
WSGIDaemonProcess kevin processes=4 threads=12 python-path=/build/comprosloco
WSGIProcessGroup kevin
WSGIRestrictEmbedded On
WSGILazyInitialization On
WSGIScriptAlias / /build/comprosloco/comprosloco/wsgi.py

<Directory /build/comprosloco/comprosloco>
    Require all granted
</Directory>

# 29 Jan 2018 on  kosmanor.com
# 6 Mar 2018 revised reference to 1.11, but it's so modified as to be unrecognizable.  Not sure what reference was used.
# 6 Mar 2018 In particular the stuff about virtual environments is ignored here.
# WSGIScriptAlias / is set above in accordance with the mindchaser page
# WSGIPythonPath not set (semms to find my stuff without it)
# WSTIPythonHome is not set (not using a vitual environment yet)

# Added in accordance (somewhat modified) with https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/
#
Alias /static/ /usr/local/lib/python3.5/dist-packages/django/contrib/admin/static/
<Directory /usr/local/lib/python3.5/dist-packages/django/contrib/admin/static>
    Require all granted
</Directory>

A: The documentation for WSGIDaemonProcess can be found at:

*

*http://modwsgi.readthedocs.io/en/develop/configuration-directives/WSGIDaemonProcess.html
You possibly can use the user and group options.
Otherwise the directories and files need to at least be readable by the Apache user on your system. If needing to write files, then the Apache user would need write access to the files and in cases like SQLite also the directory so it can create a database lock file.

A: Very helpful comments.  I did get it solved, but the details should probably be stated, as something of the sort could happen to others.

*

*Unless you do something about it, WSGI is run as the user that Apache normally starts child processes.  On my Ubuntu 16.04, that was 'www-data'.  That user does not normally have permissions on the directories I build with my non-privileged user account.

*Django is going to need r and x permissions on all directories, and w permission on the database AND THE DIRECTORY WHERE THE DATABASE RESIDES.  The latter is because it creates its transaction and locking files there.

*If WSGI is failing on account of permissions, the apache error log is your friend.  The normal access log can be helpful too.

*You can make the WSGI child run as some other user with the WSGIDaemonProcess entry in the apache config file (/etc/apache2/apache2.conf on my system).  I added "user=me group=me' to the entry, where 'me' was my account's and group's names.  That gave it all the permissions it needed.


text:
Q: Probability of selecting different kinds of items from a set of items A debating committee of 5 students is to be selected at random by the instructor of a political science class consisting of 14 girls and 16 boys. Determine the probability of the following events:

*

*the committee will consist of all boys

*the committee will consist of $3$ girls $2$ boys

*the committee will consist of $5$ girls.

My answers:

*

*all $5$ boys means $\frac{16}{30} \times \frac{15}{29} \times \frac{14}{28} \times \frac{13}{27} \times \frac{12}{26}$

*the possibilities of having $3 $g and $2 $b are $9$ (gggbb, ggbbg, etc) so $\frac{9}{25}$

*is this the same as 1 but for girls?

A: Your answer to $(1)$ is correct, and you can use the same process for $(3)$: but the numerators change:
For $(3)$, the probability of selecting an "all-girl" committee of five will be:
$$(3)\quad \frac{14}{30} \times \frac{13}{29} \times \frac{12}{28} \times \frac{11}{27} \times \frac{10}{26}$$
For $(2)$, you're off by one: there are $10$ patterns, and the probability of each varies.
You're better off approaching $(2)$ using binomial coefficients: it greatly simplifies the process, and is less prone to error than just brute force analysis.
To use binomial coefficients for $2$, note that there are $\text{(baseline)}\; = \displaystyle \binom {30}{5}$ equally likely ways of choosing a committee of five students from 30. And of those, there are $\displaystyle (\text{3 girls, 2 boys})\;=\;\binom{14}{3} \cdot \binom{16}{2}$ ways of choosing a committee consisting of exactly 3 girls and 2 boys.
Then, the probability of selecting such a committee is equal to $$\frac{\text{3 girls, 2 boys}}{\text{baseline}} = \frac{\binom{14}{3}\binom {16}{2}}{\binom{30}{5}}$$


text:
Q: How to set JCalendar date in JDateChooser I have a JDateChooser that is used for selecting birth dates. It starts out as null date value and let's the user choose the birth date either using the textfield or the jdatechooser button which opens the Jcalendar.
What I'm trying to do is to set the JCalendar's date to -10 years from the current date. By default, the JCalendar is setting the date at the current year. I tried this code but it doesn't work -- it still sets the date to the current date. Any help will do. Thanks!
    dcBirthDateNew = new JDateChooser();
    dcBirthDateNew.setDateFormatString("MM/dd/yyyy");
    dcBirthDateNew.getDateEditor().getUiComponent().addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent evt) {
            if (evt.getSource() instanceof JTextComponent) {
                final JTextComponent textComponent=((JTextComponent)evt.getSource());
                SwingUtilities.invokeLater(new Runnable(){
                    public void run() {
                        textComponent.selectAll();
                    }});
            }
        }
    });
    JCalendar calx = dcBirthDateNew.getJCalendar();
    calx.setCalendar(getPrevDate());

private static Calendar getPrevDate() {
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    Date myDate = new Date(System.currentTimeMillis());
    System.out.println("result is "+ dateFormat.format(myDate));
    Calendar cal = Calendar.getInstance();
    cal.setTime(myDate);
    cal.add(Calendar.YEAR, -10);
    System.out.println(dateFormat.format(cal.getTime()));
    return cal;
}

A: This seems to work correctly.
Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, -10);

JDateChooser chooser = new JDateChooser(c.getTime());
this.add(chooser);

Addendum: The popup editor's date defaults to the value in the JDateChooser; if you set it explicitly, it will become the default value:
JDateChooser chooser = new JDateChooser();
chooser.getDateEditor().setDate(c.getTime());

You can update another, empty text field in a PropertyChangeListener, as shown here; the property name is "date".
Addendum: Looking closer, the JDateChooser implementation of ActionListener handles the default date described above. You can override it, replacing the lines shown below, to create a different default.
JDateChooser chooser = new MyDateChooser();
this.add(chooser);
…
private static class MyDateChooser extends JDateChooser {

    @Override
    public void actionPerformed(ActionEvent e) {
        …
        Date date = dateEditor.getDate();
        if (date == null) {
            Calendar c = Calendar.getInstance();
            c.add(Calendar.YEAR, -10);
            calendar.setTime(c.getTime());
        } else {
            calendar.setTime(date);
        }
        jcalendar.setCalendar(calendar);
        …
    }
}

A: Maybe there is another way of doing this, but this is what I have:
Date date = new Date();
Calendar calendar = Calendar.getInstance();
int subtractYearValue = 10;

int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
int currentDate= Calendar.getInstance().get(Calendar.DATE);

calendar.set(currentYear - subtractYearValue , currentMonth , currentDate);
date.setTime(calendar.getTimeInMillis());

dateChooser.setDate(date);


text:
Q: Where can I find gnome-alsamixer on ubuntu 20.04? I'm preparing new setup for my work with ASUS PRIME H310M-F R2.0 Mainboard. The problem is front audio panel is not working. And I googled people telling try with gnome-alsamixer. But I can't find it on ubuntu 20.04.

A: *

*You can install qasmixer and run it with c option to select soundcard , f.i.:
qasmixer -c 0

*You can also select correct audio device in the view => "show device" box, then save configuration by selecting "from last session" in settings => startup

*Additionnal capture settings by clicking the mic button in the bottom right

A: Install alsamixergui using:
sudo apt install alsamixergui


text:
Q: Python - Trap all signals In python 2.6 under Linux, I can use the following to handle a TERM signal:
import signal
def handleSigTERM():
    shutdown()
signal.signal(signal.SIGTERM, handleSigTERM)

Is there any way to setup a handler for all signals received by the process, other than just setting them up one-at-a-time?

A: As of Python 3.5, the signal constants are defined as an enum, enabling a nicer approach:
import signal

catchable_sigs = set(signal.Signals) - {signal.SIGKILL, signal.SIGSTOP}
for sig in catchable_sigs:
    signal.signal(sig, print)  # Substitute handler of choice for `print`

A: You could just loop through the signals in the signal module and set them up.
for i in [x for x in dir(signal) if x.startswith("SIG")]:
  try:
    signum = getattr(signal,i)
    signal.signal(signum,sighandler)
  except (OSError, RuntimeError) as m: #OSError for Python3, RuntimeError for 2
    print ("Skipping {}".format(i))

A: Works on Windows 10 and Python 3.7:
import signal
import time

def sighandler(signal,frame):
    print("signal",sig,frame)
    return

catchable_sigs = set(signal.Signals)
for sig in catchable_sigs:
    try:
        signal.signal(sig, sighandler)
        print("Setting ",sig)
        print ("value {}".format(sig))
    except (ValueError, OSError, RuntimeError) as m:
        print("Skipping ",sig)
        print ("Value {}".format(sig))

# press some keys or issue kill
x = 0
while x < 5:
    time.sleep(4)
    x += 1

Results:
Skipping  Signals.CTRL_C_EVENT
Value 0
Skipping  Signals.CTRL_BREAK_EVENT
Value 1
Setting  Signals.SIGINT
value 2
Setting  Signals.SIGILL
value 4
Setting  Signals.SIGFPE
value 8
Setting  Signals.SIGSEGV
value 11
Setting  Signals.SIGTERM
value 15
Setting  Signals.SIGBREAK
value 21
Setting  Signals.SIGABRT
value 22

A: If you want to get rid of the try, just ignore signals that cannot be caught.
#!/usr/bin/env python
# https://stackoverflow.com/questions/2148888/python-trap-all-signals
import os
import sys
import time
import signal

SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n) \
    for n in dir(signal) if n.startswith('SIG') and '_' not in n )

def receive_signal(signum, stack):
    if signum in [1,2,3,15]:
        print 'Caught signal %s (%s), exiting.' % (SIGNALS_TO_NAMES_DICT[signum], str(signum))
        sys.exit()
    else:
        print 'Caught signal %s (%s), ignoring.' % (SIGNALS_TO_NAMES_DICT[signum], str(signum))

def main():
    uncatchable = ['SIG_DFL','SIGSTOP','SIGKILL']
    for i in [x for x in dir(signal) if x.startswith("SIG")]:
        if not i in uncatchable:
            signum = getattr(signal,i)
            signal.signal(signum,receive_signal)
    print('My PID: %s' % os.getpid())
    while True:
        time.sleep(1)
main()

A: Here's a 2/3 compatible way which doesn't have as many pitfalls as the others:
from itertools import count
import signal

def set_all_signal_signals(handler):
    """Set all signals to a particular handler."""
    for signalnum in count(1):
        try:
            signal.signal(signalnum, handler)
            print("set {}".format(signalnum))
        except (OSError, RuntimeError):
            # Invalid argument such as signals that can't be blocked
            pass
        except ValueError:
            # Signal out of range
            break

Since signalnum is just a number, iterate over 1 to out of range setting the signal to a particular handle.

A: For Python 3:
for sig in signal.Signals:
    try:
        signal.signal(sig, sighandler)
    except OSError:
        print('Skipping', sig)

A: In Python3.8 we've got a new function signal.valid_signals() https://docs.python.org/3/library/signal.html#signal.valid_signals
import signal
for sig in signal.valid_signals():
    print(f"{sig:2d}",sig)

A: That code won't work in the current version of python. There are many variables starting with SIG with the same value. For instance, SIGHUP and SIG_UNBLOCK are both 1. The only way I could think of to get a list of actual signals was to just make it myself.
from signal import *
signals = {
        SIGABRT: 'SIGABRT',
        SIGALRM: 'SIGALRM',
        SIGBUS: 'SIGBUS',
        SIGCHLD: 'SIGCHLD',
        SIGCONT: 'SIGCONT',
        SIGFPE: 'SIGFPE',
        SIGHUP: 'SIGHUP',
        SIGILL: 'SIGILL',
        SIGINT: 'SIGINT',
        SIGPIPE: 'SIGPIPE',
        SIGPOLL: 'SIGPOLL',
        SIGPROF: 'SIGPROF',
        SIGQUIT: 'SIGQUIT',
        SIGSEGV: 'SIGSEGV',
        SIGSYS: 'SIGSYS',
        SIGTERM: 'SIGTERM',
        SIGTRAP: 'SIGTRAP',
        SIGTSTP: 'SIGTSTP',
        SIGTTIN: 'SIGTTIN',
        SIGTTOU: 'SIGTTOU',
        SIGURG: 'SIGURG',
        SIGUSR1: 'SIGUSR1',
        SIGUSR2: 'SIGUSR2',
        SIGVTALRM: 'SIGVTALRM',
        SIGXCPU: 'SIGXCPU',
        SIGXFSZ: 'SIGXFSZ',
        }

for num in signals:
    signal(num, h)


text:
Q: webpack output - one asset is bigger than the whole? how is it possible that:

*

*lodash.merge is reported by Webpack as having a size of 58.2Kb. the site cost-of-modules is reporting it to be only 11.5kB

*the whole bundle is smaller - 49.6kB
please tell me in comments if more information is needed to understand.
Version: webpack 2.4.1
Time: 2344ms
   Asset     Size  Chunks             Chunk Names
index.js  49.6 kB       0  [emitted]  index
   [0] (webpack)/buildin/global.js 509 bytes {0} [built]
   [2] ./index.js 68 bytes {0} [built]
   [3] ./src/facebook-login.jsx 6.76 kB {0} [built]
   [4] ./src/helpers/helpers.js 1.46 kB {0} [built]
   [5] ./src/spinner.jsx 2.84 kB {0} [built]
   [6] ./src/style/styles.js 688 bytes {0} [built]
   [9] ./~/css-loader!./~/sass-loader/lib/loader.js?{"includePaths":["absolute/path/a","absolute/path/b"]}!./src/style/spinner.scss 236 bytes {0} [built]
   //  <----lodash.merge is 58.2kb ---->
  [15] ./~/lodash.merge/index.js 58.2 kB {0} [built]
  [16] ./~/prop-types/factoryWithThrowingShims.js 1.59 kB {0} [built]
  [17] ./~/prop-types/index.js 1.08 kB {0} [built]
  [18] ./~/prop-types/lib/ReactPropTypesSecret.js 436 bytes {0} [built]
  [19] ./~/style-loader/addStyles.js 8.51 kB {0} [built]
  [21] ./src/style/spinner.scss 1.08 kB {0} [built]
  [22] ./src/style/icon.png 1.59 kB {0} [built]
  [24] multi ./index.js 28 bytes {0} [built]
    + 10 hidden modules

A: I think that website is incorrect:
$ npm i lodash.merge
...

+ lodash.merge@4.6.0
added 1 package in 0.458s

$ ls -al node_modules/lodash.merge
total 72
drwxrwxr-x 6 robert staff   204 Jun 20 16:00 .
drwxrwxr-x 3 robert staff   102 Jun 20 16:00 ..
-rw-r--r-- 1 robert staff  1951 Aug 13  2016 LICENSE
-rw-r--r-- 1 robert staff   446 Aug 13  2016 README.md
-rw-r--r-- 1 robert staff 58183 Aug 13  2016 index.js
-rw-r--r-- 1 robert staff  1804 Jun 20 16:00 package.json

So the size of index.js is pretty much what Webpack says it is.
The reason why your bundle is smaller is probably because you're creating a minified bundle. This reduces the size of index.js significantly:
$ uglifyjs < node_modules/lodash.merge/index.js | wc -c
   21635