text:
Q: how to convert Date(2019/5/10) to shamsiDate(1398/4/12) I had called a web service in my code that contains Deadline Date . the problem is the response in swagger shows like this :
{
    "id": "289",
    "serviceName": "خدمت 1",
    "deadLine": "2024/05/06",
   ...
...
  }

and I want to show deadline in Shamsi Date like 1398/4/12.
i have used a lot of convertors but it did not worked for me  and still shows the  "deadLine": "2024/05/06",
this is my view  :
public String setDeadLine(Date deadLine) {
        this.deadLine = deadLine;
         String dateFa;
       //String  dateFa= DateConvertor.miladi2date(deadLine);

       dateFa=  this.ConvertToPersianToShow(deadLine);
       return dateFa;
    }

    public String ConvertToPersianToShow(Date  deadLine)
    {
        CalendarTool cl = new CalendarTool();
        String date;
        String year = cl.getIranianYearInCentury();
        String Month = cl.getIranianMonthStr();
        String day = cl.getIranianWeekDayStr();

        date = year+"/" + Month + "/" + day;
        return date;
    }

should I type any code in my controller ?

A: RESOLVE :
I just need to add some code in ConvertToPersianToShow :
calendarTool should be filled .mine was empty
I added this code :
 String[] date = deadLine.split("/");
        if(date.length != 3)
            return null;
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.set(Integer.parseInt(date[0]),Integer.parseInt(date[1]),Integer.parseInt(date[2]));

and filled the calendar :
 CalendarTool cl = new CalendarTool(calendar);


text:
Q: Scala Convert Between Unsigned and Signed Bytes I have a unsigned data representation like this:
val str = "145 38 0 255 0 1"

I want to now get this unsigned representation as a byteString after which I can manipulate on the individual bits to extract information. So basically what I want is to get the unsigned version.
For example., the unsigned binary representation of 145 is 10010001, but the signed version is -00000111.
scala> 145.byteValue
res128: Byte = -111 // I would need an unsigned value instead!

So is there a function or an approach to convert the 145 to an unsigned representation?

A: Signed and unsigned bytes (or Ints or Longs) are just two different ways to interpret the same binary bits.
In signed bytes the first bit from the left (most significant bit) is interpreted as the sign.
0 means positive, 1 means negative.
For negative numbers, what comes after the minus sign is 256 - unsigned-value.
So in your case what we get is 256 - 145 = 111.
Java / Scala bitwise operators work on the underlying bits, not on the signed/unsigned representation, but of course the results, when printed are still interpreted as signed.
Actually, to save on confusion, I would just work with Ints (or Shorts).
But it will work just as well with bytes.
For example to get the n-th bit you could do something like:

def bitValue(byte: Byte, n: Byte) = {
    val pow2 = Math.pow(2, n - 1).toInt
    if((pow2 & byte) == 0) 0
    else 1
}

bitValue(145.byteValue, 8)
res27: Int = 1

redpajama_set_name: RedPajamaStackExchange


text:
Q: concave functions of different  behaviour in the neighbourhood of 0 from Shannon function I'm looking for an example of a concave function $g\colon [0,1]\to\mathbb{R}$, $g(0)=0$ such that:
$$\liminf_{x\to 0^+}\frac{g(x)}{-x\ln x}\neq \limsup_{x\to 0^+}\frac{g(x)}{-x\ln x}.$$
Moreover is it possible that the upper limit is infinite while the lower limit is finite?

