text:
Q: Trigger other DAG's and mark the current job as success I am using TriggerDAGRunOperator to trigger other DAG's but the current job is waiting until those DAGs executed. My requirement is that current DAG should be marked as success as soon as it trigger others.
For example below is the job, as soon as the current job triggers three parallel tasks the current job must be marked as "success" as its job is done. Present behavior is the current job is waiting until other triggered DAGs are executed and its status depends on whether others are success/failed.

Here is the current code
t0 = DummyOperator(task_id="start")

bi_triad_eom_validation_process = BashOperator(

)

bi_triad_eom_validation_process_send_email = EmailOperator(
    task_id="bi_triad_eom_validation_process_send_email",
)

trigger_bi_triad_eom_validation_dashboard = TriggerDagRunOperator(
    task_id='trigger_bi_triad_eom_validation_dashboard',
    trigger_dag_id='bi_triad_eom_validation_dashboard',
    wait_for_completion=True
)

trigger_line_item_direct_pacing_variance = TriggerDagRunOperator(
    task_id='trigger_line_item_direct_pacing_variance',
    trigger_dag_id='line_item_direct_pacing_variance'
)

trigger_line_item_axt_pacing_variance = TriggerDagRunOperator(
    task_id='trigger_line_item_axt_pacing_variance',
    trigger_dag_id='line_item_axt_pacing_variance'
)

trigger_bidl_finance_invoice_automation_gate_2 = TriggerDagRunOperator(
    task_id='trigger_bidl_finance_invoice_automation_gate_2',
    trigger_dag_id='bidl_finance_invoice_automation_gate_2'
)

t0  >> bi_triad_eom_validation_process >> bi_triad_eom_validation_process_send_email >> [trigger_bi_triad_eom_validation_dashboard ,trigger_line_item_axt_pacing_variance , trigger_line_item_direct_pacing_variance]

A: It's not immediately marking as success for two reasons:
trigger_bi_triad_eom_validation_dashboard = TriggerDagRunOperator(
    task_id='trigger_bi_triad_eom_validation_dashboard',
    trigger_dag_id='bi_triad_eom_validation_dashboard',
    wait_for_completion=True
)

The wait_for_completion=True will block the current dag until bi_triad_eom_validation_dashboard has completed.
I can see why you've done this because you want to trigger bidl_finance_invoice_automation_gate_2 conditionally, only if bi_triad_eom_validation_dashboard succeeds.
Move
trigger_bidl_finance_invoice_automation_gate_2 = TriggerDagRunOperator(
    task_id='trigger_bidl_finance_invoice_automation_gate_2',
    trigger_dag_id='bidl_finance_invoice_automation_gate_2'
)

Into bi_triad_eom_validation_dashboard. Then remove wait_for_completion=True in
trigger_bi_triad_eom_validation_dashboard = TriggerDagRunOperator(
    task_id='trigger_bi_triad_eom_validation_dashboard',
    trigger_dag_id='bi_triad_eom_validation_dashboard',
    wait_for_completion=True
)

and you will have the behaviour you're after.


text:
Q: Check Boxes, Store in Array and utilize switch statement Thank you in advance to anyone who answers this.
What I need help on:
How to display the number of checkboxes selected by automatically updated them?For example: If I select 1 check box from SECTION A it will display 1 from SECTION A. If I select another box it will display 2 from SECTION A automatically, but it will also subtract the value if the check box is unselected. Kind of like a tally
Again, thank you for helping me and for your time.
    var infoArray=new Array();

function userSelection(userInput)
{
  var itemName = userInput.name;
  var itemName2 = userInput.value;

 switch(itemName)
 {
  case "sectionR":
 {
  switch(itemName2)
 {
  case "repair car":
       infoArray[0]=1;
  break;

  case "wood work":
       infoArray[0]=1;
  break;

  case "explore forest":
       infoArray[0]=1;
  //end of case "sectionR"
 }
  //end of sub switch
 }
  break;

   case "sectionA":
 {
  switch(itemName2)
 {
  case "clothing design":
       infoArray[1]=1;
  break;

  case "public singing":
       infoArray[1]=1;
  break;

  case "decorate":
       infoArray[1]=1;
  //end of sub switch
 }
 // end of case sectionA
 }
 //end of main switch
 }
    var userOutput=new Array();
   for(var i=0; i<itemName.length; i++)
   {
      userOutput.push(itemName[i].checked);
   }

document.getElementById("selectionTotal").innerHTML = "R SECTION" + "&nbsp" + "," + "&nbspA SECTION" + "<br>" +
infoArray;

 //end of userSelection()
}

A: There is a problem in the first two lines of your function:
var userInput = document.getElementsByName('sectionR');
var userOutput = document.getElementsByName('sectionR').value;

First of all, it could be written simpler and more elegant:
var userInput = document.getElementsByName('sectionR');
var userOutput = userInput.value;

But that would still contain the same error. document.getElementsByName("sectionR") returns an array with all elements with the name "sectionR". So you can't get a value from the array. You have to iterate through the elements:
var userOutput = []; // or var userOutput = new Array();
for (var i=0; i < userInput.length; i++) {
    userOutput.push(userInput[i].value);
}

Now you have the values for all elements with the name "sectionR" in your array userOutput and can use them later.
Also a notice on your for-loop. You declare x=0 without the keyword var. This makes the variable x visible in the global scope. It can lead to some unexpected behaviour if your code is longer and you use avariable with the same name somewhere else in your code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What ruby languaje is used by bluepill cookbook I have some doubts about a specific attribute of bluepill cookbook.
default["bluepill"]["bin"] = "#{node['languages']['ruby']['bin_dir']}/bluepill

Where and when is defined this value?
I want to use the bluepill as a system's gem and not as a chef's gem, What values or options I have for this attribute:
default["bluepill"]["bin"] = ?????

A: That value comes from Ohai, which is a tool used by Chef to get the JSON representation of important system information (like where a Ruby lives or what users are present on a system).
That attribute may be changed to any value, but it must point to a Ruby that exists on the system. Note: that attribute does not install Ruby - it just tells Bluepill where to find Ruby.


text:
Q: Installing oracle VM on ubuntu 16.04 Trying to install oracle VM on ubuntu on 16.04 ..It keeps erroring our when start oracle VM:
RTR3InitEx failed with rc=-1912 (rc=-1912)

The VirtualBox kernel modules do not match this version of VirtualBox. The installation of VirtualBox was apparently not successful. Executing

'/sbin/vboxconfig'

may correct this. Make sure that you do not mix the OSE version and the PUEL version of VirtualBox.

where: supR3HardenedMainInitRuntime what: 4 VERR_VM_DRIVER_VERSION_MISMATCH (-1912) - The installed support driver doesn't match the version of the user.

kishore@kishore-ThinkPad-T410:/usr/bin$ dpkg --list virtualbox-*
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                        Version            Architecture       Description
+++-===========================-==================-==================-===========================================================
ii  virtualbox-5.1:i386         5.1.24-117012~Ubun i386               Oracle VM VirtualBox
un  virtualbox-guest-additions- <none>             <none>             (no description available)
un  virtualbox-guest-modules    <none>             <none>             (no description available)
un  virtualbox-ose              <none>             <none>             (no description available)

ishore@kishore-ThinkPad-T410:/usr/bin$ uname -a
Linux kishore-ThinkPad-T410 4.4.0-83-generic #106-Ubuntu SMP Mon Jun 26 17:54:43 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

let me know if you need more information

A: You installed a 32-bit version of VirtualBox. That is wrong for your 64-bit system.
Run
sudo apt purge virtualbox-5.1:i386

and install the 64-bit version using dpkg.


text:
Q: InvalidCastException when retrieving object from sqlite table using Linq2DB I have a problem trying to get records from a Sqlite table using Linq2db+SQLite, here is my table below
CREATE TABLE LogEntry
(
Time DATETIME NOT NULL ON CONFLICT ROLLBACK DEFAULT (CURRENT_TIMESTAMP),
Reference STRING NOT NULL ON CONFLICT ROLLBACK,
Team STRING,
Operator STRING,
ETMachine STRING,
CheckPoint BOOLEAN DEFAULT (0) NOT NULL
);

down is C# code:
using (var db = new DataConnection())
  {
        var newItem = new LogEntry()
        {
          CheckPoint = false,
          ETMachine = "232323", // <= cause
          Operator = "asdasd",
          Reference = "asasas",
          Team = "wewe",
          Time = DateTime.Now
        };

        db.Insert<LogEntry>(newItem);

        foreach (var item in db.LogEntries) //<= error occurs here
        {
          MessageBox.Show(string.Format("{0}:{1}", item.ID, item.Time));
        }
}

and entity
    [Table("LogEntry")]
    public partial class LogEntry
  {
    [Column(Name = "ROWID"), NotNull, PrimaryKey, Identity] public int ID { get; set; } // datetime
    [Column, NotNull    ] public DateTime Time       { get; set; } // datetime
        [Column, NotNull    ] public string   Reference  { get; set; } // string(max)
        [Column,    Nullable] public string   Team       { get; set; } // string(max)
        [Column,    Nullable] public string   Operator   { get; set; } // string(max)
        [Column,    Nullable] public string   ETMachine  { get; set; } // string(max)
        [Column, NotNull    ] public bool     CheckPoint { get; set; } // boolean
    }

