text:
Q: what does "consensus call" mean? Can anybody explain what "consensus call" means in this sentence for me -
To be sure, a recession is not the consensus call on Wall Street, with projections in recent days showing increased optimism?
Thanks a lot.

A: To "call" something can be to predict it, or make a judgment on it.
For instance: if there is an election and the candidates seem to have a similar number of supporters, then people who predict elections might say that the election is "too close to call".  But if candidate X is clearly ahead, even though the election hasn't happened it might be said that those making predictions are "calling the election for candidate X".
The "consensus call" here is the "prevailing opinion on the likelihood of a recession".  Due to recent optimistic information, the consensus is not to "make the call" that there will be a recession.
(Note: In finance terminology, there is another meaning of call... in terms of a kind of stock option:
https://en.wikipedia.org/wiki/Call_option
...but this isn't talking about that.)

A: A consensus is when most people agree on a decision.
A call (in market terms) is a forecast on the future.
A consensus call is the same market call made by a majority of market watchers (analysts, strategists, portfolio managers).  Having a consensus leads to herding where most market participants will do the same thing at the same time. To do the opposite of the consensus is to be contrarian.
In your example, the projection is the forecast.  When a recession occurs most participants will be gloomy in their outlook, however, your example is saying that there is increased optimism in projections which means most people (the consensus) do not think a recession will occur.
As a side note, the consensus can be horribly wrong at times, especially at turning points.


text:
Q: How is the Kubernetes job queue sorted? When jobs cannot be scheduled due to cluster resource limits, are they scheduled in FIFO order when resources free up?
Or is there any other mechanism? Thanks!

A: *

*Jobs are scheduled like any other pod.

*The main difference is that Jobs doesn't have ReplicaSet since ReplicaSet is used for managing replication while job does not require replication, its run and is completed.

So to answer your question it will behave just like any other pod regarding scheduling.

redpajama_set_name: RedPajamaStackExchange


text:
Q: can we say "look forward and downward"? Suppose I'm instructing people to learn Chinese kungfu and I ask them to look at the direction, downward and forward(it's the movement of their eyes).
If I want to say "look forward and look downward at the same time", can I express it in the following way?

"look forward and downward."

I don't know if it's natural in English. If not, how should we say?
Thank you in advance.

A: You can use either "look forward" or "look downward" in English but the instruction "look forward and downward" is a little confusing because the directions are considered somewhat different from each other.
Another complicating factor is the idiom, "forward and upward" which isn't directly related to physical directions. If you were to say "forward and downward" many people would associate the phrase with the idiom and assume you were invoking some form of wordplay.
The alternative you mention in the comments is much more clear:

Look down in front of you.

This is a relatively common expression and means exactly what you want it to mean. You can also omit "down":

Look in front of you.

Most English speakers will look slightly ahead of themselves and then scan downward looking for the intended object.


text:
Q: what is best approach for consuming Soap based webservices in android what is best approach for consuming Soap based webservices in android

A: A web service is any piece of software that makes itself available over the internet that can be remotely invoked using HTTP, that is, it can be activated using HTTP requests. XML is used to encode all communications to a web service. Web services allows you to expose the functionality of your existing code over the network but code are completely invisible to Web site surfers and software users. Their job is to run silently in the background,For example, a client invokes a web service by sending an XML message, then waits for a corresponding XML response. Because all communication is in XML, web services are not tied to any one operating system or programming language--Java can talk with Perl; Windows applications can talk with Unix applications,thus  providing a way for applications to work with each other to get the user the information or functionality he needs.
                Along with XML, Web Services uses standardized industry standard protocol for the communication. All the four layers (Service Transport, XML Messaging, Service Description and Service Discovery layers) uses the well defined protocol in the Web Services protocol stack. This standardization of protocol stack gives the business many advantages like wide range of choices, reduction in the cost due to competition and increase in the quality.
Read This Tutorial  for entire information.
And read this previous Question on same topic.


text:
Q: is using clear-site-data header removing client sides storages other than browser? i was coming to http headers and that was it :
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data
my question is that by using this header are we able to clear storages in other client platforms other than browsers such as android or ios native application?


text:
Q: STATUS_NETWORK_ERROR_OPERATION_FAILED in Android I am implementing the necessary code. But when I try to submit the score I am getting this error. I tried out the solutions provided in answers to different questions, but I couldn't solve my problem.
Code:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setupView();
    beginUserInitiatedSignIn();
}

public void onClick(View v) {
    switch (v.getId()) {
        case R.id.play_button:
            Games.Leaderboards.submitScoreImmediate(getApiClient(),
                    getString(R.string.leaderboard_winner),
                    numGuesses).setResultCallback(new myLeaderBoardSubmitScoreCallback());
            numGuesses++;
            break;
        case R.id.bests:
            startActivityForResult(Games.Leaderboards.getLeaderboardIntent(getApiClient(), getString(R.string.leaderboard_winner)), 2);
            break;
    }
}

Android Manifest Permisssions:
<uses-permission android:name="com.android.vending.BILLING" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />

A: Based from the documentation, STATUS_NETWORK_ERROR_OPERATION_FAILED error means that a network error occurred while attempting to perform an operation that requires network access. There is a possibility that you are not signed in when this error occurs. Make sure to perform some sort of check, such as getGamesClient.isConnected() or isSignedIn().
Also, maybe you are submitting a score greater than the one you have configured on the console to be the min value for that leaderboard.


text:
Q: ExoPlayer no sound on video with mp3 sound stream I'm using ExoPlayer (actually a library ExoMedia based on ExoPlayer) to play video.
The problem is that mp4 video with mp3 sound stream plays without a sound. Here is the video info, retrieved with ffprobe:
[STREAM]
index=0
codec_name=h264
codec_long_name=H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
profile=High
codec_type=video
codec_time_base=1/50
codec_tag_string=avc1
codec_tag=0x31637661
width=704
height=544
coded_width=704
coded_height=544
has_b_frames=2
sample_aspect_ratio=34:33
display_aspect_ratio=4:3
pix_fmt=yuv420p
level=30
color_range=N/A
color_space=unknown
color_transfer=unknown
color_primaries=unknown
chroma_location=left
timecode=N/A
refs=1
is_avc=true
nal_length_size=4
id=N/A
r_frame_rate=25/1
avg_frame_rate=25/1
time_base=1/12800
start_pts=0
start_time=0.000000
duration_ts=37680128
duration=2943.760000
bit_rate=1713055
max_bit_rate=N/A
bits_per_raw_sample=8
nb_frames=73594
nb_read_frames=N/A
nb_read_packets=N/A
DISPOSITION:default=1
DISPOSITION:dub=0
DISPOSITION:original=0
DISPOSITION:comment=0
DISPOSITION:lyrics=0
DISPOSITION:karaoke=0
DISPOSITION:forced=0
DISPOSITION:hearing_impaired=0
DISPOSITION:visual_impaired=0
DISPOSITION:clean_effects=0
DISPOSITION:attached_pic=0
TAG:language=eng
TAG:handler_name=DataHandler
TAG:encoder=libx264
[/STREAM]
[STREAM]
index=1
codec_name=mp3
codec_long_name=MP3 (MPEG audio layer 3)
profile=unknown
codec_type=audio
codec_time_base=1/48000
codec_tag_string=.mp3
codec_tag=0x33706d2e
sample_fmt=s16p
sample_rate=48000
channels=2
channel_layout=stereo
bits_per_sample=0
id=N/A
r_frame_rate=0/0
avg_frame_rate=0/0
time_base=1/48000
start_pts=0
start_time=0.000000
duration_ts=141282432
duration=2943.384000
bit_rate=192000
max_bit_rate=N/A
bits_per_raw_sample=N/A
nb_frames=122641
nb_read_frames=N/A
nb_read_packets=N/A
DISPOSITION:default=1
DISPOSITION:dub=0
DISPOSITION:original=0
DISPOSITION:comment=0
DISPOSITION:lyrics=0
DISPOSITION:karaoke=0
DISPOSITION:forced=0
DISPOSITION:hearing_impaired=0
DISPOSITION:visual_impaired=0
DISPOSITION:clean_effects=0
DISPOSITION:attached_pic=0
TAG:language=eng
TAG:handler_name=DataHandler
[/STREAM]
[FORMAT]
filename=C:\Users\Vlad\Downloads\╨Т╨╕╨┤╨╡╨╛\5f387ac8b35310be0b24ac276ca821b7.mp4
nb_streams=2
nb_programs=0
format_name=mov,mp4,m4a,3gp,3g2,mj2
format_long_name=QuickTime / MOV
start_time=0.000000
duration=2943.760000
size=703042708
bit_rate=1910597
probe_score=100
TAG:major_brand=qt
TAG:minor_version=512
TAG:compatible_brands=qt
TAG:encoder=Lavf55.19.104
[/FORMAT]

And here comes an info of mp4 video with AAC sound stream, which actually works:
[STREAM]
index=0
codec_name=h264
codec_long_name=H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
profile=High
codec_type=video
codec_time_base=1001/48000
codec_tag_string=avc1
codec_tag=0x31637661
width=1280
height=718
coded_width=1280
coded_height=718
has_b_frames=2
sample_aspect_ratio=1:1
display_aspect_ratio=640:359
pix_fmt=yuv420p
level=31
color_range=N/A
color_space=unknown
color_transfer=unknown
color_primaries=unknown
chroma_location=left
timecode=N/A
refs=1
is_avc=true
nal_length_size=4
id=N/A
r_frame_rate=24000/1001
avg_frame_rate=24000/1001
time_base=1/24000
start_pts=0
start_time=0.000000
duration_ts=62087025
duration=2586.959375
bit_rate=1760057
max_bit_rate=N/A
bits_per_raw_sample=8
nb_frames=62025
nb_read_frames=N/A
nb_read_packets=N/A
DISPOSITION:default=1
DISPOSITION:dub=0
DISPOSITION:original=0
DISPOSITION:comment=0
DISPOSITION:lyrics=0
DISPOSITION:karaoke=0
DISPOSITION:forced=0
DISPOSITION:hearing_impaired=0
DISPOSITION:visual_impaired=0
DISPOSITION:clean_effects=0
DISPOSITION:attached_pic=0
TAG:language=eng
TAG:handler_name=DataHandler
TAG:encoder=libx264
[/STREAM]
[STREAM]
index=1
codec_name=aac
codec_long_name=AAC (Advanced Audio Coding)
profile=LC
codec_type=audio
codec_time_base=1/48000
codec_tag_string=mp4a
codec_tag=0x6134706d
sample_fmt=fltp
sample_rate=48000
channels=2
channel_layout=stereo
bits_per_sample=0
id=N/A
r_frame_rate=0/0
avg_frame_rate=0/0
time_base=1/48000
start_pts=0
start_time=0.000000
duration_ts=124174336
duration=2586.965333
bit_rate=165399
max_bit_rate=N/A
bits_per_raw_sample=N/A
nb_frames=121264
nb_read_frames=N/A
nb_read_packets=N/A
DISPOSITION:default=1
DISPOSITION:dub=0
DISPOSITION:original=0
DISPOSITION:comment=0
DISPOSITION:lyrics=0
DISPOSITION:karaoke=0
DISPOSITION:forced=0
DISPOSITION:hearing_impaired=0
DISPOSITION:visual_impaired=0
DISPOSITION:clean_effects=0
DISPOSITION:attached_pic=0
TAG:language=rus
TAG:handler_name=DataHandler
[/STREAM]
[FORMAT]
filename=C:\Users\Vlad\Downloads\╨Т╨╕╨┤╨╡╨╛\08f4d03dd55dfbeb62aa2a7a51a2f63c.mp4
nb_streams=2
nb_programs=0
format_name=mov,mp4,m4a,3gp,3g2,mj2
format_long_name=QuickTime / MOV
start_time=0.000000
duration=2586.966000
size=624371238
bit_rate=1930821
probe_score=100
TAG:major_brand=qt
TAG:minor_version=512
TAG:compatible_brands=qt
TAG:encoder=Lavf55.19.104
[/FORMAT]