A: You can have any pair $-\infty\le a\le b\le+\infty$ as limit inferior and limit superior, choosing a suitable concave function $g$ (and whatever is the nonnegative concave function $h(x)$ in place of $-x\log x$, satisfying $h(0)=0$ and $h'(0)=+\infty$). Idea: construct $g$ piecewise linear. To do so define inductively a strictly decreasing sequence $x_k\to0$, and a decreasing sequence of values $y_k=g(x_k)\to0$, thus defining intervals $J_k:=[x_{k+1},x_k]$ where $g$ is affine. The only constraint to get a concave function is that the slope of $g$ on each interval $J_k$ has to be smaller than $y_k/x_k$, and increasing wrto $k$; this is not an obstruction to approach any limit inferior and limit superior for $g(x)/h(x)$, provided that $x_{k+1} > 0$ is choosen small enough.


text:
Q: Pull data from SqlServer Database into jQuery Full Calendar using codeigniter3 I am facing same issue from so many days... Previously I worked with same calendar with PHP, but my project is in Codeigniter, so it is not fitted into my project... So now I am working with Codeigniter..
Controller Code
class Calendar extends CI_Controller
{
    public function __construct()
    {
        Parent::__construct();
        $this->load->model('Calendar_model');
    }

    public function index()
    {
        $this->load->view('Calendar_view');
    }

    public function load()
    {

        $query = $this->Calendar_model->load_events();

        $data_events = array();

        foreach($query->result() as $row)
        {
            $data_events[] = array(
                "title" => $row->title,
                "start" => date('Y-m-d H:i:s',strtotime($row->start_event)),
                "end"   => date('Y-m-d H:i:s',strtotime($row->end_event))
            );
        }

        echo json_encode($data_events);
    }
}

Model Code
class Calendar_model extends CI_Model
{
    public function __construct()
    {
        Parent::__construct();
    }

    public function load_events()
    {
        $query = $this->db->get("events");

        return $query;
    }
}

When I run the above with this url http://localhost/calendar_sql_copy/index.php/Calendar/load,
I got following data
[{"title":"Meeting2","start":"2019-09-30 00:00:00","end":"2019-09-30 00:00:00"},{"title":"Meeting2","start":"2019-02-08 00:00:00","end":"2019-03-08 00:00:00"}]

But when I try to pull same data into Fullcalendar in following way..
<script>
    $(document).ready(function(){
         var calendar = $('#calendar').fullCalendar({

        editable:true,
            header:{
                left:'prev,next today',
                center:'title',
                right:'month,agendaWeek,agendaDay'
            },
        selectable:true,
        selectHelper:true,
        // events:[
        //   {
        //   "title":"Meeting2",
        //   "start":"2019-09-30 00:00:00",
        //   "end":"2019-09-30 00:00:00"
        //   }
        // ]
       events:'<?php echo site_url('Calendar/load'); ?>'
</script>

If I show same data in static way as
events:[
           {
              "title":"Meeting2",
              "start":"2019-09-30 00:00:00",
              "end":"2019-09-30 00:00:00"
            }
        ]

It pops up into calendar,
But when I try to render with URL like below,
events:'<?php echo site_url('Calendar/load'); ?>'

Here is the data from the browser Network tool: https://intouchsystems-my.sharepoint.com/:u:/g/personal/gurubaran_k_icsoft_co_in/EZE8m-w3Pn1HoktYxL2yHPQBKcuosFXP1M3uT69bh9qn9Q?e=4%3a5RjKNu&at=9
It does not show even my Calendar....
Where I done mistake please tell me....
It is very important module in my project...
In my organization no WebDevelopers are there, and I am new to this Codeigniter...

A: Based on the information provided both in the question and the comments, the the reason for the problem is this:
<!-- Calendar.php --> <!-- Calendar_model.php -->
in your AJAX Response. Your response must contain JSON only and nothing else. No other text, no whitespace at the start and end...nothing except the JSON. If you include other data like this then jQuery (and thus fullCalendar) cannot parse the JSON correctly.
Please ensure that the server is not outputting extra data in the response. That will fix the problem.


text:
Q: Graph Theory: How quickly will triadic closure create a complete graph? Imagine we are given a graph $G$ comprised of nodes $N$ and edges $E$.  Assume the graph is connected (i.e. there exists a path connecting any pair of nodes).  We can then iteratively update this graph by adding new links in accordance with triadic closure.  Specifically, at each step:
for any triplet of nodes $\{i, j, k\} \in N$ such that $(i,j) \in E$ and $(j,k) \in E$ but $(i,k) \notin E$, we add the edge $(i,k)$ to $E$.  (In other words, if two of the three edges in the triangle are present, we add the missing edge.)
My question is, how many steps will be needed before the graph is complete (i.e. every pair of nodes is connected by an edge)?
I conjecture that the answer is the graph width minus 1.  (By graph width I mean the number of edges between the two most distant nodes in the original graph, where distance is measured measured by minimum path length.)  From playing with a few examples of small size, this seems to hold but I cannot prove it in general.

A: Let $u$ and $v$ be nonadjacent vertices in a connected graph $G$. Since $G$ is connected, there is a path $u$, $x_1$, $\dots$, $x_n$, $v$. Since $u \sim x_1$ and $x_1 \sim x_2$, we have the edge $ux_2$ after one triadic closure. (Perhaps we already had the edge $ux_2$, but that only makes the convergence quicker.) Now we have $u \sim x_2$ and $x_2 \sim x_3$, so we have the edge $ux_3$ after a second triadic closure. Continuing in this way, we have the edge $uv$ after $n$ triadic closures, which is one less than the graph width at most.
This bound is best possible, since a path on $n$ edges will require exactly $n-1$ triadic closures.


text:
Q: What did I do wrong in the expansion or consideration of proof The question is if $z_1$ and $z_2$ are complex numbers and satisfy the condition $|z_1+z_2|=|z_1-z_2|$, then show arguments of $z_1$ and $z_2$ are $\frac{\pi}{2}$ apart
I consider $z_1=r_1\cos(\theta_1)+r_1\sin(\theta)i$ and $z_2=r_2\cos(\theta_2)+r_2\sin(\theta_2)i$ but after expansion and cancel of the term, I get the equation $\cos(\theta_1-\theta_2)=-\cos(\theta_1-\theta_2)$?
$\theta_1-\theta_2=-(\theta_1-\theta_2)$

A: At the end of the claim the text "apart." is missing.
The equation $|z_1+z_2|=|z_1-z_2|$ is equivalent with $|z_1+z_2|^2=|z_1-z_2|^2$, and this is equivalent with $z_1\bar z_2+\bar z_1 z_2=0$, or ${\rm Re}(z_1\bar z_2)=0$. Writing $z_k=x_k+i y_k$ $(k=1, \>2)$ the last says that
$$x_1x_2+y_1y_2=0\ .$$
This means that the ${\mathbb R}^2$-vectors ${\bf z}_k:=(x_k,y_k)$ are orthogonal, so that $\arg(z_1)$ and $\arg(z_2)$ are ${\pi\over2}$ apart.


text:
Q: I am using firebase_admob to implement ads in my flutter app, but ads are not working in release build apk The test ads show with no problem, and even the real ads were appearing on my app when i made an debug build, when i realized the debug build is working fine and made a final release, the ads stopped appearing on my app. Even now on my emulator the app shows the test ads, but with the released app, no ads appear.
I haven't received any communication either as to why this is happening. Any help would be much appreciated
Thanks
i have already tried to install released app on real device but no ads on real device(even ads are loading on real device with debug and profile mode)

A: Example for android native app.
Please test the production admobid , admod unit with the admob sample at https://github.com/googlesamples/android-ads/tree/master/admob/BannerExample
Replace existing admob ids and admob units, please check it the ads are getting served .
If no , then there might be some issue with you admob unit , or its not been fully approved for ads.
If you have created admob unit , recently , please wait for some time .
Hope that helps.


text:
Q: Rails, HAML remember me checkbox not working All,
I am working on a login form. As part of that form, I have included a "Remember me" checkbox, designed to store an encrypted session hash in the user database if checked. I am probably missing something on the basic side, but for the life of me, I cannot get the checkbox to function properly.  Specifically, every submission of the login results in a session hash being stored to the database, even if the checkbox is not clicked, leading me to believe that the checkbox simply is not set up correctly.
Show me the error of my ways!
the login view:
.container
%h1 Log in
%div{:class => "row"}
    %div{:class => "col-md-6 col-md-offset-3"}
        = form_for :session, :url => login_path, :class => "form-horizontal", :id => "login_form" do |f|
            %div{:class => "form-group"}
                = f.label :email, "Email Address"
                = f.text_field :email, :class => "form-control", :id => "email", :placeholder => "Email"
            %div{:class => "form-group"}
                = f.label :password, "Password"
                = f.password_field :password, :class => "form-control", :id => "password", :placeholder => "Password"
            %div{:class => "form-group"}
                = f.label :remember_me, "Remeber me"
                = f.check_box :remember_me, :type => "checkbox", :value => "1", :checked => "1"

                = f.submit "Go Get Em!", :class => "btn btn-default pull-right"
        %p Don't have an account? #{ link_to 'Sign Up', signup_path}

And the sessions controller method:
def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
        log_in(user)
        params[:session][:remember_me] == '1' ? remember(user) : forget(user)
        remember user
        redirect_to root_url #redirect_to user
    else
       flash.now[:danger] = "Invalid email/password comination" #fix
       render 'new'
    end
end

A: params[:session][:remember_me] == '1' ? remember(user) : forget(user)
remember user

I'm not quite sure you have a second "remember user" in there, that's probably the issue that causes what you're experiencing.


text:
Q: Jenkins build error after slave change The build for this job is getting failed because of the following error.
I'm not sure what this is about. Can anyone help me resolve this?

A: The first "[ERROR]" line ends with the problem: "Unsupported major.minor version 52.0"
This means there's a problem with a version of... something. A quick search would reveal that that's the error returned when you're trying to run something (in this case the analysis) with an incompatible version of Java.
The "52.0" at the end could be clearer, but this answer decodes that number to Java 8, which is actually the version that's required to run analysis, not the version you're running.
So. Upgrade your version of Java and/or make sure any copy of Java 8 that's already on the machine is used for analysis.


text:
Q: Point a subdomain to phpmyadmin installed on an ubuntu 12.04 I've been struggling a little bit with this setup. i've installed all the prerequisites for phpmydamin and itself is available at ip/phpmyadmin. Now i have a subdomain that i want to point to it. let's say i want to point data.somedomain.com to the phpmyadmin such a way that instead of ip/phpmyadmin i can access it as data.somedomain.com.I've been doing simple VirtualHost creation but i think am kind of lost in this one.
here is the /etc/phpmyadmin/apache.conf:
# phpMyAdmin default Apache configuration
<VirtualHost *:80>
  ServerName data.somedomain.com

  Alias /phpmyadmin /usr/share/phpmyadmin

 <Directory /usr/share/phpmyadmin>
    Options FollowSymLinks
    DirectoryIndex index.php

    Options All
    AllowOverride All
    Require all granted
    <IfModule mod_php5.c>
            AddType application/x-httpd-php .php

            php_flag magic_quotes_gpc Off
            php_flag track_vars On
            php_flag register_globals Off
            php_admin_flag allow_url_fopen Off
            php_value include_path .
            php_admin_value upload_tmp_dir /var/lib/phpmyadmin/tmp
            php_admin_value open_basedir /usr/share/phpmyadmin/:/etc/phpmyadmin/:/var/lib/phpmyadmin/
    </IfModule>
   <IfModule mod_php5.c>
            AddType application/x-httpd-php .php

            php_flag magic_quotes_gpc Off
            php_flag track_vars On
            php_flag register_globals Off
            php_admin_flag allow_url_fopen Off
            php_value include_path .
            php_admin_value upload_tmp_dir /var/lib/phpmyadmin/tmp
            php_admin_value open_basedir /usr/share/phpmyadmin/:/etc/phpmyadmin/:/var/lib/phpmyadmin/
    </IfModule>

</Directory>

# Authorize for setup
<Directory /usr/share/phpmyadmin/setup>
    <IfModule mod_authn_file.c>
        AuthType Basic
        AuthName "phpMyAdmin Setup"
        AuthUserFile /etc/phpmyadmin/htpasswd.setup
    </IfModule>
    Require valid-user
 </Directory>

 # Disallow web access to directories that don't need it

 <Directory /usr/share/phpmyadmin/libraries>
    Order Deny,Allow
    Deny from All
 </Directory>
 <Directory /usr/share/phpmyadmin/setup/lib>
    Order Deny,Allow
    Deny from All
 </Directory>

</VirtualHost>

what i did add was the <VirtualHost> tag wrapper and the ServerName and these Options All AllowOverride All Require all granted
when i access the url it throws a 404 code : The requested URL / was not found on this server.
and the logs contains this entry : File does not exist: /etc/apache2/htdocs
thanks for your suggestions.

A: All you need to do is setup a subdomain for apache. You can do this by creating a configuration file in /etc/apache2/sites-available.
Here's mine ..
<VirtualHost *:80>
   ServerAdmin adminn@example.local
   ServerName phpmyadmin.example.local
   DocumentRoot /usr/share/phpmyadmin
   <Directory />
       Options FollowSymLinks
       AllowOverride None
   </Directory>
   LogLevel notice
   CustomLog /var/log/apache2/access.log combined
   ErrorLog /var/log/apache2/error.log
   ServerSignature On
</VirtualHost>

Save that to /etc/apache2/sites-available/phpmyadmin.conf and enable the subdomain.
a2ensite phpmyadmin

And restart the apache server
service apache2 reload

Now you should be able to use phpmyadmin from phpmyadmin.example.local.

A: What you really need here is a CNAME with your DNS solution.  For example, if you used someone like godaddy.com, you'd add a cname data.somedomain.com on their dns management page that resolves to somedomain.com.
A cursory look through your nginx virtual host, you may want to start with a minimal config first that simply points requests for data.somedomain.com to your /usr/share/phpmyadmin.  I'd also suggest locking down phpmyadmin with htaccess (nothing worse than having your db hacked.)

A: There error message you mentioned File does not exist: /etc/apache2/htdocs is definitely a sign of the parameter DocumentRoot not being properly specified for the virtualhost. Make sure you point it to the right directory.

A: phpMyAdmin is still setup under the path /phpmyadmin, you should find that http://data.example.com/phpmyadmin/ works. You can either change the Alias directive (and other references to /phpmyadmin) to / to present it under the root:
Alias / /usr/share/phpmyadmin

Or you can redirect / to /phpmyadmin:
RewriteRule   ^/$  /phpmyadmin/  [R]


text:
Q: Why getting this exception "System.InvalidOperationException: Timeouts are not supported on this stream" inconsistently I am getting the exception "System.InvalidOperationException: Timeouts are not supported on this stream" whil loading the hotlist data from the web service. Plz find below the exception log trace for the same.

[2014-12-09 09:38:10.4402]  Information: 0033216: <-Get Hot List
  Started() [2014-12-09 09:38:33.9415]        Error: 0033217:
  System.InvalidOperationException: Timeouts are not supported on this
  stream.
Server stack trace:     at System.IO.Stream.get_ReadTimeout()    at
  System.ServiceModel.Channels.HttpChannelUtilities.CreateResponseWebException(WebException
  webException, HttpWebResponse response)    at
  System.ServiceModel.Channels.HttpInput.WebResponseHttpInput.WebResponseInputStream.Read(Byte[]
  buffer, Int32 offset, Int32 count)    at
  System.ServiceModel.Channels.MessageEncoder.BufferMessageStream(Stream
  stream, BufferManager bufferManager, Int32 maxBufferSize)    at
  System.ServiceModel.Channels.MessageEncoder.ReadMessage(Stream stream,
  BufferManager bufferManager, Int32 maxBufferSize, String contentType)
  at
  System.ServiceModel.Channels.HttpInput.ReadChunkedBufferedMessage(Stream
  inputStream)    at
  System.ServiceModel.Channels.HttpInput.ParseIncomingMessage(HttpRequestMessage
  httpRequestMessage, Exception& requestException)    at
  System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
  timeout)    at
  System.ServiceModel.Channels.RequestChannel.Request(Message message,
  TimeSpan timeout)    at
  System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message
  message, TimeSpan timeout)    at
  System.ServiceModel.Channels.ServiceChannel.Call(String action,
  Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
  Object[] outs, TimeSpan timeout)    at
  System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
  methodCall, ProxyOperationRuntime operation)    at
  System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
  message)
Exception rethrown at [0]:     at
  System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
  reqMsg, IMessage retMsg)    at
  System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
  msgData, Int32 type)    at
  DMS.Integration.Proxy.Reference.ReferenceWebService.getHotlist(getHotlistRequest
  request)    at
  DMS.Integration.Proxy.Reference.ReferenceWebServiceClient.DMS.Integration.Proxy.Reference.ReferenceWebService.getHotlist(getHotlistRequest
  request)    at
  DMS.Integration.Proxy.Reference.ReferenceWebServiceClient.getHotlist(getHotlist
  getHotlist1)    at DMS.Services.HotListServiceProxy.GetHotList()    at
  DMS.GUI.Utils.AddToHotListHelper.b__5()    at
  DMS.Lib.Base.ServiceProxyWrapper`1.Execute() [2014-12-09
  09:38:33.9415]        Error: 0033218: System.ApplicationException:
  getHotList
[2014-12-09 09:38:33.9415]  Information: 0033219: Service Call Timing,
  94835ms, Action :getHotList

I can confirm that while getting the hotlist, we are not doing any memory stream operations.
Please find below the bindings for the service in app.config:
 <bindings>
        <basicHttpBinding>
            <binding name="basicBinding" maxBufferSize="209715200" maxReceivedMessageSize="209715200">
                <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
                    maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
                <security mode="TransportCredentialOnly">
                    <transport clientCredentialType="Basic"/>
                </security>
            </binding>
        </basicHttpBinding>
    </bindings>

The isssue is coming in QA environment and application is installed on server and by connecting to VPN only they can access the application for testing.


text:
Q: The subtle difference between #ifdef and #if for a macro defined as 0 Given the C file below:
$ cat macros.c
#ifdef MACRO
#  error MACRO is defined
#else
#  error MACRO is undefined
#endif
#if MACRO
#  error MACRO is non-zero
#else
#  error MACRO is zero
#endif

What is the expected output of the following?
$ gcc           -c macros.c
$ gcc -DMACRO   -c macros.c
$ gcc -DMACRO=0 -c macros.c

Answer: Here's what the gcc's preprocessor on my machine does.
$ gcc           -c macros.c
macros.c:4:4: error: #error MACRO is undefined
macros.c:9:4: error: #error MACRO is zero
$ gcc -DMACRO   -c macros.c
macros.c:2:4: error: #error MACRO is defined
macros.c:7:4: error: #error MACRO is non-zero
$ gcc -DMACRO=0 -c macros.c
macros.c:2:4: error: #error MACRO is defined
macros.c:9:4: error: #error MACRO is zero
$

Lesson: #ifdef MACRO evaluates to true for defined-ness even if the defined value is 0 (zero).
Another C preprocessor gotcha! Is this how it should be as per the C standard?

A: Any undefined macro is treated as it were defined as 0 for the purposes of evaluating the controlling expressions of #if statements.  From C99 §6.10.1/3-4 (emphasis added):

3) Preprocessing directives of the forms
# if constant-expression new-line groupopt
# elif constant-expression new-line groupopt
check whether the controlling constant expression evaluates to nonzero.
4) Prior to evaluation, macro invocations in the list of preprocessing tokens that will become
  the controlling constant expression are replaced (except for those macro names modified
  by the defined unary operator), just as in normal text. If the token defined is
  generated as a result of this replacement process or use of the defined unary operator
  does not match one of the two specified forms prior to macro replacement, the behavior is
  undefined. After all replacements due to macro expansion and the defined unary
  operator have been performed, all remaining identifiers (including those lexically
  identical to keywords) are replaced with the pp-number 0, and then each preprocessing
  token is converted into a token. [...]

So, for example, expressions like this:
#if !FOO

Will evaluate to 1 if FOO is undefined, since it will be treated as a 0, and then !FOO would be evaluated as !0, which is 1.

A:  #ifdef  only cares if MACRO has been defined or not. Value doesn't matter.
 #if  checks for the value of MACRO and evaluates MACRO accordingly.
That is correct behaviour

A: The behavior is as per the standard.
C99 Standard: 6.10.1 Conditional inclusion:
Para 2: Preprocessing directives of the forms
# if constant-expression new-line groupopt
# elif constant-expression new-line groupopt

check whether the controlling constant expression evaluates to nonzero.
Para 4: Preprocessing directives of the forms
# ifdef identifier new-line groupopt
# ifndef identifier new-line groupopt

check whether the identifier is or is not currently defined as a macro name. Their
conditions are equivalent to #if defined identifier and #if !defined identifier
respectively.


text:
Q: AngularJs controller value doesn't update after factory resolve I'm trying to build a user page where it shows it's main data, details, address, etc.. When I make the first load, it doesn't show on the screen until I change the page and go back to the user page. It's problaby because of the promise return after I already went to that page.
I can't (don't want to) use this data to be loaded during the resolve on the stateChange because it make the app feels freezing, since it will only change screen after all the data is resolved, and if it take some time, it seems the page isn't working.
I also tried using $scope.$digest() (on the controller) and $rootScope.$apply() on the factory, but both situations give me the digest running error.
Using .then() isn't an option (unless there is a proper way) because if I'm returning to that page after the first load, there will be errors.
The way I'm loading this is from a parent (abstract) controller and storing those values in a factory, something like this:
//Parent Controller
function parentController(requestFactory, storeFactory, $q) {
    var
        user = storeFactory.userGet(),
        data = storeFactory.dataGet()
        [...more load...];

    if(!user || !data ...) {
        var promises = {
            user:    requestFactory.get('userGet'),
            data:    requestFactory.get('dataGet'),
            [...more requests...]
        };

        return $q.all(promises).then(function(resolve){
            storeFactory.userAdd(resolve.user);
            storeFactory.dataAdd(resolve.data);
            [...more update...]
        });
    }
}

//Factory
function storeFactory() {
    var
        data    = null,
        user    = null,
        address = null,
        endereco = null;

    var service = {
        userGet: _userGet,
        userAdd: _userAdd,
        [...more definitions...]
    };
    return service;

    function _userGet() {
        return user;
    }
    function _userAdd(data) {
        return user = data;
    }
    [...more functions...]
}

// child Controller 01
function child1Controller(storeFactory) {
    vm.user = storeFactory.userGet();
}

// child Controller 02
function child2Controller(storeFactory) {
    vm.address = storeFactory.addressGet();
}

I also need to load all these data on the beginning because there is dependent data, for example, the address depends on the user, etc..

So, if I access the page user > address it's not showing anything on the screen, but if I go to other page and came back, everything will show like it's supposed to show.
Is there a way to solve this problem? To make the data update automatically?

A: The way I could solve this problem, was to create a single object with nested arrays in the factory, instead of creating multiple arrays. Also, in the controller, I can't set the specific array direct to the vm, I need to set the array inside the object, this way it's automatically updated.
//Factory
var data = {
    user: null,
    address: null,
    [...]
};

function _userAdd(value) {
    return data.user = value;
}
[...etc...]

//Controller
function child1Controller(storeFactory) {
    vm.maindata = storeFactory.data;
}

After doing this, I need to specify the nested array on the view, like this:

{{vm.maindata.user}}

{{address}}

Even though it's working, it doesn't feel like the right way to do, so, if there is a better way to achieve this result, I'm open to suggestions.


text:
Q: Как создать файл сразу в Sublime Text 3 Мне хотелось бы сразу создавать файлы и открывать их в ST3, а то приходится создавать файл и только потом через ST открывать его, это неудобно и долго.
Я у одного ютубера видел такую вещь, что когда он создаёт файл вот так:

в указанном стрелкой окне был раздел "текстовый файл Sublime Text 3" или чуть по-другому, кто-нибудь знает, как это сделать?


text:
Q: How to append some data into existing xlsx sheet R? I´m trying to read a xlsx file and write one data frame into the same sheet of xlsx without remove the other rows of my data frame.
I tried with the library("XLConnect") and with the function appendWorksheet() but the data is not writing in the correct place, and with the library("xlsx") but I can´t find a function similar to appendWorksheet.
I just want to read my xlsx file and write my data that is into a data frame and write into the same xlsx file without removing the previous rows.

A: There doesn't seem to be a great way to append data to an xlsx file. You can create a function which will read in the sheet and append data to the dataframe and then overwrite the xlsx.
library(xslx)
appendxlsx <- function(df2, path, sheetName) {
  df1 <- read.xlsx2(path, sheetName = sheetName)
  colnames(df2) <- colnames(df1)
  df <- rbind(df1, df2)
  write.xlsx2(df, path, sheetName = sheetName)
}

Then you would just call the function supplying the updated dataframe (df2), the path to the xlsx, and the sheet name. Something like this:
appendxlsx(df2=df2, "/path/to/xlsx", sheetName = "Sheet1")


text:
Q: Update an array element with inc mongo update HI All I have this Data in mongo,
{"articleId" : [
            {
                    "articleId" : "9514666",
                    "articleCount" : 1
            }
    ],

    "count" : NumberLong(1),
    "timeStamp" : NumberLong("1416634200000"),
    "interval" : 1,
    "tags" : "famous"
 }

I want to update it using this new data
 {"articleId" : [
            {
                    "articleId" : "9514666",
                    "articleCount" : 3
            }
            {
                    "articleId" : "9514667",
                    "articleCount" : 3
            }
    ],

    "count" : NumberLong(6),
    "timeStamp" : NumberLong("1416634200000"),
    "interval" : 1,
    "tags" : "famous"
 }

What i need in the output is
{"articleId" : [
            {
                    "articleId" : "9514666",
                    "articleCount" : 4
            }
            {
                    "articleId" : "9514667",
                    "articleCount" : 3
            }
    ],

    "count" : NumberLong(7),
    "timeStamp" : NumberLong("1416634200000"),
    "interval" : 1,
    "tags" : "famous"
 }

Could you please suggest me how can i achieve this this using update operation
My update query will have tags field as query parameter.

A: I accomplished it with your criteria which was to use the tags field in your query. I of course had to filter on the document further to only update that specific document.
I presumed other documents may have a tag of "famous". I created two documents with tags:famous to prove this worked when updating 1 document. Here's my solution with comments.
//basics
db = test
collection = test

//data looked like this with two documents for testing
/* 0 */
{
    "_id" : ObjectId("5498778567bbbc2fff723515"),
    "articleId" : [
        {
            "articleId" : "9514666",
            "articleCount" : 1
        }
    ],
    "count" : 1,
    "timeStamp" : "1416634200000",
    "interval" : 1,
    "tags" : "famous"
}

/* 1 */
{
"_id" : ObjectId("5498781567bbbc2fff723516"),
"articleId" : [
    {
        "articleId" : "951466622",
        "articleCount" : 22
    }
],
"count" : 1,
"timeStamp" : "1416634200000",
"interval" : 1,
"tags" : "famous"
}

//confirmed I can query the one document like this
db.test.find({'tags': 'famous','articleId.articleId':'9514666'})

//was able to execute an update as described
db.test.update({'tags': 'famous','articleId.articleId':'9514666'}, {"articleId" : [
        {
                "articleId" : "9514666",
                "articleCount" : 4
        },
        {
                "articleId" : "9514667",
                "articleCount" : 3
        }
],

"count" : 7,
"timeStamp" : "1416634200000",
"interval" : 1,
"tags" : "famous"
})

//Resulting update to document is
/* 0 */
{
 "_id" : ObjectId("5498778567bbbc2fff723515"),
 "articleId" : [
    {
        "articleId" : "9514666",
        "articleCount" : 4
    },
    {
        "articleId" : "9514667",
        "articleCount" : 3
    }
],
"count" : 7,
"timeStamp" : "1416634200000",
"interval" : 1,
"tags" : "famous"
}

//showing both documents, only first one updated obviously
/* 0 */
{
"_id" : ObjectId("5498778567bbbc2fff723515"),
"articleId" : [
    {
        "articleId" : "9514666",
        "articleCount" : 4
    },
    {
        "articleId" : "9514667",
        "articleCount" : 3
    }
],
"count" : 7,
"timeStamp" : "1416634200000",
"interval" : 1,
"tags" : "famous"
}

/* 1 */
{
"_id" : ObjectId("5498781567bbbc2fff723516"),
"articleId" : [
    {
        "articleId" : "951466622",
        "articleCount" : 22
    }
],
"count" : 1,
"timeStamp" : "1416634200000",
"interval" : 1,
"tags" : "famous"
}


text:
Q: ERROR: cannot launch node of type [msf_updates/pose_sensor]: can't locate node [pose_sensor] in package [msf_updates] I am following this tutorial:
http://wiki.ros.org/ethzasl_sensor_fusion/Tutorials/Introductory%20Tutorial%20for%20Multi-Sensor%20Fusion%20Framework
 and have compiled the package in the catkin workspace. I tried to get the new namespace and launch the filter but I am unable to do so because I get an error that the pose_sensor node cannot be located. I have source'd my devel/setup.bash.
However, that hasn't fixed the problem. I still get the error:
NODES
  /msf_viconpos_sensor (msf_updates/pose_sensor)

ROS_MASTER_URI=http://localhost:11311

ERROR: cannot launch node of type [msf_updates/pose_sensor]: can't locate node [pose_sensor] in package [msf_updates]

EDIT:
After adding the missing code, here is the new error I get when I run catkin_make:
/bin/sh: 1: cannot open /home/yukti/catkin_ws/src/fix-unused-typedef-warning.patch: No such file
glog_catkin-master/CMakeFiles/glog_src.dir/build.make:101: recipe for target 'glog_catkin-master/glog_src-prefix/src/glog_src-stamp/glog_src-patch' failed
make[2]: *** [glog_catkin-master/glog_src-prefix/src/glog_src-stamp/glog_src-patch] Error 2
CMakeFiles/Makefile2:502: recipe for target 'glog_catkin-master/CMakeFiles/glog_src.dir/all' failed
make[1]: *** [glog_catkin-master/CMakeFiles/glog_src.dir/all] Error 2
make[1]: *** Waiting for unfinished jobs....
[  3%] Linking CXX shared library /home/yukti/catkin_ws/devel/lib/libmsf_timing.so
[  3%] Built target msf_timing
Makefile:138: recipe for target 'all' failed
make: *** [all] Error 2
Invoking "make -j2 -l2" failed

EDIT 2:
After running a different make command as follows:
cmake .. -DCMAKE_BUILD_TYPE=release -DCMAKE_INSTALL_PREFIX=/usr/local

I was able to successfully compile. However, I still get the same error that;
can't locate node [pose_sensor] in package [msf_updates]

EDIT 3: Edit 2 was incorrect because I had an incorrect src folder in my home folder which contained a CMakeLists.txt. If following the correct order, I still get a compilation error akin to Edit 1.
EDIT 4: cmake failed after adding all the changes from the pull request. Here is the log:
Base path: /home/yukti/catkin_ws
Source space: /home/yukti/catkin_ws/src
Build space: /home/yukti/catkin_ws/build
Devel space: /home/yukti/catkin_ws/devel
Install space: /home/yukti/catkin_ws/install
####
#### Running command: "cmake /home/yukti/catkin_ws/src -DCATKIN_DEVEL_PREFIX=/home/yukti/catkin_ws/devel -DCMAKE_INSTALL_PREFIX=/home/yukti/catkin_ws/install -G Unix Makefiles" in "/home/yukti/catkin_ws/build"
####
-- The C compiler identification is GNU 5.4.0
-- The CXX compiler identification is GNU 5.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Using CATKIN_DEVEL_PREFIX: /home/yukti/catkin_ws/devel
-- Using CMAKE_PREFIX_PATH: /home/yukti/catkin_ws/devel;/opt/ros/kinetic
-- This workspace overlays: /home/yukti/catkin_ws/devel;/opt/ros/kinetic
-- Found PythonInterp: /usr/bin/python (found version "2.7.12")
-- Using PYTHON_EXECUTABLE: /usr/bin/python
-- Using Debian Python package layout
-- Using empy: /usr/bin/empy
-- Using CATKIN_ENABLE_TESTING: ON
-- Call enable_testing()
-- Using CATKIN_TEST_RESULTS_DIR: /home/yukti/catkin_ws/build/test_results
-- Found gmock sources under '/usr/src/gmock': gmock will be built
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - not found
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE
-- Found gtest sources under '/usr/src/gmock': gtests will be built
-- Using Python nosetests: /usr/bin/nosetests-2.7
-- catkin 0.7.14
-- BUILD_SHARED_LIBS is on
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- ~~  traversing 12 packages in topological order:
-- ~~  - asctec_mav_framework (metapackage)
-- ~~  - catkin_simple
-- ~~  - ethzasl_msf
-- ~~  - glog_catkin
-- ~~  - msf_timing
-- ~~  - sensor_fusion_comm
-- ~~  - asctec_hl_comm
-- ~~  - asctec_hl_gps
-- ~~  - asctec_hl_interface
-- ~~  - msf_core
-- ~~  - msf_distort
-- ~~  - msf_updates
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- +++ processing catkin metapackage: 'asctec_mav_framework'
-- ==> add_subdirectory(asctec_mav_framework-master/asctec_mav_framework)
-- +++ processing catkin package: 'catkin_simple'
-- ==> add_subdirectory(catkin_simple-master)
-- +++ processing catkin package: 'ethzasl_msf'
-- ==> add_subdirectory(ethzasl_msf/ethzasl_msf)
-- +++ processing catkin package: 'glog_catkin'
-- ==> add_subdirectory(glog_catkin-master)
-- +++ processing catkin package: 'msf_timing'
-- ==> add_subdirectory(ethzasl_msf/msf_timing)
CMake Error at /opt/ros/kinetic/share/catkin/cmake/test/gtest.cmake:169 (add_executable):
  add_executable cannot create target "msf_timing_tests" because another
  target with the same name already exists.  The existing target is an
  executable created in source directory
  "/home/yukti/catkin_ws/src/ethzasl_msf/msf_timing".  See documentation for
  policy CMP0002 for more details.
Call Stack (most recent call first):
  /opt/ros/kinetic/share/catkin/cmake/test/gtest.cmake:79 (_catkin_add_executable_with_google_test)
  /opt/ros/kinetic/share/catkin/cmake/test/gtest.cmake:28 (_catkin_add_google_test)
  ethzasl_msf/msf_timing/CMakeLists.txt:46 (catkin_add_gtest)

-- +++ processing catkin package: 'sensor_fusion_comm'
-- ==> add_subdirectory(ethzasl_msf/sensor_fusion_comm)
-- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy
-- sensor_fusion_comm: 5 messages, 2 services
-- +++ processing catkin package: 'asctec_hl_comm'
-- ==> add_subdirectory(asctec_mav_framework-master/asctec_hl_comm)
-- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy
-- Generating .msg files for action asctec_hl_comm/Waypoint /home/yukti/catkin_ws/src/asctec_mav_framework-master/asctec_hl_comm/action/Waypoint.action
Generating for action Waypoint
-- asctec_hl_comm: 18 messages, 3 services
-- +++ processing catkin package: 'asctec_hl_gps'
-- ==> add_subdirectory(asctec_mav_framework-master/asctec_hl_gps)
-- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy
-- Found PkgConfig: /usr/bin/pkg-config (found version "0.29.1")
-- Checking for module 'eigen3'
--   Found eigen3, version 3.2.92
CMake Warning at /opt/ros/kinetic/share/cmake_modules/cmake/Modules/FindEigen.cmake:62 (message):
  The FindEigen.cmake Module in the cmake_modules package is deprecated.

  Please use the FindEigen3.cmake Module provided with Eigen.  Change
  instances of find_package(Eigen) to find_package(Eigen3).  Check the
  FindEigen3.cmake Module for the resulting CMake variable names.

Call Stack (most recent call first):
  asctec_mav_framework-master/asctec_hl_gps/CMakeLists.txt:7 (find_package)

-- Found Eigen: /usr/include/eigen3
-- Eigen found (include: /usr/include/eigen3)
CMake Warning at /opt/ros/kinetic/share/catkin/cmake/catkin_package.cmake:166 (message):
  catkin_package() DEPENDS on 'eigen' but neither 'eigen_INCLUDE_DIRS' nor
  'eigen_LIBRARIES' is defined.
Call Stack (most recent call first):
  /opt/ros/kinetic/share/catkin/cmake/catkin_package.cmake:102 (_catkin_package)
  asctec_mav_framework-master/asctec_hl_gps/CMakeLists.txt:21 (catkin_package)

-- +++ processing catkin package: 'asctec_hl_interface'
-- ==> add_subdirectory(asctec_mav_framework-master/asctec_hl_interface)
-- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy
-- Boost version: 1.58.0
-- Found the following Boost libraries:
--   signals
--   system
--   thread
--   chrono
--   date_time
--   atomic
-- +++ processing catkin package: 'msf_core'
-- ==> add_subdirectory(ethzasl_msf/msf_core)
-- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy
CMake Warning at /opt/ros/kinetic/share/cmake_modules/cmake/Modules/FindEigen.cmake:62 (message):
  The FindEigen.cmake Module in the cmake_modules package is deprecated.

  Please use the FindEigen3.cmake Module provided with Eigen.  Change
  instances of find_package(Eigen) to find_package(Eigen3).  Check the
  FindEigen3.cmake Module for the resulting CMake variable names.

Call Stack (most recent call first):
  ethzasl_msf/msf_core/CMakeLists.txt:18 (find_package)

-- Eigen found (include: /usr/include/eigen3)
-- Could NOT find Doxygen (missing:  DOXYGEN_EXECUTABLE)
CMake Warning at /opt/ros/kinetic/share/catkin/cmake/catkin_package.cmake:166 (message):
  catkin_package() DEPENDS on 'eigen' but neither 'eigen_INCLUDE_DIRS' nor
  'eigen_LIBRARIES' is defined.
Call Stack (most recent call first):
  /opt/ros/kinetic/share/catkin/cmake/catkin_package.cmake:102 (_catkin_package)
  ethzasl_msf/msf_core/CMakeLists.txt:44 (catkin_package)

CMake Error at /opt/ros/kinetic/share/catkin/cmake/test/gtest.cmake:169 (add_executable):
  add_executable cannot create target "test_similaritytransform" because
  another target with the same name already exists.  The existing target is
  an executable created in source directory
  "/home/yukti/catkin_ws/src/ethzasl_msf/msf_core".  See documentation for
  policy CMP0002 for more details.
Call Stack (most recent call first):
  /opt/ros/kinetic/share/catkin/cmake/test/gtest.cmake:79 (_catkin_add_executable_with_google_test)
  /opt/ros/kinetic/share/catkin/cmake/test/gtest.cmake:28 (_catkin_add_google_test)
  ethzasl_msf/msf_core/CMakeLists.txt:78 (catkin_add_gtest)

CMake Error at /opt/ros/kinetic/share/catkin/cmake/test/gtest.cmake:169 (add_executable):
  add_executable cannot create target "test_static_statelist" because another
  target with the same name already exists.  The existing target is an
  executable created in source directory
  "/home/yukti/catkin_ws/src/ethzasl_msf/msf_core".  See documentation for
  policy CMP0002 for more details.
Call Stack (most recent call first):
  /opt/ros/kinetic/share/catkin/cmake/test/gtest.cmake:79 (_catkin_add_executable_with_google_test)
  /opt/ros/kinetic/share/catkin/cmake/test/gtest.cmake:28 (_catkin_add_google_test)
  ethzasl_msf/msf_core/CMakeLists.txt:80 (catkin_add_gtest)

-- +++ processing catkin package: 'msf_distort'
-- ==> add_subdirectory(ethzasl_msf/msf_distort)
-- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy
-- +++ processing catkin package: 'msf_updates'
-- ==> add_subdirectory(ethzasl_msf/msf_updates)
-- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy
-- Configuring incomplete, errors occurred!
See also "/home/yukti/catkin_ws/build/CMakeFiles/CMakeOutput.log".
See also "/home/yukti/catkin_ws/build/CMakeFiles/CMakeError.log".
Invoking "cmake" failed

A: You don't have the right CMake files unfortunately and the admins of the repo do not seem very interested in maintaining it.
However, this pull request contains the necessary CMakeLists to launch pose_sensor
https://github.com/ethz-asl/ethzasl_msf/pull/141/files
Specifically, here is the diff that you need
https://github.com/ethz-asl/ethzasl_msf/pull/141/files#diff-a855f8508d144ac9c52a05344bfeba5cR7
install(TARGETS
    pose_sensor
    DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
    LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
)

in this file https://github.com/ethz-asl/ethzasl_msf/blob/20a4a61e1a8a1051bc752203e3b4f17795c0264d/msf_updates/src/pose_msf/CMakeLists.txt


text:
Q: Define checkbox true-value and false-value to a non-string value (other primitives, object, or expression) I can't set my v-model value to anything other than a string when the corresponding checkbox is checked/unchecked.
https://jsbin.com/haqofus/edit?html,console,output

<input type="checkbox" v-model="checkbox" true-value="null" false-value="new Date()" @change="log(checkbox)">checkbox

<input type="checkbox" v-model="checkbox2" true-value=null false-value='{ "prop": "value" }' @change="log(checkbox2)">checkbox2

<input type="checkbox" v-model="checkbox3" true-value="methodReturningNewDate" false-value="methodReturningObject" @change="log(checkbox3)">checkbox3

app = new Vue({
  el: "#app",
  data: {
    checkbox: "init",
    checkbox2: "init2",
    checkbox3: "init3"
  },
  methods: {
    log: function (message) {
      console.log(message);
    },
    methodReturningNewDate: function () {
      return new Date();
    },
    methodReturningObject: function () {
      return { "prop": "value" };
    }
  }
})

A: You need to bind the values or else they are evaluated as strings,  i.e. :false-value="new Date()"

new Vue({
  el: "#app",
  data: {
    checkbox: "init",
    checkbox2: "init2",
    foo: {
      a: 1,
    },
  },
  methods: {
    log: function (message) {
      console.log(message);
    }
  }
})

    <input type="checkbox" v-model="checkbox" true-value="null" :false-value="new Date()" @change="log(checkbox)">checkbox
    <input type="checkbox" v-model="checkbox2" true-value=null :false-value="foo" @change="log(checkbox2)">checkbox2


text:
Q: Does "capitalistic enterprise" mean capitalism in this sentence? The question is simple. In the following sentence, can I replace "capitalistic enterprise" with "capitalism" without any change in meaning?

Capitalistic enterprise involves a ruthless belief in the importance of increasing material production to the utmost possible extent now and in the immediate future.

Definitions of "enterprise" in Concise Oxford English Dictionary are:

*

*a project or undertaking, especially a bold one. ▶bold resourcefulness.

*a business or company
Which meaning is used in the above sentence?

A: 'Capitalism' is a more passive word - meaning 'the entirety of the world that is involved in enterprise, commerce, or business'.
'Capitalistic enterprise' refers to the actions taken by enterprises, to generate money. This phrase works better with what the author is saying in this sentence - because he goes on to explain what that action actually is.
If you put purely 'Capitalism' - which is a general concept, not necessarily an activity at that moment - then the sentence becomes rather pallid and somewhat loses its meaning and drive.
So yes - it does make a difference, and a negative one.

A: "... can I replace "capitalistic enterprise" with "capitalism" without any change in meaning?" No.
The intention of the author is to distinguish between the organization's type and its nature. The adjective capitalistic refers to the mindset/ belief/ approach rather than the corporate structure. The use of capitalistic here is intentional.

A: In your statement, with the term Capitalist enterprise, you're specifically referring to the intending process of 'increasing material production'.  Capitalism denotes not just the process at play, but the subsequent results that have stemmed, will stem, or are stemming, from its undertaking.

A: Capitalism could be substituted in this quotation for "capitalistic enterprise."  Note, however, that Bertrand Russell's definition of capitalism is from 1917; and most capitalistic enterprises today are services rather than manufacturing enterprises.
A comment mentions that "all capitalistic enterprises aspire to be monopolies", which is pure speculation about the intent of those who form them.  Capitalism is defined by the English Oxford Living Dictionaries as:

An economic and political system in which a country's trade and
  industry are controlled y private owners for profit, rather than by
  the state. 'an era of free-market capitalism' 'private ownership is a
  key feature of capitalism'

The reference to OPEC in comments is a red herring, as OPEC is the Organization of Petroleum Exporting Countries, which are about as far as you can get from private enterprises.


text:
Q: React this.setState doesnt rerender content I am writing simple application which need to rerender specified content.
My ideas about resolving the issue was to provide initializing data in constructor because something breaks react structure?But maybe helpful might be a tip how to map two dimensional  array in render method. Propably here is the problem?
function Pool(props) {
        return(
            <p className={`${props.row}`}>

        );
}

export default class Board extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            mainArray: [],
         };
    }

    createBoard() {
    let children=[];
    let array=[];
        for(let i=0;i<20;i++){
            children=[];
            for(let j=0;j<20;j++){
                children.push(<Pool key={`${i}${j}`} row={`${square1}`}/>);
            }
        array.push(<div key={`${i}`}>{children}
);
        }
    this.state.mainArray=array;
    return this.state.mainArray;
    }

    startGame = () => {
        let array1=[];
        array1=this.state.mainArray.slice;
        let i=6;
        for(let j in array1[6]){
            array1[6][j]=<Pool key={`${i}${j}`} row={`${square2}`}/>;
        }
        this.setState({mainArray: array1});

    }

    render() {
        return (

            {this.createBoard()}
            <button onClick={this.startGame}>Start the game!</button>

        );
    }
}

I am trying to change the colour of the sixth row for example.Regards

A: This is incorrect:
        let array1=[];
        array1=this.state.mainArray.slice;

mainArray.slice() is a copy, but mainArray.slice is a function.
Instead, begin with
        let array1 = this.state.mainArray.slice();


text:
Q: MYSQL: mysqldump returns empty after import I need some help, why is it that after importing an mysqldump (table) at first you can see result, but when you exit
 mysql -uroot -proot

and select again the table then check, it returns empty.

A: first connect mysql by below command-
mysql -uroot -proot

Note: assuming root is password of root user.
Now connect to database in which you imported table-
use my_db;

Now check your table by-
show tables;
or
show tables like 'my_table'

If still getting error then show how you import data and show first few lines of your backup if possible.

A: Or start mysql command shell using:
>mysql -u youruser -p yourdatabase

and then check up your table.
mysql>select * from yourtable;

P.S If you didn't choose any database you get appropriate error 1046:
 No database selected.

If you don't get such error message and see you table empty YOU CHOSE WRONG DATABASE.


text:
Q: App closes after intent activity change - Kotlin I have an image gallery on a Fragment and I want to create a program that, once the user clicks on a certain image, the program redirects the user to an Activity where more details are presented. However, after implementing the Intent, the program just crashes when the Activity opens.
I don't know what I might be doing wrong as I do not have much experience with fragments (I believe it is something I'm doing wrong in the fragment intent)
Here's the code:
Fragment
package cm.a12872_a18797.favlist.fragments

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import cm.a12872_a18797.favlist.ImageDetailActivity
import cm.a12872_a18797.favlist.Modal
import cm.a12872_a18797.favlist.R

class HomeFragment : Fragment() {

    lateinit var rootView: View

    public val modalList = ArrayList<Modal>()

    lateinit var gridView: GridView

    private var descriptions = arrayOf(
        "Golden Bridge", "Tampa Bay Buccaneers", "Chevrolet Camaro",
        "Vegetable Casserole", "Sweet and Sour Chicken", "Design Vector",
        "Pork Loin", "Sidney's Opera House", "Pasta Dish",
        "Dope Setup", "Singapore", "Tacos Dish",
        "Toquio", "Warm Salad Dish"
    )
    private var images = intArrayOf(
        R.drawable.bridge, R.drawable.buccaneers, R.drawable.camaro,
        R.drawable.casserole, R.drawable.chicken, R.drawable.design,
        R.drawable.lombo, R.drawable.operahouse, R.drawable.pasta,
        R.drawable.setup, R.drawable.singapore, R.drawable.tacos,
        R.drawable.toquio, R.drawable.warmsalad
    )

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        rootView = inflater.inflate(R.layout.fragment_home, container, false)

        gridView = rootView.findViewById(R.id.home_grid)

        for (i in descriptions.indices){
            modalList.add(Modal(descriptions[i], images[i]))
        }

        var customAdapter = GridAdapter(modalList, this@HomeFragment.requireContext())
        gridView.adapter = customAdapter

        gridView.setOnItemClickListener() { adapterView, view, position, l ->
            var intent = Intent(this@HomeFragment.requireContext(), ImageDetailActivity::class.java)
            intent.putExtra("data", modalList[position])
            startActivity(intent)
        }

        return rootView
    }

    class GridAdapter(var itemModel : ArrayList<Modal>, var context: Context): BaseAdapter(){

        var layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
            var view = convertView

            if (view == null){
                view = layoutInflater.inflate(R.layout.home_grid_row, parent, false)
            }

            var imageViewName = view?.findViewById<ImageView>(R.id.grid_image)
            imageViewName?.setImageResource(itemModel[position].image!!)

            return view!!
        }

        override fun getItem(position: Int): Any {
            return itemModel[position]
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getCount(): Int {
            return itemModel.size
        }

    }
}

Activity:
package cm.a12872_a18797.favlist

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import cm.a12872_a18797.favlist.fragments.HomeFragment
import cm.a12872_a18797.favlist.fragments.ListsFragment
import cm.a12872_a18797.favlist.fragments.SearchFragment
import com.google.android.material.bottomnavigation.BottomNavigationView

class ImageDetailActivity : AppCompatActivity() {

    val TAG = "ImageDetailActivity"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_image_detail)

        //region Bottom Navigation Menu =====================================

        val bottomNavigation: BottomNavigationView = findViewById(R.id.bottom_navigation)

        val homeFragment = HomeFragment()
        val listsFragment = ListsFragment()
        val searchFragment = SearchFragment()

        bottomNavigation.setOnNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.nav_home -> {
                    setCurrentFragment(homeFragment)
                    Log.i(TAG, "Home Selected")
                }
                R.id.nav_lists -> {
                    setCurrentFragment(listsFragment)
                    Log.i(TAG, "My Lists Selected")
                }
                R.id.nav_search -> {
                    setCurrentFragment(searchFragment)
                    Log.i(TAG, "Search Selected")
                }
            }
            true
        }

        //endregion ==

        val detailText = findViewById<TextView>(R.id.detailText)
        val detailImage = findViewById<ImageView>(R.id.detailImage)

        var modalItems: Modal = intent.getSerializableExtra("data") as Modal

        detailText.text = modalItems.name
        detailImage.setImageResource(modalItems.image!!)
    }

    private fun setCurrentFragment(fragment : Fragment) =
        supportFragmentManager.beginTransaction().apply {
            replace(R.id.fl_wrapper, fragment)
            commit()
        }
}

Modal Class:
package cm.a12872_a18797.favlist

import java.io.Serializable

class Modal : Serializable {

    var name:String? = null
    var image:Int? = null

    constructor(name:String, image:Int){
        this.name = name
        this.image = image
    }
}


text:
Q: Python scientific notation - Convert D to E I have a text file with a lot of values that are in scientific notation. However, instead of writing the scientific notations in terms of E (i.e. 2.0E-05), it is written in terms of D (i.e. 2.0D-05).
LATI    LONGI   AREA    CO2
   -0.5548999786D+01        0.3167600060D+02        0.1000000000D+07        0.1375607300D+08
   -0.1823500061D+02        0.3668500137D+02        0.1000000000D+07        0.6878036500D+07
   -0.6650000215D+00        0.2960499954D+02        0.7500000000D+06        0.5086381000D+07
   -0.9671999931D+01        0.2264999962D+02        0.1000000000D+07        0.2657306000D+08
   -0.1321700001D+02        0.4895299911D+02        0.6893938750D+06        0.8595105000D+07
   -0.1152099991D+02        0.2493499947D+02        0.1000000000D+07        0.2615907200D+08

How can I replace all the D's with E's?
Based on another stackoverflow answer, I wrote the following loop, but it's very slow and there is probably an easier way.
for ind in range(len(df_fires.LATI)):
    val = df_fires.LATI[ind]
    df_fires.LATI[ind] = float(val.replace('D','E'))

    val = df_fires.LONGI[ind]
    df_fires.LONGI[ind] = float(val.replace('D','E'))

Example file: https://www.dropbox.com/s/5glujwqux6d0msh/test.txt?dl=0

A: Try sed to replace all D's with E's in the file. Do this before parsing the file with python.
sed -e 's:D:E:g' test.txt >> test_new.txt
If you want to keep this in python, try this solution https://stackoverflow.com/a/11332274/5196039

A: You can use apply to apply your function to every element in the your column.
Not sure if it will be faster as I only have a small dataset but is definitely less code:
import pandas as pd

columns = ['LATI', 'LONGI', 'AREA', 'CO2']
data = [['-0.5548999786D+01', '0.3167600060D+02', '0.1000000000D+07', '0.1375607300D+08'],
['-0.1823500061D+02', '0.3668500137D+02', '0.1000000000D+07', '0.6878036500D+07'],
['-0.6650000215D+00', '0.2960499954D+02',  '0.7500000000D+06', '0.5086381000D+07'],
['-0.9671999931D+01', '0.2264999962D+02', '0.1000000000D+07',  '0.2657306000D+08'],
['-0.1321700001D+02', '0.4895299911D+02', '0.6893938750D+06', '0.8595105000D+07'],
['-0.1152099991D+02',  '0.2493499947D+02', '0.1000000000D+07', '0.2615907200D+08']]

df = pd.DataFrame(columns=columns, data=data)
for column_name in columns:
    df[column_name] = df[column_name].apply(lambda x: x.replace('D', 'E'))

Output from df:
                LATI        ...                      CO2
0  -0.5548999786E+01        ...         0.1375607300E+08
1  -0.1823500061E+02        ...         0.6878036500E+07
2  -0.6650000215E+00        ...         0.5086381000E+07
3  -0.9671999931E+01        ...         0.2657306000E+08
4  -0.1321700001E+02        ...         0.8595105000E+07
5  -0.1152099991E+02        ...         0.2615907200E+08


text:
Q: how to create a simple python web serivce, that would run locally and handle parallel requests So, as the header indicates, im trying to understand what is the most simple way to create a rest api web service, that would run locally on my pc, and would be able to handle requests in parallel (just using my several local cores).
I was checking out flask, but im not sure that's the right option. i know by default it runs with a single instance, and it has an option of using a "process" param, which doesnt work for me and seem not to be the solution.
im looking for something simple, but couldnt find anything.
all i want to be able to do, is be able to receive REST requests and handle them in parallel using a process pool for example.
note: I'm using windows. so gunicorn isn't an option i think


text:
Q: Loading Cell Option Definitions on Kernel Launch for Stylesheets I have my own stylesheet that I like using so much I change all my documents to it almost immediately, but as I demo Mathematica to people I cannot use DefaultStyleDefinitions as it unnecessarily confuses people. I therefore have a function (typed verbatim, not loaded) in my init.m file that pastes the definitions from a stylesheet into the EvaluationNotebook[]
BeginPackage["PasteStyles`"]
pasteStyleSheet::usage="pasteStyleSheet[stylesheet, \"Admin\"] pastes the style definitions provided by stylesheet located in $BaseDirectory (etc)"; Begin["`Private`"]
pasteStyleSheet[stylesheet_String,"Admin"]:=SetOptions[EvaluationNotebook[],StyleDefinitions->Get[FileNameJoin[{$BaseDirectory,"FrontEnd","StyleSheets",stylesheet<>".nb"}]]]
pasteStyleSheet[stylesheet_String,"User"]:=SetOptions[EvaluationNotebook[],StyleDefinitions->Get[FileNameJoin[{$UserBaseDirectory,"FrontEnd","StyleSheets",stylesheet<>".nb"}]]]
pasteStyleSheet[stylesheet_String,"System"]:=SetOptions[EvaluationNotebook[],StyleDefinitions->Get[FileNameJoin[{$InstallationDirectory,"SystemFiles","FrontEnd","StyleSheets",stylesheet<>".nb"}]]]
End[]
EndPackage[]

