text:
Q: AttributeError: 'Config' object has no attribute 'http_backend' when starting shinken-arbiter? Shinken is installed via pip in a virtualenv:
sudo /opt/shinken/bin/pip install -e git+https://github.com/naparuba/shinken.git#egg=shinken

Everything goes smoothly until the last step:
sudo /opt/shinken/bin/shinken-arbiter -d -c /opt/shinken/etc/nagios.cfg -c /opt/shinken/etc/shinken-specific.cfg

[1385534688] Critical : I got an unrecoverable error. I have to exit
[1385534688] Critical : You can log a bug ticket at https://github.com/naparuba/shinken/issues/new to get help
[1385534688] Critical : Exception trace follows: Traceback (most recent call last):
  File "/opt/shinken/src/shinken/shinken/daemons/arbiterdaemon.py", line 563, in main
    self.load_config_file()
  File "/opt/shinken/src/shinken/shinken/daemons/arbiterdaemon.py", line 467, in load_config_file
    self.http_backend = self.conf.http_backend
AttributeError: 'Config' object has no attribute 'http_backend'

Traceback (most recent call last):
  File "/opt/shinken/bin/shinken-arbiter", line 8, in <module>
    execfile(__file__)
  File "/opt/shinken/src/shinken/bin/shinken-arbiter", line 118, in <module>
    daemon.main()
  File "/opt/shinken/src/shinken/shinken/daemons/arbiterdaemon.py", line 563, in main
    self.load_config_file()
  File "/opt/shinken/src/shinken/shinken/daemons/arbiterdaemon.py", line 467, in load_config_file
    self.http_backend = self.conf.http_backend
AttributeError: 'Config' object has no attribute 'http_backend'

arbiterdaemon.py: https://github.com/naparuba/shinken/blob/master/shinken/daemons/arbiterdaemon.py

*

*Python 2.7.6

*pip 1.4.1 from /opt/shinken/lib/python2.7/site-packages (python 2.7)

*shinken-arbiter: 1.4

A: It seems that the http_backend property is missing in the master branch. I have tried to reinstall the branch 1.4 and now it's working fine:
sudo /opt/shinken/bin/pip install -e git+https://github.com/naparuba/shinken.git@branch-1.4#egg=shinken


text:
Q: Horizontal scrollable Textview not working This is the xml file for scroll the textview,but it is not working.
<TextView
    android:id="@+id/txt_join_crew"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_centerVertical="true"
    android:ellipsize="marquee"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:marqueeRepeatLimit="marquee_forever"
    android:paddingEnd="5dp"
    android:paddingRight="5dp"
    android:scrollHorizontally="true"
    android:singleLine="true"
    android:text="@string/join_my_crew"
    android:textSize="@dimen/content_text_size" >
</TextView>

this is the xml code and it is not working.

A: You code work but you have add this code in java
TextView tv=(TextView)findViewById(R.id.txt_join_crew);
 tv.setSelected(true);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Forwarding high quality graphics from matlab via ssh I am connecting to a local server that runs MATLAB (version 2015a) via ssh with the X forwarding option (ssh -X).