Could somebody suggest a way to play the mp3 stream sound in the video?
I've created an issue in the ExoPlayer repo on GitHub


text:
Q: Impersonate as a logged in Windows user without providing password c# I have hosted a web service which uploads the attachments on a specific physical server where the user has access. For Example:- If user1 logs in, it will upload the docs in  C:\Folders\user1(myattachements). If user2 logs in, it will upload the docs in C:\Folders\user2(myattachements). User1 will not have access to user2 path. Since my web service is running under ApplicationPoolIdentity, I need to impersonate as a logged in windows user. Is it possible to run the webservice under logged in Windows user without he providing his password. please help on this.. Thanks in advance!!!

A: You can change the identity that IIS uses for the application pool which is your best bet. OR you can give the ApplicationPoolIdentity access to the folder that you are trying to write files to.

A: Web service is running under an application pool as it's hosted in IIS and this application pool runs under a particular identity. Identity user can be an admin user and can access server resources based on privileges. User1 or User2 are consumers of this web service. Access and privilege depends on ApplicationPoolIdentity, not on User1 or User2.


text:
Q: Can't get out of grub terminal After a boot-repair, ironically, my grub is broken. When I starty laptop, it boots into terminal,  it's written 'grub>_'
I searched for solutions, like 'set prefix, set root and insmod normal' and 'linux /boot/....' . None of these 2 solutions are working. Can anyone help with that?
Note: Due to another boot issue, I am not able to boot via a live usb.

A: If your grub menu does not appear but the grub prompt with black screen shows, as long as your Linux system is still intact you can bypass the grub stage and boot directly into Ubuntu. Once you've done that you can easily fix grub from there. The steps to boot up are as follows:
a) First remove all external drives. Determine where your root partition is. In this case we already know it's sda5. If you don't know and you have one disk you can find out by typing ls (hd0,x)/ trying different values for 'x' which is the number of the root partition on that disk. If you have more than one disk you may have to use hd1 or a higher number if you don't know which disk Ubuntu is installed on. Once you hit the right disk/partition numbers you'll see listed the basic system folders and the 2 files vmlinuz and initrd. Note these 2 files are symlinks to the kernel and initrd image respectively but they must be present.
b) Now set the root with set root=(hd0,5) or whatever is the correct combination for disk/partition you found in (a). Press Enter.
c) Now we need to map the linux kernel to root. Type linux /boot/vm. At this point press the Tab button. The command will partially complete by offering a choice of (usually) 2 kernel versions. Take the higher number by typing it and press Tab button again. The whole kernel version number should autocomplete. You should be seeing something like linux /boot/vmlinuz-4.15.0-55-generic depending on kernel version. You still need to add root=/dev/sda5 to this line. So the whole command is linux /boot/vmlinuz-4.15.0-55-generic root=/dev/sda5. Press Enter.
d) Now we do similar for initrd. Type initrd /boot/in then press Tab button. Again it will offer 2 versions so choose the same version as in c) using Tab button again to autocomplete. You should see something like initrd  /boot/initrd.img-4.15.0-55-generic as the complete command, depending on kernel version. Press Enter.
e) Then type boot. Press Enter.
After a a couple of minutes of splash screen activity you will eventually reach the user login screen, then proceed as normal. If during boot-up you reach the intrafms prompt and booting stops, you've probably mistyped something in the earlier stages and need to start again. Remember, this process boots you into Linux. Grub still needs a couple more commands to fix it once you're in.


text:
Q: Tail Loss Calculations
Two corporations each have a 4% chance of going bankrupt and the event
  that one of the two companies will go bankrupt is independent of the
  event that the other company will go bankrupt.
We assume that each company has outstanding bonds. However, risks due
  to changes in interest rates as well as the positive return due
  tointerest are being ignored. A bond from any of the two companies
  will return 0 if the corporation does not go bankrupt and 1 if it
  does go bankrupt.
Suppose an investor buys 1000 worth of bonds of the first
  corporation, which is then called portfolio P1, and similarly, an
  investor buys $1000 worth of bonds of the second corporation, which is
  then called portfolio P2.

Calculate the tail loss for the portfolios P1, P1 and P1 + P2. Assume VaR critical level =5%
I solved the tail loss using:
Tail loss (P1) = Tail loss (P2) = 1000 x 0.04 = 40
Tail loss (P1 + P2) = 1000 x 0.0768 + 2000 x 0.0016 = 76.8 + 3.2=80
Should I divide the tail losses by their respective probabilities?
TL(P1) = TL(P2) = 1000x0.04/0.04 = 1000
TL(P1+P2) = (1000x0.0768 + 2000x0.0016)/(0.0768 + 0.0016) = 1020


text:
Q: 64bit int Spin Box in QT I'm building a windows program which shall have controls for 64bit numeric values. these controls shall be switchable to be signed or unsigned.
I found two controls:
"Spin Box"(int32) and "Double Spin Box"(double)
with double I'd be able to cover the range but it can't handle the precision.
Is there a way to change the data type of these controls?
Is it possible to create an own control which can handle signed and unsigned 64bit values?
Is it possible to create a 128bit Spin box?
The only work around I can see right now is in using a string control and manually convert to an INT64 or UINT64 but I'm not very happy with this solution
Any other Ideas?
I'm on QT 4.7.4 and VS2010 with C++
thx

A: You can derive QAbstractSpinBox and reimplement at least the virtual functions stepBy, stepEnabled and possibly validate() and fixup() for the input validation.

A: I don't use fixup function. See code of my Сustom QSpinBox.
class QLongLongSpinBox derived from QAbstractSpinBox
Don't forget call
setMaximum(std::numeric_limits<qlonglong>::max());
setMinimum(std::numeric_limits<qlonglong>::min());

after creating QLongLongSpinBox.
see qlonglongspinbox.h file:
#include <QtWidgets/QWidget>
#include <QtWidgets/QAbstractSpinBox>
#include <QtWidgets/QLineEdit>

class QLongLongSpinBoxPrivate;
class Q_WIDGETS_EXPORT QLongLongSpinBox : public QAbstractSpinBox
{
    Q_OBJECT

    Q_PROPERTY(qlonglong minimum READ minimum WRITE setMinimum)
    Q_PROPERTY(qlonglong maximum READ maximum WRITE setMaximum)

    Q_PROPERTY(qlonglong value READ value WRITE setValue NOTIFY valueChanged USER true)

    qlonglong m_minimum;
    qlonglong m_maximum;
    qlonglong m_value;

public:
    explicit QLongLongSpinBox(QWidget *parent = 0)
    {
        connect(lineEdit(), SIGNAL(textEdited(QString)), this, SLOT(onEditFinished()));
    };
    ~QLongLongSpinBox() {};

    qlonglong value() const
    {
        return m_value;
    };

    qlonglong minimum() const
    {
        return m_minimum;
    };

    void setMinimum(qlonglong min)
    {
        m_minimum = min;
    }

    qlonglong maximum() const
    {
        return m_maximum;
    };

    void setMaximum(qlonglong max)
    {
        m_maximum = max;
    }

    void setRange(qlonglong min, qlonglong max)
    {
        setMinimum(min);
        setMaximum(max);
    }

    virtual void stepBy(int steps)
    {
        auto new_value = m_value;
        if (steps < 0 && new_value + steps > new_value) {
            new_value = std::numeric_limits<qlonglong>::min();
        }
        else if (steps > 0 && new_value + steps < new_value) {
            new_value = std::numeric_limits<qlonglong>::max();
        }
        else {
            new_value += steps;
        }

        lineEdit()->setText(textFromValue(new_value));
        setValue(new_value);
    }

protected:
    //bool event(QEvent *event);
    virtual QValidator::State validate(QString &input, int &pos) const
    {
        bool ok;
        qlonglong val = input.toLongLong(&ok);
        if (!ok)
            return QValidator::Invalid;

        if (val < m_minimum || val > m_maximum)
            return QValidator::Invalid;

        return QValidator::Acceptable;
    }

    virtual qlonglong valueFromText(const QString &text) const
    {
        return text.toLongLong();
    }

    virtual QString textFromValue(qlonglong val) const
    {
        return QString::number(val);
    }
    //virtual void fixup(QString &str) const;

    virtual QAbstractSpinBox::StepEnabled stepEnabled() const
    {
        return StepUpEnabled | StepDownEnabled;
    }

public Q_SLOTS:
    void setValue(qlonglong val)
    {
        if (m_value != val) {
            lineEdit()->setText(textFromValue(val));
            m_value = val;
        }
    }

    void onEditFinished()
    {
        QString input = lineEdit()->text();
        int pos = 0;
        if (QValidator::Acceptable == validate(input, pos))
            setValue(valueFromText(input));
        else
            lineEdit()->setText(textFromValue(m_value));
    }

Q_SIGNALS:
    void valueChanged(qlonglong v);

private:
    Q_DISABLE_COPY(QLongLongSpinBox)

    Q_DECLARE_PRIVATE(QLongLongSpinBox)
};

A: To use you custom class (Widget) it in Qt Creator:

*

*create QWidget widget

*List item

*select Promote to..  in widget menu
New Promoted Class:
QWigdet
Promoted class name QLongLongSpinBox
Header file: write qlonglongspinbox.h
Promote

*select Promote to QLongLongSpinBox

*save

You can see
<item>
    <widget class="QLongLongSpinBox" name="value_integer" native="true"/>
</item>

and:
<customwidgets>
  <customwidget>
   <class>QLongLongSpinBox</class>
   <extends>QWidget</extends>
   <header>qlonglongspinbox.h</header>
   <container>1</container>
  </customwidget>
</customwidgets>