I have an issue in that I use options for cells such as WholeCellGroupOpener and ReturnCreatesNewCell that Mathematica doesn't seem to know anything about when my function is evaluated. I found this out because I used to find $CellContext throughout my pasted style definitions.
Currently, I have shoved the following lines into the package to make sure it works.
System`WholeCellGroupOpener;
System`ReturnCreatesNewCell;

My questions are:

*

*Why do I get $CellContext for some functions that should be on `System?

*How do I ensure my function works as intended? Does it need to live somewhere else?

Justifications:

*

*I need to paste the styles, as I email the notebooks out.

*I spend most of my time making fun things in the front end, I'm expecting this stylesheet to eventually become something that no one else will ever want to use.


text:
Q: how to calculate control points on a bezier curve? I do have a bezier curve, and at a certain point, I want a second bezier curve "branching off" the first curve in a smooth manner. Together with calculating the intersection point (with a percentage following the Bezier curve), I need also the control point (the tangent and weight).
The intersection point is calculated with the following piece of javascript:
getBezier = function getBez(percent,p1,cp1,cp2,p2) {
    function b1(t) { return t*t*t }
    function b2(t) { return 3*t*t*(1-t) }
    function b3(t) { return 3*t*(1-t)*(1-t) }
    function b4(t) { return (1-t)*(1-t)*(1-t) }
    var pos = {x:0,y:0};
    pos.x = p1.x*b1(percent) + cp1.x*b2(percent) + cp2.x*b3(percent) + p2.x*b4(percent);
    pos.y = p1.y*b1(percent) + cp1.y*b2(percent) + cp2.y*b3(percent) + p2.y*b4(percent);
    return pos;
}

(Non IE browsers can see it in action at http://www.iscriptdesign.com -> Tutorial -> Groups & Paths).
All I need now is the controlpoint or (tangent and weight) for the branchpoint ( I don't have a clue where to start, and I hope somebody can point to some code, or mathematical equation, if possible as function from the same parameters as the getBezier function above).

A: Found and implemented it: de-Casteljau algorithm turned out to be the fastest implementable solution. It is currently present under:
iScriptDesign (Tutorial ->Spit Bezier).

A: Example usage (I think, i need help from @drjerry)
I have a css3 timing function, this is called ease-in-out: cubic-bezier(.42,0,.58,1). Graphically this looks like: http://cubic-bezier.com/#.42,0,.58,1
I want to make a new timing function that is just the bottom half and then top half of this graph.
So the bottom half is ease-in: cubic-bezier(.42,0,1,1). Graphically: http://cubic-bezier.com/#.42,0,1,1
And the top half is ease-out: cubic-bezier(0,0,.58,1). Graphically: http://cubic-bezier.com/#0,0,.58,1
So now what confuses me is that according to the script at iScriptDesign it tells me they are different.
iScriptDeisgn says the starting half of ease-in-out is (which is ease-in) is: cubic-bezier(.21, 0, .355, .25). Graphically: http://cubic-bezier.com/#.21,0,.35,.25
iScriptDeisgn says the ending half of ease-in-out is (which is ease-out) is: cubic-bezier(.145, .25, .29, .5). Graphically: http://cubic-bezier.com/#.14,.25,.29,.5
Why is the ease-in and ease-out returned by the iScriptDesign split function different from the real ease-in and real ease-out? I don't get it.
Code for this example.
//////////////////START FROM ISCRIPTDESIGN
var splitBezier = function(array, perc) {
    array.unshift({x:0, y:0});
    var coll = [];
    while (array.length > 0) {
    for (var i = 0;i < array.length-1; i++) {
        coll.unshift(array[i]);
        array[i] = interpolate(array[i], array[i+1], perc);
    }
    coll.unshift(array.pop());
    }
    return {b1: [{x:coll[5].x, y:coll[5].y}, {x:coll[2].x, y:coll[2].y},{x:coll[0].x, y:coll[0].y}]
        , b2: [{x:coll[1].x - coll[0].x,y:coll[1].y-coll[0].y}, {x:coll[3].x - coll[0].x,y:coll[3].y-coll[0].y}, {x:coll[6].x - coll[0].x,y:coll[6].y-coll[0].y}]};
}

var interpolate = function (p0, p1, percent) {
    if (typeof percent === 'undefined') percent = 0.5;
    return  {x: p0.x + (p1.x - p0.x) * percent
         , y: p0.y + (p1.y - p0.y) * percent};
}
//////////////////END FROM ISCRIPTDESIGN
var coord = function (x,y) {
  if(!x) var x=0;
  if(!y) var y=0;
  return {x: x, y: y};
}
var easeInOut = [new coord(.42,0), new coord(.58,1), new coord(1,1)];
var split50percent = splitBezier(easeInOut.slice(), .5);

So split50percent is set to:
({
    b1: [{
        x: 0.21,
        y: 0
    }, {
        x: 0.355,
        y: 0.25
    }, {
        x: 0.5,
        y: 0.5
    }],
    b2: [{
        x: 0.14500000000000002,
        y: 0.25
    }, {
        x: 0.29000000000000004,
        y: 0.5
    }, {
        x: 0.5,
        y: 0.5
    }]
})

Same thing with easeInOutSine

*

*easeInOutSine:.44,.05,.55,.95

*REAL

*

*easeInSine:0.47, 0, 0.745, 0.715

*easeOutSine:0.39, 0.575, 0.565, 1

*iScriptDesign

*

*easeInSine:.22,.03,.36,.26

*easeOutSine:.14,.24,.28,.48


text:
Q: Why class .setTexure() method behaves differently? sfml sprite class .setTexure() method doesnt work inside of constructor for iterator, but does work when iterator is already made
We're trying to construct structure for frames that are being drawn onto the window. We're using sfml library, with their sprite and texture classes. In the constructor for the frameData structure we load a texture from file then apply it to the sprite using the .setTexture() method. We either get white block or a program crash depending on the machine when we compile and run our program.
If we create do a pointer reference to texture with .setTexture() outside the constructor for frameData, it works!
All if this is with an iterator structure that iterates through the different frames. Here is the relevant code, First this is in the header for the FrameData struct:
private:
    struct FrameData
    {
        FrameData(const std::string& fileName, int frameDelay);

        sf::Texture texture;
        sf::Sprite sprite;
        unsigned int frameDelay;
    };

Second, here are the actual constructors, not working:
const sf::Sprite& SpriteAnimator::currentFrame() const
{
    return currentFrame_->sprite;
}

SpriteAnimator::FrameData::FrameData(const std::string& fileName, int frameDelay)
: frameDelay(frameDelay)
{
    texture.loadFromFile(fileName);
    sprite.setTexture(texture);
}

And thirdly, here is what does work:
const sf::Sprite& SpriteAnimator::currentFrame() const
{
    currentFrame_->sprite.setTexture(currentFrame_->texture);
    return currentFrame_->sprite;
}

SpriteAnimator::FrameData::FrameData(const std::string& fileName, int frameDelay)
: frameDelay(frameDelay)
{
    texture.loadFromFile(fileName);
    sprite.setTexture(texture);
}

Any ideas about why this happens, are we missing something? We want to have the constructor work properly, the current frame is returned a lot more frequently than the texture changing, so we don't need to update the texture every time the current frame is returned.
Thank you!

A: SOLVED! Read last paragraph of the class documentation for sf::sprite:

It is important to note that the sf::Sprite instance doesn't copy the
  texture that it uses, it only keeps a reference to it. Thus, a
  sf::Texture must not be destroyed while it is used by a sf::Sprite
  (i.e. never write a function that uses a local sf::Texture instance
  for creating a sprite).

So creating a repository for textures outside of the scope of this class, then passing references works, like strongdrink recommended!

A: I had a similar problem with this. My solution was to store all of my textures in a container outside of the class and use a pointer to the texture instead of the texture itself. This kills 2 birds with one stone because you don't have to store more than 1 of the same texture if you are going to create another object from the class.


text:
Q: Configuring ui-grid using webpack I am new to Webpack and node. Need help in configuring ui-grid.
I wanted to bundle angular using webpack, So I installed angular using npm and after installing I could see index.js file inside angular folder in node_modules, which actually export angular module. To include angular module I include following line in entry file of webpack.
const angular = require('angular');
And it works fine. Now I am trying to do same thing for ui-grid but I could not find index.js file there which actually imports ui-grid module.
Please provide pointers about how to include ui-grid and what is the concept of index.js.


text:
Q: Remove all occurrences of strings from list Someone please tell me there is a cleaner way to write this!? I want to remove all instances of 'Features & Benefits'. There must be a cleaner way to do this for strings in a list.
lov_headers = [x.find('displayname').text for x in soup.find_all('attributedefinition')]

if 'Part number' in lov_headers:
    lov_headers.remove('Part number')
if 'Product Features' in lov_headers:
    lov_headers.remove('Product Features')
if 'Packaging' in lov_headers:
    lov_headers.remove('Packaging')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')

A: Put what you want to remove into a set(), then use a list comprehension to filter out the results that you don't want:
to_remove = set(['Part number', 'Features & Benefits', 'Product Features', 'Packaging'])

new_list = [i for i in lov_headers if i not in to_remove]

A: You can use a while loop:
while 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')


text:
Q: Many files "missing from working copy" in Release-iphonesimulator I'm having trouble with a whole bunch of warnings about missing files since upgrading to Swift 3 in Xcode 8.1. I've attached an image with a sample of the errors. There are about 40 of them in total.
All refer to files missing from MyApp/build/MyApp.build/Release-iphonesimulator/MyApp.build/Objects-normal/x86-64/.... None of them are files which I would not have touched or edited.

I have cleaned and rebuilt, cleaned build folder, deleted all derived data, and a few other things, all with no luck. The app compiles and runs, but has this stack of warnings I can't get rid of.
I also double checked my Release Search Path in Build Settings. Here is what I have it set to:

These have me stumped. Any suggestions appreciated.

A: I finally solved this. It WAS version control related. I had tried committing and resetting status, with no luck. However, when I tried a Pull, it said I had uncommitted changes, even though I had just committed. Therefore, I tried Discard All Changes, and that solved it. Did a clean and build and the warnings are now gone.


text:
Q: how to sort a dictionary with specified 2 keys I am trying to sort a dictionary in python, let's say I have {'c' : 1, 'b' : 3, 'g' : 3, 'a' : 1}
The first thing I would like to do is to sort the dict descending from the highest value.
Then, if I have keys with the same value, I would like to order the keys with the exact value ascending
lexicographically. The result should be like that:
{'b' : 3, 'g' : 3, 'a' : 1, 'c' : 1}
Also, How can I get the first key after I sorted the dictionary?
I did this.
enter image description here
However, I would like a better and shorter way.
Thanks


text:
Q: Get string value from Bokeh Multiselect My goal here was to create a Bokeh widgetbox which you could use to provide input to a form, however the only widgets that allow me to get my inputs back from Bokeh's javascript side into Python variables are RadioButtonGroups. Otherwise, Multiselect, AutocompleteInput, and others are ONLY able to return my input if it's in the form of an integer. This is being done in a Jupyter NB using Python and Bokeh 0.13.0, if you happen to have any questions or I've left anything out please don't hesitate to let me know.
Please see code below:
import os, time, sys
from bokeh.layouts import widgetbox
from bokeh.models.widgets import RadioButtonGroup, Button, TextInput
from bokeh.models.widgets.inputs import MultiSelect
from bokeh.models.widgets import AutocompleteInput
from bokeh.models.callbacks import CustomJS
from bokeh.io import output_notebook, show
from bokeh.models import ColumnDataSource
from bokeh.models.widgets.markups import Div
from bokeh.resources import INLINE
output_notebook(resources=INLINE)

ipies=[str(i.strip('.ipynb')) for i in os.listdir() if i.endswith('.ipynb')]
minutes=0
hours=0
days=0
months=0
daysmonth=0
days=0

minute_options=[str(i) for i in range(1,60)]
minute_options.append("*")
minute_callback = CustomJS(args=dict(a=minute_options), code="""
    var options=a;
    console.log(options[parseInt(cb_obj.active)]);
    var ind=options[parseInt(cb_obj.active)];
    IPython.notebook.kernel.execute('minutes='+ind+'');
""")
minute_rbg = RadioButtonGroup(
        labels=minute_options, callback=minute_callback, active=len(minute_options)-1)
min_title=Div(text="Which minute on the hour, * for every minute")

hour_options=[str(i) for i in range(24)]
hour_options.append("*")
hour_callback = CustomJS(args=dict(a=hour_options), code="""
    var options=a;
    console.log(options[parseInt(cb_obj.active)]);
    var ind=options[parseInt(cb_obj.active)];
    IPython.notebook.kernel.execute('hours='+ind+'');
""")
hour_rbg = RadioButtonGroup(
        labels=hour_options,callback=hour_callback,active=len(hour_options)-1)
hour_title=Div(text="Which hour in a day, * for every hour")

day_month_options=[str(i) for i in range(1,32)]
day_month_options.append("*")
day_month_callback = CustomJS(args=dict(a=day_month_options), code="""
    var options=a;
    console.log(options[parseInt(cb_obj.active)]);
    var ind=options[parseInt(cb_obj.active)];
    IPython.notebook.kernel.execute('daysmonth='+ind+'');
""")
day_month_rbg = RadioButtonGroup(
        labels=day_month_options,callback=day_month_callback,active=len(day_month_options)-1)
day_month_title=Div(text="Which day in a month, * for every day of the month")

month_options=[str(i) for i in range(1,13)]
month_options.append("*")
month_callback = CustomJS(args=dict(a=month_options), code="""
    var options=a;
    console.log(options[parseInt(cb_obj.active)]);
    var ind=options[parseInt(cb_obj.active)];
    IPython.notebook.kernel.execute('months='+ind+'');
""")
month_rbg = RadioButtonGroup(
        labels=month_options, callback=month_callback,active=len(month_options)-1)
month_title=Div(text="Which month in a year, * for every month")

day_week_options=[str(i) for i in range(7)]
day_week_options.append("*")
day_week_callback = CustomJS(args=dict(a=day_week_options), code="""
    var options=a;
    console.log(options[parseInt(cb_obj.active)]);
    var ind=options[parseInt(cb_obj.active)];
    IPython.notebook.kernel.execute('days='+ind+'');
""")
day_week_rbg = RadioButtonGroup(
        labels=day_week_options, callback=day_week_callback, active=len(day_week_options)-1)
days_week_title=Div(text="Which day in a week, * for every day of the week")
import pandas as pd
ipies_pd = pd.DataFrame({"a":ipies})
#Selection source: IPIES CDS
cds = ColumnDataSource(data=ipies_pd)

#Selection source: autocompleteinput & multiselect widgets
selection_callback = CustomJS(args=dict(source=cds), code="""
    // THIS CALLBACK ONLY BRINGS BACK SELECTIONS IF THEY ARE INTEGERS
    var cbobj = cb_obj.value;
    IPython.notebook.kernel.execute("auto_c_value = "\"+ cbobj + "\");
    """)
ms = MultiSelect(title="power", callback=selection_callback, options=ipies)
auto_c=AutocompleteInput(completions=ipies, height=100, callback=selection_callback)

button_callback = CustomJS(code="""
    var cur_index = IPython.notebook.get_selected_index()+1;
    var end_index=IPython.notebook.ncells();
    IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index()+1, IPython.notebook.ncells());
""")
button = Button(label="button~!", button_type="primary", callback=button_callback)

w_box = widgetbox(min_title, minute_rbg, hour_title, hour_rbg, day_month_title, day_month_rbg,
                 month_title, month_rbg,days_week_title, day_week_rbg, button,
                  ms, auto_c, width=800, sizing_mode='scale_both')

show(w_box)


text:
Q: turn on/off sound globally in cocos2d app I have used a singleton class and using in all the classes to turn app sound on/off. Problem is when I change the screen the sound turns on even if it was Muted. I call sound method in init of every class, so it turns on. But if I don't call from init it never starts. I am messed up.
Following is what I have used
//SingletonClass.m
+(SingletonClass*)sharedMySingleton
{
 .....
}
+(id)alloc{
 ......
}

-(id)init{
    self = [super init];
         if (self != nil) {
             // initialize stuff here
             is_sound_enable = TRUE;
    //         [[SimpleAudioEngine sharedEngine] setMute:NO];
             [[SimpleAudioEngine sharedEngine] resumeBackgroundMusic];
            }
      return self;
}

-(void)setsound{
    if(is_sound_enable == TRUE){
//       [[SimpleAudioEngine sharedEngine] setMute:NO]; //this is not working when called again
        [[SimpleAudioEngine sharedEngine] resumeBackgroundMusic];
//        is_sound_enable = FALSE;
    }
    else{
//        [[SimpleAudioEngine sharedEngine] setMute:YES]; // this is not working when called again
        [[SimpleAudioEngine sharedEngine] pauseBackgroundMusic];
//        is_sound_enable = TRUE;
    }

    if(is_sound_enable == TRUE){
        is_sound_enable = FALSE;
    }
    else{
        is_sound_enable = TRUE;
    }
}

//MyClass.m
-(void)toggleSoound{
[[SingletonClass sharedMySingleton] setsound];
}

A: Create SingletonClass.h file as follows
#import <Foundation/Foundation.h>
#import "AVFoundation/AVFoundation.h"

@interface SingletonClass : NSObject
{
    BOOL is_sound_enable;
    AVAudioPlayer *audioPlayer;
}

@property (nonatomic,assign) BOOL is_sound_enable;
@property (nonatomic,retain) AVAudioPlayer *audioPlayer;

+ (SingletonClass *)sharedInstance;
-(void)checkAndPlayMusic;
-(void)loadNewFile:(NSURL*)newFileURL;

@end

Create SingletonClass.m file as follows
#import "SingletonClass.h"

@implementation SingletonClass

@synthesize is_sound_enable;
@synthesize audioPlayer;

#pragma mark -
#pragma mark Singleton Variables
static SingletonClass *singletonHelper = nil;

#pragma mark -
#pragma mark Singleton Methods
- (id)init {
    if ((self = [super init])) {
        is_sound_enable = YES;
        NSString *strPath = @""; //<-- Assign path here
        NSURL *url = [NSURL URLWithString:strPath];
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        [audioPlayer prepareToPlay];
        audioPlayer.numberOfLoops = -1; //<-- This will set it to infinite playing.
    }

    return self;
}
+ (SingletonClass *)sharedInstance {
    @synchronized(self) {
        if (singletonHelper == nil) {
            [[self alloc] init]; // assignment not done here
        }
    }
    return singletonHelper;
}
+ (id)allocWithZone:(NSZone *)zone {
    @synchronized(self) {
        if (singletonHelper == nil) {
            singletonHelper = [super allocWithZone:zone];
            // assignment and return on first allocation
            return singletonHelper;
        }
    }
    // on subsequent allocation attempts return nil
    return nil;
}
- (id)copyWithZone:(NSZone *)zone {
    return self;
}
- (id)retain {
    return self;
}
- (unsigned)retainCount {
    return UINT_MAX;  // denotes an object that cannot be released
}
//- (void)release {
- (void)dealloc {
    [audioPlayer release];
    [super dealloc];
}
- (id)autorelease {
    return self;
}

-(void)resumeBackgroundMusic
{
    //Your code
    NSLog(@"Playing music");
    [self.audioPlayer play];
}

-(void)pauseBackgroundMusic
{
    //Your code here
    NSLog(@"Paused music");
    [self.audioPlayer pause];
}

-(void)checkAndPlayMusic
{
    if(self.is_sound_enable)
        [self resumeBackgroundMusic];
    else
        [self pauseBackgroundMusic];
}

//Added this new method to load new music file.
-(void)loadNewFile:(NSURL*)newFileURL
{
    if(self.audioPlayer)
        [self.audioPlayer release];

    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:newFileURL error:nil];
    [audioPlayer prepareToPlay];
    audioPlayer.numberOfLoops = -1;
}

@end

Now what you have to do is
SingletonClass *sgHelper = [SingletonClass sharedInstance];
sgHelper.is_sound_enable = NO; //<--Set here NO or YES according to your requirement and music will be played accordingly.
[sgHelper checkAndPlayMusic];

Let me know if u need further help.


text:
Q: How can I import HTMLButtonElement into ReactNative I'd like use HTMLButtonElement instead React Button element in my code.
I get error when I run this code:
import React from 'react';
import {SafeAreaView} from 'react-native';

const App = () => {
  return (
    <SafeAreaView>
      <button title="test" data-code="test" />
    </SafeAreaView>
  );
};

export default App;

Error message is:

ReactNativeJS: Invariant Violation: View config getter callback for
component button must be a function (received undefined). Make
sure to start component names with a capital letter.


text:
Q: Conditional Expectation Dice Roll Q) Roll two fair dice. Let $X_{1}, X_{2}$ be the values on each die and $Y = X_{1} + X_{2}$ their sum. Compute $E[X_{1}\mid Y = 8]$. Compute $E[X_{1}\mid X_{2} = 4]$.
A) So far I have that the sample space is $\{(i,j):i,j \in {1,\dotsc,6}\}$, so in total there are $36$ possible outcomes so $P[Y=(i,j)]=1/36$ for all $i,j \in{1,\dotsc,6}$. I also have the following equation to calculate conditional expectation but I don't fully understand the numerator.
$$E[A\mid B=b]=\frac{E[A \times 1_{B=b}]}{P[B=b]}$$

A: We want $E[X_1|Y=8]$ now $Y=X_1+X_2 \iff X_1=Y-X_2$.
So we have $E[X_1|Y=8]=E[Y-X_2|Y=8]=E[Y|Y=8]-E[X_2|Y=8]$ by linearity of expectation.
Clearly $E[Y|Y=8]=8$ and $E[X_2|Y=8]=E[X_1|Y=8]$ as they are identically distributed so $2E[X_1|Y=8]=8$ and $E[X_1|Y=8]=4$.
For the second $X_1,X_2$ are independent so the result should be obvious.
The numerator is using the indicator function on the event that the random variable $B=b$.

A: One way to compute the conditional expectation is to use the conditional distribution, i.e.,
$$E(X_1|Y = 8) = \sum_{x=1}^6 xP(X_1=x|Y=8) = \sum_{x=1}^8x\frac{P(X_1=x,Y=8)}{P(Y=8)}.$$
In your case, because $Y = X_1 + X_2$, we can rewrite $(X_1=x,Y=8)$ as $(X_1=x,X_2 = 8-x).$ Can you take it from here? As a point of reference, the final answer is $E(X_1|Y=8) = 4$.

A: Since $X_2$ is independent of $X_1$, the answer to (B) is trivially $$E[x_1|X2] = E[X_1] = \frac72$$
An easy way to approach (A) is to use Bayes' theorem
$$
P(X_1 = x | Y = y) = \frac{P((X_1 = x) \wedge (Y = y))}{P(Y=y))}
$$
which in plain English is just the fact that within the subset of cases where $Y=y$, the set of cases of $X_1 = x$ is merely the set of cases where
$X_1 = x$ and $Y=y$.
Well, P(Y=8) is the probability of a roll of two dice adding to $8$, which is $\frac5{36}$
And given that the sum is $8$, the first die can be $2,3,4,5,6$.  Each of the combinations represents one outcome of a 2-dice roll, for example, $(3,5)$, and has the probability $\frac1{36}$.
Thus applying the above Bayes' theorem,
$$
P(X_1 = 2 | Y = 8) = \frac{P((X_1 = 2) \wedge (X_1+X_2))}{P(Y=y))}
=\frac{ \frac1{36}}{\frac{5}{36}} = \frac15
\\P(X_1 = 3 | Y = 8) = \frac{P((X_1 = 2) \wedge (X_1+X_2))}{P(Y=y))}
=\frac{ \frac1{36}}{\frac{5}{36}} = \frac15
\\ \vdots
\\P(X_1 = 6 | Y = 8) = \frac{P((X_1 = 2) \wedge (X_1+X_2))}{P(Y=y))}
=\frac{ \frac1{36}}{\frac{5}{36}} = \frac15
$$
each with equal probability, namely $\frac15$.
Now the expectation becomes easy:
$$\frac15\cdot 2 +\frac15\cdot 2 +\frac15\cdot 2 +\frac15\cdot 2 +\frac15\cdot 2 = \frac{20}{5} = 4$$
An easier way, but one that takes a bit more intuition, is to say that
$$E[Y] = E[X_1] + E[X_2]$$
and note that $X_1$ and $X_2$ are identically distributed so they have the same expectation, while if we are restricted to cases with $Y=8$ then $E[Y]=8$.  So $E[X_1|Y=8] = \frac12\cdot 8 = 4$.


text:
Q: Stackless python network performance degrading over time? So i'm toying around with stackless python, writing a very simple webserver to teach myself programming with microthreads/tasklets. But now to my problem, when I run something like ab -n 100000 -c 50 http://192.168.0.192/ (100k requests, 50 concurrency) in apache bench I get something like 6k req/s, the second time I run it I get 5.5k, third time 5k, fourth time, 4.5k, etc. all the way down to 100req/s or something.
The problem goes away when I restart the python script, though.
Now my question is why? Am i forgetting to delete tasklets? I've checked the stackless.getruncount() (and it always seems to return 1, for some reason) so it doesn't seem like there would be any dead tasklets hanging around? I've tried calling .kill() on all tasklets that are done, didn't help. I just can't figure this one out.
import socket
import select
import stackless
import time

class socket_wrapper(object):
    def __init__(self, sock, sockets):
        super(socket_wrapper, self).__init__()
        self.sock = sock
        self.fileno = sock.fileno
        self.sockets_list = sockets
        self.channel = stackless.channel()
        self.writable = False
        self.error = False

    def remove(self):
        self.sock.close()
        self.sockets_list.remove(self)

    def send(self, data):
        self.sock.send(data)

    def push(self, bytes):
        self.channel.send(self.sock.recv(bytes))

def stackless_accept(accept, handler, recv_size=1024, timeout=0):
    sockets = [accept]

    while True:
        read, write, error = select.select(sockets, sockets, sockets, timeout)

        for sock in read:
            if sock is accept:
                # Accept socket and create wrapper
                sock = socket_wrapper(sock.accept()[0], sockets)

                # Create tasklett for this connection
                tasklet = stackless.tasklet(handler)
                tasklet.setup(sock)

                # Store socket
                sockets.append(sock)

            else:
                # Send data to handler
                sock.push(recv_size)

        # Tag all writable sockets
        for sock in write:
            if sock is not accept:
                sock.writable = True

        # Tag all faulty sockets
        for sock in error:
            if sock is not accept:
                sock.error = True
            else:
                pass # should do something here if the main socket is faulty

        timeout = 0 if socket else 1
        stackless.schedule()

def simple_handler(tsock):
    data = ""

    while data[-4:] != "\r\n\r\n":
        data += tsock.channel.receive()

    while not tsock.writable and not tsock.error:
        stackless.schedule()

    if not tsock.error:
        tsock.send("HTTP/1.1 200 OK\r\nContent-length: 8\r\n\r\nHi there")
        tsock.remove()

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("192.168.0.192", 8000))
sock.listen(5)

stackless.tasklet(stackless_accept)(sock, simple_handler)
stackless.run()

A: Two things.
First, please make Class Name start with an Upper Case Letter.  It's more conventional and easier to read.
More importantly, in the stackless_accept function you accumulate a list of Sock objects, named sockets.  This list appears to grow endlessly.  Yes, you have a remove, but it isn't always invoked.  If the socket gets an error, then it appears that it will be left in the collection forever.


text:
Q: Backward ARIMA forecast I want to try and predict previous values for random data that has properties of ARIMA process.
Problem is that I dont understand ARIMA model mathematically, so I dont know if that's even possible or allowed.
For example can I simply invert time axis and use ARIMA predictor? I would guess no.
Or can I use negative shift operator somehow?


text:
Q: Input From Single User on Discord.js I want to be able to obtain the response from a user. The problem is that I don't know how to make sure that I get a specific user's response and not somebody else's. How would I be able to do this?
For example ask for minimum and maximum numbers and then get a random number from between them.
Here's what I've tried:
const Discord = require('discord.js');

const client = new Discord.Client();

const prefix = '-';

client.on('message', message => {
    if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();

if(command === random) {
    message.channel.send('Please enter your starting number')
    channel.fetchMessages({ limit: 1 }).then(messages => {
        let min = messages.first();
    })
    message.channel.send('Please enter your limit')
    channel.fetchMessages({ limit: 1 }).then(messages => {
        let max = messages.first();
    })

    getRndInteger(min,max)

    function getRndInteger(min, max) {
        console.log(Math.floor(Math.random() * (max - min + 1) ) + min);
      }

}

});

I want it to wait until the user who activated it says a number (it could also have a timeout).

A: You can use Channel.createMessageCollector() to wait until your target user has replied, here's a quick example:
let min, max;
const filter = (msg) => msg.author.id === message.author.id; // only match messages from whoever sent the command
const collector = message.channel.createMessageCollector(filter, { max: 2 });
collector.on("collect", (m) => {
  if(!min) { // if min hasn't already been set, set it
    min = parseInt(m.content);
  } else { // otherwise set max
    max = parseInt(m.content);
  }
});
collector.on("end", () => {
  getRndInteger(min, max);
});

There are other ways to go about this but I believe this is the most straightforward because you would need multiple listeners otherwise.


text:
Q: How to catch JavaScript errors in all Iframes (with window.error)? I know one can add event listener for window.error.
However when working with Iframes, each iframe has its own window element, and window.error should be created for each and every iframe.
Is it possible somehow to define error event handler in one location, where all errors will
trigger this specific method?

A: This might work.
function myHandler(msg, url, line){
  //do stuff here...
}

//hook in all frames...
function addErrorHandler(win, handler){
  win.onerror = handler;
  for(var i=0;i<win.frames.length;i++){
    addErrorHandler(win.frames[i], handler);
  }
}
//start with this window... and add handler recursively
addErrorHandler(window, myHandler);

A: I haven't tried this so please don't hang me for it :-)
In the master/parent window that holds all of the iframes, you could create your error handing function there.  Then use jQuery to grab all of your iFrames in your page and register the .error handler to point to your function registered in the parent window.
PS: Also while were on the topic of javascript error handling, this is pretty cool too: https://damnit.jupiterit.com/


text:
Q: Is this verse from Lady Gaga grammatically correct?
"I want your love and I want your revenge
  You and me could write a bad romance"

I have always seen "You and I", as opposed to "You and me". I rely on a rule of thumb that if we remove the other person ("you and"), then what remains (I or me) should make grammatical sense.
Here, "Me could write a bad romance" does not make sense, but who am I to question the grammar of an English-speaking singer?