I get
'System.InvalidCastException' occurred in System.Data.SQLite.dll
Additional information: Specified cast is not valid.
@ System.Data.SQLite.SQLiteDataReader.VerifyType(Int32 i, DbType typ)
@ System.Data.SQLite.SQLiteDataReader.GetString(Int32 i)
@ lambda_method(Closure , IDataReader )
@ LinqToDB.Expressions.ConvertFromDataReaderExpression.ColumnReader.GetValue(IDataReader dataReader) dans i:\linq2db\Source\Expressions\ConvertFromDataReaderExpression.cs:ligne 128
@ lambda_method(Closure , QueryContext , IDataContext , IDataReader , Expression , Object[] )
@ LinqToDB.Linq.Query`1.<Map>d__6a.MoveNext() dans i:\linq2db\Source\Linq\Query.cs:ligne 1218
@ Peel.FrmMain.Testdb2() dans C:\Users\Administrateur\Documents\Work\Projects\PeeL\src\Peel\FrmMain.cs:ligne 67

I searched a little bit and found out that the issue rises when a string field of the table have numeric values ex. ETMachine property above, although the value is passed as string literal.
Here, if I change the 232323 to 232a323 it will work fine.
My question, How can I force Linq2db to insert the value as string and not numeric?
Or, How can I force the Linq2DB to get values as its appropriate field type?
BTW target framework is 4.0.

A: I finally found the problem, the issue was in column datatype STRING, after I changed it to TEXT it worked fine.
According to SQLite Documentation...

2.1 Determination Of Column Affinity
The affinity of a column is determined by the declared type of the column, according to the following rules in the order shown:

*

*If the declared type contains the string "INT" then it is assigned INTEGER affinity.

*If the declared type of the column contains any of the strings "CHAR", "CLOB", or "TEXT" then that column has TEXT affinity. Notice
  that the type VARCHAR contains the string "CHAR" and is thus assigned
  TEXT affinity.

*If the declared type for a column contains the string "BLOB" or if no type is specified then the column has affinity BLOB.

*If the declared type for a column contains any of the strings "REAL", "FLOA", or "DOUB" then the column has REAL affinity.

*Otherwise, the affinity is NUMERIC. Note that the order of the rules for determining column affinity is important. A column whose
  declared type is "CHARINT" will match both rules 1 and 2 but the first
  rule takes precedence and so the column affinity will be INTEGER.

In my case it's string which does not contain CHAR then the type is NUMERIC.


text:
Q: Find a general solution for this recurrence: $a_n = \sqrt{a_{n-1}a_{n-2}}$ Find a general solution for this recurrence:
$$a_n = \sqrt{a_{n-1}a_{n-2}}$$
when $a_1 = 2$, $a_2 = 8$.

My attempt to solve it:
This recurrence isn't a regular one. In order to solve it,
I have tried to count the first elements in this recurrence, which are $$a_1 = 2, a_2 = 8, a_3 = 4, a_4 = \sqrt{32}, a_5 = \sqrt{512} ...,$$ but I didn't find any way to proceed.
Any help will be very appreciated.

A: Taking logs,
and letting
$b_n = \log a_n$,
this becomes
$b_n
=\frac12(b_{n-1}+b_{n-2})
$.
The characteristic polynomial is
$x^2-\frac12 x-\frac12 = 0$
which has roots
$x
=\dfrac{\frac12\pm\sqrt{\frac14+2}}{2}
=\dfrac{\frac12\pm\sqrt{\frac94}}{2}
=\dfrac{\frac12\pm\frac32}{2}
=\dfrac{2, -1}{2}
=1, -\frac12
$
so the solutions are
$b_n = 1$
and
$b_n = (-1/2)^n
$.
As a check
$\frac12(b_{n-1}+b_{n-2})
=\frac12((-1/2)^{n-1}+(-1/2)^{n-2})
=\frac12(-1/2)^{n-2}(-\frac12+1)
=\frac12(-1/2)^{n-2}(\frac12)
=\frac14(-1/2)^{n-2}
=(-1/2)^{n}
$.
Therefore
$b_n = u+v(-1/2)^{n}$
for any reals $u$ and $v$,
so,
$a_n = rs^{(-1/2)^{n}}$
where $r$ and $s$ are
positive reals
(actually, you can let them be
any types that you can raise to a real power).

A: Hint: By taking the log (with respect to any base) of both sides, we can rewrite the recurrence as
$$
\log(a_n) = \frac 12[\log(a_{n-1}) + \log(a_{n-2})]
$$
So, the sequence $b_n := \log(a_n)$ satisfies a linear recurrence.


text:
Q: Error while building ruby trunk I cloned the trunk branch from my fork of Ruby on GitHub and I am following the directions in the README to build ruby-trunk. Step #2 in the How to compile and install is

If ./configure does not exist or is older than configure.in, run
autoconf to (re)generate configure.

The configure file wasn't there in the repo so I ran autoconf. When I execute the generated configure file, I get an error
build git:(trunk) ../configure
config.guess already exists
config.sub already exists
configure: error: cannot run /bin/bash ../tool/config.sub

I use zsh so I thought that may have something to do with the problem. So I did a clean clone of the repo again and followed the same directions using bash but I still got the same error.
I did google this and all replies to this error said that I have to have ruby already installed to build ruby. But I already have several rubies installed on my system and I'm still getting this error each time. I use rbenv to manage the ruby versions.
Has anyone else faced this problem or does anyone else have any suggestions about what I can do to resolve this?


text:
Q: How to draw an irregular shape with residues connected to the contour? I'm trying to draw on LaTeX some steps of a demonstration of the Residue Theorem, and I wanted to explicitly show what are the contour and the poles that I'm using. Using the Tikz package, I was able to draw the contour and the poles, with the method shown below:
\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{positioning, arrows, decorations.markings, calc}

\begin{document}

\begin{tikzpicture}[>=stealth]
        % axis
        \draw [->](-3.6,-0.4) -- (-3.6,4) node[above]{$\Im(z)$};
        \draw [->](-4,0) -- (3,0) node[right]{$\Re(z)$};

        % irregular shape
        \draw  plot[smooth, tension=.9, very thick] coordinates {(-3.5,2.5) (-3,3.2) (-2.4, 3.3) (-1,3.7) (0,3.4) (2,3.9) (2.5,3.5) (3,2.5) (2.5,0.2) (0,0.7) (-3,0.2) (-3.5,2.5)}[postaction={decorate,
             decoration={markings,
             mark=between positions -3.5 and 3 step 0.25 with {\arrow{<};}}}];

        % poles
        \path[draw, postaction={decorate,
             decoration={markings,
             mark=between positions 0.2 and 1 step 0.33 with {\arrow{<};}}}]
             (-2,1.3)  arc (0:360:0.4) --cycle;
        \path[draw, postaction={decorate,
             decoration={markings,
             mark=between positions 0.2 and 1 step 0.33 with {\arrow{<};}}}]
             (0,2.5)  arc (0:360:0.4) --cycle;
        \path[draw, postaction={decorate,
             decoration={markings,
             mark=between positions 0.2 and 1 step 0.33 with {\arrow{<};}}}]
             (1.9,1.7)  arc (0:360:0.4) --cycle;
\end{tikzpicture}

\end{document}

The only thing left to do is connect the contour with the poles inside it, like that

and I don't know how to do it. At first thought I considered manually trace the lines between the contour and the poles and erase the inner areas between two lines, but it looks like a lot of work for something that can be more simple. Is this the only way to do that or there is a more efficient way?

A: Here is a solution that automates the process with the command \contour:

Each circle must be given a name. For convenience, I also used the \coordinate command for each of the poles. Then you must choose, for each pole, a coordinate outside the main shape. The contours will be drawn parallel to the line from the external point to the corresponding pole.
For example, \contour{e1}{p1}{circle1}; will create the contour around the pole (p1) by intersecting two parallel lines with circle1 and the irregular shape, which I named mainshape.
The distance between the parallel lines is controlled globally by \conw
Four intersection points are calculated (i1) and (i2) form the inward path; (i3) and (i4) form the outward path. First small arcs of mainshape and the circle are "erased" by drawing very thick white lines over them. Note: If your background color isn't white you will need to change this. Then the parallel lines are drawn with arrows.
Note: I changed the mark positions of your irregular shape. They were preventing the code from compiling properly.
Here is the code:
\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{positioning, arrows, decorations.markings, calc, intersections}

\newcommand{\conw}{.05}
\newcommand{\contour}[3]{\coordinate (uu) at ($(#1)!1cm!(#2)-(#1)$); % unit vector from e1 to p1
    \path[name path=line2] let \p0=(uu), \p1=(#1), \p2=(#2) in
        (\x1+\y0*\conw,\y1-\x0*\conw)--(\x2+\y0*\conw,\y2-\x0*\conw);
    \path[name path=line1] let \p0=(uu), \p1=(#1), \p2=(#2) in
        (\x1-\y0*\conw,\y1+\x0*\conw)--(\x2-\y0*\conw,\y2+\x0*\conw);
    \path[name intersections={of=line1 and mainpath, by={i1}},
        name intersections={of=line1 and #3, by={i2}},
        name intersections={of=line2 and #3, by={i3}},
        name intersections={of=line2 and mainpath, by={i4}}];
    \draw[very thick,white](i1)--(i4);
    \draw[very thick,white](i2)--(i3);
    \begin{scope}[decoration={markings, mark=at position 0.5 with {\arrow{>}}}]
    \draw[line cap=round, postaction={decorate}](i1)--(i2);
    \draw[line cap=round, postaction={decorate}](i3)--(i4);
    \end{scope}
    }

\begin{document}

\begin{tikzpicture}[>=stealth]

        % axis
        \draw [->](-3.6,-0.4) -- (-3.6,4) node[above]{$\Im(z)$};
        \draw [->](-4,0) -- (3,0) node[right]{$\Re(z)$};

        % irregular shape
        \draw[name path=mainpath] plot[smooth, tension=.9, very thick] coordinates {(-3.5,2.5) (-3,3.2) (-2.4, 3.3) (-1,3.7) (0,3.4) (2,3.9) (2.5,3.5) (3,2.5) (2.5,0.2) (0,0.7) (-3,0.2) (-3.5,2.5)}[postaction={decorate,
             decoration={markings,
             mark=between positions 0.05 and 1 step 0.25 with {\arrow{<};}}}];

        % poles
        \coordinate(p1) at (-2.4,1.3);
        \coordinate(p2) at (-.4,2.5);
        \coordinate(p3) at (1.5,1.7);
        \path[name path= circle1, draw, postaction={decorate,
             decoration={markings,
             mark=between positions 0.2 and 1 step 0.33 with {\arrow{<};}}}]
             (-2,1.3)  arc (0:360:0.4) --cycle;
        \path[name path= circle2, draw, postaction={decorate,
             decoration={markings,
             mark=between positions 0.2 and 1 step 0.33 with {\arrow{<};}}}]
             (0,2.5)  arc (0:360:0.4) --cycle;
        \path[name path= circle3, draw, postaction={decorate,
             decoration={markings,
             mark=between positions 0.2 and 1 step 0.33 with {\arrow{<};}}}]
             (1.9,1.7)  arc (0:360:0.4) --cycle;

        % contours
        \coordinate(e1) at (-4,3);
        \coordinate(e2) at (-1,4);
        \coordinate(e3) at (1,0);
        \contour{e1}{p1}{circle1};
        \contour{e2}{p2}{circle2};
        \contour{e3}{p3}{circle3};

\end{tikzpicture}

\end{document}


text:
Q: How to override DependencyInjection part of bundle? I am trying to override parts of FOSElasticaExtension https://github.com/FriendsOfSymfony/FOSElasticaBundle to handle configuration and parameters a little differently via bundle inheritance (somewhat described here http://symfony.com/doc/master/cookbook/bundles/override.html). Unfortunately the documentation for this is lacking and I get strange errors (like configuration not getting injected at all) when attempting the override.
vendor/acme/Acme/ElasticaBundle/AcmeElasticaBundle.php
<?php
namespace Acme\ElasticaBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * Extends FOS Elastica bundle.
 */
class AcmeElasticaBundle extends Bundle
{
    public function getParent()
    {
        return 'FOSElasticaBundle';
    }
}

vendor/acme/Acme/ElasticaBundle/DependencyInjection/Configuration.php
<?php
namespace Acme\ElasticaBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

use FOS\ElasticaBundle\DependencyInjection\Configuration as BaseConfiguration;

class Configuration extends BaseConfiguration
{
}

vendor/acme/Acme/ElasticaBundle/DependencyInjection/AcmeElasticaExtension.php
<?php
namespace Acme\ElasticaBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Config\FileLocator;

use FOS\ElasticaBundle\DependencyInjection\FOSElasticaExtension as Extension;

/**
 * Overrides some parts of FOS Elastica extension.
 */
class AcmeElasticaExtension extends Extension
{
}

app/AppKernel.php
<?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new FOS\ElasticaBundle\FOSElasticaBundle(),
            new Acme\ElasticaBundle\PhoenixElasticaBundle(),
        );
    }
}

Error:
ErrorException: Notice: Undefined index: indexes in /home/tatsh/test-site/vendor/friendsofsymfony/elastica-bundle/FOS/ElasticaBundle/DependencyInjection/Configuration.php line 367

That is this line: https://github.com/FriendsOfSymfony/FOSElasticaBundle/blob/master/DependencyInjection/Configuration.php#L367
I have not changed my configuration so I am not sure what could be the cause. I would think that their code that validates configuration is running fine and retrieving the values but the MergeExtensionConfigurationPass seems to not going properly with this:
in /home/tatsh/test-site/vendor/friendsofsymfony/elastica-bundle/FOS/ElasticaBundle/DependencyInjection/Configuration.php line 367
at ErrorHandler->handle('8', 'Undefined index: indexes', '/home/tatsh/test-site/vendor/friendsofsymfony/elastica-bundle/FOS/ElasticaBundle/DependencyInjection/Configuration.php', '367', array('nestings' => array())) in /home/tatsh/test-site/vendor/friendsofsymfony/elastica-bundle/FOS/ElasticaBundle/DependencyInjection/Configuration.php line 367
at Configuration->getNestings() in /home/tatsh/test-site/vendor/friendsofsymfony/elastica-bundle/FOS/ElasticaBundle/DependencyInjection/Configuration.php line 283
at Configuration->getMappingsNode() in /home/tatsh/test-site/vendor/friendsofsymfony/elastica-bundle/FOS/ElasticaBundle/DependencyInjection/Configuration.php line 265
at Configuration->getTypesNode() in /home/tatsh/test-site/vendor/friendsofsymfony/elastica-bundle/FOS/ElasticaBundle/DependencyInjection/Configuration.php line 188
at Configuration->addIndexesSection(object(ArrayNodeDefinition)) in /home/tatsh/test-site/vendor/friendsofsymfony/elastica-bundle/FOS/ElasticaBundle/DependencyInjection/Configuration.php line 30
at Configuration->getConfigTreeBuilder() in /home/tatsh/test-site/vendor/symfony/symfony/src/Symfony/Component/Config/Definition/Processor.php line 52
at Processor->processConfiguration(object(Configuration), array(array())) in /home/tatsh/test-site/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/DependencyInjection/Extension.php line 103
at Extension->processConfiguration(object(Configuration), array(array())) in /home/tatsh/test-site/vendor/friendsofsymfony/elastica-bundle/FOS/ElasticaBundle/DependencyInjection/FOSElasticaExtension.php line 23
at FOSElasticaExtension->load(array(array()), object(ContainerBuilder)) in /home/tatsh/test-site/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Compiler/MergeExtensionConfigurationPass.php line 42
at MergeExtensionConfigurationPass->process(object(ContainerBuilder)) in /home/tatsh/test-site/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/DependencyInjection/MergeExtensionConfigurationPass.php line 39
at MergeExtensionConfigurationPass->process(object(ContainerBuilder)) in /home/tatsh/test-site/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php line 119
at Compiler->compile(object(ContainerBuilder)) in /home/tatsh/test-site/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/ContainerBuilder.php line 453
at ContainerBuilder->compile() in /home/tatsh/test-site/app/bootstrap.php.cache line 950
at Kernel->buildContainer() in /home/tatsh/test-site/app/bootstrap.php.cache line 859
at Kernel->initializeContainer() in /home/tatsh/test-site/app/bootstrap.php.cache line 571
at Kernel->boot() in /home/tatsh/test-site/app/bootstrap.php.cache line 614
at Kernel->handle(object(Request)) in /home/tatsh/test-site/web/app_dev.php line 28

A: Easy way to fix: Implement the load() method even if stub. Do not call the parent load() method.
<?php
/**
 * Overrides some parts of FOS Elastica extension.
 */
class AcmeElasticaExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
    }
}


text:
Q: IronPython Method Overloading I have some IronPython code that is creating a Mutex using the following constructor:

public Mutex(
    bool initiallyOwned,
    string name,
    out bool createdNew
)

Since the last parameter is an out parameter you do not pass it to the method and instead it becomes an extra return value like this:
mutex, sucess = Mutex(True, 'some_mutex')

When this code runs it throws a TypeError saying that the Mutex object is not iterable. Since it is only returning one value this leads me to believe that IronPython is not choosing the correct overload. The Ironpython documentation says that you can control the exact overload that gets called by using the Overloads method on method objects.
The following bit of code attempts that, however, I get a ValueError stating that the index was out of range:
new_mutex = Mutex.__new__.Overloads[type(True), String, type(True)]
mutex, sucess = new_mutex(Mutex, True, 'some_mutex')

If I try using the Overloads attribute to force using a different overload it executes correctly. Anyone know where I'm going wrong?

A: You could explicitly pass the out bool to the constructor like this:
success = clr.Reference[bool]()
mutex = Mutex(True, 'some_mutex', success)

# success.Value is your bool result

That lets the overload resolution stuff just do its thing.
I'm not quite sure how to extract the right method from __new__.Overloads, but there has to be a way. If I just say Mutex.__new__.Overloads, it shows me a list that includes the overload that you're looking for.


text:
Q: How to bind event to hide menu I have created a small plugin to show a dropdown menu when a div is clicked.
Below is the code to get it to work
$('#clickable_div').click(function() {
    $('#nav_menu').showMenu({
        parent:'#clickable_div'
    });
});

Jsfiddle with the plugin : http://jsfiddle.net/HtNK3/
So now basically i want to add a functionality where i need to hide the dropdown div when user clicks anywhere
in the document but not on the dropdown div which is open
How can this be achieved ?

A: I am using something like this:
//Close popup menus by clicking anywhere
$("body").mouseup(function(event){
        if (!$(event.target).hasClass("YOUR_CLASS_HERE")) {
        $("#nav_menu").hide();
    }
});

A: I would use setTimout when the mouse leaves the dropdown (mouseleaveevent) and then hide the div. Pretty common and easy.
Buggy but basic example:
http://jsfiddle.net/HtNK3/5/


text:
Q: Is there any way to redirect stdout to a parquet file on bash? I want to generate a parquet file for later processing with Spark. This parquet consists in a list of all nested files (json or xml) within a certain root folder together with their corresponding timestamps and paths, and excluding some folders from search.
So far I was generating it with the following python script:
import subprocess
from io import StringIO

import pandas as pd

PATH = input("Enter path: ") or "."

proc = subprocess.Popen(
    'find %(path)s \( -path "%(path)s/venv/*" -o -path "%(path)s/_forms/*" -o -path "%(path)s/failed/*" -o -path "%(path)s/logs/*" -o -path "%(path)s/OLD/*" \) -prune -o \( -type f -name *.xml -o -name *.json \) -exec du --time {} +'
    % {"path": PATH},
    shell=True,
    stdout=subprocess.PIPE,
)
buff = StringIO(proc.communicate()[0].decode())

df = pd.read_csv(buff, sep="\t", header=None, names=["size", "timestamp", "path"])
df.to_parquet("paths.parquet")

The problem with this approach is that, when output is very big, process eventually is killed (I suppose due to OOM issues when buffering), so I've decided to move it to a pure bash script. It is something like:
cat <(echo -e 'size\ttimestamp\tpath') <(find . \( -path "./venv/*" -o -path "./_forms/*" -o -path "./failed/*" -o -path "./logs/*" -o -path "./OLD/*" \) -prune -o \( -type f -name *.xml -o -name *.json \) -exec du --time {} +)

But this way how can I construct a valid parquet compressed file as in python-pandas approach? Can I just redirect it to > paths.parquet or an external package is needed for that?


text:
Q: How to close file in C that is already opened I am write application to read DICOM file and I must using other library to do it. I find that the library will open file but it don't close file when finishing. And the library is not open source. I know that open file limiting is 1024 in Linux and I can change the number. But I don't want to do the way. I like to close the file that is opened by library. How to close file in C if I know it is opening. I am using DICOM2NII library that is got from http://cbi.nyu.edu/software/dinifti.php.
And this is the code to open file but it does not close
bool DICOMImage::OpenFile(const char *path)
{
    bool retValue = true;
    DCM_Objects handle_;
    unsigned long options = DCM_ORDERLITTLEENDIAN | DCM_FORMATCONVERSION | DCM_VRMASK;
    // Try opening as PART10, if it fails it's might be bcause it does not have
    // a preable and the try it that way
    if ( DCM_OpenFile(path, options | DCM_PART10FILE, &handle_) != DCM_NORMAL )
    {
        DCM_CloseObject(&handle_);
        COND_PopCondition(TRUE);
        if ( DCM_OpenFile(path, options, &handle_) != DCM_NORMAL )
        {
          retValue = false;
        }
        else
          retValue=true;
    }

    return retValue;
}

A: In your DICOMImage class, add a member
DCM_OBJECT *handle_;

and in your destructor close the file
DICOMImage::DICOMImage() : handle_(0) { ... }

DICOMImage::~DICOMImage() {
    if (handle_ != 0)
        DCM_CloseObject(&handle_);
}

and use this member handle_ in DICOMImage::OpenFile() as well, of course.

A: You could first test all file descriptors to see which ones are in use by doing a dummy fcntl(fd, F_GETFD) on every fd from 0 up to getdtablesize().  When the library function returns there will be one more open fd which you can just close with close().  You could also just call close(fd) on everything that wasn't open before and one of those will succeed (and you can stop at that point in your search).
It's likely you can do the initial probe up to the first unused fd and the library will end up using that fd provided it doesn't do anything more complex than open one file.  If it opens multiple files or uses dup() it could end up elsewhere.
To spell this out:
#include <iostream>
#include <vector>
#include <unistd.h>
#include <fcntl.h>

std::vector<bool> getOpenFileMap()
{
    int limit = getdtablesize();
    std::vector<bool> result(limit);

    for (int fd = 0; fd < limit; ++fd)
        result[fd] = fcntl(fd, F_GETFD) != -1;
    return result;
}

void closeOpenedFiles(const std::vector<bool> &existing)
{
    int limit = existing.size();
    for (int fd = 0; fd < limit; ++fd)
        if (!existing[fd])
            close(fd);
}

int getLikelyFd()
{
    int limit = getdtablesize();

    for (int fd = 0; fd < limit; ++fd)
        if (fcntl(fd, F_GETFD) != -1)
            return fd;
}

int main()
{
    std::vector<bool> existing = getOpenFileMap();
    int fd = open("/dev/null", O_RDONLY);
    closeOpenedFiles(existing);
    bool closed = write(fd, "test", 4) == -1;
    std::cout << "complex pass " << std::boolalpha << closed << std::endl;

    int guess = getLikelyFd();
    fd = open("/dev/null", O_RDONLY);
    bool match = fd == guess;
    std::cout << "simple pass " << std::boolalpha << match << std::endl;
}


text:
Q: Ao seleciona CheckBox desaparecer linha Salve amigos!
Estou tentando criar um site web onde tenha várias funções e caminhos diferentes para um usuário usufruir. Porem vejo que no futuro pode acabar tendo muito mais conteúdo do que desejo mostrar ao usuário.
O que estou tentando criar agora é o seguinte, fazer com que ao selecionar um Checkbox uma determinada linha desapareça para visualização, no caso que ela fique oculta. estou usando a seguinte logica

Sobre mim

Relatorios

Locação

Estoque

<input type="checkbox" id="sobremim" > Sobre mim
 <input type="button" onclick="Sobremim()" value="Enviar">

E para manter o Checkbox selecionando mesmo apos sair da pagina, uso a seguinte logica.

Porem a mesma não desaparece, gostaria de descobrir o que ah de errado na minha logica.

A: Dentro da função Sobremim você tá usando jQuery certo?
Se sim, então está faltando o $ antes do parênteses e, pelo que eu saiba, o jQuery não tem o método display. Uma alternativa é usar os métodos hide e show:
function Sobremim(){
    if(document.getElementById('sobremim').checked){
        $("#sobremim2").hide();
    } else {
        $("#sobremim2").show();
    }
}

E se quiser utilizar JavaScript puro:
function Sobremim(){
    if(document.getElementById('sobremim').checked){
        document.getElementById('sobremim2').style.display = 'none';
    } else {
        document.getElementById('sobremim2').style.display = 'list-item';
    }
}

Repare que utilizei list-item como display, porque é o padrão do
.
Além disso, um outro jeito de persistir os estados dos checkboxes é usar um objeto JSON e converter para string antes de salvar no localStorage e vice-versa na hora de recuperá-lo:
document.addEventListener("DOMContentLoaded", function(){
    // Recupera estado dos checkbox do localStorage ou, se não tiver, cria objeto vazio
    var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {};

    var checkbox = $("input[type='checkbox']");

    checkbox.on("change", function(e) {
        // Altera estado do checkbox na lista
        checkboxValues[e.target.id] = e.target.checked;
        // Atualiza estado dos checkboxes no localStorage
        localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
    });

    $.each(checkboxValues, function(key, value) {
      $("#" + key).prop('checked', value);
    });
});


text:
Q: Check how many parameters block being passed has, and then invoke yield with different parameters I want to know if something like this is possible, as hash.each does two different things based on arguments passed to block
{ "a"=>3, "b"=>2}.each {|k| puts k}

{ "a"=>3, "b"=>2}.each {|k,v| puts k}

Both output different things, and not just what's below..
a
b
..
a
b

I get this
a
3
b
2
..
a
b

So I want to know if there is a way to get my function to do something custom depending on the number of arguments of block being passed to it.
like this
def my_method
   if yield.args==2
     yield("hi","bro")
   else
     yield("what's up")
   end
end

my_method {|a,b| puts a; puts b;} #"hi" "bro"

my_method {|a| puts a; } #"whats up"

A: def my_method(&block)
  if block.arity == 2
    yield("hi", "bro")
  else
    yield("what's up")
  end
end

Also look at the documentation since Proc#arity has special behavior for default/named arguments, etc.

A: You can capture the block as a Proc and then inspect its parameters:
def my_method(&blk)
  blk.parameters
end

my_method {|a|}
# => [[:opt, :a]]

my_method {|a, b|}
# => [[:opt, :a], [:opt, :b]]

Note, however, that this is not what happens with Hash#each. Hash#each just follows the Enumerable#each protocol and always yields one single item to the block, which is a two-element Array of key and value. Normal block parameter binding then takes care of the rest:
def my_method
  yield ['Hello', 'World']
end

my_method {|a| p a }
# ["Hello", "World"]

my_method {|a, b| p a, b }
# "Hello"
# "World"

my_method {|a, b, c| p a, b, c }
# "Hello"
# "World"
# nil


text:
Q: How can I delete event from calendar on android >= 8? I tried quite a few things, read a lot of SO posts about it but can't seem to.
I want to delete all the events.
Here is how I insert my calendar events:
                ContentResolver cr = Objects.requireNonNull(myContext.getContentResolver());
            ContentValues values = new ContentValues();
            values.put(CalendarContract.Events.DTSTART, myEventCalendar.getStartEvent());
            values.put(CalendarContract.Events.DTEND, myEventCalendar.getEndEvent());
            values.put(CalendarContract.Events.TITLE, myEventCalendar.getTitle());
            values.put(CalendarContract.Events.DESCRIPTION, myEventCalendar.getDescription());
            values.put(CalendarContract.Events.CALENDAR_ID, 1);
            values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
            Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);

This method works great, but I can't seem to remove the events afterwards.
Here is my code:
    @RequiresApi(api = Build.VERSION_CODES.O)
public void deleteEventCalendar(Context myContext) {
    Uri deleteUri = null;
    Cursor cursor = myContext.getContentResolver().query(CalendarContract.Calendars.CONTENT_URI, null, null, null, null);
    while (cursor.moveToNext()) {
        long id = cursor.getLong(cursor.getColumnIndexOrThrow(CalendarContract.Events._ID));
        deleteUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, id);
        myContext.getContentResolver().delete(deleteUri, null, null);
    }
    cursor.close();
}

}
I feel like I'm not that far but it's still impossible.
Please help me.

A: The answer was in front of me from the start...
I was calling CalendarContract.Calendar and not CalendarContract.Event.
I was able to test this on different devices and everything works.
public void deleteEventCalendar(Context myContext) {
    Uri deleteUri = null;
    Cursor cursor = myContext.getContentResolver().query(CalendarContract.Events.CONTENT_URI, null, null, null, null);
    while (cursor.moveToNext()) {
        long id = cursor.getLong(cursor.getColumnIndexOrThrow(CalendarContract.Events._ID));
        deleteUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, id);
        Log.i("id calendar","mon id"+id);
        myContext.getContentResolver().delete(deleteUri, null, null);
    }
    cursor.close();
}


text:
Q: The Wordpress way URL on static / dynamic pages I would like to add a menu or footer like in Wordpress or any other CMS.
That really dont work with PHP includes because if a website file is in subdirectory there is a problem with the path.
As you know a normal static menu looks like

About

but CMS menu looks like

About

And that on all pages so no problems with the path
if you try it with static/dynamic pages you have to add the path or the url and that looks really ugly or not
<?php
define('WEB_ROOT', '../');  // relative path to /
?>
...

Solution

       or

Solution

       or

<a href="<?php echo WEB_ROOT; ?>solution">Solution

I think thats a bad idea and really ugly.
so how to solve that kind of problem maybe with adding a web root in php like above but looks not really good so do you have any other ideas?
And that Solution should also work for CSS and JS not only for static contents, so all styles are same and menus looks just like the other pages even if it is in the subdirectories

A: Generally in Wordpress I use the site url to generate full urls:
site_url('/about');
As for JS/CSS files, it depends where you are putting them. If the files are located in a specific theme use:
get_template_directory();

A: you can use it...in "a" tag href="", use this:
echo home_url('index.php/about');
or remove the index.php, just about [the name of the page.]
Done.


text:
Q: Accessing a map's value which is a vector pair C++ I have a map declared by
map <string, vector<pair<int, string>>>;

As I iterate through the map I want to access the data in the vector to print out and do operations on, I've been trying to use myMap.at(string1).first to access the integer associated with the key string1, but I keep getting type errors. Could someone explain the best way to access the data in this vector pair from its key?

A: Given:
map <string, vector<pair<int, string>>> myMap;

the:
myMap.at(string1).first

obviously should not compile. myMap.at(), if successfully matched with an associated value, will give you a vector. You are trying to use .first on that vector. vectors do not have .first and such members. Maybe you instead want:
map <string, pair<int, string>> myMap;

If you are sure that you want your original data type, accessing the first pair associated with string1 would be:
myMap.at(string1).at(0).first

This will fetch a vector<pair<int, string>> associated with string1 and give you the first element in the first pair of that vector.


text:
Q: Saving NSTextViewData to RTF doc Trying to export NSTextView data to an RTF doc. My old code, mainly "filename" from NSSavePanel is depreciated. The docs state "use URL". How can I do this?
Thanks.
NSSavePanel *panel = [NSSavePanel savePanel];

[panel setAllowedFileTypes:[NSArray arrayWithObject:@"rtf"]];
if ([panel runModal] == NSOKButton){

[[textView RTFFromRange:
      NSMakeRange(0, [[textView string] length])]
     writeToFile:[panel filename] atomically:YES];

}

A: As the doc says, you should use the URL method of NSSavePanel.
The code will look the same, but you'll use the NSString writeToURL:atomically:encoding:error: method instead :
NSSavePanel *panel = [NSSavePanel savePanel];

[panel setAllowedFileTypes:[NSArray arrayWithObject:@"rtf"]];
if ([panel runModal] == NSOKButton){
    [[textView RTFFromRange:NSMakeRange(0, [[textView string] length])] writeToURL:[panel URL] atomically:YES encoding:NSUTF8StringEncoding error:NULL];
}

Note the two parameters to specify an encoding (here I set UTF-8), and an error object. I give NULL here, but you would perhaps give a valid object to get error information.


text:
Q: Injector error when trying to establish routing I'm testing the Angular framework, and my last tests are being based on the routing thingy.
I was making an example in which I have the typical project setup: source folder with index.html, which has this:
<!DOCTYPE HTML>

      <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
      <link rel="stylesheet" type="text/css" href="css/styles.css">

And then, the folders js (with controllers, directives, module definition...), css, and plugins (where I have the angular.js and angular-route.jos).
This is what I have in my module definition at js/app.js:
var app = angular.module('test', ['ngRoute', 'controllers', 'directives', 'services']);

app.config(['$routeProvider',function($routeProvider) {
    $routeProvider.
    when('/index', {
        templateUrl: 'templates/main.html',
        controller: 'mainCtrl'
    }).
    otherwise({
        redirectTo: '/index'
    });

}]);

It should work when inputting localhost/testSite/index, retrieving me to this template:

Test siteFor test purposes

    Test, test, test!

... shouldn't it? Well, it doesn't.
I'm having this error each time I access my index.html:
Error: [$injector:modulerr] http://errors.angularjs.org/1.5.0-rc.1/$injector/modulerr?p0=test&p1=%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.5.0-rc.1%2F%24injector%2Fmodulerr%3Fp0%3Ddirectives%26p1%3D%255B%2524injector%253Anomod%255D%2520http%253A%252F%252Ferrors.angularjs.org%252F1.5.0-rc.1%252F%2524injector%252Fnomod%253Fp0%253Ddirectives%250AP%252F%253C%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A6%253A421%250Afe%252F%253C%252F%253C%252F%253C%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A25%253A136%250Ab%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A24%253A188%250Afe%252F%253C%252F%253C%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A24%253A1%250Ag%252F%253C%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A39%253A201%250An%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A7%253A364%250Ag%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A39%253A49%250Ag%252F%253C%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A39%253A218%250An%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A7%253A364%250Ag%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A39%253A49%250Agb%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A43%253A53%250Azc%252Fc%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A20%253A421%250Azc%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A21%253A225%250Aae%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A20%253A41%250A%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A304%253A355%250Ab%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A181%253A440%250AMf%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A36%253A391%250ALf%252Fd%2540http%253A%252F%252Flocalhost%252FtestSite%252Fplugins%252Fangular.js%253A36%253A340%250A%0AP%2F%3C%40http%3A%2F%2Flocalhost%2FtestSite%2Fplugins%2Fangular.js%3A6%3A421%0Ag%2F%3C%40http%3A%2F%2Flocalhost%2FtestSite%2Fplugins%2Fangular.js%3A39%3A475%0An%40http%3A%2F%2Flocalhost%2FtestSite%2Fplugins%2Fangular.js%3A7%3A364%0Ag%40http%3A%2F%2Flocalhost%2FtestSite%2Fplugins%2Fangular.js%3A39%3A49%0Ag%2F%3C%40http%3A%2F%2Flocalhost%2FtestSite%2Fplugins%2Fangular.js%3A39%3A218%0An%40http%3A%2F%2Flocalhost%2FtestSite%2Fplugins%2Fangular.js%3A7%3A364%0Ag%40http%3A%2F%2Flocalhost%2FtestSite%2Fplugins%2Fangular.js%3A39%3A49%0Agb%40http%3A%2F%2Flocalhost%2FtestSite%2Fplugins%2Fangular.js%3A43%3A53%0Azc%2Fc%40http%3A%2F%2Flocalhost%2FtestSite%2Fplugins%2Fangular.js%3A20%3A421%0Azc%40http%3A%2F%2Flocalhost%2FtestSite%2Fplugins%2Fangular.js%3A21%3A225%0Aae%40http%3A%2F%2Flocalhost%2FtestSite%2Fplugins%2Fangular.js%3A20%3A41%0A%40http%3A%2F%2Flocalhost%2FtestSite%2Fplugins%2Fangular.js%3A304%3A355%0Ab%40http%3A%2F%2Flocalhost%2FtestSite%2Fplugins%2Fangular.js%3A181%3A440%0AMf%40http%3A%2F%2Flocalhost%2FtestSite%2Fplugins%2Fangular.js%3A36%3A391%0ALf%2Fd%40http%3A%2F%2Flocalhost%2FtestSite%2Fplugins%2Fangular.js%3A36%3A340%0A
What may be causing this?

A: This errors messages are really annoying to read but here is the transalation : no mod 'directives' for module 'test' :
Error: [$injector:modulerr] http://errors.angularjs.org/1.5.0-rc.1/$injector/modulerr?p0=test&p1=%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.5.0-rc.1%2F%24injector%2Fmodulerr%3Fp0%3Ddirectives%26p1%3D%255B%2524injector%253Anomod%255D%2520http%253A%252F%252Ferrors.angularjs.org%252F1.5.0-rc.1%252F%2524injector%252Fnomod%253Fp0%253Ddirectives
SO check your declaration of your module directives.


text:
Q: Is it possible to have Mutiple Bootstrapper classes in Prism? I am new to Prism.
In my WPF(Uses Prism and Unity) project, I wanted to have 2 startup projects. If ProjectOne is selected as startup project, I wanted to load ModuleA, ModuleB and ModuleC. But if ProjectTwo is selected as startup project, I wanted to load ModuleA, ModuleB, ModuleX and ModuleY.
Both Startup projects has its own ResourceDirectory to apply style and themes.
Can I use different Bootstrapper classes for different projects? If ProjectOne is selected as startup project, BootstrapperOne is called(from ProjectOne's App.xaml.cs's OnStartup) and If ProjectTwo is selected as startup project, BootstrapperTwo get invoked from ProjectTwo's App.xaml.cs's OnStartup.


text:
Q: Why does disassembly show me push/pop to same register? I have disassembled a C file.
At the start of what used to be a function I see
endbr64
push     %rax
pop      %rax

as the first instructions.
Why is the content of %rax pushed and then popped without any changes to the stack or the register in between? I would expect %rax to be unchanged by that operation.

A: Apparently, it is due to the "-fstack-clash-protection" flag in GCC (see godbolt.org/z/Pvd1ox9d3). It is removed, however, if the call to exit() is removed.
In case the link goes down: The following code is compiled there with x86-64 gcc 12.2 using the flags
"-fstack-clash-protection -O1":
#include <stdio.h>
#include <stdlib.h>

void fun(void) {
    printf("hello\n");

    exit(EXIT_SUCCESS);
}


text:
Q: My pygame isn't working but everything seems fine Everything seems fine but my computer found that i have invalid syntax and it marks colon(:).
code:
if keys[pygame.K_RIGHT] and man.x < 500 - man.width: # <- here he marks this colon
        man.x = man.x + man.vel
        man.right = True
        man.left = False
        man.standing = False

Full code:
import pygame
pygame.init()

cl = pygame.time.Clock()

lefty = [pygame.image.load('Game/L1.png'),pygame.image.load('Game/L2.png'),pygame.image.load('Game/L3.png'),pygame.image.load('Game/L4.png'),pygame.image.load('Game\L5.png'),pygame.image.load('Game/L6.png'),pygame.image.load('Game/L7.png'),pygame.image.load('Game/L8.png'),pygame.image.load('Game/L9.png')]
righty = [pygame.image.load('Game/R1.png'),pygame.image.load('Game/R2.png'),pygame.image.load('Game/R3.png'),pygame.image.load('Game/R4.png'),pygame.image.load('Game/R5.png'),pygame.image.load('Game/R6.png'),pygame.image.load('Game/R7.png'),pygame.image.load('Game/R8.png'),pygame.image.load('Game/R9.png')]
gr = pygame.image.load('Game/bg.jpg')
st = pygame.image.load('Game/standing.png')

win = pygame.display.set_mode((500,480))
name = pygame.display.set_caption("photo game")

class player(object):
    def __init__(self, x, y, width, height):
        self.jumpCount = 10
        self.jump=False
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 5
        self.left = False
        self.right = False
        self.walkCount= 0
        self.standing = True

    def draw(self,win):
        if self.walkCount+1>=27:
            self.walkCount=0
        if not(self.standing):
            if self.left:
                win.blit(lefty[self.walkCount//3],(self.x,self.y))
                self.walkCount +=1
            elif self.right:
                win.blit(righty[self.walkCount//3],(self.x,self.y))
                self.walkCount +=1
        else:
            if self.right:
                win.blit(righty[0], (self.x, self.y))
            else:
                win.blit(lefty[0], (self.x, self.y))

class projectiles(object):
    def __init__(self,x,y,radius,color,facing):
        self.x = x
        self.y = y
        self.radius = radius
        self.color = color
        self.facing = facing
        self.vel = 8 * facing

    def draw(win, self):
        pygame.draw.radius(win, self.color, (self.x, self.y), self.radius, self.facing)

def redrawchar():
    win.blit(gr,(0,0))
    man.draw(win)
    for bullet in bullets:
        bullet.draw(win)
    pygame.display.update()

man = player(50, 420, 62, 62)
while True:
    cl.tick(27)
    bullets = []

    for events in pygame.event.get():
        if events.type == pygame.QUIT:
            break

    for bullet in bullets:
        if bullet.x < 500 and bullet.x > 0:bullet.x += bullet.vel
        else: bullets.pop(bullets.index(bullet))

    for events in pygame.event.get():
        if events.type == pygame.QUIT:
            break

    keys = pygame.key.get_pressed()
    if keys[pygame.K_c]:
        if man.right:
            facing=1
        else:
            facing = -1
        if len(bullets) < 5:
            bullets.append(projectiles((round(man.x + man.weight //2)), (round(man.y + man.height //2)), 6, (0,0,0), facing)

    if keys[pygame.K_RIGHT] and man.x < 500 - man.width: #here is that error
        man.x = man.x + man.vel
        man.right = True
        man.left = False
        man.standing = False

    elif keys[pygame.K_LEFT] and man.x > man.vel-5-5:
        man.x-=man.vel
        man.left = True
        man.right = False
        man.standing = False

    else:
        man.standing = True
        man.walkCount=0
    if not(man.jump):
        if keys[pygame.K_SPACE]:
            man.jump = True
            man.right = False
            man.left = False
            man.walkCount=0
    else:
        if man.jumpCount>=-10:
            man.y -= (man.jumpCount*abs(man.jumpCount)) *0.5
            man.jumpCount -=1
        else:
            man.jumpCount = 10
            man.jump = False

    redrawchar()
pygame.quit()

I tryed to put 500 - man.width in brackets like (500 - man.width): but it's not working.
Can someone please help.
I am working in py 3.7 and everything is ok and seems to be right. However why does my computer not like that colon(:) for some reason?
Does anyone have any ideas why?

A: The syntax error is not caused by the line:

if keys[pygame.K_RIGHT] and man.x < 500 - man.width:

This  line is syntactically correct. It is the line before that line, which causes the error:

if len(bullets) < 5:
   bullets.append(projectiles((round(man.x + man.weight //2)), (round(man.y + man.height //2)), 6, (0,0,0), facing)

At the end of the call to bullets.append is missing the closing bracket ). This causes the syntax error in the next line, because the subsequent tokens are unexpected.


text:
Q: SQL Server : error converting data type varchar to numeric unless I use REPLACE I have a database that is using varchar(255) as a placeholder for storing many different data types. I am trying to do convert some of these values to decimal for a numerical comparison.
If I try to use the following function it will result in the error in the title
ISNUMERIC(Value + 'e0') = 1 and CONVERT(decimal (16,4), Value) < CONVERT(decimal (16,4),11)

I thought this was strange so I moved the CONVERT into the select statement to see if there were still some values the ISNUMERIC wasn't catching. There were not. The CONVERT above was able to successfully convert every single column with no errors.
select CONVERT(decimal (16,4), Value)

Next I tried wrapping the select in another select and moving the comparison to an outer query.  That didn't work either and also resulted in a lot of memory usage so I scrapped that idea.
One of my co-workers thought maybe there was one row of data that was causing an issue and even though the CONVERT on the select worked fine it was worth trying just to see.  We tried a REPLACE inside the CONVERT, as below:
ISNUMERIC(Value + 'e0') = 1 and CONVERT(decimal (16,4),REPLACE(Value, 'blah', '')) < CONVERT(decimal (16,4), 11)

...and somehow this worked. No matter what we type in the replace it works just fine. It clearly isn't replacing anything. I read that REPLACE will truncate very large data (8,000+ bytes) but this is a varchar(255) and so there isn't any large data in there to truncate.
I'm mostly curious as to why this works or if there is something else likely going on here and the REPLACE coincidentally worked? It doesn't make any sense to me.
Edit: Just to be clear, I am stuck with this database design. I cannot change it. I realize this is a terrible way to store data. Trust me.
Edit #2: I just found out that TRY_CONVERT will also work. My original question still stands I think. Even though I have two potential solutions I don't understand why it breaks.

A: Presumably, your expression is in the where clause:
where ISNUMERIC(Value + 'e0') = 1 and CONVERT(decimal (16,4), Value) < CONVERT(decimal (16,4),11)

SQL Server does not guarantee the order of valuation of expressions.  So, you don't know if the convert() is going first or the isnumeric().  For such an expression in the where clause, all databases reserve the right to evaluate them in any order the optimization engine wants.
This is one case where using case in the where clause is beneficial.  case does have some guarantees on the order of valuation.  The following should work:
where (case when ISNUMERIC(Value + 'e0') = 1
            then CONVERT(decimal(16,4), Value)
       end) < CONVERT(decimal(16,4), 11)

The second convert is unnecessary clutter, in my opinion:
where (case when ISNUMERIC(Value + 'e0') = 1
            then CONVERT(decimal(16,4), Value)
       end) < 11

By the way, the use of 'e0' is a clever way to just look for valid, non-exponential numbers.


text:
Q: Allocating string with malloc I'm new in programming in C and now I'm studying strings.
My question is: if I allocate a string using malloc (as in the code below), is the NULL character automatically inserted at the end of the string?
I find an answer in another question here, and it seems that the NULL character is not automatically included.
But here comes the problem: I know functions like strlen don't work if there isn't the NULL character, and in this code I use it and it works. So I think there is \0 at the end of my string, even if I don't write it anywhere.
What's the answer?
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv) {
    char *stringa1;
    int n;
    int i;

    printf("How many characters in the string? ");
    scanf("%d", &n);

    stringa1 = (char*) malloc(n*sizeof(char));

    printf("Insert the string: ");
    scanf("%s", stringa1);

    free(stringa1);

    return 0;
}

A:
if I allocate a string using malloc (as in the code below), is the NULL character automatically inserted at the end of the string?

No. malloc() returns a block of uninitialized memory.

I know functions like 'strlen' don't work if there isn't the NULL character, and in this code I use it and it works. So I think there is '\0' at the end of my string, even if I don't wrote it nowhere.

scanf() inserts the null byte ('\0') for you when you use %s format specifier (assuming scanf() succeeded).
From man scanf():

s  Matches a sequence of non-white-space characters; the next
      pointer must be a pointer to the initial element of a
      character array that is long enough to hold the input sequence
      and the terminating null byte ('\0'), which is added
      automatically. The input string stops at white space or at
      the maximum field width, whichever occurs first.

(emphasis mine).
By the way, you should do error checking for scanf() and malloc() calls.

A: malloc() returns a void* pointer to a block of memory stored in the heap. Allocating with malloc() does not initialize any string, only space waiting to be occupied.To add a null-terminating character, you either have to do this yourself, or use a function like scanf(), which adds this character for you. Having said this, you need to allocate space for this \0 character beforehand.
Your malloc() call should be this instead:
stringa1 = (char*) malloc((n+1)*sizeof(char)); /*+1 for '\0' character */

Note: You don't need to cast return of malloc. For more information, read this.
Another thing to point out is sizeof(char) is 1, so multiplying this in your malloc() call is not necessary.
You also need to check if malloc() returns NULL. This can be done like this:
if (stringa1 == NULL) {
    /* handle exit */

Also, you can only use strlen() on a null-terminated string, otherwise this ends up being undefined behaviour.
Once scanf() is called, and the stringa1 contains some characters, you can call strlen() on it.
Additionally, checking return of scanf() is also a good idea. You can check it like this:
if (scanf("%d", &n) != 1) {
    /* handle exit */

Your code with these changes:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    char *stringa1 = NULL;
    size_t n, slen;

    printf("How many characters in the string? ");
    if (scanf("%zu", &n) != 1) {
        printf("Invalid input\n");
        exit(EXIT_FAILURE);
    }

    stringa1 = malloc(n+1);
    if (stringa1 == NULL) {
        printf("Cannot allocate %zu bytes for string\n", n+1);
        exit(EXIT_FAILURE);
    }

    printf("Insert the string: ");
    scanf("%s", stringa1);

    slen = strlen(stringa1);
    printf("String: %s Length: %zu\n", stringa1, slen);

    free(stringa1);
    stringa1 = NULL;

    return 0;
}

A: malloc returns pointer to an uninitialized memory extent.
If you want that the memory extent would be initialized by zeroes then you can use another standard function calloc instead of malloc.
Take into account that usually such a question like this
printf("How many characters in the string? ");

imply that the terminating zero is not counted. So you have to allocate one more byte of memory. For example
stringa1 = ( char* )malloc( ( n + 1 ) *sizeof( char ) );

or
stringa1 = ( char* )calloc( n + 1, sizeof( char ) );

In the last case you may apply the function strlen which returns 0 because the memory extent is zero-initialized.
This call of scanf
scanf("%s", stringa1);

is unsafe. It is better to use fgets instead. For example
fgets( stringa1, n + 1, stdin );

This function can append the string with the new line character. To remove it from the string you can write
stringa1[strcspn( stringa1, "\n" )] = '\0';

A: The definition of "string" in C is a sequence of characters, terminated by a null character.
To allocate memory for a string, count the chracters (e.g. strlen) and add 1 for this terminating null character.
Functions like scanf and strcpy add the null character; a function like strncpy doesn't always do that.

A: The easy way to achieve this is to include cs50 library.
Just use get_string function:
#include <stdio.h>
#include <cs50.h>

int main(void) {
    // input the string to stringa1
    char *stringa1 = get_string("Insert the string: ");

    // call the string
    printf("The string you type was: %s\n", stringa1);

    return 0;
}

Sample output:
Insert the string: Hello World, I am newbie!
The string you type was: Hello World, I am newbie!


text:
Q: do EJBs get injected on a servlet everytime a request is done on the servlet? I am trying to copy the MVC design pattern. And this is what I do, I have a servlet which handles all the requests. In it, are the injected ejbs. So in this controller/servlet is declared 7 to 15 ejbs with the @EJB annotations.
I just want to ask if for example, 1 user calls the maincontroller/servlet. do the ejbs get injected only on that call or everytime a user calls the servlet do they get injected everytime? or the ejbs are injected the first time the servlet is created?

A: Resources are injected at the time of object creation ( since you cannot inject into static fields, but just member variables ).
In the case of a servlet, the servlet class is loaded by the servlet container and then an instance is created. At this time, the @EJB or @Resource is injected. The container then calls the init() method

A: Injection is done when creating the object and since Servlet Container  usually (but not mandatory - in case of single thread model) creates a single instance of a servlet and then serves the request in separate thread, the EJB in your case should be created once in case you are not using SingleThreadModel.


text:
Q: Can I register multiple resources with one handler and one URI in Open Rasta? I want to register mutliple resources with one handler and one URI.so want to confirm that is this possible in open rasta.
I have gone through a bit of websites regarding open rasta but couldn't able to conclude that whether this is possible or not?
  ResourceSpace.Has
           .ResourcesOfType<Request>()
           .AtUri("/processing")
           .HandledBy<SomeHandler>()
           .TranscodedBy<SomeCodec>();

I need to handle all the request which are derived from the base class "Request".
It would be great if some body could actually shed light on this.

A: So if everything is a request and you want to tunnel stuff, you can, using the registration you have provided.
The matching will be done based on the most approaching type, so
public void Post(SpecificRequest specificRequest) { /*handles the SpecificRequest type */ }
public void Post(Request myRequest) { /* handles the default case */ }

That said, be aware that in ReSTful system we tend to try and identify different things with different URIs, leading to one registration per type.

A: In my fairly limited experience of OpenRasta you can use the .And method to add additional .AtUri resource locations.
I.e. in your case
ResourceSpace.Has
       .ResourcesOfType<Request>()
       .AtUri("/processing").And.AtUri("/processing/{processid}")
       .HandledBy<SomeHandler>()
       .TranscodedBy<SomeCodec>();

where the {curley brackets} specify the input parameter of your Handler method i.e.:
public class SomeHandler
{
    public Request Get(int processid = 0) //specify a default value for the uri case /processed
    {
        if (processid == 0)
            return Context.Set<Request>().ToList(); //Context comes from my DbContext derived class which is part of my entity model.
        else
            return GetRequestFromProcessId(processid) //this is a private method in your handler class using Linq to SQL to retreive the data your interested in.  I can't see your handler so I'm making it up.
     }
 }

I found in the OpenRasta documentation a note which specifed that you MUST have destinct (only one) ResourceSpace definition for each matching Type and Handler.  In other words you must not duplicate the same ResourceOfType class with the same HandledBy handler class.  I tested this and it is the case and perhaps why you are asking the question in the first place.
N.b. this code is completely untested, I've just taken the patern of what I've written and substituted in your classes and uri where known.  This also assumes you are trying to retrieve data from a HTTP GET verb.  The other contributer, went down the POST route, but you haven't specified.


text:
Q: bug in nthroot using fixedpoint Here is my attempted solution to exercise 1-45 from Structure and Interpretation of Computer Programs, implemented in Haskell:
fixedpoint :: (Double->Double) -> Double -> Double -> Double
fixedpoint f guess err
  | err > abs next-guess  = next
  | otherwise             = fixedpoint f next err
  where next = f guess

avg :: Double -> Double -> Double
avg a b = (a+b)/2

avgdamp :: (Double -> Double) -> (Double -> Double)
avgdamp f = \ x -> avg x (f x)

log2 :: Double -> Double
log2 = (/ log 2) . log

repeated :: (a->a) -> Int -> (a->a)
repeated f n = \ x -> (iterate f x) !! n

nthroot :: Int -> Double -> Double -> Double
nthroot n x err = fixedpoint (repeated avgdamp numdampsneeded $ eqn) 1.0 err where
  numdampsneeded = floor $ log2 $ fromIntegral n  -- experimentally determined
  eqn = \ y -> x/y^(n-1)

I tested the helper procedures one-by-one, they seemed fine. I looked at 3 blogs on which solutions are posted and mine seems to correspond to them with some minor exceptions like implementation language and that I use explicit error argument.
Nevertheless I get ridicolous results from nthroot, and I do not have a clue.
> nthroot 2 16 0.000000001
5.1911764705882355

> nthroot 3 8 0.000001
2.447530864197531

> nthroot 3 27 0.001
7.0688775510204085

> nthroot 5 32 0.001
6.563864764681383

or in this case I expect to get back (approximation of) [0..16] as in octave
 > [0:16].^(1/2).^2

ans =
    0.00000    1.00000    2.00000    3.00000    4.00000    5.00000    6.00000    7.00000    8.00000    9.00000   10.00000   11.00000   12.00000   13.00000   14.00000   15.00000   16.00000

but
> map (^2) $ map (\x -> nthroot 2 x 0.000001) [0..16]
[0.25,1.0,2.006944444444444,3.0625,4.2025,5.4444444444444455,6.79719387755102,8.265625,9.852623456790123,11.559999999999999,13.388946280991735,15.340277777777777,17.41457100591716,19.612244897959187,21.933611111111112,24.37890625,26.94831314878893]

Any guess of what could be behind these bad results is welcome.

A: Function application binds tighter than any infix operator. Therefore,
abs next - guess  ==  (abs next) - guess

which isn't really what you want. If you fix this issue, your algorithm works fine.


text:
Q: SOAP Envelope Size I'll ask the question first, and then give some background:
Does anyone know if the SOAP Envelope Size is calculated including the headers, or just the content outside of the tags?
Content-Length includes the header information, but I can't assume that Content-Length = Envelope Size. The SOAP specification doesn't seem to address the Envelope Size, and I'm starting to worry that it's a "Up to the implementer" kind of thing.
Any answers or leads would be great.

A: If you are checking the if it exceeds maximum size you can do this way:
      if (maxMessageSize > 0) {
            FixedByteArrayOutputStream fbaos = new FixedByteArrayOutputStream(maxMessageSize);
            try {

            } catch (XMLStreamException e) {
                handleException("Error in checking the message size", e, synCtx);
            } catch (SynapseException syne) {
                synLog.traceOrDebug("Message size exceeds the upper bound for caching, request will not be cached");
                return;
            } finally {
                try {
                    fbaos.close();
                } catch (IOException e) {
                    handleException("Error occurred while closing the FixedByteArrayOutputStream ", e, synCtx);
                }
            }
        }

This is not the most efficient way to do it though. So I have asked it here


text:
Q: sed incremental counter without any loop program I am trying to achieve incremental counter using sed i could be wrong but is it possible with sed?
file.txt contain following
127.0.0.1
I want to run sed on file.txt so every time it increment number with i++ so next time if i run sed on same file result would be 127.0.0.2 so on and on.
I don't want to use any kind of while loop etc.. just use sed or awk is it possible?

A: You might pick a language that has IP address processing module, for example:
$ cat file.txt
192.168.1.254
$ ruby -ripaddr -i -lne 'puts IPAddr.new($_).succ' file.txt
$ cat file.txt
192.168.1.255
$ ruby -ripaddr -i -lne 'puts IPAddr.new($_).succ' file.txt
$ cat file.txt
192.168.2.0

A: $ cat file
127.0.0.1
$ awk 'BEGIN{FS=OFS="."} {$NF=$NF+1} 1' file
127.0.0.2

A: Using gnu sed:
sed -i -r 's/(.*)([^.]+)$/echo \1$((\2+1))/e' file

Here is the test result:
$cat file
127.0.0.1

$ sed -i -r 's/(.*)([^.]+)$/echo \1$((\2+1))/e' file

$ cat file
127.0.0.2

$ sed -i -r 's/(.*)([^.]+)$/echo \1$((\2+1))/e' file

$ cat file
127.0.0.3

A: sed 's/9$/10/;t
h;y/12345678/23456789/;G;s/.*\(.\)\n\(.*\)./\2\1/'

limited to .1 -> .10 as define in comment


text:
Q: How to apply Format object to index values in pandas Question:   I have a data frame with column names with respective values. But when i apply format object to column headings, they are not responding.
Code:
import pandas as pd

root = "C:\Users\543904\Desktop\New folder\"

dict = {'name':["aparna", "pankaj"],
        'degree': ["MBA", "BCA"],
        'score':[90, 40]}

df = pd.DataFrame(dict)

writer = pd.ExcelWriter(root + 'output', engine = "xlsxwriter")
df.to_excel(writer, sheet_name='df', index = False)

workbook = writer.book
worksheet = writer.sheets['df']

Format_Object = workbook.add_format({'text_wrap': True})
Format_Object.set_bold()
Format_Object.set_align('center')
Format_Object.set_align('top')
Format_Object.set_border(1)
Format_Object.set_bg_color('#0ef0ce')

worksheet.set_row(0, 20, Format_Object)

writer.save()

expected:
Expected
Actual:
Actual

A: This is explained in the XlsxWriter docs on Working with Python Pandas and XlsxWriter:

Pandas writes the dataframe header with a default cell format. Since it is a cell format it cannot be overridden using set_row(). If you wish to use your own format for the headings then the best approach is to turn off the automatic header from Pandas and write your own. For example:

# Turn off the default header and skip one row to allow us to insert a
# user defined header.
df.to_excel(writer, sheet_name='Sheet1', startrow=1, header=False)

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Add a header format.
header_format = workbook.add_format({
    'bold': True,
    'text_wrap': True,
    'valign': 'top',
    'fg_color': '#D7E4BC',
    'border': 1})

# Write the column headers with the defined format.
for col_num, value in enumerate(df.columns.values):
    worksheet.write(0, col_num + 1, value, header_format)


text:
Q: Creating a single exe file from Python code
Possible Duplicate:
py2exe - generate single executable file

A friend of mine managed to pack some a Ruby script he wrote in a single exe file. When I tried to do the same thing for a Python script, with py2exe, I also got several pyd files and a dll.
Is it possible to pack a Python script with all it's DLL's and pyd files into just one exe, and get rid of the other files?

A: According to py2exe.org:

The --bundle  or -b  command line switch will create less files because binary extensions, runtime dlls, and even the Python-dll itself is bundled into the executable itself, or inside the library-archive if you prefer that.
...
Using a level of 1 includes the .pyd and .dll files into the zip-archive or the executable itself, and does the same for pythonXY.dll. The advantage is that you only need to distribute one file per exe, which will however be quite large.

There's also another little tutorial on creating a single exe which will expand DLLs into a temporary directory at runtime, then delete the tempdir when Python exits.

A: This page can probably help you. More specifically, it seems that you can achieve this by setting bundle_files to 1 and zipfile to None. I haven't tested it, and it may not work if you have additional DLL files.
The other approach on that page seems clumsy: creating an installer that will expand the project into a temporary directory before running it, and removing the temporary directory after the application terminates.


text:
Q: Dividing Up CodeIgniter Multi-File DropZone Uploader Code into MVC? I am fairly new to CodeIgniter and I am trying to convert a working DropZone multi-file uploader to the MVC CodeIgniter format. I have seen some other examples here but need to get recommendations for my specific code.
I know how to place the upload/form page in a view and load via a controller.  However, the form handler code is where I need help.
Upload/Form Page:

<link rel="stylesheet" type="text/css" href="css/dropzone.css" />

<form action="upload_thumbnails.php" class="dropzone">
</form>

What parts of the form handler code should go in the model vs controller?  This is the section I am struggling with.
Form Handler Code:
if(!empty($_FILES)){

  function createThumbnail($filename) {
    $final_width_of_image = 200;
    $path_to_image_directory = 'uploads/';
    $path_to_thumbs_directory = 'uploads/thumbs/';

    if(preg_match('/[.](jpg)$/', $filename)) {
        $im = imagecreatefromjpeg($path_to_image_directory . $filename);
    } else if (preg_match('/[.](gif)$/', $filename)) {
        $im = imagecreatefromgif($path_to_image_directory . $filename);
    } else if (preg_match('/[.](png)$/', $filename)) {
        $im = imagecreatefrompng($path_to_image_directory . $filename);
    }

    $ox = imagesx($im);
    $oy = imagesy($im);
    $nx = $final_width_of_image;
    $ny = floor($oy * ($final_width_of_image / $ox));
    $nm = imagecreatetruecolor($nx, $ny);
    if(!imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy)){
        header("HTTP/1.0 500 Internal Server Error");
        echo 'Thumbnail Not created';
        exit();
    }
    if(!file_exists($path_to_thumbs_directory)) {
        if(!mkdir($path_to_thumbs_directory)) {
            header("HTTP/1.0 500 Internal Server Error");
            echo 'Thumbnail Not Created';
            exit();
        }
    }
    // Save new thumbnail image
    imagejpeg($nm, $path_to_thumbs_directory . $filename);

  }

//database configuration
$dbHost = 'localhost';
$dbUsername = 'insertnamehere';
$dbPassword = 'insertpwhere';
$dbName = 'ci_local';
//connect with the database
$conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($mysqli->connect_errno){
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$targetDir = "uploads/";
$fileName = $_FILES['file']['name'];
$targetFile = $targetDir.$fileName;

if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
    // NEW
    //createThumbnail($file['file']['name']);
    createThumbnail($fileName);
    // NEW

    //insert file information into db table
    $conn->query("INSERT INTO files (file_name, uploaded) VALUES('".$fileName."','".date("Y-m-d H:i:s")."')");
} else {
    echo "Ooops";
}

}
Any recommendations will be greatly appreciated.

A: Your createThumbnail function is a good example of something that should go either in a model or a library or a helper. A helper just contains functions, whereas a library or model are class based and therefore can access class properties and have constructors. I would lean towards making it either a library or a helper as it isn't coupled (thus reusable) to anything specific or other functions.
Generally you only want to return or throw Exceptions in any function that is not in a controller.

*

*This allows you to set your output in one file rather than having to
search through your models, libraries, .etc. if you want to change
your output down the road (for example if you plan on using AJAX).

*Also allows for code bases that aren't tightly coupled and can be
easily ported to other installations that may be different.

*Good for readability.

Models
Anything database related should go in a model as models represent the data logic in or the actual data used by your application. You should really use Codeigniter's in-built database functions instead of initializing the database and running the query yourself. Your insert or update statements should move into a model related to the controller.
Controllers
Your controller is just used for loading models, and any variables the view may require. It also should be used to set the response, whether that be a flash message or json encoded. In many examples it is also used for form_validation or data checks before performing CRUD operations that exist within the related model.
tl;dr anything database related go in the model, anything reusable and not tightly coupled goes in a library, or if it has no specific relation to oop goes in a helper (like an array sorting algorithm), anything form/input/view/response related goes in a controller.

Roughly you can do something like this (code may not work out of the box; I use my own implementation that differs from the default dz behavior as I employing jquerys sortable as well... I also am unsure about the error handling as I do that using another technique):
// byte_helper.php

/**
 * Gets max upload size from post_max_size and upload_max_filesize
 * Returns whichever is smaller
 *
 * @return int
 */
function file_upload_max_size() {
    $max_size = convert_to_bytes(ini_get('post_max_size'));
    $upload_max = convert_to_bytes(ini_get('upload_max_filesize'));
    if ($upload_max > 0 && $upload_max < $max_size) {
        $max_size = $upload_max;
    }
    return $max_size;
}

/**
 * Converts KB (K) through GB (G) to bytes
 *
 * @param string $from
 * @return int bytes
 */
function convert_to_bytes($from) {
    $number = filter_var($from, FILTER_SANITIZE_NUMBER_INT);
    $type = strtoupper(str_replace($number, '', $from));
    switch ($type) {
        case "KB":
        case "K":
            $number = $number * 1024;
            break;
        case "MB":
        case "M":
            $number = $number * pow(1024, 2);
            break;
        case "GB":
        case "G":
            $number = $number * pow(1024, 3);
            break;
    }
    return fix_integer_overflow($number);
}

/**
 * Fixes integer overflow
 *
 * @param int $size
 * @return int
 */
function fix_integer_overflow($size) {
    if ($size < 0) {
        $size += 2.0 * (PHP_INT_MAX + 1);
    }
    return $size;
}

class Dropzone_controller extends CI_Controller {

    public function upload() {
        if (!$this->input->is_ajax_request()) {
            exit('No direct script access allowed');
        }
        $this->load->helper('byte');
        $config['upload_path'] = ''; // upload directory realpath
        $config['file_name'] = md5(time()); // I like to set my own filename
        $config['overwrite'] = true;
        $config['allowed_types'] = 'jpg|jpeg|png|gif';
        $config['max_size'] = file_upload_max_size();
        $config['file_ext_tolower'] = true;
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('file')) {
            $this->dz_error($this->upload->display_errors('', '
'));
        }
        $data = $this->upload->data();
        $full_path = realpath($data['full_path']); // CI uses weird slashes
        // here you can use imagelib to resize if you want, I personally
        // like to use verot's class upload for that
        $this->load->model('dropzone_model');
        if (!$this->dropzone_model->add_image($full_path)) {
            @unlink($full_path); // remove orphaned image
            $this->dz_error('Failed to add image to the database!');
        }
        $this->dz_success();
    }

    // https://stackoverflow.com/questions/27030652/how-to-display-error-message-of-jquery-dropzone
    private function dz_error($error) {
        $this->output
                ->set_header("HTTP/1.0 400 Bad Request")
                ->set_output($error)
                ->_display();
        exit;
    }

    private function dz_success() {
        // don't really need to do anything here?
    }

}

class Dropzone_model extends CI_Model {

    public function add_image($full_path) {
        return $this->db->insert('sometable', array('image' => $full_path));
    }

}


text:
Q: ListBox игнорирует обновление ItemsSource Есть ListBox:
<ListBox x:Name="ModpacksGrid" Margin="0,40,200,0"
    ItemContainerStyle="{DynamicResource ModpacksListboxItem}" ItemsSource="{Binding ForModpackList}">
</ListBox>

Код стиля приводить смысла нет, ибо он (сам ListBox) в принципе работает при запуске.
Данное окно привязано к своей VM, в ней реализована коллекция public List<ModpacksGroup> ForModpackList => Config.LocalModpacks;
Сама VM реализует inotifypropertychanged с помощью KindOfMagic (который везде работает в проекте).
Так-же класс Config, ModpacksGroup, и Modpack, входящие в данную структуру тоже реализуют inotifypropertychanged.
Однако при добавлении элемента в Config.LocalModpacks ListBox не обновляется. Обновляется ForModpackList, и даже если дебаггером залезть в свойства ListBox'a, то в них в ItemsSource можно найти добавленный элемент. Однако он не отображается. Почему?


text:
Q: How to uninstall an older PHP version from centOS7 My project is on Laravel 5.2. and as per guide it required php >= 5.5.6 but there was php 5.4 intalled and I had to upgrade php version through YUM,
But now it is giving error "PDO driver not found" and I tried YUM install php-pdo
but it's giving error that "there is conflict between php56w-common and php-comon-5.4.16". I am stuck on this point

A: yum -y remove php* to remove all php packages then you can install the 5.6 ones.

A: Subscribing to the IUS Community Project Repository
cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh

Run the script:
sudo bash setup-ius.sh

Upgrading mod_php with Apache
This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.
Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.
sudo yum remove php-cli mod_php php-common

Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.
sudo yum install mod_php70u php70u-cli php70u-mysqlnd

Finally, restart Apache to load the new version of mod_php:
sudo apachectl restart

You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:
systemctl status httpd


text:
Q: TypeError: cannot pickle '_thread.RLock' object def _get_link(self, link):
    req = self.session.get(link, headers=self.headers)
    html = BeautifulSoup(req.text , 'lxml')

    if req.text.find("you're not a robot") > 0:
        html = captha_bypass.amazon_bypass(link=link)

    title = self.get_title(html)
    price = self.get_price(html)
    status = self.get_status(html)

    self.Q.put({
        "Usa Price": str(price).strip(),
        "Title": str(title).strip(),
        "Status": str(status).strip(),
        "Link": link,
    })

def get_link(self, links = []):
    data = []
    processes = []
    for l in links:
        processes.append(Process(target=self._get_link, args=(l,), daemon=True))

    with Progress() as progress:
        pbar = progress.add_task('[yellow]Started modules..[/yellow]', total=len(processes))
        for process in processes:
            process.start()
            data.append(self.Q.get())
            progress.update(pbar, advance=1)

    with Progress() as progress:
        pbar = progress.add_task('Get detail..', total=len(processes))
        for process in processes:
            process.join()
            progress.update(pbar, advance=1)

    self.console.log('\nGet detail operations end.\n', style="bold green")
    df = pd.DataFrame(data)
    return df

my arm is running on linux operating system. But it doesn't work on windows operating system.
What I want to do is run the first code block as multiprocess. This multiprocess receives a dataframe object. It creates a get request for each index.

ForkingPickler(file, protocol).dump(obj)
TypeError: cannot pickle '_thread.RLock' object


text:
Q: Can humidity damage electronic devices? My small vacation apartment has no cooker hood and even the simplest kitchen task, boiling water, creates condensation on windows. I try to keep a window open whenever possible. At what point can high room humidity cause hardware damage?

A: THe short answer is "Yes", but that really depends on just how much humidity there really is. Certainly if it is somehow able to condense in your computer it can cause damage.

A: Most general-purpose computing hardware is relatively well-protected against environmental humidity.  When operating, device temperatures will normally be somewhat above ambient, which reduces the risk of condensation.
The items you'll want to be most concerned about are tape drives and other magnetic media, especially if the tapes are stored somewhere cool.
Also, allow equipment time to warm up if it has been moved from a colder environment into the damp/humid one.

A: There are several forms of damage high humidity can cause. Condensation on metallic parts may cause corrosion and combining condensation with the dust you get in any space occupied by people can clog up vents and overlay components preventing sufficient cooling.
However, you might find that you don't in fact have a humidity problem just a condensation problem which is unlikely to really impact electronics that much. You might get a humidity sensor to check but it is generally quite hard to reach levels of humidity that will actually be damaging as that is likely to need >80% for extended periods. That would be very unhealthy and will cause far more damage to you than the electronics. Humidity should be kept at around 40-60% for occupied areas.
Condensation on the other hand simply happens when the moisture in the air touches a surface with a temperature below the dew point. This can still be unhealthy as it breeds molds which can be quite dangerous to health. But this is unlikely to cause problems to electronics left in situ. You might get some problems with electronics that you bring in from outdoors and it may be wise to let them aclimatise for a while before using indoors.
Really, you should get someone to fit an extractor fan with as large a capacity as you can so that you are getting humid air out as quickly as possible.


text:
Q: How can I get Qt5 applications to use the GTK theme in Ubuntu 17.04? Since I updated to Ubuntu 17.04, Qt5 applications (such as Qt Creator) won't use the GTK theme anymore. I tried to change this using qt5ct, but it only has the styles Fusion and Windows available, even though that the package qt5-gtk-platformtheme is installed.
How can this be fixed?
Edit: I'm using Unity.

A: Apart from qt5ct you also need to install qt5-style-plugins package, then you should get the 'gtk2' theme in qt5ct
sudo apt-get install qt5-style-plugins

And, as per the qt5ct documentation, don't forget to set QT_QPA_PLATFORMTHEME=qt5ct in /etc/X11/Xsession.d/56xubuntu-session and/or /etc/environment

A: The look and feel of Qt5 applications is determined by platform themes and styles. The platform theme is responsible for icons, fonts, etc. and the style controls how widgets are rendered. I think you'll find your application such as Qt Creator is using the GTK3 platform theme as standard.
The problem has occurred since Qt5.7. In this release, the GTK2 platform theme and style was removed and replaced with the GTK3 platform theme. I've recently been in discussion with the Qt developers and it appears there isn't a GTK3 style to complement the platform theme and there are currently no plans to implement this in the future. Therefore, on Ubuntu, the default style is "Fusion" using the GTK3 platform theme.
There are a couple of methods to add a native style as follows:

*

*The old GTK2 platform theme and style are still available in a separate package called qtstyleplugins that can be downloaded here. Unfortunately, the GTK2 style is not compatible with the GTK3 platform theme. If you want to use the GTK2 style you will have to use the GTK2 platform theme. This will mean your dialogs etc. do not look native in Ubuntu 17.04. However, you may prefer it to "Fusion".

*You didn't state what desktop environment you are using. There is a third party platform theme and style called QGnomePlatform available here and adwaita-qt available here. This provides a fully native look and feel when using Ubuntu Gnome.

For Qt Creator, I'm not 100% sure if it uses global theme/style locations. You may have to install them in {Qt_installation_folder}\Tools\QtCreator\lib\Qt\Plugins\platformthemes\ and {Qt_installation_folder}\Tools\QtCreator\lib\Qt\Plugins\styles\.


text:
Q: C# -- > Excel copy with the right format I have a problem with the numberformat in Excel.
I have created an application with wpf. There is a DataTable, where I display some numbers, like prices and other values.
To export these values to Excel, I've created a .xltx which opens, when I press export.
In my DataTable I select all cells and copy them to the clipboard. To paste it to Excel, is the PasteSpecial used.
My Problem is:
I paste the values in the german format (decimal seperator is comma and thousands seperator is a dot)
But only on one system (Windows Server 2008) the program paste it to Excel in the american format(decimal seperator dot and thousands seperator comma).
The Excel 2k10 on the Windows Server 2008 recognize the values in the german format.
For Example:
Value = 1.234.567,89 (german format)

When I paste it via the clipboard
Value = 1,234 (german format)

The Settings on the Server are all in the german format

*

*decimal seperator: comma

*thousands seperator: dot

What could I else try?
Thanks for your help


text:
Q: Why different eigenvalues of a real matrix are associated with linear independent values? If we have a real matrix $A$ such that $AV=aV$ and $AW=bW$ for two different values $a$ and $b$ and such that $V$ and $W$ are not $0$, how can we prove that $V$ and $W$ are linearly independent?

A: Assume $W=kV\ne 0.$ Thus
$$0=A0=A(W-kV)=AW-kAV=bW-kaV=(b-a)W.$$ This is not possible if $a\ne b.$
So $V$ and $W$ are linearly independent.


text:
Q: Why do my image filters cause a crash only after selecting an image from the gallery? I'm trying to create image filters in my app, but they only work if I take the image with the camera on my actual device. If I try using the code on an emulator, using the camera still breaks it. If I select an image from the phone's gallery, it crashes. I'm getting InvocationTargetException and IllegalStateException when I run this code.
Bitmap darken(Bitmap bmp) {
    for (int i = 0; i < bmp.getWidth(); i++) {
        for (int j = 0; j < bmp.getHeight(); j++) {
            int red = (bmp.getPixel(i, j) >> 16) & 0xFF;
            int green = (bmp.getPixel(i, j) >> 8) & 0xFF;
            int blue = (bmp.getPixel(i, j) >> 0) & 0xFF;
            red -= 25.5;
            green -= 25.5;
            blue -= 25.5;
            if (red < 0) {
                red = 0;
            }
            if (green < 0) {
                green = 0;
            }
            if (blue < 0) {
                blue = 0;
            }
            bmp.setPixel(i, j, Color.rgb(red, green, blue));
        }
    }
    return bmp;
}

Here's where that method gets called.
final Button darkenButton = (Button) findViewById(R.id.darkenButton);
darkenButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            BitmapDrawable bDraw = (BitmapDrawable) imageView.getDrawable();
            Bitmap bmap = bDraw.getBitmap();
            bmap = darken(bmap);
            imageView.setImageBitmap(bmap);
        }
    });


text:
Q: Book suggestion for practicing tough Ordinary DE problems I am preparing myself for a post undergraduate (masters) entrance exam in mathematics. Can someone suggest a really good practice material with challenging questions of all types for ordinary differential equations (any order/homogeneous/non-homogeneous etc.)? Do you think Differential Equations - Martin Braun useful for this purpose? I don't want any elementary text as I already have it, I think a good practice material would be more useful..

A: It is hard to advice some book. Because differential equations are either easy to solve (these equations are in undergrauate textbooks) or difficult. When I studied mathematics we over in undergraduate course all types of ODEs, but solution of them was mainly "mechanical work". Difficult nonlinear equations are solved by numerical methods. So maybe you can go in this way.
You can also look at some applications of ODE, there you can find difficult problems...equations with uncertain data, control theory, dynamical systems, biomathematics. In textbooks of ODEs are mainly basic exercices but problems from practice can be extremely tough (my experience from industry). Try to look at some textbooks in this fields, there could be more difficult problems.
I have job as mathematician for industry and sometimes find solution of some problem is not easy exercise.

A: A Book of Problems in Ordinary Differential Equations (English)
de M.L. Krasnov (Author), A.I. Kiselyov (Author), G.I. Makarenko (Author), Vladimir Shokurov


text:
Q: Embarcadero "Conditional defines" settings - whats the difference? What's the difference between these two settings in Project Options window?

A: The first contains global conitionals.  The second inherits the global conditionals and can add additional conditionals if desired.  It is just another way of sharing common conditionals across multiple build configurations.