in *.ui file
in ui_*.h generating file you see you class:
#include "qlonglongspinbox.h"
QLongLongSpinBox *object_name;
value_integer = new QLongLongSpinBox(YourWidgetName);
value_integer->setObjectName(QStringLiteral("value_integer"));
verticalLayout->addWidget(value_integer);

A: Just for the sake of completeness: every time you run into a problem like this, remember that (in case everything else fails) you can just download the Qt source code and make your own QSpinBox64 or QSpinBox128 class in a matter of minutes by modifying the needed parts.


text:
Q: Is it considered rude to say something won't be explained in a text because you assume the reader is knowledgeable about it? I'm a non native English speaker writing a dissertation in British English. In the dissertation I'm explaining a new advanced form of a certain method (let's call this method "x"). Because of word limit I wish to omit any explanation of the standard form of "x", since usage of this form is widespread in my field. Would it be considered rude to write something like the following?

We assume the reader is knowledgeable about standard 'x', so these will not be explained in this document. Instead we will focus on the new capabilities provided by "advanced x".

A: Yes, this is very common in academic writing and is also used in all forms of writing.
A basic level of education and / or knowledge of the reader is assumed.  To describe the simple details would be considered to be an insult to the intelligence of the reader.  Many referees of academic journals would reject a paper that included information that should be known to the reader.
There is a proverb which describes this situation - "Don't teach your Grandmother to suck eggs".


text:
Q: Apache Camel CXF endpoint null reply I followed chapter 7 of Camel in Action book and implemented a CXF route.
<cxf:cxfEndpoint
    id="orderEndpoint"
    address="http://localhost:9000/order/"
    serviceClass="test.order.OrderEndpoint"
    wsdlURL="wsdl/order.wsdl" />

<camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
        <!-- Expose route as web service endpoint -->
        <from uri="cxf:bean:orderEndpoint" />
        <to uri="log:orderEndpoint_MsgIn" />
        <to uri="seda:incomingOrders" />
        <transform>
            <constant>OK</constant>
        </transform>
        <to uri="log:orderEndpoint_MsgOut" />
    </route>

    <!-- test route -->
    <route>
        <from uri="seda:incomingOrders" />
        <to uri="mock:end" />
    </route>
</camelContext>

Then I implemented a java console class to test the route
public static void main(String[] args) throws Exception{
    Main main = new Main();
    AbstractApplicationContext context = new ClassPathXmlApplicationContext(
            "META-INF/spring/cxfWsComponentTestContext.xml"
            );

    main.setApplicationContext(context);

    main.start();
    ProducerTemplate producer = main.getCamelTemplate();

    List<Object> params = new ArrayList<Object>();
    params.add("motor");
    params.add(1);
    params.add("honda");

    String reply = producer.requestBody("cxf:bean:orderEndpoint", params, String.class);
    LOG.info("Received reply from orderEndpoint = " + reply);

    Thread.sleep(10000);

    main.stop();

}

Expect that the console log should display
"Received reply from orderEndpoint = OK"

However, I got
"Received reply from orderEndpoint = null"

In the console log I can see that the entry
"orderEndpoint_MsgOut           INFO  Exchange[ExchangePattern: InOut, BodyType: String, Body: OK]"

which means that the Web service should have generated reply message "OK", but I'm not sure why this reply message was not carry over as a return value of the requestBody() method call...
I downloaded Camel in Action chapter 7's sample code and run the Junit test case, it was able to return the result as expected... I tried to compare the route definitions and source code with mine but not able to spot any difference so far...
Would like to see if anyone can give some clues on this.
--- Edit 1 ---
I have updated the route definition and remain only the route as below
    <route>
        <from uri="cxf:bean:orderEndpoint" />
        <transform>
            <constant>OK</constant>
        </transform>
        <to uri="seda:incomingOrders" />
    </route>

And updated the main method
    producer.requestBody("cxf:bean:orderEndpoint", params, String.class);
    ConsumerTemplate consumer = producer.getCamelContext().createConsumerTemplate();
    Exchange reply = consumer.receive("seda:incomingOrders");
    LOG.info("Received reply from seda:incomingOrders = " + reply);

However, it failed with timeout exception
org.apache.camel.ExchangeTimedOutException: The OUT message was not received within: 30000 millis. Exchange[Message: OK]
at org.apache.camel.component.seda.SedaProducer.process(SedaProducer.java:144)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:129)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:448)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:118)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:80)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.component.cxf.CxfConsumer$1.asyncInvoke(CxfConsumer.java:95)
at org.apache.camel.component.cxf.CxfConsumer$1.invoke(CxfConsumer.java:75)
at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at org.apache.cxf.interceptor.ServiceInvokerInterceptor$2.run(ServiceInvokerInterceptor.java:126)
at org.apache.cxf.workqueue.SynchronousExecutor.execute(SynchronousExecutor.java:37)
at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:131)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:251)
at org.apache.cxf.transport.http_jetty.JettyHTTPDestination.doService(JettyHTTPDestination.java:234)
at org.apache.cxf.transport.http_jetty.JettyHTTPHandler.handle(JettyHTTPHandler.java:70)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1129)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1065)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:497)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
at java.lang.Thread.run(Thread.java:745)

A: You are requesting the body of the CXF endpoint. If you look at your route, you can see that you set the content of the body in the transform tag, which comes after in the route definition. Therefore, it is logical that you don't get OK as a result of requestBody(). The same applies to your seda endpoint. I'd bet that the Logged body for orderEndpoint_MsgIn is different from OK.
Concerning your log at orderEndpoint_MsgOut being correct, it is because you log the body after the transform step.
In order to receive OK, you can use this route :
<route>
    <from uri="cxf:bean:orderEndpoint" />
    <transform>
        <constant>OK</constant>
    </transform>
    <wireTap uri="seda:incomingOrders" />
</route>

And use ConsumerTemplate with the seda endpoint :
ConsumerTemplate consumer = producer.getCamelContext().createConsumerTemplate();
String reply = consumer.receive("seda:incomingOrders");
LOG.info("Received reply from seda = " + reply);

You should use this code between the requestBody() and the main.stop().
For an explanation on the use of wireTap rather than to, see this post


text:
Q: How much Amperage can pass through a BMS and DC stepup boost converter? In my Mini UPS project for my router, I made a little circuit by using a 18650 li-ion battery charger module, a 3.7v /2800mAH li-ion battery, and the DC step-up boost converter. My router requires 9v/0.6A current. So once I connected this UPS for my router and switch it on and

simulate this circuit – Schematic created using CircuitLab
It seems quickly light up and disappear all lights in the router (Not working)
What i went wrong here? Have BMS or step-up converter a certain output power limit? Are my BMS, step-up converter, and or the battery not enough power to driving my router?


text:
Q: Turn Off Anti-Aliasing For Bitmap I've recently started testing for my game on other peoples phones. For some reason the whole game is getting really "blurry" for their phones, but not for mine. All of them has got a higher android version then I do.
I've tried finding a good answer around the web for this, but all I can find is the answer for if you are using the res/drawable folders. I am loading my images from the assets folder with a special load method. I am then stretching them out when I draw them onto the screen with the "c.drawBitmap()". I am drawing using an "android.view.View".
So now, anyone that has the answer for turning the anti-aliasing off for bitmaps when creating 8-bit games. It would be an impossibility for me to resize the images before rendering them onto the screen, because of me creating an image from an integer array, that refreshes with a rate of about 60 fps.

A: That blurriness, is most probably because of low resolution of your bitmaps. It may be fine on the test device of yours, but when you use them on higher resolution screens you will either get raw/pixelated or blurry/AA'd results after scaling. An appropriate solution is to have different images for different resolutions, or to be more accurate; densities. Android already do the choosing part:
ldpi
mdpi
hdpi
...

I am assuming you know these identifiers.
Put your high resolution image to res/drawable-hdpi, low resolution to res/drawable-ldpi etc.


text:
Q: How to handle template (layouts) inheritance in Jekyll? I want to have a template "_layouts/template1.html" extend (Django-style) a template _layouts/default.html.
I'm putting this as a YAML front matter in _layouts/template1.html
---
layout: default
---
{{page.content}}

but apparently it doesn't work the way I'd like it to work (all the additional markup that is present in template1.html but IS NOT in default.html does not render). It looks like the file that uses template1 layout purely extends default.html.
Is there any way to have layouts inheritance in Jekyll?

A: Jekyll's Liquid templates extend pretty easily, you just have to be sure you're extending and not overwriting your desired template.
You may actually want to extend page and not default.
So, in your template Front Matter:
---
layout:page
---

A: Try the Liquid Inheritance Gem: https://github.com/danwrong/liquid-inheritance
Reference: http://www.sameratiani.com/2011/10/22/get-jekyll-working-with-liquid-inheritance.html

A: What you mean is simply {{ content }}.
Yes, layouts can be piped.  In your case, if a page uses template1 layout, it is the content for template1.  Then, the result of template1  is the content for default.

A: template1.html from your example will extend default.html as long as the latter contains a {{ content }} block. See here for example. What it won't do is it won't overwrite anything that default.html already contains. For that you'll need the Liquid Inheritance Gem, as mentioned by @juddlyon.


text:
Q: E possivel pegar dados do mês inteiro no postgreSQL Como faço para que a partir de um mês especifico eu consiga obter todos os dados gravado no banco: acho que se deve passar o ano / mês como parâmetro por exemplo variavel = "2016/10"; lembrando que o tipo do dado no banco e timestamp
  SELECT * FROM dados WHERE data_registro = variavel

A: Opção 1: Utilização do TO_CHAR:
select * from dados where TO_CHAR(data_registro, 'MM/YYYY') = '01/2016'

Opção 2: Utilização com ranges:
select * from dados where data_registro >= '2016-01-01'::DATE
and data_registro <= '2016-01-31'::DATE

Opção 3: Utilização do overlaps
select * from dados where (data_registro, data_registro)
OVERLAPS ('2016-01-01'::DATE, '2016-01-31'::DATE);

Opção 4: Com Extract:
select * from dados
where
Extract(month from data_registro) >= Extract(month from '2016-01-01'::DATE)
and Extract(month from data_registro) <= Extract(month from '2016-01-31'::DATE)

Opção 5: Utilização de intervals baseados em data corrente:
SELECT *
FROM   dados
WHERE  Extract(month from data_registro) >= Extract(month from Now())
AND    Extract(month from data_registro) <= Extract(month from Now() + Interval '20 day')

A: Só dando continuidade as opções já citadas
Opção com date_trunc
SELECT * FROM dados WHERE
   date_trunc('month', data_registro) = date_trunc('month', '2015-03-01');

Neste caso o parametro pode ser qualquer data válida no mês, ele vai truncar ambos para o mesmo mês.
Referência

A: Tem como usar BETWEEN:
SELECT dados
FROM   tabela
WHERE  tabela.data BETWEEN '2016-01-01' AND '2016-01-31'