However when I start MATLAB I get this warning:
libGL error: failed to open drm device: Permission denied
libGL error: failed to load driver: nouveau
libGL error: dlopen /usr/lib64/dri/swrast_dri.so failed (/usr/local/MATLAB/R2015a/bin/glnxa64/../../sys/os/glnxa64/libstdc++.so.6: version `GLIBCXX_3.4.18' not found (required by /lib64/libLLVM-3.5-mesa.so))
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
MATLAB is selecting SOFTWARE OPENGL rendering.

When I start MATLAB as root then instead of Permission denied in the first line, I get:
libGL error: failed to authenticate magic 1
The graphics are terrible, even the text (See the screenshot below). I suppose this issue is related to forwarding the graphics to guest system via ssh. So I thought the display option in MATLAB can be set to the guest-system X-display which I did by:
matlab -display guest-ip:0
Even then I am getting the OpenGL error and there is no graphical output (matlab runs in shell and figure windows do not pop up).
The host has centos-7 and the guest has fedora-20 and both have mesa-libGLU installed. What is the right way to forward high quality graphics?

Host system

Guest system (for comparison)

A: I had this same issue and solve it using the guide from:
http://cplusadd.blogspot.com/2012/01/speeding-up-matlab-over-x11-forwarding.html
If you log into machine A via ssh from machine B, and then run the matlab terminal command in the home directory of A, create a file in the home directory titled java.opts with the contents:
-Dsun.java2d.pmoffscreen=false

Then ssh using these options:
ssh -c arcfour,blowfish-cbc -Y -C username@server

For myself, this made running matlab over ssh much, much better.


text:
Q: concat selected option and input text in angularJS controller I am working with an AngularJS application. I am trying to access selected option from dropdown and input text in controller. Where I am not able to get access selected option in controller and also i want to concatenate selected option with input text.
HTML
<select ng-model="countSelector"
        ng-change="changeCount('{{countSelector}}')"
        ng-options="country.name for country in countries">
</select>
<input  type="text"
        placeholder="Mobile Number"
        ng-model="MobileNumber"/>
<button class="button button-block button-balanced"
        ng-click="signUp(MobileNumber , countSelector)">
            Verify
</button>

Controller
$scope.countries = [ {
    name: "India",
    dial_code: "+91",
    code: "IN"
}, {
    name: "Israel",
    dial_code: "+972",
    code: "IL"
}, {
    name: "Afghanistan",
    dial_code: "+93",
    code: "AF"
}, {
    name: "Albania",
    dial_code: "+355",
    code: "AL"
}, {
    name: "Algeria",
    dial_code: "+213",
    code: "DZ"
}, {
    name: "AmericanSamoa",
    dial_code: "+1 684",
    code: "AS"
}]

$scope.signUp = function(MobileNumber, countSelector){
    var Mobile = MobileNumber;
    console.log(Mobile);
    var code = countSelector;
    console.log(countSelector);
};

A: Try this snippet.

var myApp = angular.module('myApp',[]);

myApp.controller('GreetingController', ['$scope', function($scope) {

$scope.countries = [ {
    name: "India",
    dial_code: "+91",
    code: "IN"
}, {
    name: "Israel",
    dial_code: "+972",
    code: "IL"
}, {
    name: "Afghanistan",
    dial_code: "+93",
    code: "AF"
}, {
    name: "Albania",
    dial_code: "+355",
    code: "AL"
}, {
    name: "Algeria",
    dial_code: "+213",
    code: "DZ"
}, {
    name: "AmericanSamoa",
    dial_code: "+1 684",
    code: "AS"
}]

$scope.signUp = function(MobileNumber, countSelector){
    var code = countSelector;
    console.log(countSelector);
    var Mobile = MobileNumber;
    console.log(countSelector.dial_code + Mobile);
};
}]);

<select ng-model="countSelector"
        ng-change="changeCount('{{countSelector}}')"
        ng-options="country.name for country in countries">
</select>
<input  type="text"
        placeholder="Mobile Number"
        ng-model="MobileNumber"/>
<button class="button button-block button-balanced"
        ng-click="signUp(MobileNumber , countSelector)">
            Verify
</button>

A: you can access selected option via ng-model="countSelector" so just use $scope.countSelector then you could concat with $scope.MobileNumber

A: to access the country name try like this(since it is a object):
<select ng-model="countSelector"
    ng-change="changeCount('{{countSelector}}')"
    ng-options="country.name for country in countries">
</select>
<input  type="text"
    placeholder="Mobile Number"
    ng-model="MobileNumber"/>
<button class="button button-block button-balanced"
    ng-click="signUp(MobileNumber , countSelector.name)">
        Verify
</button>

{{countSelector.name}}-{{MobileNumber}}


text:
Q: kill a function after a certain time in windows I've read a lot of posts about using threads, subprocesses, etc.. A lot of it seems over complicated for what I'm trying to do...
All I want to do is stop executing a function after X amount of time has elapsed.
def big_loop(bob):
    x = bob
    start = time.time()
    while True:
        print time.time()-start

This function is an endless loop that never throws any errors or exceptions, period.
I"m not sure the difference between "commands, shells, subprocesses, threads, etc.." and this function, which is why I'm having trouble manipulating subprocesses.
I found this code here, and tried it but as you can see it keeps printing after 10 seconds have elapsed:
import time
import threading
import subprocess as sub
import time

class RunCmd(threading.Thread):
    def __init__(self, cmd, timeout):
        threading.Thread.__init__(self)
        self.cmd = cmd
        self.timeout = timeout

    def run(self):
        self.p = sub.Popen(self.cmd)
        self.p.wait()

    def Run(self):
        self.start()
        self.join(self.timeout)

        if self.is_alive():
            self.p.terminate()
            self.join()

def big_loop(bob):
    x = bob
    start = time.time()
    while True:
        print time.time()-start

RunCmd(big_loop('jimijojo'), 10).Run()  #supposed to quit after 10 seconds, but doesn't
x = raw_input('DONEEEEEEEEEEEE')

What's a simple way this function can be killed. As you can see in my attempt above, it doesn't terminate after 20 seconds and just keeps on going...
***OH also, I've read about using signal, but I"m on windows so I can't use the alarm feature..  (python 2.7)
**assume the "infinitely running function" can't be manipulated or changed to be non-infinite, if I could change the function, well I'd just change it to be non infinite wouldn't I?
Here are some similar questions, which I haven't able to port over their code to work with my simple function:
Perhaps you can?
Python: kill or terminate subprocess when timeout
signal.alarm replacement in Windows [Python]
Ok I tried an answer I received, it works.. but how can I use it if I remove the if __name__ == "__main__": statement? When I remove this statement, the loop never ends as it did before..
import multiprocessing
import Queue
import time

def infinite_loop_function(bob):
    var = bob
    start = time.time()
    while True:
        time.sleep(1)
        print time.time()-start
    print 'this statement will never print'

def wrapper(queue, bob):
    result = infinite_loop_function(bob)
    queue.put(result)
    queue.close()

#if __name__ == "__main__":

queue = multiprocessing.Queue(1) # Maximum size is 1
proc = multiprocessing.Process(target=wrapper, args=(queue, 'var'))
proc.start()

# Wait for TIMEOUT seconds
try:
    timeout = 10
    result = queue.get(True, timeout)
except Queue.Empty:
    # Deal with lack of data somehow
    result = None
finally:
    proc.terminate()

print 'running other code, now that that infinite loop has been defeated!'
print 'bla bla bla'
x = raw_input('done')

A: Use the building blocks in the multiprocessing module:
import multiprocessing
import Queue

TIMEOUT = 5

def big_loop(bob):
    import time
    time.sleep(4)
    return bob*2

def wrapper(queue, bob):
    result = big_loop(bob)
    queue.put(result)
    queue.close()

def run_loop_with_timeout():
    bob = 21 # Whatever sensible value you need
    queue = multiprocessing.Queue(1) # Maximum size is 1
    proc = multiprocessing.Process(target=wrapper, args=(queue, bob))
    proc.start()

    # Wait for TIMEOUT seconds
    try:
        result = queue.get(True, TIMEOUT)
    except Queue.Empty:
        # Deal with lack of data somehow
        result = None
    finally:
        proc.terminate()

    # Process data here, not in try block above, otherwise your process keeps running
    print result

if __name__ == "__main__":
    run_loop_with_timeout()

You could also accomplish this with a Pipe/Connection pair, but I'm not familiar with their API. Change the sleep time or TIMEOUT to check the behaviour for either case.

A: There is no straightforward way to kill a function after a certain amount of time without running the function in a separate process.  A better approach would probably be to rewrite the function so that it returns after a specified time:
import time

def big_loop(bob, timeout):
    x = bob
    start = time.time()
    end = start + timeout
    while time.time() < end:
        print time.time() - start
        # Do more stuff here as needed

A: Can't you just return from the loop?
start = time.time()
endt = start + 30
while True:
    now = time.time()
    if now > endt:
        return
    else:
        print end - start

A: import os,signal,time
cpid = os.fork()
if cpid == 0:
  while True:
     # do stuff
else:
  time.sleep(10)
  os.kill(cpid, signal.SIGKILL)

You can also check in the loop of a thread for an event, which is more portable and flexible as it allows other reactions than brute killing. However, this approach fails if # do stuff can take time (or even wait forever on some event).


text:
Q: Android app crashes when i use FeedListAdapter for ListView on Android 4.4 only This is the feedlist adapter. When i call this from the activity the app crashes on Android 4.4 but the code works fine on 5.0 and above. Please help. Been trying to fix this for about a week now with no luck. The app crashes on this link
    view.setOnClickListener(new View.OnClickListener() {
 public class FeedListAdapter extends BaseAdapter {
        private Activity activity;
        private LayoutInflater inflater;
        private List<FeedItem> feedItems;
        private SharedPreferences mAdminPreferences;

        public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
            this.activity = activity;
            this.feedItems = feedItems;
        }

        @Override
        public int getCount() {
            return feedItems.size();
        }

        @Override
        public Object getItem(int location) {
            return feedItems.get(location);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (inflater == null)
                inflater = (LayoutInflater) activity
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (convertView == null)
                convertView = inflater.inflate(R.layout.feed_item, null);

            final TextView name = (TextView) convertView.findViewById(R.id.name);
            final TextView projectid = (TextView) convertView.findViewById(R.id.project_id);
            TextView timestamp = (TextView) convertView
                    .findViewById(R.id.timestamp);
            final TextView statusMsg = (TextView) convertView
                    .findViewById(R.id.txtStatusMsg);
            final TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
            // final TextView usertype = (TextView) convertView.findViewById(R.id.usertype);

            FeedItem item = feedItems.get(position);

            name.setText(item.getName());
            projectid.setText(item.getId());
            url.setText(item.getUrl());

            final String userid = (item.getUserid());
            final String story = (item.getStory());
            final String coursename = (item.getCourseName());
            final String courseduration = (item.getCourseDuration());
            final String amount = (item.getAmount());
            final String extradetails = (item.getExtraDetails());
            final String videourl = (item.getVideoUrl());
            final String school = (item.getSchool());

            // My code to instantiate buttonclick and get name of item being clicked

            View view = convertView.findViewById(R.id.layoutclick);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String namegotten = name.getText().toString();
                    String projectidgotten = projectid.getText().toString();
                    String msg = statusMsg.getText().toString();
                    String urlgotten = url.getText().toString();

                    Toast.makeText(v.getContext(), namegotten + projectidgotten, Toast.LENGTH_SHORT).show();

                            Collect.getInstance().getActivityLogger()
                                    .logAction(this, "downloadBlankForms", "click");

                    Intent i = new Intent(v.getContext(), Activity_AllForms_Download.class);

                    i.putExtra("id", projectidgotten);
                    v.getContext().startActivity(i);

                }
            });

            // Chcek for empty status message
            if (!TextUtils.isEmpty(item.getStatus())) {
                statusMsg.setText(item.getStatus());
                statusMsg.setVisibility(View.VISIBLE);
            } else {
                // status is empty, remove from view
                statusMsg.setVisibility(View.GONE);
            }

            // Checking for null feed url
            if (item.getUrl() != null) {
                url.setText(Html.fromHtml(""
                        + item.getUrl() + " "));

                // Making url clickable
                url.setMovementMethod(LinkMovementMethod.getInstance());
                url.setVisibility(View.VISIBLE);
            } else {
                // url is null, remove from the view
                url.setVisibility(View.GONE);
            }

            return convertView;
        }

    }

Here is the LOG
D/AndroidRuntime: Shutting down VM
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa4d2bb20)
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: org.odk.collect.android, PID: 31036
                  java.lang.NoClassDefFoundError: org.odk.collect.android.adapters.FeedListAdapter$1
                      at org.odk.collect.android.adapters.FeedListAdapter.getView(FeedListAdapter.java:115)
                      at android.widget.AbsListView.obtainView(AbsListView.java:2263)
                      at android.widget.ListView.onMeasure(ListView.java:1147)
                      at android.view.View.measure(View.java:16497)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
                      at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
                      at android.view.View.measure(View.java:16497)
                      at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1226)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                      at android.widget.ScrollView.onMeasure(ScrollView.java:326)
                      at android.view.View.measure(View.java:16497)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                      at android.view.View.measure(View.java:16497)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
                      at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
                      at android.view.View.measure(View.java:16497)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                      at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
                      at android.view.View.measure(View.java:16497)
                      at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
                      at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
                      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
                      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
                      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
                      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
                      at android.view.Choreographer.doCallbacks(Choreographer.java:574)
                      at android.view.Choreographer.doFrame(Choreographer.java:544)
                      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
                      at android.os.Handler.handleCallback(Handler.java:733)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:136)
                      at android.app.ActivityThread.main(ActivityThread.java:5017)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                      at dalvik.system.NativeStart.main(Native Method)
Application terminated.

The crash ends here.

A: My pscuode code:--

        // View view = convertView.findViewById(R.id.layoutclick);

        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String namegotten = name.getText().toString();
                String projectidgotten =  projectid.getText().toString();
                String msg = statusMsg.getText().toString();
                String urlgotten = url.getText().toString();

                Toast.makeText(v.getContext(), namegotten + projectidgotten, Toast.LENGTH_SHORT).show();

                        Collect.getInstance().getActivityLogger()
                                .logAction(this, "downloadBlankForms", "click");

                Intent i = new Intent(v.getContext(), Activity_AllForms_Download.class);

                i.putExtra("id", projectidgotten);
                v.getContext().startActivity(i);

            }
        });


text:
Q: Компиляция cpp Есть программа написана на C++. Цель написать функцию которая компилирует cpp в exe. В комментариях говорили про make файл. Если я не ошибаюсь make файл это порядок компиляции. Если честно то даже не знаю как правильно задать вопрос. В общем программа должна уметь скомпилировать проект созданный и написанный в MVS. Интересует любая информация касательно этого.
A: в заголовочном файле cstdlib есть функция system, которая в качестве аргумента принимает shell-команду для исполнения. Например
    system("g++ -o example helloworld.cpp");


text:
Q: Find the range of the function,$f(x)=\int_{-1}^{1}\frac{\sin x}{1-2t\cos x+t^2}dt$ Find the range of the function,$f(x)=\int_{-1}^{1}\frac{\sin x}{1-2t\cos x+t^2}dt$
I tried to solve it,i got range $\frac{\pi}{2}$ but the answer is ${\frac{-\pi}{2},\frac{\pi}{2}}$
$f(x)=\int_{-1}^{1}\frac{\sin x}{1-2t\cos x+t^2}dt=\int_{-1}^{1}\frac{\sin x}{(t-\cos x)^2+\sin^2x}dt=\sin x\int_{-1}^{1}\frac{1}{(t-\cos x)^2+\sin^2x}dt$
$=\frac{\sin x}{\sin x}\left[\tan^{-1}\frac{t-\cos x}{\sin x}\right]_{-1}^{1}=\tan^{-1}\frac{1-\cos x}{\sin x}+\tan^{-1}\frac{1+\cos x}{\sin x}$
$=\tan^{-1}\tan\frac{x}{2}+\tan^{-1}\cot\frac{x}{2}=\frac{\pi}{2}$
But i am not getting $\frac{-\pi}{2}$.Have i done some wrong?Please enlighten me.

A: Notice, second last line,
$$\frac{\sin x}{\sin x}\left[\tan^{-1}\left(\frac{t-cos x}{\sin x}\right)\right]_{-1}^{1}$$
$$=\tan^{-1}\left(\frac{1-cos x}{\sin x}\right)-\tan^{-1}\left(\frac{-1-cos x}{\sin x}\right)$$
$$=\tan^{-1}\left(\frac{1-cos x}{\sin x}\right)+\tan^{-1}\left(\frac{1+cos x}{\sin x}\right)$$
$$=\tan^{-1}\left(\frac{\frac{1-cos x}{\sin x}+\frac{1+cos x}{\sin x}}{1-\frac{1-cos x}{\sin x}\frac{1+cos x}{\sin x}}\right)$$
$$=\tan^{-1}\left(\frac{\frac{2}{\sin x}}{1-\frac{1-cos^2 x}{\sin^2 x}}\right)$$
$$=\tan^{-1}\left(\frac{\frac{2}{\sin x}}{1-\frac{sin^2 x}{\sin^2 x}}\right)$$
$$=\tan^{-1}\left(\frac{\frac{2}{\sin x}}{1-1}\right)=\tan^{-1}(\infty)=\frac{\pi}{2}$$

A: You've accomplished the tougher part
Now observe that $$\dfrac{1-\cos x}{\sin x}\cdot\dfrac{1+\cos x}{\sin x}=1$$
and use $\arctan y+\arctan\dfrac1y=$sgn$(y)\cdot\dfrac\pi2$  (Proof)

A: $$f(x)=\int_{-1}^{1}\frac{\sin x}{t^2-2t\cos x+1}\ dt$$
$$=\int_{0}^{1}\frac{\sin x}{t^2-2t\cos x+1}+\frac{\sin x}{t^2+2t\cos x+1}\ dt$$
$$=2\sin x\int_{0}^{1}\frac{t^2+1}{(t^2+1)^2-4t^2\cos^2 x}\ dt$$
$$=2\sin x\int_{0}^{1}\frac{1+\frac {1}{t^2}}{\biggl(t+\frac {1}{t}\biggr)^2-4\cos^2 x}\ dt$$
$$=2\sin x\int_{0}^{1}\frac{1}{\biggl(t-\frac {1}{t}\biggr)^2+(2\sin x)^2}\ d\biggl(t-\frac {1}{t}\biggr)$$
$$=\biggl(\arctan \biggl(\frac{t-\frac {1}{t}}{2\sin x}\biggr)\biggr)_{0}^{1}$$
$$=\frac {\pi}{2} \text { for } \sin x>0$$
Or
$$=-\frac {\pi}{2} \text { for } \sin x<0$$
Hence Range of $$f(x)=\biggl\{-\frac {\pi}{2},\frac {\pi}{2}\biggr\}$$


text:
Q: Multiply trig functions of the same base? Is $\frac{1}{\sin(x)}\frac{\cos(x)}{\sin(x)} = \frac{\cos(x)}{\sin^2(x)}$ correct?

A: Yes, the rule
$$\frac{a}{b} \cdot \frac{c}{d} = \frac{ac}{bd}$$ iff $b,d \not= 0$
always holds. With $a=1$, $b=d=\sin(x)$ and $c=\cos(x)$ we get the result:
$$\frac{\cos(x)}{\sin^2(x)}$$


text:
Q: VS 2012 project load error, incompatible .Net version I'm getting an error when I try to load a project in VS 2012. This project was created on the same machine and it was working fine but now it has started to complain about project target framework.

From the error message I don't understand the difference between .NETFramework,Version=v4.5 and change target to .Net Framework 4.5
When I choose to download and install .NETFramework,Version=v4.5, the installer says this version is already part of OS and need not be installed separately.
I'm working on VS 2012 on Windows 8 64 bit OS.
Any pointers will be helpful, Thanks


text:
Q: How to create a vector with components bigger than a number in numpy? For example, I have a vector like this:
v = np.array([2, 4, 1, 7, 9, 3, 5])

I want to compare each component to a number to obtain a new vector which components are bigger of equal to the number (in case if the original component is less). For the above example and limit=3 the result should be:
np.array([3, 4, 3, 7, 9, 3, 5])

How can I do it with numpy?

A: You can simply do
v[v <= 3] = 3

which gives you the desired output:
array([3, 4, 3, 7, 9, 3, 5])

Brief explanation:
v <= 3

creates a Boolean array
array([ True, False,  True, False, False,  True, False], dtype=bool)

and the command
v[v <= 3]

sets all values to 3 where this Boolean array evaluates to True.

A: You can also use numpy.clip:
>>> np.clip(v, 3, None)
array([3, 4, 3, 7, 9, 3, 5])

The second argument is a maximum, but I've given it only a minimum.
This can also be provided with an out argument, in this case, if you supply itself as the target, it will work in-place:
>>> x = np.clip(v, 3, None, v)
>>> id(x), id(v)
(4357557104, 4357557104)
>>> v
array([3, 4, 3, 7, 9, 3, 5])
>>>

The docs:

out : ndarray, optional
    The results will be placed in this array. It may be the input
    array for in-place clipping.  `out` must be of the right shape
    to hold the output.  Its type is preserved.

This could potentially be useful if you are memory constrained (I believe no intermediate boolean array gets created).


text:
Q: Do Android services using startForeground impact Play Store auto updates? I'm using startForeground to run a service in my app.  Does this impact Play Store auto updates when it's running?  It seems like it does because I'll release a new version and a test tablet will still be running the old one for days after the release.  The app shows "pending update" in Google Play on the device.
As background, this is not a normal consumer app and does need to run all the time to sync data.  Without the foreground service I found even persistent alarms would stop running in a timely fashion after a few days, so as far as I'm aware, startForeground is the only way to keep the app running permanently.
Thanks for reading!

A: You can create an application which the Android system puts under whitelist application.
Under certain circumstances, a background app is placed on a temporary whitelist for several minutes. While an app is on the whitelist, it can launch services without limitation, and its background services are permitted to run.
An app is placed on the whitelist when it handles a task that's visible to the user, such as:

*

*Handling a high-priority Firebase Cloud Messaging (FCM) message.

*Receiving a broadcast, such as an SMS/MMS message.

*Executing a PendingIntent from a notification.

*Starting a VpnService before the VPN app promotes itself to the
foreground.

So you can create a high-priority FCM message for your update and send it as an update notification or just a blank message.
Set Up a Firebase Cloud Messaging Client App on Android


text:
Q: Significance of Kretschmann scalar to flat spaces? If you are given a spacetime embedded with a particular metric tensor that satisfies the vacuum field equations of general relativity, how do you confirm that you aren't simply dealing with a Minkowski spacetime that has been changed via some exotic coordinate transformation?
Or, more specifically if I have an exact solution to the vacuum field equations that has a Kretschmann scalar value of $0$. Is this just the Minkowski spacetime in a different coordinate system?

A: A zero Kretschmann scalar does not mean the Riemann tensor is zero. For example in the Kerr metric the sign of $K$ can change as we move towards the black hole, and that means it necessarily passes through zero. For details of this see this paper on the Arxiv.
There is some related discussion in Interpreting the Kretschmann scalar.


text:
Q: My mysqlx python query is inserting a "AS" statement instead of a "SELECT" statement. Why? Here is the python code I am running.
def queryOrg(self, OrgID):
        session = mysqlx.get_session(
            {'host': db.HOST, 'port': db.PORT, 'user': db.USER, 'password': db.PASSWORD})
        org_schema = session.get_schema('Organizations')
        org_table = org_schema.get_table('Organizations')
        result = org_table.select(["*"]).where('Organization_ID = ' + str(OrgID)).execute()
        print(result)

And here is the error output
mysqlx.errors.OperationalError: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS `*` FROM `Organizations`.`Organizations` WHERE (`Organization_ID` = 2)' at line 1

When I run...
def queryOrg(self, OrgID):
        session = mysqlx.get_session(
            {'host': db.HOST, 'port': db.PORT, 'user': db.USER, 'password': db.PASSWORD})
        org_schema = session.get_schema('Organizations')
        org_table = org_schema.get_table('Organizations')
        result = org_table.select(["*"]).where('Organization_ID = ' + str(OrgID)).get_sql()
        print(result)

I get this output.
SELECT * FROM Organizations.Organizations WHERE Organization_ID = 2

So, it seems to be generating the correct mysql query when I use the .get_sql() method, but when I call the .execute() method somehting changes the query to 'AS * FROM Organizations.Organizations WHERE (Organization_ID = 2)'
I have no idea why this would be happening.  I am running a MySQL server on a ubuntu rasberry pi, version 8.031-0ubuntu0.22.04.1  and I am running python 3.8.10 with pip3 mysql-connector-python 8.0.30.
This function is getting called through a flask app.  I am running flask on version 2.2.2
Any help at all would be very welcome.

A: Oh!  I think I found a solution.  the .select() method sets the '*' as a default when nothing is passed into it.  Trying to pass ["*"] into .select() caused the mysqlx to generate something like 'SELECT * AS * ...' which was causing the problem. This new code works perfectly.
def queryOrg(self, OrgID):
        session = mysqlx.get_session(
            {'host': db.HOST, 'port': db.PORT, 'user': db.USER, 'password': db.PASSWORD})
        org_schema = session.get_schema('Organizations')
        org_table = org_schema.get_table('Organizations')
        result = org_table.select().where(("Organization_ID = '%s'") % str(OrgID)).execute()
        print(result.fetch_one())


text:
Q: Hided status bar, but it's now replaced with white bar (iPhone Interface XIB) I've used this code to hide the status bar
[application setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
On the view xib I have set the status bar to 'none' so there is no status bar.
When i run the app, the status bar has disappeared with the carrier, battery info etc. But is now a white bar, so in essence the status bar is there, but is white.
I have also tried changing it via the p list. But by me doing this, all my objects move 'up' and the sizing messes up.
Thanks

A: Be sure to set the statusBar hidden before you set the self.window frame, something like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [application setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

//rest of the code here

return YES;
}

Doing so the window seems to position itself without leaving space for the StatusBar, thus filling the whole screen

A: Without the status bar you have a 20x320 points rectangle to work with. Your view sizing needs to adjust to this, and then you need to fill that space with something. Of course your views will move 'up' and your sizing get messed up. So what are you gonna put there?


text:
Q: Pandas Concatenate/Merge Two Dataframes with Priority How can you concatenate | merge two pandas dataframes with priority, keeping the row from a priority dataframe if a specific column value matches. Is there a type of join that describes this?
import pandas as pd
Cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [22000,25000,27000,35000]}
Cars2 = {'Brand': ['Honda CRV','Toyota Celica','Ford Explorer','Audi A8'],
        'Price': [40000,25000,37000,100000]}

df_priority = pd.DataFrame(Cars, columns= ['Brand', 'Price'])
df2 = pd.DataFrame(Cars2, columns= ['Brand', 'Price'])

# df_merge_with_priority = Merge dataframes and keep rows from df_priority if price matches

df_merge_with_priority expected output:
Brand: Honda CRV, Honda Civic, Toyota Corolla, Ford Explorer, Ford Focus, Audi A4, Audi A8
Price: 40000, 22000, 25000, 27000, 37000, 35000, 100000
Notice how the price of the Toyota Corolla and Toyota Celica are the same however, we want to keep only the Corolla in this instance. Any thoughts on how to join with priority?

A: if you are looking for the first of priority vs df2, you can try with:
pd.concat((df_priority,df2)).sort_index().drop_duplicates('Price') #.reset_index(drop=True)

            Brand   Price
0     Honda Civic   22000
1       Honda CRV   40000
2  Toyota Corolla   25000
3      Ford Focus   27000
4   Ford Explorer   37000
5         Audi A4   35000
6         Audi A8  100000


text:
Q: How to display texture on the screen? I have a unity scene. I try to display a texture that changes dynamically.
I draw some shape on this texture. How can I do it?
If I use onGUI and  Graphics.DrawTexture method, it works too slow on mobile platform.

A: Use a canvas with an Image attached to it
You can apply a texture through there.
The OnGUI method is deprecated, try not to use it.


text:
Q: is there a getConfig() for Protractor? I've the following config.js file:
var testName = 'Testing';
var HtmlReporter = require('protractor-html-screenshot-reporter');
var reporter = new HtmlReporter({
    baseDirectory: './protractor-result', // a location to store screen shots.
    docTitle: 'Report Test Summary',
    docName: 'protractor-tests-report.html'
});
exports.config = {

    seleniumAddress: 'http://hub.browserstack.com/wd/hub',
    multiCapabilities: [

        {
            name: testName,
            browserName: 'Chrome',
            browser_version: '39.0',
            os: 'OS X',
            os_version: 'Yosemite',
            resolution: '1920x1080',
            'browserstack.user': browserstackUser,
            'browserstack.key': browserstackKey,
            'browserstack.debug': 'true',
            'browserstack.selenium_version': '2.45.0'
        }
        ,
        {
            name: testName,
            browserName: 'IE',
            browser_version: '11.0',
            os: 'Windows',
            os_version: '8.1',
            resolution: '2048x1536',
            'browserstack.user': browserstackUser,
            'browserstack.key': browserstackKey,
            'browserstack.debug': 'true',
            'browserstack.selenium_version': '2.45.0',
            'browserstack.ie.driver': '2.44',
            //ignoreProtectedModeSettings: true
        }
    ],

    // Spec patterns are relative to the current working directly when
    // protractor is called.

    suites: {
        waitlist: './././specs/waitlist_page_spec.js',
        press: './././specs/press_page_spec.js',
        news: './././specs/news_page_spec.js',
        landing: './././specs/landing_page_spec.js'
    },

    // Maximum number of total browser sessions to run. Tests are queued in
    // sequence if number of browser sessions is limited by this parameter.
    // Use a number less than 1 to denote unlimited. Default is unlimited.
    maxSessions: 2,

    // protractor will save the test output in json format at this path.
    // The path is relative to the location of this config.
    resultJsonOutputFile: null,

    framework: 'jasmine2',

    // Options to be passed to Jasmine-node.
    jasmineNodeOpts: {
        showColors: true,
        defaultTimeoutInterval: 100000,
        realtimeFailure: true,
        showTiming: true,
        includeStackTrace: true,
        isVerbose: true,
        onComplete: null
    },

    onPrepare: function () {
        jasmine.getEnv().addReporter(reporter);
        browser.driver.manage().window().maximize();
        global.dvr = browser.driver; //variable to call selenium directly
        global.isAngularSite = function (flag) {
            browser.ignoreSynchronization = !flag; //This setup is to configure when testing non-angular pages
        };
        //browser.manage().timeouts().pageLoadTimeout(90000);
        browser.manage().timeouts().implicitlyWait(100000);

    }

};

And I would like to find a way to ask on my test that if the capability.browserName is IE do a certain/especial action, so, I would like to do some sort of getConfig(), is that possible? does anyone had implemented something similar?
Thanks all for your time!

A: The getCapabilities in browser returns a promise with these values:
browser.getCapabilities().then(function (capabilities) {
    browser = capabilities.caps_.browserName;
    platform = capabilities.caps_.platform;
}).then(function displayEnv() {
    console.log('Browser:', browser, 'on platform', platform);
});


text:
Q: After returning from suspend the keyboard and mouse doesn't respond I have 64-bit Ubuntu 14.04 on Dell Inspiron-3537.
After resuming from suspend it takes me to log-in screen, and I'm unable to move cursor and no hotkeys are working nor "ctrl+alt+f1".
I tried sudo pm-suspend and after resuming it takes me to my desktop and this time I'm able to move my cursor but again nothing won't work.
Graphic drivers are installed.

A: I had the exact same problem, I am assuming you are using a kernel newer than 3.12.
It happened to me after the kernel upgrade. The solution is to try another kernel.
Mine was fixed by downgrading to 3.12. LP told me it may be fixed if I upgrade to 3.15, but i did not try that.

A: You can press Ctrl+Alt+F1 and login to your account, then enter:
sudo apt-get update && apt-get install fglrx fglrx-pxpress

...then reboot. The problem will be solved.

A: You're possibly seeing this bug: Black screen after login from suspend in Xubuntu 14.04. Try removing light-locker and light-locker-settings and installing xscreensaver to solve the issue of buggy suspend/resume.
source


text:
Q: What are the four slots under emblem and badges I'v just noticed that we have 4 slots for some sort of badges.
I'm just level 3 and I already have 2. I didn't accomplish anything special. Some players have 4 or 3. Everyone seems to have a least one.
Why ?

A: These icons on your callsign represent your highest rank or level of prestige in the previous four Call of Duty games.  They are for (from left to right):

*

*Call of Duty 4: Modern Warfare

*Call of Duty: World at War

*Call of Duty: Modern Warfare 2

*Call of Duty: Black Ops

The shape/style of the icon differs depending on what the highest level of prestige the player earned is just like they do in Modern Warfare 3, or just show the rank icon if you never prestiged in that game.  The CoD Wikia has images of all the prestige icons that you can look at for reference.  Suffice it to say that if someone has an icon in each of these slots, they've probably been playing Call of Duty for many years.
This is one of several features that were introduced in Modern Warfare 3 to honor long-time players of the franchise.  In addition to an icon representing your prestige, if you have prestiged at least once in any of these games, you get an additional Prestige Token in Modern Warfare 3.
For instance, if you've prestiged 4 times in Black Ops and 1 time in Modern Warfare 2, you'd get an additional 2 tokens, one for having prestiged at least once in Black Ops, and one for prestiging at least once in MW2.  Your callsign will also show the 4th prestige icon for Black Ops, and the first prestige icon for MW2.

A: These are to show your current level in all of the previous Call of Duty Games.  Here is the order:
1st slot - Call of Duty: Modern Warfare
2nd slot - Call of Duty: World at War
3rd slot - Modern Warfare 2
4th slot - Black Ops
Also, if you have prestiged in any of the previous games you get a prestige token to use in the Modern Warfare 3 Prestige Shop (with a max of one token per previous game, there is nothing to be gained after the first prestige).


text:
Q: Need to read a csv file that is in a different path than the one where jupyter notebook is run on I am looking to read a csv file present in my local drive ex: C:\Users\Studyfolder\abc.csv
My python libraries are installed in another directory - a path created for python 3 libraries ex:C:\Users\Anaconda3_2\envs\py3
On Anaconda Prompt- i have set my cd path as - C:\Users\Anaconda3_2\envs\py3 since naturally, all python libraries will be installed there
On Jupyter Notebook, I am looking to read the csv file to extract the dataframe. For definite reason when i run the command
df = pd.read_csv('abc.csv'), the file wouldn't be found under the path cd'd on Anaconda prompt
Should i be saving all my data files in the same path where python libraries are installed OR there is a better way i can still read the file without having to save it in the cd path shown above?
P.S New to Jupyter notebooks and Python in general
import pandas as pd

df = pd.read_csv('abc.csv')
df.head()

FileNotFoundError                         Traceback (most recent call last)
 in
      1 # load abc data into data frame
----> 2 df = pd.read_csv('abc.csv')

A: If you activate your anaconda environment, the jupyter environment should be tied to that interpreter. In that case, it doesn't really matter where you start your notebook from, it will always have access to the libraries installed there. For example:
conda activate py3

This will now tie conda to that environment:
import sys
sys.path
['C:\\Users\\Anaconda3_2\\envs\\py3'...]

So you can start jupyter wherever, as long as you pass a legitimate path. The full path will work anywhere:
# I'm at C:\Users\Anaconda3

df = pd.read_csv("C:\\Users\\Studyfolder\\abc.csv")

If you want to use relative paths, it's very dependent on where you call jupyter notebook from:
# Still at C:\\Users\\Anaconda3
df = pd.read_csv("..\\Studyfolder\\abc.csv")

Where the .. indicates to go back a directory

A: In general, I would suggest writing your scripts outside the python library in a directory structure that works best for your projects. The simple reason is that your python libraries are already added to PYTHONPATH and hence are available anywhere, whereas your project files are only available from your project folders.
In your case, there are two approaches you can take -

*

*Provide the file location as a relative path to your current directory. So, df = pd.read_csv('..\..\..\Studyfolder\abc.csv')

*Add the folder path into your system path by adding these statements before reading your file -

import sys
sys.path.append("C:\\Users\Studyfolder")


text:
Q: serialize dictionary in field for a rest API end point django rest framework I have a serializer where I want to render a dictionary, I am also converting that dictionary to a JSON format, but I am getting the following error:
Object of type Job is not JSON serializable.
The code looks like this:
jobs_by_hour = serializers.SerializerMethodField()

 def get_jobs_by_hour(self, obj):
    jobs = Job.objects.annotate(hour=ExtractHour('dt_start'))
    res = defaultdict(lambda: [])
    for x in jobs:
        res[x.hour].append(x)
    return json.dumps(res)

I am a newb at this and I don't know how to fix this issue, any help is welcome. ultimately, with this dictionary i want to display the data grouped by the hour, so i get 24 lists of jobs

A: You are appending the queryset object. You need to append serialized data. Something like this should work.
 def get_jobs_by_hour(self, obj):
    jobs = Job.objects.annotate(hour=ExtractHour('dt_start'))
    res = defaultdict(lambda: [])
    for x in jobs:
        res[x.hour].append(JobSerializer(x).data)
    return json.dumps(res)

Add a field hour in your default JobSerializer.


text:
Q: How to know the file upload duration within a Spring Rest Controller I need the ability know the duration of a file upload within a @PostMapping method in a @RestController.
So far I've had no luck.
I thought of using HttpServerletRequest.getDateHeader() but this obviously isn't server time and isn't trustworthy.
fun receiveFile(@RequestParam("file") file: MultipartFile, request: HttpServletRequest){
    ...
}


text:
Q: How to expand all folders (not folded code blocks) in PhpStorm? Please note that I am not referring to folded code blocks, but to the folders in the Project View.
command + - collapses all folders (Project View).
There's also an icon to collapse all folders in the Project View. However, I don't see an icon or a command in the keymap that expand all folders in the Project View.
Is it possible? If so, how?

A:
Is it possible? If so, how?

Yes and No.

If you want one button/action that would expand all tree nodes till the very end (recursively) (opposite to collapse all) -- then answer is "No".
Why?

[1] "Expand all" in Project view is meaningless for any reasonable-sized project, for performance and other reasons.
[2] At least in debugger, most of the trees can be expanded infinitely and this is not always obvious when you're about to expand one. Do you realize that?

The 2nd one can also apply to Project View because of cyclic symbolic links.
Related tickets:

*

*https://youtrack.jetbrains.com/issue/IDEA-96225

*https://youtrack.jetbrains.com/issue/IDEA-52772

*https://youtrack.jetbrains.com/issue/IDEA-90984

*https://youtrack.jetbrains.com/issue/IDEA-106264

But "Yes" -- you can expand next level in all sub folders simultaneously (one level at a time). So using it few times in a row will most likely expand whole tree (depends on how deep the tree is).
For that just use NumPad * on desired main node (e.g. project root).
P.S. You can re-assign shortcut to whatever else you desire -- corresponding action is called Fully Expand Tree Node.


text:
Q: OData Client doesn't include error message when Bad Request Response received from OData Service I have an odata client (generated using odata connected service) to call a odata service and add some data.
public async Task<ActionResult> AddOrder(Order order)
{
    try
    {
        var client = new Container(new Uri(ConfigHelper.ApiUrl)) { Timeout = 60 * 60,
            AddAndUpdateResponsePreference = DataServiceResponsePreference.IncludeContent
            };
        client.AddToOrder(order);
        client.SaveChanges();
    }
    catch (Exception ex)
    {
        return Json("Error: AddOrder request failed. " + ex.Message + " : " + ex.InnerException?.Message);
    }
    return Json("AddOrder request has completed successfully");
}

Odata service implementation
[HttpPost]
public async Task<IHttpActionResult> Post(Order order)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    try
    {
        db.Order.Add(order);
        await db.SaveChangesAsync()
        return Created(order);
    }
    catch (Exception)
    {
        throw;
    }
}

the OData service returns BadRequest response incase of model validation errors. for example, below is one sample response from the service
Status Code:400

Header Info:-
Pragma:no-cache
OData-Version:4.0
Content-Length:221
Cache-Control:no-cache
Content-Type:application/json; odata.metadata=minimal; charset=utf-8
Date:Sun, 27 Nov 2022 07:06:49 GMT
Expires:-1
Server:Microsoft-IIS/10.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
{"error":{"code":"","message":"The request is invalid.","innererror":{"message":"order.ProductName : The field ProductName must be a string or array type with a maximum length of '20'.\r\n","type":"","stacktrace":""}}}

the client.SaveChanges() call throws an exception in this case but the exception does not include the innnererror message indicating the validation error message. all it says BadRequest
InnerException:

Response property of exception:

I've tried updating the OData Client nuget package, tried setting option SaveChangesOptions.BatchWithIndependentOperations when calling SaveChanges(), no luck. could some please help?
client.SaveChanges(SaveChangesOptions.BatchWithIndependentOperations);

currently using Microsoft.OData.Client version 7.12.5 which is the latest version.

A: I presume that you received DataServiceRequestException.
DataServiceRequestException has a property Response of DataServiceResponse type.
DataServiceResponse is a collection of OperationResponse and each OperationResponse has a property Error with an error thrown by the operation.
Here you should be able to find more details what exactly failed.
DataServiceRequestException
DataServiceResponse
OperationResponse


text:
Q: Does exists other way of indenting ffmpeg batch script? How can I indent code in a Batch script other than using temporal variables %= =%?
This is the only code that works for me with indentation.
::2020-12-31 10:43:40
@ECHO OFF
::SET VIDEO="E:\Vídeos\test.mp4"
SET VIDEO=%1
SET /P TITULO=Introduzca el título del vídeo:
ffmpeg ^
    -y ^
    -loglevel verbose ^
    -i %VIDEO% ^
    -vf ^
          scale=^
%=          =%width=-2:^
%=          =%height=360,^
%=      =%drawtext=^
%=          =%fontfile='C\:/Windows/Fonts/impact.ttf':^
%=          =%text=%TITULO%:^
%=          =%fontcolor=white:^
%=          =%borderw=1:^
%=          =%fontsize=18:^
%=          =%alpha=0.99:^
%=          =%x=(w-tw)/2:^
%=          =%y=th/4:^
%=          =%expansion=none,^
%=      =%drawtext=^
%=          =%fontfile='C\:/Windows/Fonts/arial.ttf':^
%=          =%text='WATERMARK':^
%=          =%fontcolor=white:^
%=          =%borderw=1:^
%=          =%fontsize=18:^
%=          =%alpha=0.60:^
%=          =%x=w-tw-10:^
%=          =%y=h-th-10:^
%=          =%expansion=none^
    -map 0:v ^
    -map 0:a? ^
    -c:v h264 ^
    -crf 30 ^
    -c:a aac ^
    -q:a 1 ^
    -ac 1 ^
    %VIDEO:~0,-5%_WATERMARK.mp4

If I try to use spaces or tabs in the "-vf" section ffmpeg interprets them as the end of the filter and the start of the output file argument .

A: You should quote the video-filter expression. Then you don't need those temporal variables:
ffmpeg^
  -y^
  -loglevel verbose^
  -i %VIDEO%^
  -vf ^"^
    scale=^
      width=-2:^
      height=360,^
    drawtext=^
      fontfile='C\:/Windows/Fonts/impact.ttf':^
      text='%TITULO%':^
      fontcolor=white:^
      borderw=1:^
      fontsize=18:^
      alpha=0.99:^
      x=(w-tw)/2:^
      y=th/4:^
      expansion=none,^
    drawtext=^
      fontfile='C\:/Windows/Fonts/arial.ttf':^
      text='WATERMARK':^
      fontcolor=white:^
      borderw=1:^
      fontsize=18:^
      alpha=0.60:^
      x=w-tw-10:^
      y=h-th-10:^
      expansion=none^
  "^
  -map 0:v^
  [...]

Yes, that's ^" at the beginning and " at the end.
Also please quote the "TITULO"-variable within the expression: '%TITULO%'.
Finally, as a side note; the encoding.
There's a pretty good chance your Batch script is encoded as ANSI (Windows-1252).
This means your Introduzca el título del vídeo will come out as Introduzca el tφtulo del vφdeo.
The ANSI encoded í (ALT+0237) comes out as the OEM encoded φ (ALT+237).
In order to get the OEM encoded í (ALT+161) you have to enter the ANSI encoded ¡ (ALT+0161).
So Introduzca el t¡tulo del v¡deo will come out as Introduzca el título del vídeo.
This website has a nice chart where you can look it up, but charmap can also help.
If you highlight the í, then you'll see U+00ED (0xA1): Latin Small Letter I With Acute      Keystroke: Alt+0237 mentioned below.
ED (hex) = 237 (dec) and A1 (hex) = 161 (dec).
You can ignore this if your Batch script is encoded as OEM (CP437).


text:
Q: Changing color of bottom border on hover In this plunk I have a div that's resizable at the bottom border (using jQueryUI). What I need is to change the color of the bottom border when the mouse hovers it. Note that when the div is hovered over other borders, the color of the bottom border should not change.
Mouseover events work at the element level, not at the border level, so I'm not sure this can be achieved. Any ideas?
HTML

Javascript
  $(".div2").resizable({
    handles: "s"
  });

A: You can use a pseudoelement.
You create the border to show on hover, position it in relation to the handle, and set it to be transparent until it's hovered over:
Updated plunker
Relevent CSS:
  .ui-resizable-handle:after {
    content: '';
    display: block;
    height: 1px;
    width: 100%;
    background: transparent;
    position: absolute;
    bottom: 4px;
    left: 0;
    right: 0;
  }

  .ui-resizable-handle:hover:after {
    background: blue;
  }

A: Quick css hack might do the job - hover style changes bottom border on mouse hover and then active switches it back to the original color when it is being resized.
.div2:hover {
  border-bottom-color: green;
}

.div2:active {
  border-bottom-color: solid orange;
}

A: You might be able to try something as simple as this

$(".div2").resizable({
    handles: "s"
  });

function borderOver() {
    document.getElementById("div2").style.border-bottom = "solid, red, 1px";
}

function borderOut() {
  document.getElementById("div2").style.border-bottom = "solid, white, 1px";
}


text:
Q: Vertical lines to separate boxplot groups in python I would like to draw additional vertical lines that will separate grouped boxplots like in the right-hand picture. The left-hand picture is the original picture (source: https://www.originlab.com/doc/Origin-Help/DoubleY-Box-Chart). I would appreciate for help how to do that by using matplotlib or seaborn package. Thank you and best regards.

The simple code I am using to create example boxplot:
fig, ax = plt.subplots(1, sharex=False, sharey=False, gridspec_kw={'hspace': 0}, figsize=(10, 5))
bill = sns.load_dataset("tips")
sns.boxplot(x="day", y="total_bill", hue="sex", data=bill, palette="PRGn")

A: You can use this line to draw the vertical lines using matplotlib provided you have created axes or plots. I have put x in [1,2,3,4] as an example you can replace the elements of the list with desired widths.
[ax.axvline(x, color = 'r', linestyle='--') for x in [1,2,3,4]] # you can put your desired colour instead of red.

or
[plt.axvline(x, color = 'r', linestyle='--') for x in [1,2,3,4]]


text:
Q: Поиск самой длинной строки в массиве Задание звучит так:

You should implement the function String findLongestName(String []
names) which takes an array of Strings as an input containing a list
of names, and return the String that has the longest name.
To do so, try to follow these steps:

*

*The first step is to calculate and store the length of the input
array, this is done using names.length; and store that in an integer
variable.

*Then create a new String called longestName that will store
the longest name in the array of names, initialize it with the first
name in the array, that is names[0].

*Next, you should create a for
loop that will compare every name in the array using names[i] against
the longestName. Only replace the longestName value if the names[i] is
longer.

*Finally, return the longestName variable as the return value
of the function.

Вот мой код:
public String findLongestName(String[] names) {
    int size = names.length;
    String longestName = names[0];
    for (int i = 0; i <= size; i++) {
        if (names[i].length() > longestName.length()) {
            longestName = names[i];
        }
    }
    return longestName;
}

На попытку воспроизвести код выходит ошибка, что нужно что-то исправить (в прямом смысле что-то, так как прохожу обучение языку на сайте). В чем проблема, не подскажите? Принципиально не хочу смотреть ответ и пытаюсь сам понять в чем моя ошибка.

A: Хм, даже не знаю, как ответить, чтобы Вам не смотреть ответ ). Тем не менее, иметь принципы в наше время - похвально.
Индексы элементов в массиве изменяются от нуля до length минус один.
for (int i = 0; i < size; i++) {
  ...

A: Для поиска максимального элемента в массиве есть метод Stream.max(Comparator):
public static void main(String[] args) {
    String[] names = {"Иван", "Пётр", "Фёдор"};

    System.out.println(findLongestName(names)); // Фёдор
}

public static String findLongestName(String[] names) {
    return Arrays.stream(names).max(Comparator.comparing(String::length)).get();
}


text:
Q: Proving that CFG generates a language I need to construct a CFG for the language consisting of even length palindromes with the same number of a's and b's and then prove that it generates that language.
This is the CFG I got:
S→ abba | baab | abSba | baSab | ε
I'm unsure of what to do to prove it (I just came up with this logically)...If anyone could point me in the right direction I would appreciate it. Thank you!


text:
Q: XPS13 - White screen on boot I have an XPS 13 9380 which was working quite well. In the last few days I cannot boot it anymore. When booting I end up in a white screen with some rubbish in the upper left corner.
I have manage to boot it in safe mode but I cannot work out yet where it is failing when booting in normal mode.

*

*Are there any known issues in the last week that affect XPS 13?

*any tips for diagnosing this kind of problems?


text:
Q: Calculating via months showing all for Jan?!? (MySql Workbench 6.3 CE) I have a script which calculates the percentage increase or decrease against the previous months total. E.g. Jan's percentage will be 0, then whatever Feb's total is, the pecentage is worked out against Jan's etc.
I have created the table in sqlfiddle (http://sqlfiddle.com/#!9/8c2eac/2/0)
The results show every month as January, i want to see Jan, Feb, March etc, in the correct order, so that the percentage calculations are worked out correctly also. Any ideas?
http://sqlfiddle.com/#!9/8c2eac/2/0
SELECT monthname(concat('1970-', lpad('1', A.MONTH, '0'), '-01')) AS MONTH,
       A.SALES_AMOUNT,
       CASE
         WHEN A.SALES_AMOUNT IS NULL
           THEN NULL
         WHEN B.SALES_AMOUNT IS NULL
           THEN NULL
         WHEN A.SALES_AMOUNT = 0
           THEN NULL
         ELSE
           ROUND((B.SALES_AMOUNT / A.SALES_AMOUNT - 1) * 100,2)
       END AS PERCENTAGE
       FROM (SELECT month(TRANSACTION_DATE) AS MONTH,
                    ROUND(sum(SALES_AMOUNT),2) AS SALES_AMOUNT
                    FROM SALES
                    WHERE year(TRANSACTION_DATE) = 2018
                    GROUP BY MONTH) A
            LEFT JOIN (SELECT month(TRANSACTION_DATE) AS MONTH,
                              ROUND(sum(SALES_AMOUNT),2) AS SALES_AMOUNT
                              FROM SALES
                              WHERE year(TRANSACTION_DATE) = 2018
                              GROUP BY MONTH) B
                      ON A.MONTH - 1 = B.MONTH
       ORDER BY A.MONTH;

Result:
January 45163.22
January 34531.15    30.79
January 44194.98    -21.87
January 30826.68    43.37
January 39016.04    -20.99
January 37284.25    4.64
January 37640.08    -0.95
January 39703.85    -5.20
January 34958.94    13.57
January 34447.61    1.48
January 39161.90    -12.04
January 36986.16    5.88

A: Looks suspiciously like the answer I gave here. I made a mistake there, I thought I'd already edited out --  it's a leftover from a quick test. Turns out, I didn't, sorry for that.
Replace monthname(concat('1970-', lpad('1', A.MONTH, '0'), '-01')) with monthname(concat('1970-', lpad(A.MONTH, 2, '0'), '-01')).
(And maybe consider accepting my answers if you use them.)

Edit:
Switch roles of A and B:
SELECT monthname(concat('1970-', lpad(A.MONTH, 2, '0'), '-01')) AS MONTH,
       A.SALES_AMOUNT,
       CASE
         WHEN A.SALES_AMOUNT IS NULL
           THEN NULL
         WHEN B.SALES_AMOUNT IS NULL
           THEN NULL
         WHEN B.SALES_AMOUNT = 0
           THEN NULL
         ELSE
           ROUND((A.SALES_AMOUNT / B.SALES_AMOUNT - 1) * 100,2)
       END AS PERCENTAGE
       FROM (SELECT month(TRANSACTION_DATE) AS MONTH,
                    ROUND(sum(SALES_AMOUNT),2) AS SALES_AMOUNT
                    FROM SALES
                    WHERE year(TRANSACTION_DATE) = 2018
                    GROUP BY MONTH) A
            LEFT JOIN (SELECT month(TRANSACTION_DATE) AS MONTH,
                              ROUND(sum(SALES_AMOUNT),2) AS SALES_AMOUNT
                              FROM SALES
                              WHERE year(TRANSACTION_DATE) = 2018
                              GROUP BY MONTH) B
                      ON A.MONTH - 1 = B.MONTH
       ORDER BY A.MONTH;


text:
Q: SQS - all messages goes into flight even when maxNumberOfMessages is set to 1 I have a defined pod scaling based on the number of messages in sqs. And i want each pod to process 1 message.
So if i have 3 messages, i will have 3 pods and each processing 1 message.
This is how i am retreiving the messages from sqs. with withMaxNumberOfMessages(1)
ReceiveMessageRequest receiveMessageRequest = new
ReceiveMessageRequest(queueUrl).withMaxNumberOfMessages(1).withWaitTimeSeconds(10);
List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
System.out.println("Number of messages - "+messages.size());

And i can see the number of messages it picks is 1.
Issue that i am facing is  when 1 pod run, all the messages in queue goes into flight-mode. And the remaining pods gets zero messages to read.
Why is that happening. even though i specified maxNumberOfMessages to 1 , why all the messages goes into flight-mod. I expect it to just pick 1 message and that message goes into flight-mode and the remaining messages remain in queue and is available for other pods
This is how i ran the code on pod startup
@EventListener(ApplicationReadyEvent.class)
    public void init() throws InterruptedException {
        SQSS3Event message = sqsRepository.getMessage(queueUrl);
        while(message != null){
            System.out.println(message.getBucketName());
            System.out.println(message.getFileName());
            System.out.println(message.getReceiptHandle());
            sqsRepository.changeMessageVisibility(queueUrl, message.getReceiptHandle(), 70);
            Thread.sleep(60000);
            sqsRepository.changeMessageVisibility(queueUrl, message.getReceiptHandle(), 10);
            sqsRepository.deleteMessage(queueUrl,message.getReceiptHandle());

            message = sqsRepository.getMessage(queueUrl);
        }
        System.out.println("No more messages to process");
    }

And this is the helper method for retrieving message from SQS
public SQSS3Event getMessage(String queueUrl){
    ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(queueUrl).withMaxNumberOfMessages(1).withWaitTimeSeconds(10);
    List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
    System.out.println("Number of messages - "+messages.size());
    if(messages.size()>0) {
        S3EventNotification notification = S3EventNotification.parseJson(messages.get(0).getBody());
        return SQSS3Event.builder()
                .bucketName(notification.getRecords().get(0).getS3().getBucket().getName())
                .fileName(notification.getRecords().get(0).getS3().getObject().getKey())
                .receiptHandle(messages.get(0).getReceiptHandle())
                .build();
    }
    else {
        return null;
    }
}

Added print statements to read queue attributes before reading and after reading a message
ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest().withQueueUrl(queueUrl).withMaxNumberOfMessages(1).withWaitTimeSeconds(5);
GetQueueAttributesResult att = sqs.getQueueAttributes(queueUrl, List.of("ApproximateNumberOfMessages", "ApproximateNumberOfMessagesNotVisible"));
System.out.println("##########################Before reading##########################");
System.out.println("No of Messages - "+ att.getAttributes().get("ApproximateNumberOfMessages"));
System.out.println("No of Messages on Flight - "+ att.getAttributes().get("ApproximateNumberOfMessagesNotVisible"));
System.out.println("##################################################################");
ReceiveMessageResult result = sqs.receiveMessage(receiveMessageRequest);
List<Message> messages = result.getMessages();

System.out.println("No of messages in the result - "+messages.size());

S3EventNotification notification = S3EventNotification.parseJson(messages.get(0).getBody());
att = sqs.getQueueAttributes(queueUrl, List.of("ApproximateNumberOfMessages", "ApproximateNumberOfMessagesNotVisible"));
System.out.println("##########################After reading##########################");
System.out.println("No of Messages - "+ att.getAttributes().get("ApproximateNumberOfMessages"));
System.out.println("No of Messages on Flight - "+ att.getAttributes().get("ApproximateNumberOfMessagesNotVisible"));
System.out.println("##################################################################");

Output

##########################Before reading##########################
No of Messages - 4
No of Messages on Flight - 0
##################################################################
No of messages in the result- 1
##########################After reading##########################
No of Messages - 0
No of Messages on Flight - 4
##################################################################

With the trace
 ##########################Before reading##########################
No of Messages - 2
No of Messages on Flight - 0
##################################################################
2022-04-07 21:59:24.036 TRACE 21096 --- [           main] c.a.s.sqs.buffered.ReceiveQueueBuffer    : Spawned receive batch #1 (1 of 10 inflight) for queue http://localhost:4576/queue/upload-notifications
2022-04-07 21:59:24.166 DEBUG 21096 --- [rWorkerThread-1] c.a.s.sqs.MessageMD5ChecksumHandler      : Message body: {"Records": [{"eventVersion": "2.0", "eventName": "ObjectCreated:Put", "eventTime": "2022-04-07T19:14:39.050963Z", "userIdentity": {"principalId": "AIDAJDPLRKLG7UEXAMPLE"}, "eventSource": "aws:s3", "requestParameters": {"sourceIPAddress": "127.0.0.1"}, "s3": {"configurationId": "testConfigRule", "object": {"versionId": "096fKKXTRTtl3on89fVO.nfljtsv6qko", "eTag": "d41d8cd98f00b204e9800998ecf8427e", "sequencer": "0055AED6DCD90281E5", "key": "3.txt", "size": 1024}, "bucket": {"arn": "arn:aws:s3:::uploads-toprocess", "name": "uploads-toprocess", "ownerIdentity": {"principalId": "A3NL1KOZZKExample"}}, "s3SchemaVersion": "1.0"}, "responseElements": {"x-amz-id-2": "eftixk72aD6Ap51TnqcoF8eFidJG9Z/2", "x-amz-request-id": "2e30a6e9"}, "awsRegion": "us-east-1"}]}
2022-04-07 21:59:24.167 DEBUG 21096 --- [rWorkerThread-1] c.a.s.sqs.MessageMD5ChecksumHandler      : Expected  MD5 of message body: 9428bd5190b9d47af3368b3f67c62d02
2022-04-07 21:59:24.167 DEBUG 21096 --- [rWorkerThread-1] c.a.s.sqs.MessageMD5ChecksumHandler      : Message body: {"Records": [{"eventVersion": "2.0", "eventName": "ObjectCreated:Put", "eventTime": "2022-04-07T19:15:50.375772Z", "userIdentity": {"principalId": "AIDAJDPLRKLG7UEXAMPLE"}, "eventSource": "aws:s3", "requestParameters": {"sourceIPAddress": "127.0.0.1"}, "s3": {"configurationId": "testConfigRule", "object": {"versionId": "096fKKXTRTtl3on89fVO.nfljtsv6qko", "eTag": "d41d8cd98f00b204e9800998ecf8427e", "sequencer": "0055AED6DCD90281E5", "key": "3.txt", "size": 1024}, "bucket": {"arn": "arn:aws:s3:::uploads-toprocess", "name": "uploads-toprocess", "ownerIdentity": {"principalId": "A3NL1KOZZKExample"}}, "s3SchemaVersion": "1.0"}, "responseElements": {"x-amz-id-2": "eftixk72aD6Ap51TnqcoF8eFidJG9Z/2", "x-amz-request-id": "a8ba5ab3"}, "awsRegion": "us-east-1"}]}
2022-04-07 21:59:24.167 DEBUG 21096 --- [rWorkerThread-1] c.a.s.sqs.MessageMD5ChecksumHandler      : Expected  MD5 of message body: 18ce2856addac8a08c394ce8fbd7d315
2022-04-07 21:59:24.167 TRACE 21096 --- [rWorkerThread-1] c.a.s.sqs.buffered.ReceiveQueueBuffer    : Queue http://localhost:4576/queue/upload-notifications now has 1 receive results cached
2022-04-07 21:59:24.168 TRACE 21096 --- [rWorkerThread-1] c.a.s.sqs.buffered.ReceiveQueueBuffer    : Spawned receive batch #2 (1 of 10 inflight) for queue http://localhost:4576/queue/upload-notifications
No of messages in the result- 1
##########################After reading##########################
No of Messages - 0
No of Messages on Flight - 2
##################################################################

Solution - (Got a workaround. Eventhough i don't fully understand it)
I was using spring cloud aws dependencies and was using an @Autowired AmazonSQS instance to interact with the queue. That one by default, gets 10 messages into some kind of BufferQueue and then serves the messages one by one. That was the reason why all messages goes into flight and then processed one by one.
Was able to override that one by defining a simple bean.
@Bean
public SimpleMessageListenerContainer simpleMessageListenerContainer(AmazonSQSAsync amazonSQSAsync) {
    SimpleMessageListenerContainer simpleMessageListenerContainer = new SimpleMessageListenerContainer();
    simpleMessageListenerContainer.setAmazonSqs(amazonSQSAsync);
    simpleMessageListenerContainer.setMessageHandler(queueMessageHandler());
    simpleMessageListenerContainer.setMaxNumberOfMessages(1);
    simpleMessageListenerContainer.setTaskExecutor(threadPoolTaskExecutor());
    return simpleMessageListenerContainer;
}

And now it works in sync with withMaxNumberOfMessages(n) as expected

A: Solution - (Got a workaround. Eventhough i don't fully understand it)
I was using spring cloud aws dependencies and was using an @Autowired AmazonSQS instance to interact with the queue. That one by default, gets 10 messages into some kind of BufferQueue and then serves the messages one by one. That was the reason why all messages goes into flight and then processed one by one.
Was able to override that one by defining a simple bean.
@Bean
public SimpleMessageListenerContainer simpleMessageListenerContainer(AmazonSQSAsync amazonSQSAsync) {
    SimpleMessageListenerContainer simpleMessageListenerContainer = new SimpleMessageListenerContainer();
    simpleMessageListenerContainer.setAmazonSqs(amazonSQSAsync);
    simpleMessageListenerContainer.setMessageHandler(queueMessageHandler());
    simpleMessageListenerContainer.setMaxNumberOfMessages(1);
    simpleMessageListenerContainer.setTaskExecutor(threadPoolTaskExecutor());
    return simpleMessageListenerContainer;
}

And now it works in sync with withMaxNumberOfMessages(n) as expected


text:
Q: Can't connect with my server on different PC using sockets TPC in C I'm working on a client / server program using sockets. The server just listen for connections and prints it's username. The client tries to find the server and sends it's username. When you run the client, you have to pass three arguments: Your username, the IP address and the port.
The program works fine on same computer, but when I try to connect on a different PC, it can't connect. After a while, it prints "Error connecting to host.".
I am doing something wrong?
Thanks!
Edit: Just one more info. My desktop (server) is on tethed USB internet connection, provided from my smartphone. The client is on Wi-Fi.
Edit2: Now the desktop is on cable and the notebook (client) is on Wi-Fi. Internet conection is up on both devices. I still can't connect. Connection timeout is the error.
Edit3: Well, now I connected both devices on wired (same router) and I connected fine. Seems I have to send an email to IT department of my uni.
client.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#define PORT 4000
#define WORD_SIZE 256

int main(int argc, char * argv[]) {
    pthread_t tid;
    int sockfd;
    struct sockaddr_in serv_addr;
    struct hostent * server;

    if (argc != 4)
    {
        printf("Not enough arguments, please inform:\n");
        printf("<username> <server_ip_adress> <port>");
        return -1;
    }

    char username[WORD_SIZE], server_ip[WORD_SIZE], port[WORD_SIZE];
    strcpy(username, argv[1]);
    strcpy(server_ip, argv[2]);
    strcpy(port, argv[3]);

    server = gethostbyname(server_ip);
    if (server == NULL)
    {
        printf("Error: no such host\n");
        return -1;
    }

    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        printf("Error opening socket\n");
        return -1;
    }

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);
    serv_addr.sin_addr = * ((struct in_addr * ) server->h_addr);
    bzero( & (serv_addr.sin_zero), 8);

    int status = connect(sockfd, (struct sockaddr * ) & serv_addr, sizeof(serv_addr));
    if (status < 0)
    {
        printf("Error connecting to host.\n");
        return -1;
    }

    if (send(sockfd, username, WORD_SIZE, 0) < 0)
    {
        printf("Error sending username.\n");
        close(sockfd);
        return -1;
    }

    printf("Username sent.\n");
    close(sockfd);

    return 0;
}

server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 4000
#define WORD_SIZE 256

int main(int argc, char *argv[])
{
    int serverSockfd;
    socklen_t clilen;
    struct sockaddr_in serv_addr, cli_addr;

    if ((serverSockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        printf("Error creating the socket.\n");

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);
    serv_addr.sin_addr.s_addr = INADDR_ANY;

    if (bind(serverSockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    {
        printf("Error binding the socket.\n");
        return -1;
    }

    if (listen(serverSockfd, 5) < 0)
    {
        printf("Error on listening.\n");
        return -1;
    }

    int newSockfd;
    while (1)
    {
        newSockfd = accept(serverSockfd, (struct sockaddr *)&cli_addr, &clilen);
        if (newSockfd < 0)
        {
            printf("Error on accept a new client.\n");
            continue;
        }

        char username[WORD_SIZE];
        if (recv(newSockfd, username, WORD_SIZE, 0) < 0)
        {
            printf("Error receiving username.\n");
            close(newSockfd);
            continue;
        }

        printf("User %s logged in.\n", username);
        close(newSockfd);
    }
}


text:
Q: AQL update succeeds in collection loop but throws not found error in graph traversal I am trying to figure out how to update edge documents using a graph traversal query in arangodb. I am able to do this using the standard
FOR e IN collectionName UPDATE e with {newProps} IN collectionName. However I cannot figure out what is wrong with my attempt to accomplish the same thing using the
FOR v, e, p IN 1..5 OUTBOUND @startId GRAPH @graphName syntax.
I am using the arangodb:latest docker image on macOS Mojave 10.14.3, and I am using arango's go library (github.com/arangodb/go-driver) to query by building a query string and sending it using the Database.Query() function. I have tried just returning the key for the edge I'm trying to update (i.e. just returning e._key instead of attempting to update in the query below), and have verified using arangosh that that is indeed the correct key of the edge I'm trying to update. Additionally as stated above, I have been able to update an edge using the relational AQL syntax.
Here is my query:
FOR v, e, p IN 1..5 OUTBOUND @startId GRAPH @graphName
    FILTER e.@key0 == @val0
    UPDATE e._key WITH {@propName0: @propValue0} IN has_skill
    RETURN {new: NEW, old: OLD}

and here are my bind variables:
[graphName:Matthew_Loughney, key0:_from, propName0:testProp, propValue0:testVal, startId:applicant/232, val0:applicant/232]

I would expect that when I view the has_skill collection using arangosh, I would see that my edge now has a property testProp with value testVal; however, I instead just get the error AQL: document not found (while executing) and my edge remains unchanged.

A: It turned out that my filter was returning some edges not in the has_skill collection (4 total to be exact), so when it tried to update in has_skill, it succeeded for the one I wanted but failed for the other 3, and since the UPDATE operation is atomic that made it fail for all of them. I did not notice this because I was only looking at the first edge returned when looking at the keys, and this wasn't an issue in my FOR e IN collectionName query because obviously those are all in the correct collection, so that only returned the 1 edge I was looking for.


text:
Q: Meteor `Please add the Android platform` but next `Platform android already added` Source
I do tutorial:

https://www.meteor.com/tutorials/blaze/running-on-mobile

Error
I am executing command:
 meteor run android-device

And obtaining info that I should add android platform
Please add the Android platform to your project first.
Run: meteor add-platform android

But when I run command:
meteor add-platform android --verbose

Then I get confounding error suggesting that platform android already added
Adding platform Android to Cordova project
%% No scripts found for hook "before_platform_add".
=> Errors executing Cordova commands:

   While adding platform Android to Cordova project:
   Cordova error: Platform android already added.
   at /home/daniel/.meteor/packages/meteor-tool/.1.4.3_2.18ygcop++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/lib/node_modules/cordova-lib/src/cordova/platform.js:130:31
   at _fulfilled (/home/daniel/.meteor/packages/meteor-tool/.1.4.3_2.18ygcop++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/lib/node_modules/q/q.js:787:54)
   at self.promiseDispatch.done (/home/daniel/.meteor/packages/meteor-tool/.1.4.3_2.18ygcop++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/lib/node_modules/q/q.js:816:30)
   at Promise.promise.promiseDispatch (/home/daniel/.meteor/packages/meteor-tool/.1.4.3_2.18ygcop++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/lib/node_modules/q/q.js:749:13)
   at /home/daniel/.meteor/packages/meteor-tool/.1.4.3_2.18ygcop++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/lib/node_modules/q/q.js:557:44
   at flush (/home/daniel/.meteor/packages/meteor-tool/.1.4.3_2.18ygcop++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/lib/node_modules/q/q.js:108:17)
   at nextTickCallbackWith0Args (node.js:489:9)
   at process._tickCallback (node.js:418:13)
   => awaited here:
   at Function.Promise.await
   (/home/daniel/.meteor/packages/meteor-tool/.1.4.3_2.18ygcop++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/lib/node_modules/meteor-promise/promise_server.js:35:12)
   at CordovaProject.runCommands (/tools/cordova/project.js:715:22)
   at CordovaProject.addPlatform (/tools/cordova/project.js:372:10)
   at CordovaProject.ensurePlatformsAreSynchronized (/tools/cordova/project.js:403:12)
   at /tools/cli/commands-cordova.js:60:20
   at /tools/utils/buildmessage.js:271:13
   at [object Object]._.extend.withValue (/tools/utils/fiber-helpers.js:89:14)
   at /tools/utils/buildmessage.js:264:29
   at [object Object]._.extend.withValue (/tools/utils/fiber-helpers.js:89:14)
   at /tools/utils/buildmessage.js:262:18
   at [object Object]._.extend.withValue (/tools/utils/fiber-helpers.js:89:14)
   at /tools/utils/buildmessage.js:253:23
   at [object Object]._.extend.withValue (/tools/utils/fiber-helpers.js:89:14)
   at Object.capture (/tools/utils/buildmessage.js:252:19)
   at Object.main.captureAndExit (/tools/cli/main.js:271:29)
   at Command.func (/tools/cli/commands-cordova.js:42:8)
   at /tools/cli/main.js:1483:23
   (If the error message contains suggestions for a fix, note that this may not apply to the Meteor integration. You can try running again with the --verbose option to help diagnose the issue.)

Additional info:
Smartphone is connected
adb devices
List of devices attached
b799f64c    device

My system info:
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.2 LTS
Release:    16.04
Codename:   xenial

NPM
npm -v
3.5.2

Compiling by pure Cordova works correctly

A: If you added platform in .meteor/platforms file by hand, stuff can go wrong, so just re-add the platform.
meteor remove-platform android
meteor add-platform android


text:
Q: Dynamic creation of columns using csvHelper I have a worker with various fields that are fetched from server. I am using CSVHelper package to convert this class to an excel sheet.
Worker has Fields like :
class Worker
{
    string name;
    string phone;
    string age;
    Dictionary<string,object> customerField;
}

I can map the name, phone, number like
class WorkerMap : CsvClassMap<Worker>
{
    public WorkerMap()
    {
        Map(m => m.name);
        Map(m => m.phone);
        Map(m => m.age);
    }
}

And I generate the map by :
csv.Configuration.RegisterClassMap<WorkerMap>();

Write the list of workers by :
csv.WriteRecords(workerList);

How can I map the customerField dictionary to the excel sheet such that the Key (string) is another column name and the value(object) is the value of the column.
Does CSVHelper help us do it at runtime. I looked through the documentation. Couldn't find anything that worked for me.

A: Dictionary isn't supported but ExpandoObject is supported.
https://github.com/JoshClose/CsvHelper/blob/48e70742e06007dae3a635c418b7e3358f667c4f/src/CsvHelper.Tests/Writing/MultipleHeadersTest.cs
https://github.com/JoshClose/CsvHelper/blob/b74a2f95a101158f4cdedd25fae6e8392b58855b/src/CsvHelper.Tests/Writing/DynamicTests.cs
If you follow the first link above you'll find the WriteDynamicHeader method in use on lines 50 & 57.
With help of an extension method I create an ExpandoObject for each record and use CsvHelper to write that object.The Dictionary<string, object> parameter named document is what I wish to create the CSV record from.
public static class DictionaryCsvExtentions
{
    public static dynamic BuildCsvObject(this Dictionary<string, object> document)
    {
        dynamic csvObj = new ExpandoObject();

        foreach (var p in document)
        {
            AddProperty(csvObj, p.Key, p.Value);
        }

        return csvObj;
    }

    private static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
    {
        var expandoDict = expando as IDictionary<string, object>;
        if (expandoDict.ContainsKey(propertyName))
        {
            expandoDict[propertyName] = propertyValue;
        }
        else
        {
            expandoDict.Add(propertyName, propertyValue);
        }
    }
}

Now I can create an ExpandoObject from my dictionary like this
var csvObj = myDictonary.BuildCsvObject();

and with that, following Josh's tests in the link above we have all we need to use a dictionary fairly seamlessly with CsvHelper. I don't think this is a better solution to Michael's, just a different approach.
credit where credit is due the basic ExpandoObject from dictionary code is from  here (where there is a lot more explanation!) https://www.oreilly.com/learning/building-c-objects-dynamically

A: I don't think that writing a dictionary is supported at this time. For one thing, CsvHelper would have a difficult time knowing what headers to write. Fortunately, it's not too complex to use CsvWriter manually, writing a field at a time. If we assume that each Worker has the same keys in customerField then your code might look something like this.
var firstWorker = workerList.First();
var keys = firstWorker.customerField.Keys.ToList();

var headers = new []{ "name", "phone", "age"}.Concat(keys).ToList();
var csv = new CsvWriter( textWriter );

// Write the headers
foreach( var header in headers )
{
    csv.WriteField(header);
}
csv.NextRecord();

// Write the rows
foreach( var item in workerList)
{
    csv.WriteField(item.name);
    csv.WriteField(item.phone);
    csv.WriteField(item.age);
    var dict = worker.customerField;
    foreach (var key in keys)
    {
        csv.WriteField(dict[key]);
    }
    csv.NextRecord();
}

This code is untested, but should get you pretty close to the behavior you need. If the customerField dictionary keys are not consistent in the list then the code would be a bit more complicated but it's still solvable.

A: Recently had the same problem and for the sake of completeness posting another answer. We had fairly complex ClassMap<Worker> like class and did want to loose it. Also, we needed both CSV write and read hence the ExpandoObject from the robs answer was needed as well. Eventually, the approach is like combination of the Michael Richardson and robs answer that should bring best of both worlds.
On top of that, to distinguish dictionary fields in the CSV file during read it is a good idea to prefix them with something like "customerField.".
First we need conversion of dictionary to/from Worker.customerField:
public static class WorkerExtensions
{
    const string CustomerFieldPrefix = nameof(Worker.customerField) + ".";

    public static dynamic GetCustomerFieldExpando(this Worker worker)
    {
        var expando = new ExpandoObject() as IDictionary<string, object>;

        foreach (var fieldPair in worker.customerField)
        {
            expando[CustomerFieldPrefix + fieldPair.Key] = fieldPair.Value ?? "";
        }

        return expando;
    }

    public static void SetCustomerField(this Worker worker, ExpandoObject expando)
    {
        var columnsToValues = expando as IDictionary<string, object>;

        foreach (var columnValuePair in columnsToValues)
        {
            if (columnValuePair.Key.StartsWith(CustomerFieldPrefix)
                && columnValuePair.Key.Length > CustomerFieldPrefix.Length)
            {
                string key = columnValuePair.Key.Substring(CustomerFieldPrefix.Length);
                worker.customerField[key] = columnValuePair.Value;
            }
        }
    }
}

Next, CSV write can use both ClassMap and ExpandoObject and looks like this:
        csv.Configuration.HasHeaderRecord = true;
        csv.Configuration.RegisterClassMap<WorkerMap>();

        csv.WriteHeader<Worker>();
        (workers.First().GetCustomerFieldExpando() as IDictionary<string, object>)
            .Keys.ToList().ForEach(key => csv.WriteField(key));
        csv.NextRecord();

        foreach (var worker in workers)
        {
            csv.WriteRecord(worker);
            csv.WriteRecord(worker.GetCustomerFieldExpando());
            csv.NextRecord();
        }

Finally, CSV read can also combine both ClassMap and ExpandoObject:
        List<Worker> workers = new List<Worker>();

        csv.Configuration.HasHeaderRecord = true;
        csv.Configuration.RegisterClassMap<WorkerMap>();

        csv.Read();
        csv.ReadHeader();
        var columns = csv.Context.HeaderRecord;

        while (csv.Read())
        {
            var worker = csv.GetRecord<Worker>();
            workers.Add(worker);

            ExpandoObject expando = csv.GetRecord<dynamic>();
            worker.SetCustomerField(expando);
        }

In case of CSV read things get more complicated if you want to read real types into dictionary values (not just strings). We needed predefined associations between dictionary keys and data types to be able to convert to proper types from the ExpandoObject.


text:
Q: Given $ax^2+bxy+cy^2+dx+ey+f$, what is the best way to get {a,b,c,d,e,f}? Test cases:
SeedRandom[0]
rand = RandomInteger[{-5, 5}, {5, 6}]
poly = rand.{x^2, x y, y^2, x, y, 1}

res1 = MonomialList[#, {x, y}, "DegreeLexicographic"] /. x | y -> 1 & /@ poly

res2 = CoefficientRules[#, {x, y}, "DegreeLexicographic"][[All, 2]] & /@ poly

res1 == rand
res2 == rand

{{5, 2, -5, 3, -3, -4}, {0, 3, -5, 1, 2, 5}, {-3, -4, -5,    1, -4,
  -3}, {5, 5, 3, 5, 1, 5}, {0, 0, 3, -1, 0, 4}}
{-4 + 3 x + 5 x^2 - 3 y + 2 x y - 5 y^2,   5 + x + 2 y + 3 x y - 5
  y^2, -3 + x - 3 x^2 - 4 y - 4 x y - 5 y^2,   5 + 5 x + 5 x^2 + y + 5 x
  y + 3 y^2, 4 - x + 3 y^2}
{{5, 2, -5, 3, -3, -4}, {3, -5, 1, 2, 5}, {-3, -4, -5, 1, -4, -3}, {5,
  5, 3, 5, 1, 5}, {3, -1, 4}}
{{5, 2, -5, 3, -3, -4}, {3, -5, 1, 2, 5}, {-3, -4, -5, 1, -4, -3}, {5,
  5, 3, 5, 1, 5}, {3, -1, 4}}
False
False

When one of the coefficients is zero, I want to get 0, not a missing entry.

A: CoefficientArrays come to mind, but it needs some tweaking. The below solutions work for polynomials of order $2$.
Demonstration
{m0, m1, m2} = CoefficientArrays[poly[[1]], {x, y}] // Normal

{-4, {3, -3}, {{5, 2}, {0, -5}}}

We want upper-right triangular elements of m2:
Flatten@Table[m2[[i, i ;;]], {i, 1, Length@m2}]

{5, 2, -5}

Make it a function:
RU[m_] := Flatten@Table[m[[i, i ;;]], {i, 1, Length@m}]

and Join it with m1 and m0:
RU[m2]~Join~m1~Join~{m0}

{5, 2, -5, 3, -3, -4}

Function
Clear@RU

coeff[pol_] :=
 Block[{ca = CoefficientArrays[pol, {x, y}] // Normal // Reverse, RU},
   RU[m_] := Flatten@Table[m[[i, i ;;]], {i, 1, Length@m}];
  RU[First@ca]~Join~Flatten@Rest@ca]

(coeff /@ poly) == rand

True

The function coeff gives the coefficients in the exact same order as the OP requested.
Three variables
However, a re-arrangement of the terms will make the computations easier:
SeedRandom[0]
rand3 = RandomInteger[{-5, 5}, {3, 10}]
poly3 = rand3.{x^2, y^2, z^2, x y, y z, x z, x, y, z, 1};

{{5, 2, -5, 3, -3, -4, 0, 3, -5, 1}, {2, 5, -3, -4, -5, 1, -4, -3, 5,
    5}, {3, 5, 1, 5, 0, 0, 3, -1, 0, 4}}

So here squares come first, then mixed terms, first order terms, and the free term.
{m0, m1, m2} = CoefficientArrays[poly3[[1]], {x, y, z}] // Normal

{1, {0, 3, -5}, {{5, 3, -4}, {0, 2, -3}, {0, 0, -5}}}

Then
Flatten[Table[Diagonal[m2, k], {k, 0, 2}]]~Join~m1~Join~{m0}

{5, 2, -5, 3, -3, -4, 0, 3, -5, 1}

and
% == rand3[[1]]

True

The same line of reasoning should apply to any number of variables, hence
N variables
coeffN = Module[{ca = CoefficientArrays[#, Variables@#] // Normal},
   Flatten[Table[Diagonal[ca[[3]], k], {k, 0, 2}]]~Join~ca[[2]]~Join~{ca[[1]]}
    ] &;

E.g.
(coeffN /@ poly3) == rand3

True

A: You can also use CoefficientList as follows:
Flatten[Table[Diagonal[#, -i], {i , 0, Length[#[[1]]] - 1}]] & /@
  PadLeft[Reverse /@ CoefficientList[poly, {x, y}]]

{{5, 2, -5, 3, -3, -4},
   {0, 3, -5, 1, 2, 5},
   {-3, -4, -5, 1, -4, -3},
  {5, 5, 3, 5, 1, 5},
  {0, 0, 3, -1, 0, 4}}

% == rand

True

For arbitrary polynomials in two variables, we can define a function
ClearAll[dlexCL]
dlexCL = Module[{cl = Reverse @ CoefficientList[#, Variables[#]]}, Flatten @
 Table[Diagonal[PadLeft[cl, {#, #}&@Length@cl[[1]]], -i], {i, 0, Length@cl[[1]] - 1}]]&;

dlexCL /@ poly == rand

True

dlexCL[1 + x^2 + 3 x^3 y + 2 y^4, {x, y}]

{0, 3, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}

A: I do not understand your code, I am just answering the title of your post:

Given ax^2+bxy+cy^2+dx+ey+f, what is the best way to get
  {a,b,c,d,e,f}?

expr = a x^2 + b x y + c y^2 + d x + e y + f;
r = Flatten[CoefficientList[expr, {x, y}]]
DeleteCases[r, 0]

A: I find a combination of Series and LogicalExpand useful for this sort of problem:
pattern = a x^2 + b x y + c y^2 + d x + e y + f;

vars = {a, b, c, d, e, f};

res =
  vars /. Flatten[
      Solve[LogicalExpand[Series[pattern == #, {x, 0, 2}, {y, 0, 2}]],
        vars]] & /@ poly;

res == rand
(* True *)


text:
Q: Equation for tangent plane at a point find an equation for the tangent plane at the point (1,-1,4) for the surface given by $$z^2-2x^2-2y^2-12=0$$
my answer/work: $$<-4x,-4y,2z>$$
plug in points to obtain $$<-4,4,8>$$
plug into tangent plane equation.
$$z-8=-4(x-1)+4(y+1)$$
This was just a simple quiz and my professor marked -1 off this problem.. what did i do wrong? was i supposed to continue and distribute everything? because from my knowledge i thought the tangent equation was just $$z-z_o=f_x(x_o,y_o)(x-x_o)+f_y(x_o,y_o)(y-y_o)$$

A: One way
Note that
$$z^2-2x^2-2y^2-12=0\implies z=\pm \sqrt{2x^2+2y^2+12}.$$ Since the point $(1,-1,4)$ has $z>0$ we consider $$z=\sqrt{2x^2+2y^2+12}.$$ Now
$$\frac{\partial z}{\partial x}=\frac{2x}{\sqrt{2x^2+2y^2+12}}$$ and
$$\frac{\partial z}{\partial y}=\frac{2y}{\sqrt{2x^2+2y^2+12}}.$$ Evaluating at $(1,-1)$ we have $$\frac{\partial z}{\partial x}=\frac12,\quad \frac{\partial z}{\partial y}=-\frac12.$$ Thus, the equation of the tangent plane is $$z-4=\frac12(x-1)-\frac12(y+1).$$
Another way
If you call $f(x,y,z)=z^2-2x^2-2y^2-12$ and you get $$\nabla f=(f_x,f_y,f_z)$$ and evaluates it at the point $(1,-1,4)$ you get the normal vector of the plane at such a point. Thus you can write the equation of the plane as $$4(x-1)-4(y+1)+8(z-4)=0.$$


text:
Q: How do I reverse the stacked bar order in R ggplot As you can see the percentages are on the wrong stacked bar which I'd like to change. I have tried position_fill(reverse = TRUE) however it just wipes out my graph completely.
df2 <- data.frame(table(food$BusinessType, food$classification))
names(df2) <- c('Type', 'Rating', 'Count')
df2

df2 <- ddply(df2, .(Type), transform, percent=Count/sum(Count) *100)
df2 <- ddply(df2, .(Type), transform, pos = (cumsum(Count) - 0.9 * Count))
df2$label <- paste0(sprintf('%.0f', df2$percent), '%')

ggplot(df2, aes(x=Type, y=Count, fill=Rating)) +
  geom_bar(stat = 'identity') +
  geom_text(aes(y = pos, label = label), size =4) +
  ggtitle('Business Type Ratings')


text:
Q: cvc-elt.1: Cannot find the declaration of element 'configuration' I want to use Logback in my Web Project,but in logback.xml there is a problem:

cvc-elt.1: Cannot find the declaration of element 'configuration'.

Here is my XML:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <property name="USER_HOME" value="logs" />
    <property scope="context" name="FILE_NAME" value="mylog-logback" />

    <timestamp key="byDay" datePattern="yyyy-MM-dd" />

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>

    <appender name="file"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${USER_HOME}/${FILE_NAME}.log</file>

        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <fileNamePattern>${USER_HOME}/${byDay}/${FILE_NAME}-${byDay}-%i.log.zip
            </fileNamePattern>
            <minIndex>1</minIndex>
            <maxIndex>10</maxIndex>
        </rollingPolicy>

        <triggeringPolicy
            class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>5MB</maxFileSize>
        </triggeringPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            </pattern>
        </encoder>

    </appender>

    <logger name="com.linkcos.object.*" level="track" additivity="false">
        <appender-ref ref="file" />
        <!-- <appender-ref ref="STDOUT" /> -->
    </logger>

    <root level="info">
        <appender-ref ref="file" />
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

This is really a strange question,please help me!

A: Add xmlns and xsi in the configuration tag
<configuration
    xmlns="http://ch.qos.logback/xml/ns/logback"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://ch.qos.logback/xml/ns/logback http://ch.qos.logback/xml/ns/logback/logback.xsd">

A: Do not import logback.xml to Spring Application.


text:
Q: Code generation to initialise by default to empty list instead of null Does Swagger code generation tool have an option for selecting whether the generated classes should have Lists, Maps etc. defaulted to null or empty?
Previously, the default was empty, for example private List<String> names = new List<String>.
At the moment the default is null, i.e. private List<String> names = null
The change was done in April 2017 and based on what I understand from the changes made there is no option for selecting which to use, it's always defaulted to null from that point onwards.
The discussion contains reasons why this is better and I have nothing against that. But I have a legacy app that have used some form of (Swagger) generated sources with little modifications and I'm trying to get rid of these and use swagger generated model only. The problem is that the code is originally written in a manner that there can be no null values and thus null checks are not done.
So what can be done? Use previous version of Swagger codegen?
The API is not in my control and thus yaml modification is not an option (if that would even provide help).

A: I solved this issue as I was speculating in the question and downgraded the codegen cli version to 2.2.2, which is AFAIK the last version that creates lists and maps empty instead of null.

A: Based on a comment [Java] How can we set List and Map to null by default in models? you'd need to edit any mustache template files for java (most likely pojo.mustache) and change the way lists/maps are instantiated.

A: I was able to do this in my specification file: default: []