Se o campo em questão for do tipo TIMESTAMP, dependendo do seu BD, deve-se lembrar de fazer o CAST (ex.: Postgres tabela.data::DATE)


text:
Q: Java taking too much memory on linux vm Doing a top shows this
top - 22:04:27 up  7:47,  3 users,  load average: 0.02, 0.08, 0.26
Tasks:   1 total,   0 running,   1 sleeping,   0 stopped,   0 zombie
Cpu(s):  2.9% us,  0.9% sy,  0.0% ni, 95.9% id,  0.0% wa,  0.0% hi,  0.2% si
Mem:   7914188k total,  2750184k used,  5164004k free,    54392k buffers
Swap: 16383992k total,        0k used, 16383992k free,   415828k cached

  PID USER    PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 2970 xxxxxx  18   0 24.5g 258m  10m S    0  3.3   0:42.05 java

VIRT is 24.5g and the hard disk is only 20g.
pmap -x 2970 reveals 95 times 262136k as anon.
Please advise as to is something wrong??

A: From a practical point of view (discover how much memory is used by the process) the VIRT column is almost meaningless, don't worry about it.
Virtual Memory Usage from Java under Linux, too much memory used


text:
Q: Modeling a database using entity relationship diagram I've created this ERD, take a look: https://i.gyazo.com/ea3ad2073ad5302834b642dea7467662.png
But now I want to add some more information to my diagram, but I do not how I should do that.
I want to modify my previous ERD, I need to ensure that every single shift is delivered to the hospital where the doctor works. Also, I need to register the Medical Insurance of each patient.
Hope you can help me

A: You can model the Works at relationship in your ERD, but complex constraints like ensuring that a doctor's shifts occur at the hospital they work at can only be properly represented in the physical schema since it relies on a composite FK constraint.
I would make a note on my ERD diagram to indicate the constraint:

Then, in the physical schema:
CREATE TABLE Works_At (
    doctor_dna VARCHAR NOT NULL,
    hospital_code VARCHAR NOT NULL,
    PRIMARY KEY (doctor_dna),
    UNIQUE KEY (doctor_dna, hospital_code)
);

CREATE TABLE Shifts (
    shift_id INT NOT NULL,
    doctor_dna VARCHAR NOT NULL,
    patient_dna VARCHAR NOT NULL,
    hospital_code VARCHAR NOT NULL,
    date DATETIME NOT NULL,
    hour INT NOT NULL,
    PRIMARY KEY (shift_id),
    FOREIGN KEY (doctor_dna, hospital_code) REFERENCES Works_At (doctor_dna, hospital_code)
);

Note the UNIQUE KEY in Works_At and the composite FOREIGN KEY constraint in Shifts.
Some comments on your diagram: it's redundant to use both Crow's feet and 1-N cardinality indicators. I would advise only 1-N cardinality indicators since your diagram mostly uses Chen's notation. Crow's feet are more commonly used in table diagrams.
Second, I believe Shifts is incorrectly modeled as a weak entity set. Weak entity sets are entity sets that are (at least partially) identified by a single parent entity set. If your intent is that Shifts are uniquely identified by Patient, Doctor and Hospital, it would be better represented as a ternary relationship between those entity sets. However, in my experience, patients aren't limited to a single visit per doctor / hospital. Perhaps you meant to use Date and Hour as weak keys, but that makes for a complicated relation, and if you ever wanted to associate anything else with shifts, you would have to include all 5 columns as a composite foreign key in another table. Personally, I would rather introduce a surrogate key to make it a regular entity set.
If might be a good idea to do the same for Person. There are numerous problems with using DNA as an identifier. Size (DNA profiles tend to be large), privacy concerns (identifiers could contain valuable or sensitive information), practical difficulties (must every doctor and patient undergo DNA sequencing before the can be registered?), accuracy (limited profiles may not be guaranteed unique while full profiles would be impractical).
As for medical insurance, I suggest you study the topic online (or even consult with an expert in the field) and determine what entities, attributes and relationships you require. Once you know what information you want to add, I can advise on how to add it.


text:
Q: Laravel eloquent search for name relation Okay, so I'm a bit stuck.
I've created a group system in my project.
The group system is 5 models:

*

*Group

*GroupCategory

*GroupMember

*GroupPost

*GrouPostComment

What I'm trying to do is a search for members in a group by username input.
But I only store the user_id in the GroupMember model, and not username wich is stored in the User model. I do not have any relations to groups in the User model yet.
Is there some kind of relation I have to put in?
I've not come to understand the Morph relation yet.
Here are a list of the relations for the Group some of the models needed.
Group model
public function category() {
    return $this -> belongsTo('App\GroupCategory', 'category_id');
}

public function owner() {
    return $this -> hasOne('App\GroupMember', 'group_id') -> where('owner', true);
}

public function mods() {
    return $this -> hasMany('App\GroupMember', 'group_id') -> where('mod', true);
}

public function members() {
    return $this -> hasMany('App\GroupMember', 'group_id');
}

public function posts() {
    return $this -> hasMany('App\GroupPost', 'group_id');
}

public function comments() {
    return $this -> hasMany('App\GroupPostComment', 'group_id');
}

GroupMember model
public function groups() {
    return $this -> belongsToMany('App\Group');
}

public function posts() {
    return $this -> hasMany('App\GroupPost');
}

public function comments() {
    return $this -> hasMany('App\GroupPostComment');
}

public function user() {
    return $this -> belongsTo('App\User');
}

Just to clearify. I have an input field where the admin can type in a letter or parts of the username he's looking for, then it does a AJAX search where it looks for only members in the group, but it looks by username. And username is not in the GroupMember model, but in the User model.
How would I do this?
Thanks in advance.
Edit: The controller method.
 /**
 * @param Group $group
 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
 *
 * Manage users
 */
public function getManageUsers(Group $group) {

    $group = $group -> with('members.user');

    // Usernames can be "test0", "test1", "test2"
    // If i search "1" only "test1" should be in the result
    $yourSearchQuery = '1';

    // The query
    $result = $group -> whereHas('members', function ($query) use ($yourSearchQuery) {
        $query -> whereHas('user', function ($query) use ($yourSearchQuery) {
            $query -> where('name', 'LIKE', '%'. $yourSearchQuery .'%');
        });
    }) -> get();

    // Check the results manually
    // It still returns all members of the group
    dd($result);

}

A: So I finally fixed it!
Just had to modify the answer from Odin Thunder a bit.
This was the query that works.
$result = $group -> members() -> whereHas('user', function($query) use($q) {
    $query -> where('name', 'LIKE', '%'. $q .'%');
}) -> get();

A: You can get data through relations, try this code for example:
$group = Group::first();

return $group->members->user

Don`t forget:
use (namespace of group model)

For search:
$yourSearchQuery - string what we must find
$group = Group::with('members.user');

$result = $group -> whereHas('members', function ($query) use ($yourSearchQuery) {
    $query -> whereHas('user', function ($query) use ($yourSearchQuery) {
        $query->where('name', 'LIKE', '%'. $yourSearchQuery .'%');
    }
})->get();


text:
Q: Separating WAL Log and the data in two two different disk for Postgres SQL I'm looking for a reference and ways to separating the WAL transaction Logs and the data into two different disk for postgres.

A: That can be done when you create the cluster:
initdb --waldir=/somewhere/else datadir

But you can also do it later:

*

*stop the server

*move pg_wal somewhere else

*create a symbolic link pg_wal instead that points to the new location
Note that a pg_basebackup will not preserve the symbolic link, so if you want to create a standby where pg_wal is a symbolic link, you'll need to use the --waldir option of pg_basebackup.


text:
Q: Problem with multiple select removing more than 1 option There seems to be a problem with the JS Code for Opera browsers, as it only removes the last option tag that is selected within a multiple select tag, can someone please help me.
Here is the HTML for this:
<select id="actions_list" name="layouts" multiple style="height: 128px; width: 300px;">
    <option value="forum">forum</option>
    <option value="collapse">collapse</option>
    <option value="[topic]">[topic]</option>
    <option value="[board]">[board]</option>
</select>

Of course it's within a form tag, but there's a ton more code involved with this form, but here is the relevant info for this.
Here is the JS that should handle this, but only removes the last selected option in Opera, not sure about other browsers, but it really needs to remove all selected options, not just the last selected option...
var action_list = document.getElementById("actions_list");
var i = action_list.options.length;
while(i--)
{
    if (action_list.options[i].selected)
    {
        action_list.remove(i);
    }
}

What is wrong with this?  I can't figure it out one bit.

A: You can do it much easier using jQuery:
$('#actions_list option:selected').remove()

A: It's easiest to do this with jQuery but it you want to do this using plain Javascript you can.
The problem you are experiencing is that when you remove an item from the options list in Opera it deselects all the selected items, so only the first is removed. A workaround is to first remember which items were selected before removing any.
var action_list = document.getElementById("actions_list");

// Remember selected items.
var is_selected = [];
for (var i = 0; i < action_list.options.length; ++i)
{
    is_selected[i] = action_list.options[i].selected;
}

// Remove selected items.
i = action_list.options.length;
while (i--)
{
    if (is_selected[i])
    {
        action_list.remove(i);
    }
}

A: $.each($('[name="alltags"] option:selected'), function( index, value ) {
  $(this).remove();
});

try this instead to remove multiple selection

A: Removing multiple options from select based on condition:
while(SelectBox.length > 1){
    if(SelectBox[SelectBox.length -1].text != "YourCondition"){
       SelectBox.remove(SelectBox.length -1);
    }
}


text:
Q: cordova 4 android back button error I'm using Cordova 4.0.0 and Android 4.4.2.
Everytime Android's virtual back button is pressed, I get an error:
unimplemented WebView method onKeyDOwn called from: android.webkit.WebView.onKeyDown(WebView.java:2169)
And then it pops up an alert with jQuery unknown nodeType (I have jquery in my asset/www).
I tried to override onKeyDown in CordovaApp but it doesn't seem to do anything.
@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }

I'm a little stumped why says not implemented but pops up a DOM related error.
I searched everywhere can couldn't find an answer. Any help is greatly appreciated.

A: Try this:
document.addEventListener("backbutton", onBackKeyDown, false);

function onBackKeyDown(ev){
    // Something
}

http://cordova.apache.org/docs/en/4.0.0/cordova_events_events.md.html#backbutton

A: I had similar problem, but is now resolved. Try:
document.addEventListener("backbutton", onBackKeyDown, false);

function onBackKeyDown() {  history.go(-1); navigator.app.backHistory(); }


text:
Q: How to better perform a query split into subqueries in PHP In PHP I have made this query:
$getTrackID = $this->db->query("SELECT `id`,`uid` FROM `tracks`, `users` WHERE `time` > CURDATE() - interval 1 year AND `uid`=`idu` AND `public` > 0 ORDER BY RAND() LIMIT 10");
$TrackID = $getTrackID->fetch_assoc();
$id=$TrackID['id'];
$xid=$TrackID['uid'];

The problem is that it takes 1 sec to return the result. I saw this question and it seems better practice split big queries into subqueries.
Is this the case? To better perform should I need to use something like:
$getTrackTime = $this->db->query("SELECT `id`,`uid` FROM `tracks`, `users` WHERE `time` > CURDATE() - interval 1 year AND `uid`=`idu`");
// Declare the rows array
$rows = array();
while($row = $getTrackTime->fetch_assoc()) {
    // Store the result into the array
    $rowsTime[] = $row;
}

$getTrackPublic = $this->db->query(sprintf("SELECT `%s`,`%s` FROM `tracks`, `users` WHERE `public` > 0",$rowsTime['id'],$rowsTime['uid']));
$rows = array();
while($row = $getTrackPublic->fetch_assoc()) {
    $rowsPublic[] = $row;
}
...

A: Quickly get into the habit of writing your queries with some kind of formatting, proper joins, and with properly qualified column names. It makes it much easier to understand. E.g.:
SELECT t.id
     , t.uid
  FROM tracks t
  JOIN users u
    ON u.idu = t.uid
 WHERE t.time > CURDATE() - INTERVAL 1 YEAR
   AND u.public > 0
 ORDER
    BY RAND()
 LIMIT 10


text:
Q: Error creating bean with name 'studentController': Injection of autowired dependencies failed i am newbie Spring and i have error.
This is spring-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
    <context:annotation-config />
    <context:component-scan base-package="com.huyliver"></context:component-scan>

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
        <property name="packagesToScan" value="com.huyliver.model"></property>
    </bean>
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

- This is error:
org.springframework.beans.factory.BeanCreationException:
    Error creating bean with name 'studentController': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
    Could not autowire field: private com.huyliver.service.StudentService com.huyliver.controller.StudentController.studentService;
nested exception is org.springframework.beans.factory.BeanCreationException:
    Error creating bean with name 'studentServiceImpl': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
    Could not autowire field: private com.huyliver.dao.StudentDAO com.huyliver.service.impl.StudentServiceImpl.studentDAO;
nested exception is org.springframework.beans.factory.BeanCreationException:
    Error creating bean with name 'studentDAOImpl': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
    Could not autowire field: private org.hibernate.SessionFactory com.huyliver.dao.Impl.StudentDAOImpl.sessionFactory;
nested exception is org.springframework.beans.factory.BeanCreationException:
    Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Error setting property values;
nested exception is org.springframework.beans.NotWritablePropertyException:
    Invalid property 'configurationClass' of bean class [org.springframework.orm.hibernate4.LocalSessionFactoryBean]: Bean property 'configurationClass' is not writable
    or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

- This is interface StudentDAO:
 public interface StudentDAO {
        public void add(Student student);
        public void edit(Student student);
        public void delete(int studentID);
        public Student getStudent(int studentID);
        public List getAllStudent();
    }

This is StudentDAOImpl
@Repository
public class StudentDAOImpl implements StudentDAO {
    @Autowired
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void add(Student student) {
        sessionFactory.getCurrentSession().save(student);
    }

    @Override
    public void edit(Student student) {
        sessionFactory.getCurrentSession().update(student);

    }

    @Override
    public void delete(int studentID) {
        sessionFactory.getCurrentSession().delete(getStudent(studentID));

    }

    @Override
    public Student getStudent(int studentID) {
        // TODO Auto-generated method stub
        return (Student)sessionFactory.getCurrentSession().get(Student.class, studentID);
    }

    @Override
    public List getAllStudent() {
        // TODO Auto-generated method stub
        return sessionFactory.getCurrentSession().createCriteria("from Student").list();
    }

- This is Interface StudentService:
public interface StudentService {
    public void add(Student student);
    public void edit(Student student);
    public void delete(int studentID);
    public Student getStudent(int studentID);
    public List getAllStudent();
}

- This is Class StudentServiceImpl
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDAO studentDAO;

    @Transactional
    public void add(Student student) {
        studentDAO.add(student);
    }

    @Transactional
    public void edit(Student student) {
        studentDAO.edit(student);
    }

    @Transactional
    public void delete(int studentID) {
        studentDAO.delete(studentID);

    }

    @Transactional
    public Student getStudent(int studentID) {
        // TODO Auto-generated method stub
        return studentDAO.getStudent(studentID);
    }

    @Transactional
    public List getAllStudent() {
        // TODO Auto-generated method stub
        return studentDAO.getAllStudent();
    }

- I think error in ..But i can't fix it.

A: First of all reading all the errors will give you the way to debug your application. They are expressive enough :

*

*configurationClass is not writable. You can remove it from your spring webapplication context file

*Could not autowire field: private com.huyliver.service.StudentService com.huyliver.controller.StudentController.studentService; and others

*Could not autowire field: private com.huyliver.dao.StudentDAO com.huyliver.service.impl.StudentServiceImpl.studentDAO;

@Autowired fields fail because your @Autowired fields are not initialized.
Maybe because :

*

*the Hibernate Session is already closed when you try to use it again, raising a LazyInitializationException, then think about the OpenSessionInViewFilter

*and/or because you do not define a bean with the name of the properties with @Autowired annotation.

<bean id="studentService" class="com.huyliver.services.StudentService" />

<bean id="studentDAO" class="com.huyliver.dao.StudentDAO" />

Have a good debugging :)


text:
Q: Rock-Paper-Scissors-Pencil-Fire game with functions doesn't work I am trying to make a game of rock-paper-scissors-pencil-fire with functions and it doesn't work. It seems that it can't go inside the compare function(named findwinner()) and return the results.
i looked throw the web for help but i couldn't find anything. i tried assigning the variables in many different ways but with no luck.
python
#Rock-Paper-Scissors-Fire-Pencil Game
#Game:
#The player must choose his weapon and 'fight' against the computer following #the rules above.
#The player can choose between the following: Rock, Scissors, Fire, Pencil and #Paper.
#Rules: The rock beats the scissors, the scissors beat the fire, the fire #beats the pencil, the pencil beats the paper and the paper beats the rock

#Player1 is the human player
#Player2 is the computer
import random
#The game welcomes the player.
print("Wellcome to the Rock-Paper-Scissors-Fire-Pencil game!")
#The player can play as many times as he/she wants until he/she type anything #else except yes in the "Do you want to play again?" question.
def getuser():
    choices = ["rock", "scissors", "fire", "pencil", "paper"]
    #The computer chooses it's 'weapon'.
    player2 = choices[random.randint(0,4)]
    player1 = None
    while player1 not in choices:
    #The player must choose his/her 'weapon'
       player1 = input("\n PLAYER 1 - Please make a choice (rock/paper/scissors/fire/pencil):")
    print (f"\nPlayer1 choose {player1}")
    print (f"\nPlayer2 choose {player2}")
    return ()

def findwinner():
    winner = None
    p1 = getuser()[1]
    p2 = getuser()[2]
    #The game keeps how many times the player1 has won, lost or tied with the computer in the variables bellow.
    wins = 0
    losses = 0
    ties = 0
    #The game compares the choises of the players and announces if the human player won, lost or tied with the computer.
    #Then it adds the win, the lost or the tie to the summary of wins, losses or ties.
    if p1 != p2:
        if p1 == "rock":
            if p2 == "scissors" or p2 == "pencil" or p2 == "fire":
                print("\n Player1 wins this round!")
                winner = p1
                wins += 1
            else:
                print("\n Player2 wins this round!")
                winner = p2
                losses += 1
        if p1 == "paper":
            if p2 == "rock":
                print("\n Player1 wins this round!")
                winner = p1
                wins += 1
            else:
                print("\n Player2 wins this round!")
                winner = p2
                losses += 1
        if p1 == "scissors":
            if p2 == "paper" or p2 == "pencil":
                print("\n Player1 wins this round!")
                winner = p1
                wins += 1
            else :
                print("\n Player2 wins this round!")
                winner = p2
                losses += 1
        if p1 == "pencil":
            if p2 == "paper":
                print("\n Player1 wins this round!")
                winner = p1
                wins += 1
            else:
                print("\n Player2 wins this round!")
                winner = p2
                losses += 1
        if p1 == "fire":
            if p2 == "paper" or p2 == "scissors" or p2 == "pencil":
                print("\n Player1 wins this round!")
                winner = p1
                wins += 1
            else:
                print("\n Player2 wins this round!")
                winner = p2
                losses += 1
    else:
        print("\n The round is a tie!")
        winner = None
        ties += 1
    print (f"\nThe winner of this round is {winner}")

    return (winner, wins, losses, ties)

play_again = "yes"

while play_again == "yes":

    #The game shows the choises of the players.
    player1 = getuser()[1]
    player2 = getuser()[2]
    findwinner(player1, player2)

    #The game askes the player if he/she wants to play again.
    play_again = input("\nDo you want to play again?:")
else:
    #If the player doesn't want to play again, the game prints the results of all the rounds of the game and closes.
    print(f"The player1 won {findwinner()[2]} times")
    print(f"The player1 lost {findwinner()[3]} times")
    print(f"The player1 tied {findwinner()[4]} times")
    print("\n Good Bye")

A: You got a couple of problems:

*

*getuser() just prints the choices but does not return them, to fix this just change the return to player1, player2

*findwinner() does not get any parameters according to the signature, you have to change the signature to findwinner(p1, p2)

*If you are receiving the players choices by argument in findwinner(), you don't have to call getuser() again.

*Wins, losses and ties counters are going to be reset each time you call findwinner() you have to declare them as globals outside the function, and then update them inside the function.
After fixing these, you end up with this:
import random
#The game keeps how many times the player1 has won, lost or tied with the computer in the variables bellow.
# 4 FIX) declare counters as globals
wins = 0
losses = 0
ties = 0
#The game welcomes the player.
print("Welcome to the Rock-Paper-Scissors-Fire-Pencil game!")
#The player can play as many times as he/she wants until he/she type anything
#else except yes in the "Do you want to play again?" question.
def getuser():
    choices = ["rock", "scissors", "fire", "pencil", "paper"]
    #The computer chooses it's 'weapon'.
    player2 = choices[random.randint(0,4)]
    player1 = None
    while player1 not in choices:
    #The player must choose his/her 'weapon'
      player1 = input("\n PLAYER 1 - Please make a choice (rock/paper/scissors/fire/pencil):")
    print (f"\nPlayer1 choose {player1}")
    print (f"\nPlayer2 choose {player2}")
    return player1, player2  # 1 FIX) return players choice

# 2 FIX) add players choice as parameters
def findwinner(p1, p2):
    winner = None
    # 3 FIX) do not call getuser since you have the player choices as arguments
    # 4 FIX) use them as globals in the function scope
    global wins, losses, ties
    #The game compares the choises of the players and announces if the human player won, lost or tied with the computer.
    #Then it adds the win, the lost or the tie to the summary of wins, losses or ties.
    if p1 != p2:
        if p1 == "rock":
            if p2 == "scissors" or p2 == "pencil" or p2 == "fire":
                print("\n Player1 wins this round!")
                winner = p1
                wins += 1
            else:
                print("\n Player2 wins this round!")
                winner = p2
                losses += 1
        if p1 == "paper":
            if p2 == "rock":
                print("\n Player1 wins this round!")
                winner = p1
                wins += 1
            else:
                print("\n Player2 wins this round!")
                winner = p2
                losses += 1
        if p1 == "scissors":
            if p2 == "paper" or p2 == "pencil":
                print("\n Player1 wins this round!")
                winner = p1
                wins += 1
            else :
                print("\n Player2 wins this round!")
                winner = p2
                losses += 1
        if p1 == "pencil":
            if p2 == "paper":
                print("\n Player1 wins this round!")
                winner = p1
                wins += 1
            else:
                print("\n Player2 wins this round!")
                winner = p2
                losses += 1
        if p1 == "fire":
            if p2 == "paper" or p2 == "scissors" or p2 == "pencil":
                print("\n Player1 wins this round!")
                winner = p1
                wins += 1
            else:
                print("\n Player2 wins this round!")
                winner = p2
                losses += 1
    else:
        print("\n The round is a tie!")
        winner = None
        ties += 1
    print (f"\nThe winner of this round is {winner}")

    return winner  # 4 FIX) no need to return the counters anymore

play_again = "yes"

while play_again == "yes":

    #The game shows the choises of the players.
    player1, player2 = getuser()  # 1 FIX) save player choices
    findwinner(player1, player2)

    #The game askes the player if he/she wants to play again.
    play_again = input("\nDo you want to play again?:")
else:
    #If the player doesn't want to play again, the game prints the results of all the rounds of the game and closes.
    # 4 FIX) Use the global variables
    print(f"The player1 won {wins} times")
    print(f"The player1 lost {losses} times")
    print(f"The player1 tied {ties} times")
    print("\n Good Bye")

I can tell you have problems understanding function returns. Each time you do findwinner() you are calling the function AGAIN, to run it only once and save the result you assign it to a variable. As done for getuser():
player1, player2 = getuser()


text:
Q: Twig Template Cache on EC2(AWS Auto Scaling) I am developing by applying Twig Template to CodeIgniter4.
The server environment is AWS EC2 and is auto-scaled.
This is the first development in this environment.
I heard that you should be careful about creating and referencing local files.
I understand this is because it runs on multiple instances.
So I was concerned about the Twig template cache file.
If the file does not exist, a cache is created.
And if the template contents are different, the cache is updated.
At first, I thought it was okay, but I'm not sure.
I'm not sure, but should I cache the template cache in Redis?
(I'm not sure about the Twig template cache settings for Redis, so please let me know if you know it.)
What are some best practices for template caching in an autoscale environment?

A: If you do not want to make any changes to your app you could take a look at mounting an EFS mount to all your autoscaled instances (this could be done as either lifecycle hook or part of the AMI used for the autoscaling.
If you then create a symlink between all the EFS mount and the folder your twig cache is generated then all your servers would share the same file cache.


text:
Q: How can we rename the primary key of a table in FluentMigrator? I need to rename the primary key of an existing table through FluentMigrator so an automapper can automatically detect the column.
For most columns, it's a simple 1) delete any foreign key constraints on that column 2) delete indices for that column and 3) rename the column.  I have historically done this by:
Delete.ForeignKey("foreignkeyconstraint").OnTable("mytable");
Delete.Index("UserId").OnTable("mytable");
Rename.Column("UserId").OnTable("mytable").To("UserInfo_id");

However, this doesn't appear to work for primary keys, since I can't delete the automatically created index on that column.  What is the correct way to rename a primary key column with FluentMigrator?

A: Use the following method call to rename your primary key (SQL Server)
Execute.Sql("EXEC sp_rename N'[Current_Primary_Key_Name]', '[New_Primary_Key_Name]', 'object';");

A: Something like this should work as long as it is not an identity (auto increment) column as well:
Delete.PrimaryKey("PRIMARY KEY").FromTable("mytable");


text:
Q: How to route to "www.example.com/sample-article-name" to RazorPage Index.cshtmll with articleName=sample-article-name [MVC Core2.2] How to access article by url: www.example.com/some-article-name in Razor pages?
I create a blog portal in Asp.Net MVC Core 2.2 RazorPage.
I have a Page Index.chhtml with the method public void OnGet(string id)
I can access the Index with int parameter like that: www.example.com/234 - this work's
But putting string: www.example.com/some-string - doesn't work - HTTP ERROR 404
I would like access article by url: www.example.com/some-article-name.

A: Instead of id parameter at OnGet method, add page parameter at the top of index.cshtml
@page "{menuUrl?}"

and detect its value at OnGet by using RouteData.Values["menuUrl"]?.ToString()


text:
Q: direct x mouse recapturing problem i have a direct x c++ game. i use my own mouse icon and capture the mouse and keyboard when the game initialises but the problem is that if i minimise the game and select another window, for example to skip a song media player when i go back to my game screen the mouse no longer works.
as far as i understand it i need to re capture the mouse handler every time the application gets focus but how do i do this.
can i simply re use the same mouse code from the initialisation and if so where do i put it to make it run when the application regains focus.
fyi my game runs in both windowed mode and full screen would this make a difference.
thank you

A: First of all, I would advise to use the Windows cursor API instead of drawing the mouse yourself. It will be much more responsive (not suffering from low fps etc.) and it is much easier to handle. You can use animated cursors this way too.
For capturing the mouse, you can only really capture it while a mouse button is pressed. If no button is pressed and the mouse is moved outside the application window, you lose the capture.
Why do you even need to capture the mouse? You get WM_MOUSEMOVE messages etc. when the mouse is not captured.


text:
Q: Banach fixed-point theorem : Existence of solution We have the system \begin{align*}&x_1=\left (5+x_1^2+x_2^2\right )^{-1} \\ &x_2=\left (x_1+x_2\right )^{\frac{1}{4}}\end{align*} and the set $G=\{\vec{x}\in \mathbb{R}^2: \|\vec{x}-\vec{c}\|_{\infty}\leq 0.2\}$ where $\vec{c}=(0.2,1)^T$.
I want to show with the Banach fixed-point theorem that the system has a solution in $G$.
I have done the following:
Let \begin{equation*}\Phi (x_1, x_2)=\begin{pmatrix}\left (5+x_1^2+x_2^2\right )^{-1} \\ \left (x_1+x_2\right )^{\frac{1}{4}}\end{pmatrix}\end{equation*} The jacobi matrix is \begin{equation*}\nabla \Phi =\begin{pmatrix}-\frac{2x_1}{(x_1^2+x_2^2+5)^2} & -\frac{2x_2}{(x_1^2+x_2^2+5)^2} \\ \frac{1}{4(x_1+x_2)^{\frac{3}{4}}} & \frac{1}{4(x_1+x_2)^{\frac{3}{4}}} \end{pmatrix}\end{equation*}
Then we get \begin{equation*}\|\nabla \Phi \|_{\infty}=\max \left \{\frac{2x_1+2x_2}{(x_1^2+x_2^2+5)^2}, \frac{1}{2(x_1+x_2)^{\frac{3}{4}}}\right \}\end{equation*}
We want to get an upper bound for that, don't we?
How can we do that? Could you give me a hint?

A: First note that
$$G = \{(x_1,x_2)\mid \|(x_1,x_2)-(0.2,1)\|_{\infty}\leq 0.2\} =\{(x_1,x_2)\mid |x_1-0.2|\leq 0.2 \text{ and } |x_2-1|\leq 0.2\} \\= [0,0.4]\times [0.8,1.2].$$
Now, let
$$\phi_1(x_1,x_2)=(5+x_1^2+x_2^2)^{-1}\quad\text{ and }\quad \phi_2(x_1,x_2)=(x_1+x_2)^{1/4},$$
so that $\Phi(x_1,x_2)=(\phi_1(x_1,x_2),\phi_2(x_1,x_2))$.
For $(x_1,x_2)\in G$ it holds
$$0\leq \phi_1(0.2,1.2)\leq \phi_1(x_1,x_2)\leq \phi_1(0,0.8)\approx 0.1773\leq 0.4$$
and
$$0.8 \leq 0.9457\approx \phi_2(0,0.8)\leq \phi_2(x_1,x_2)\leq \phi_2(0.2,1.2)\approx 1.0878 \leq 1.2$$
It follows that $\Phi(G)\subset G$.
Now, in order to apply the Banach fixed point theorem, you want to show that $\Phi$ is a strict contraction on $(G,\|\cdot\|_{\infty})$, i.e. there exists $\alpha <1$ such that
$$\|\Phi(x)-\Phi(y)\|_{\infty}\leq \alpha \|x-y\|_{\infty},\qquad \forall x=(x_1,x_2),y=(y_1,y_2)\in G.\tag{1}$$
Let $x,y\in G$. As $\Phi$ is differentiable on $G$, by MVT, there exists
$s,t\in [0,1]$ such that $u=s x+(1-s)y$ and $v=t x+(1-t)y$ satisfy
$$(x-y)\cdot\nabla \phi_1(u) = \phi_1(x)-\phi_1(y)\quad\text{and}\quad (x-y)\cdot\nabla \phi_2(v) = \phi_2(x)-\phi_2(y).$$
Hence, if we can show that there exists $\alpha<1$ independent of $x,y$ such that
$$|(x-y)\cdot\nabla \phi_1(u)|\leq \alpha \|x-y\|_{\infty}\quad\text{and}\quad |(x-y)\cdot\nabla \phi_2(v)|\leq \alpha \|x-y\|_{\infty},$$
then, $\alpha$ satisfies $(1)$ and we are done. Now, note that
$$\max\{|(x-y)\cdot\nabla \phi_1(u)|,|(x-y)\cdot\nabla \phi_2(v)|\}\leq \max\{\|\nabla\Phi(u)(x-y)\|_{\infty},\|\nabla\Phi(v)(x-y)\|_{\infty}\}\\ \leq \max\{\|\nabla \Phi(u)\|_{\infty,\infty},\|\nabla \Phi(v)\|_{\infty,\infty}\} \|x-y\|_{\infty}$$
where
$$\|\nabla \Phi(z)\|_{\infty,\infty}=\max_{\|w\|_{\infty}\leq 1}\|\nabla\Phi(z)w\|_{\infty}.$$
Furthermore, as $u,v\in G$, combining the above arguments, we deduce that we can set
$$\alpha = \max_{z\in G}\|\nabla \Phi(z)\|_{\infty,\infty}.$$
Now, for $z\in G$, we have,
$$\|\nabla \Phi(z)\|_{\infty,\infty}=\max\{\|\nabla \phi_1(z)\|_{1},\|\nabla \phi_1(z)\|_{1}\},$$
and you have computed that
$$\|\nabla \phi_1(z)\|_{1}=\frac{2z_1+2z_2}{(z_1^2+z_2^2+5)^2}, \qquad\text{and}\qquad\|\nabla \phi_2(z)\|_{1}=\frac{1}{2(z_1+z_2)^{3/4}}.$$
As $z\in G=[0,0.4]\times [0.8,1.2]$, we find that
$$\frac{2z_1+2z_2}{(z_1^2+z_2^2+5)^2}\leq\frac{2(0.4+1.2)}{(0^2+(0.8)^2+5)^2}\approx 0.1006 \leq 0.2$$
$$\frac{1}{2(z_1+z_2)^{3/4}}\leq \frac{1}{2(0+0.8)^{3/4}}\approx 0.5911 \leq 0.6$$
Therefore, we conclude that with $\alpha=0.6$,
$$\|\Phi(x)-\Phi(y)\|_{\infty}\leq 0.6 \|x-y\|_{\infty}$$
which implies that $\Phi\colon G\to G$ is a strict contraction with respect to $\|\cdot\|_{\infty}$ and thus, as $(G,\|\cdot\|_{\infty})$ is a complete metric space, the Banach fixed point theorem implies that $\Phi$ has a unique fixed point $p\in G$. Furthermore, for every $x\in G$, the iterative sequence $\Phi^k(x)$ converges towards $p$. A simple numerical experiments shows that
$$p = (0.163190947349524, 1.049361520947913)$$


text:
Q: Divide Mesh grid by a bisector, MATLAB I have a piecewise function, where domain changes for each case. The function is as follows:

For
(x,y)greater than Divider v= f(x,y) (A1)
(x,y)less than Divider v = g(x,y)        (A2)

The location of the divider changes with tilt angle of the rectangle given in figures 1 and 2.Figure 1 & 2 The divider will always be a bisector of the rectangle. For example, the divider makes an angle (alpha + 90) with the horizontal.
If the rectangle makes an angle 0, it's easy to implement above functions as I can create meshgrid from

x =B to C & y = A to D for A1
x =A to B & y = A to D for A2

However, when the angles for the rectangle are different, I can't figure out how to create the mesh to calculate the function v using the algorithm A1 and A2 above.
I was thinking of using some inequality and using the equation of the line (as I have the co-ordinates for the center of the rectangle and the angle of tilt). But, I can't seem to think of a way to do it for all angles (for example , slope of pi/2 as in the first figure, yields infinity). Even if I do create some kind of inequality, I can't create a mesh.
1Please help me with this problem. I have wasted a lot of time on this. It seems to be out of my reach
%% Constants
Angle1=0;
Angle1=Angle1.*pi./180;

rect_center=0; % in m
rect_length=5; % in m
rect_width=1; % in m
rect_strength=1.8401e-06;

Angle2=0;
Angle2 =Angle2.*pi./180;

  %% This code calculates the outer coordinates of the rectangle by using the central point

% the following code calculates the vertices
vertexA=rect_center+(-rect_width./2.*exp(1i.*1.5708)-rect_length./2).*exp(1i.*Angle2);
vertexA=[vertexA,vertexA+2.*(rect_width./2.*exp(1i.*1.5708)).*exp(1i.*Angle2)];
vertexB=rect_center+(-rect_width./2.*exp(1i.*1.5708)+rect_length./2).*exp(1i.*Angle2);
vertexB=[vertexB,vertexB+2.*(rect_width./2.*exp(1i.*1.5708)).*exp(1i.*Angle2)];

za1=vertexA(1:numel(vertexA)/2);
za2=vertexA(1+numel(vertexA)/2:numel(vertexA));
zb1=vertexB(1:numel(vertexB)/2);
zb2=vertexB(1+numel(vertexB)/2:numel(vertexB));
arg1=exp(-1i.*Angle2);

%% This Section makes the two equations necessary for making the graphs

    syms var_z

    % Equation 1
    Eqn1(var_z)=1.5844e-07.*exp(-1i.*Angle1).*var_z./9.8692e-13;

    % subparts of the Equation 2
    A = 1.0133e+12.*(-1i.*rect_strength.*exp(-1i*Angle2)./(2*pi.*rect_length.*rect_width*0.2));
    ZA1 = var_z+za1-2*rect_center;
    ZA2 = var_z+za2-2*rect_center;
    ZB1 = var_z+zb1-2*rect_center;
    ZB2 = var_z+zb2-2*rect_center;

   ZAA2 = log(abs(ZA2)) + 1i*mod(angle(ZA2),2*pi);
   ZAA1 = log(abs(ZA1)) + 1i*mod(angle(ZA1),2*pi);
   ZBB1 = log(abs(ZB1)) + 1i*mod(angle(ZB1),2*pi);
   ZBB2 = log(abs(ZB2)) + 1i*mod(angle(ZB2),2*pi);

   %Equation 2 ; this is used for the left side of the center
   Eqn2= A*(ZA2*(log(ZA2)-1)-(ZA1*(log(ZA1)-1))+(ZB1*(log(ZB1)-1))-(ZB2*(log(ZB2)-1)));
   %Equation 3 ; this is used for the right side of the center
   Eqn3 = A.*(ZA2*(ZAA2-1)-(ZA1*(ZAA1-1))+(ZB1*(ZBB1-1))-(ZB2*(ZBB2-1)));

    %Equation 4 :Add Equation 2 and Equation 1; this is used for the left side of the center
    Eqn4 = matlabFunction(Eqn1+Eqn2,'vars',var_z);
    %Equation 5: Add Equation 3 and Equation 1; this is used for the right side of the center
    Eqn5 = matlabFunction(Eqn1+Eqn3,'vars',var_z);

    %% Prepare for making the plots

    minx=-10;     %min x coordinate
    maxx=10;      %max x coordinate
    nr_x=1000;    %nr x points
    miny=-10;     %min y coordinate
    maxy=10;      %max y coordinate
    nr_y=1000;    %nr y points

    %This vector starts from left corner (minx) to the middle of the plot surface,
    %The middle of the plot surface lies at the center of the rectange
    %created earlier
    xvec1=minx:(rect_center-minx)/(0.5*nr_x-1):rect_center;

    %This vector starts from middle to the right corner (maxx) of the plot surface,
    %The middle of the plot surface lies at the center of the rectange
    %created earlier
    xvec2=rect_center:(maxx-rect_center)/(0.5*nr_x-1):maxx;

    %the y vectors start from miny to maxy
    yvec1=miny:(maxy-miny)/(nr_y-1):maxy;
    yvec2=miny:(maxy-miny)/(nr_y-1):maxy;

    % create mesh from above vectors
    [x1,y1]=meshgrid(xvec1,yvec1);
    [x2,y2]=meshgrid(xvec2,yvec2);

     z1=x1+1i*y1;
     z2=x2+1i*y2;

    % Calculate the above function using equation 4 and equation 5 using the mesh created above
    r1 = -real(Eqn5(z1));
    r2 = -real(Eqn4(z2));

    %Combine the calculated functions
    Result = [r1 r2];

    %Combine the grids
    x = [x1 x2];
    y = [y1 y2];

 % plot contours
 [c,h]=contourf(x,y,Result(:,:,1),50,'LineWidth',1);
 % plot the outerboundary of the rectangle
 line_x=real([vertexA;vertexB]);
 line_y=imag([vertexA;vertexB]);
 line(line_x,line_y,'color','r','linestyle',':','linewidth',5)

The final Figure is supposed to look like this.Final Expected Figure.

A: I'm not sure which angle defines the dividing line so I assume it's Angle1. It looks like logical indexing is the way to go here. Instead of creating two separate mesh grids we simply create the entire mesh grid then partition it into two sets and operate on each independently.
%% Prepare for making the plots

minx=-10;     %min x coordinate
maxx=10;      %max x coordinate
nr_x=1000;    %nr x points
miny=-10;     %min y coordinate
maxy=10;      %max y coordinate
nr_y=1000;    %nr y points

% create full mesh grid
xvec=linspace(minx,maxx,nr_x);
yvec=linspace(miny,maxy,nr_y);
[x,y]=meshgrid(xvec,yvec);

% Partition mesh based on divider line
% Assumes the line passes through (ox,oy) with normal vector defined by Angle1
ox = rect_center;
oy = rect_center;
a = cos(Angle1);
b = sin(Angle1);
c = -(a*ox + b*oy);
% use logical indexing to opperate on the appropriate parts of the mesh
idx1 = a*x + b*y + c < 0;
idx2 = ~idx1;

z = zeros(size(x));
z(idx1) = x(idx1) + 1i*y(idx1);
z(idx2) = x(idx2) + 1i*y(idx2);

% Calculate the above function using equation 4 and equation 5
%   using the mesh created above
Result = zeros(size(z));
Result(idx1) = -real(Eqn5(z(idx1)));
Result(idx2) = -real(Eqn4(z(idx2)));

For example with Angle1 = 45 and Angle2 = 45 we get the following indexing
>> contourf(x,y,idx1);
>> line(line_x,line_y,'color','r','linestyle',':','linewidth',5);

where the yellow region uses Eqn5 and the blue region uses Eqn4. This agrees with the example you posted but I don't know what the resulting contour map for other cases is supposed to look like.
Hope this helps.


text:
Q: How to set a floating point register to 0 in MIPS (or clear its value). I'm currently implementing a square matrix multiplier containing single floating point numbers in MIPS assembly line code.
My problem is that once I am done summing the multiplications of the corresponding rows and columns in order to calculate my dot product I want to clear that floating point register so I can calculate the dot product for the next entry in the product matrix.Right now I keep adding the current dot product with all the previous dot products.
Things I've tried to set the floating point register as zero:
l.s $f3,$0 #loading zero into the register

addi $t0,$t0,$zero #setting a temp register as zero
l.s $f3,($t0)

I keep getting an error indicating a runtime exception and an address out of range.

A: What you are doing is loading a float from address 0, hence the fault. You want to load the value 0 instead. You can do that by mtc1 $zero, $f3. This works because all zero bits mean zero in floating point too. For other values, you'd have to do a cvt.s.w afterwards to convert the integer to floating point. Alternatively you can subtract the register from itself by sub.s $f3, $f3, $f3. Don't know if this works for all possible values (I am thinking of NaN, Inf and such) or if it is faster than transferring from the integer zero register.


text:
Q: Bug when trying to parse date in Objective-C When I was trying to convert April from 04 (MM) to Apr (MMM) it turned back into nil, is this a known issue in iOS or am I doing something wrong?
Here's my code for inspection:
NSString *dateString=@"2016-04-01";
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
NSLog(@"%@ == %@",dateString,stringFromDate);

when change dataString=@"2015-04-01" the stringFromDate returns Apr
This is my output:
this is the log image

2016-04-01 12:17:45.708[32172:2389414] 2016-04-01 == (null)
2016-04-01 12:17:47.446[32172:2389414] 2015-04-01 == Apr

A: This is probably a problem in your time zone. Note that when parsing a date without time, the time is assumed to be zero. However, some specific times don't exist, usually due to Daylight Saving Time changes (which happen in March around the world) or due to specific local time changes.
For example, in Jordan, the DST change is Apr 1 2016, 00:00 => Apr 1 2016, 01:00. That means that the time Apr 1 2016, 00:00 does not exist because March 31 2016, 23:59 becomes immediately Apr 1 2016, 01:00. If the date does not exist, date formatter must return nil.
You can usually fix the problem by using a preset GMT time zone that does not have this problem, e.g
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

or
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:[NSTimeZone systemTimeZone].secondsFromGMT];

Note that since you are not parsing time, time zone differences shouldn't affect you.
Steps to reproduce
Set the time zone on your machine to Jordan time zone:

NSString *dateString = @"2016-04-01";
NSDateFormatter* parsingFormatter = [[NSDateFormatter alloc] init];
parsingFormatter.dateFormat = @"yyyy-MM-dd";

NSLog(@"Parsed: %@", [parsingFormatter dateFromString:dateString]); // "(null)"

with time zone fix:
NSString *dateString = @"2016-04-01";
NSDateFormatter* parsingFormatter = [[NSDateFormatter alloc] init];
parsingFormatter.dateFormat = @"yyyy-MM-dd";
parsingFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

NSLog(@"Parsed: %@", [parsingFormatter dateFromString:dateString]); // "2016-04-01 00:00:00 +0000"

A: I tried your code and it gives me null for year 2022, but years 2018,2020 it gives Apr ... weird!
    NSString *dateString=@"2022-04-01";
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"+5:30"]];
[dateFormatter setDateFormat:@"MMM"];
NSString *stringFromDate = [dateFormatter stringFromDate:myDate];
NSLog(@"%@ == %@",dateString,stringFromDate);

UPDATE:
Please parse the string as this :
2016-04-01 01:00
Because of daylight saving in Jordan the clock will be shifted +1 hour so there's no time in the universe like this:
2016-04-01 00:00
This should resolve ur issues with the nil object.


text:
Q: How to map drop-downs according to JSON array length This question is about react native mobile application. I want to know how to generate dropdown according to my API JSON array length values.
In my case output values are like this
eg:- Choice 1 (Label of the Drop Down)
           -Sub Choice 1 . (Value Data)
           -Sub Choice 2 (Value Data)
           -Sub Choice 3 (Value Data)

   Choice 2 (Label of the second Drop Down)
           -Sub Choice 1 . (Value Data)
           -Sub Choice 2 . (Value Data)
           -Sub Choice 3 . (Value Data)

Like this, if API response gives Choice 1, Choice 2 -> then I need to generate 2 dropdowns accordingly.
This is my code and according to my code I only get the last Choice and Choice Data of API response array
I'm using the react-native-material-dropdown library and I need to map this accordingly with JSON array length
 if(responseText.success == true)
    {
      var count = Object.keys(responseText.data).length;  //Getting Array Data Length
      let drop_down_data = [];  //  For Dropdown box
      for(var i=0;i<count;i++){
        // Next Loop for Fetching Choice Items
        var t_count = Object.keys(responseText.data[i].choiceItems).length;
        for(var j=0;j<t_count;j++){

          var Add_On_Name = responseText.data[i].name
          console.log(Add_On_Name)
          this.setState({addOn_name: Add_On_Name});

          this.setState({riceTypeData:responseText.data[i].choiceItems[j].name});
          drop_down_data.push({ value: responseText.data[i].choiceItems[j].name});

        }

      }
      this.setState({ drop_down_data , progressDialog:false}); // Set the new state

    }

A: Hope this helps.
//This is the initial state.
state = {
   dropdownsdata: []
};

//This is going into the api successcallback
if (responseText.success) {
  let all_dropdownData = [];
  for (let i = 0; i < responseText.data.length; i++) {
    let ind_dropdownData = [];
    for (let j = 0; j < responseText.data[i].choiceItems.length; j++) {
      let Add_On_Name = responseText.data[i].choiceItems[j].name;
      let temp = {};
      temp.value = Add_On_Name;
      ind_dropdownData.push(temp);
    }
    let temp_obj = {};
    temp_obj.label = responseText.data[i].name;
    temp_obj.data = ind_dropdownData;
    all_dropdownData.push(temp_obj);
  }
  this.setState({ dropdownsdata: all_dropdownData });
}
//Function for rendering n number of dropdowns.
renderDropdowns = () => {
  return this.state.dropdownsdata.map(e => {
    return <Dropdown label={e.label} data={e.data} />;
  });
};

render(){
  return <View>{this.renderDropdowns()}</View>;
};


text:
Q: is it possible to put two kind of character sets in the same file I just asked this question out of curiousity. Generally as for as I am concerning files are stored with single character set. But where will be the the character set type saved? And is it possible to put two kind of strings(like std::string, std::wstring) in the same file?

A: Character sets were introduced to allow different programs to interpret the same set of characters (namely, single-byte characters whose decimal value is over 127, or, to put it another way, whose high-order bit is set) in different ways.  If you want to switch character sets part way through a file or stream, you would have to signal your program in some way, either in the file or out of band.
As to mixing std::string and std::wstring, while it is possible, it would be, at best, confusing.  strings are (generally) ASCII and wstrings are Unicode.  When generating your file, you could put a signal or marker in that would tell your program to switch when reading it back in.
Generally, if you need more than one character set, you should be using Unicode (which can be represented with std::wstring).  In fact, if you're handling user input at all, you should be using Unicode.
Go read Joel Spolsky's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!).  It should help to make things more clear.

A: Character encodings are totally free.  Files are containers of bytes.  You can encode text into a mixture of ASCII, UTF8, Big5, ... encoded characters, but it's up to you to tell how each is to be interpreted.
The convention, though, is to put a marker at the first position of the file, that denotes the encoding.  (cfr Byte Order Mark on wikipedia).
When using xml, this has become far more explicit (yet not completely covered): the encoding has to be on the first line, and that line has to be in utf8. (If the encoding is omitted, it means: "utf-8")

A: If your question is about the encoding of the source file itself, the answer is that the C++ standard requires an implementation to support source files encoded in the base character set. Complier implementations may support additional character sets. Consult your compiler manuals for more information.
About using std::string and std::wstring variables in the same file, yes you can use the, together.

A: A file is just a sequence of bytes. A byte is just a 8-digit (on any modern hardware) binary number, ranging from 0 to 255 if interpreted as unsigned, or from -128 to 127 if interpreted as signed.
What these bytes mean it up to whoever is designed that particular file format. It could contain a sequence of characters encoded with some single encoding indicated in some way or specified in the file format documentation, it can contain an unholy mess of different encodings with no ways to distinguish between them (I've seen such things in real, critical applications), it can contain a mix of binary and text data, or it can contain binary data that has nothing to do with any characters or character sets whatsoever.
However, if your file format isn't binary, that is, if it contains text and only text, then it's generally an extremely bad idea to mix character sets. Using something uniform and ASCII-compatible like UTF-8 is probably the best way. Even in a binary format, it is still a good idea to encode all the text data in the same encoding. UTF-8 or UTF-16 (or even UTF-32) seem to be good choices there. Sometimes there are different requirements which you have to deal with, though. For example, a binary format may have the "old" version of header and the "new" one. The old one may be using some legacy character set, and the new one may be using some Unicode. That's fine. But when it comes to pure-text formats, I've yet to see a widely used format that allows to mix character sets. Some allow you to choose a single character set for each file, and to put a marker somewhere (like XML, HTML, Python sources).


text:
Q: How to AUTO update MySQL after timestamp field expierd How do I automate MySQL Update or Insert upon expire timestamp?
So let say timestamp is 2013-06-30 20:10:00 and I would like to auto update MySQL DB upon passing that date and time so today after 2013-06-03 20:10:00.
I want to update my item, but I will not have browser open with my website, so I think so I need some kind of server trigger?? How do I do that? Many thanks
I have following Query to execute every 1 second and it doesn't work:
CREATE EVENT e_second
    ON SCHEDULE
      EVERY 1 SECOND
    DO
UPDATE online_auctions.auction_status
   SET auction_status = 'ENDED' WHERE TIMESTAMP(auction_end_date) < (select now());

A: Use can use for that

*

*Mysql events (IMHO the best candidate)

*cron job or Windows Task Scheduler (if you're on Windows platform)

If you go with option 1 you need to create an event
CREATE EVENT myevent
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR DO
UPDATE myschema.mytable
   SET mycol = mycol + 1;

Use SHOW PROCESSLIST to check if event scheduler is enabled. If it's ON you should see a process "Daemon" by user "event_scheduler". Use SET GLOBAL event_scheduler = ON; to enable the scheduler if it's currently not enabled. More on configuring event scheduler here.
If you want to see events that you've in your schema
SHOW EVENTS;

UPDATE Your update statement should look like
UPDATE online_auctions
   SET auction_status = 'ENDED'
 WHERE auction_end_date < NOW();

Here is SQLFiddle demo


text:
Q: Spark Streaming and Kafka: one cluster or several standalone boxes? I am about taking a decision about using Spark-Streaming Kafka integration.
I have a Kafka topic (I can break it into several topics) queuing several dozens of thousands of messages per minute, my spark streaming application ingest the messages by applying transformations, and then update a UI.
Knowing that all failures are handled and data are replicated in Kafka, what is the best option for implementing the Spark Streaming application in order to achieve the best possible performance and robustness:

*

*One Kafka topic and one Spark cluster.

*Several Kafka topics and several stand-alone Spark boxes (one machine with stand alone spark cluster for each topic)

*Several Kafka topics and one Spark cluster.

I am tempted to go for the second option, but I couldn't find people talking about such a solution.

A: An important element to consider in this case is the partitioning of the topic.
The parallelism level of your Kafka-Spark integration will be determined by the number of partitions of the topic.  The direct Kafka model simplifies the consumption model by establishing a 1:1 mapping between the number of partitions of the topic and RDD partitions for the corresponding Spark job.
So, the recommended setup would be: one Kafka topic with n partitions (where n is tuned for your usecase) and a Spark cluster with enough resources to process the data from those partitions in parallel.
Option #2 feels like trying to re-implement what Spark gives you out of the box: Spark gives you resilient distributed computing. Option #2 is trying to parallelize the payload over several machines and deal with failure by having independent executors. You get that with a single Spark cluster, with the benefit of improved resource usage and a single deployment.

A: Option 1 is straight forward, simple and probably more efficient. If your requirements are met, that's the one to go for (And honor the KISS Principle).