text:
Q: Center Pop Up Menu in clicked row of list I want that my pop up menu appear next to the clicked row. Look at the picture after I click the "..." button:
http://postimg.org/image/s35znsaq3/
I added my adapter that init each row. When I click on moreActionsButton, the listener call the method showPopUpMenu that open the menu. Inside the menu I will do some staff.
This is my code for the Pop Up Menu:
public class ContactsListActivity extends Activity {

      @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set layout for this activity
        setContentView(R.layout.contacts_list);

        // Connect between buttons to layout id
        list = (ListView) findViewById(R.id.my_user_list);
        spinner = (ProgressBar) findViewById(R.id.spinner);

        // Setting adapter and creating contacts list
        if (selectedGroupId != null) {
            Model.getInstance().getAllUsersByGroupId(selectedGroupId, new Model.userListReturnedListener() {
                @Override
                public void userListReturned(List<User> userList) {
                    spinner.setVisibility(View.GONE);
                    data = userList;
                    adapter = new MyAdapter();
                    list.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                }
            });
        }

        class MyAdapter extends BaseAdapter {

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

            ViewHolder holder = null;

            if (convertView == null) {
                // Creates a ViewHolder and store references to layouts we want to bind data to.
                holder = new ViewHolder();
                LayoutInflater inflater = getLayoutInflater();
                convertView = inflater.inflate(R.layout.contacts_row, null);

                // Connect between buttons to layout id
                holder.contactName = (TextView) convertView.findViewById(R.id.contactName);
                holder.contactImage = (ImageView) convertView.findViewById(R.id.contactImage);
                holder.moreActionsButton = (Button) convertView.findViewById(R.id.moreActions);

                //Save holder
                convertView.setTag(holder);
            } else {
                // Get the ViewHolder back
                holder = (ViewHolder) convertView.getTag();
            }

            // Setting user
            final User us = data.get(position);
            holder.contactName.setText(us.getFname() + " " + us.getLname());

           holder.moreActionsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopUpMenu(us);
            }
        });

        // Setting the popUpMenu buttons
        popUpMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_skype:
                        AppsCommunication.onSkypeClick(ContactsListActivity.this, user.getSkype());
                        break;

                    case R.id.1:
                        //Do something
                        break;

                    case R.id.2:
                     //Do something
                        break;

                    case R.id.3:
                    //Do something
                    default:
                        break;

                }
                return true;
            }
        });

        Object menuHelper;
        Class[] argTypes;
        try {
            Field fMenuHelper = PopupMenu.class.getDeclaredField("mPopup");
            fMenuHelper.setAccessible(true);
            menuHelper = fMenuHelper.get(popUpMenu);
            argTypes = new Class[]{boolean.class};
            menuHelper.getClass().getDeclaredMethod("setForceShowIcon", argTypes).invoke(menuHelper, true);
        } catch (Exception e) {
            // Possible exceptions are NoSuchMethodError and NoSuchFieldError
            //
            // In either case, an exception indicates something is wrong with the reflection code, or the
            // structure of the PopupMenu class or its dependencies has changed.
            //
            // These exceptions should never happen since we're shipping the AppCompat library in our own apk,
            // but in the case that they do, we simply can't force icons to display, so log the error and
            // show the menu normally.
        }

        popUpMenu.show();
    }

    // Class to handle row buttons
    class ViewHolder {
        private TextView contactName;
        private ImageView contactImage;
        private ImageButton saveContactButton;
        private ImageButton callButton;
        private ImageButton smsButton;
        private Button moreActionsButton;
        private ProgressBar contactImageProgressbar;
    }
}


text:
Q: Can X-Real-IP be set when using Proxy Protocol? My setup is as follows:
Load Balancer → nginx → Traefik
The load balancer in place does not support Proxy Protocol. Instead it adds the real IP of the client to the TCP options field (yikes, I know! Details). That's something Traefik does not support.
To get the real IP to Traefik, I added an nginx inbetween that does nothing more than accepting connections on ports 80 and 443 and adding Proxy Protocol when using SSL. Traefik is configured for Proxy Protocol. Things work as expected.
However I'd like to set the X-Real-IP header to the correct IP when Proxy Protocol is used. When I try setting the header manually through curl, that one is used, so clients can overwrite it.
How can I tell Traefik to always set X-Real-IP to the IP as adviced by Proxy Protocol?

A: I solved my problem and can see clearer now.
It depdends on which node in your configuration (Load Balancer → nginx → Traefik) terminates the clients request. In my setup (Load Balancer → Traefik) the Load Balancer uses NATing to send the request to the Traefik. Traefik then takes the client´s request and sends a new request to the corresponding backend.
So I had to configure Traefik to never trust the X-Real-Ip header but always set the request´s source ip in the X-Real-Ip header.
Configuration is something like this:
    [entryPoints.http.proxyProtocol]
      insecure = true
      trustedIPs = ["10.10.10.1", "10.10.10.2"]
    [entryPoints.http.forwardedHeaders]
      trustedIPs = ["10.10.10.1", "10.10.10.2"]

The mostly found configuration (I think) would be that the Load Balancer takes the client´s request and then sends a new request to nginx (reverse proxy load balancer). In this case the Load Balancer must set the X-Real-Ip Header, nginx must propagate the header to Traefik and Traefik must be configured to trust nginx as source for the X-Real-Ip header.

A: I just looked into the source code because of a similar problem.
Traefik sets the header X-Real-Ip with the source IP address of the request being forwarded. If the header X-Real-Ip already exists, it will be passed through unchanged.
I hope that answers the question.
if req.Header.Get (XRealIp) == "" {
  req.Header.Set (XRealIp, clientIP)
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can Hinge loss be upper bound of the 0-1 loss? I just have a question and I did not find clear explanation, hinge loss is upper bound of 0-1 loss, so does this mean upper bound regard to a single point loss such as 0 or 1 ?!. So, for example the 0-1 loss for set of points is 0 or 1, and for hinge loss we have continuous loss values from 0 to inf. So, by comparing the set of loss values for 0-1 loss and hinge loss we find the lower bound is 0 and upper bound is 1. I am right?!.
This is the link: https://www.di.ens.fr/~fbach/learning_theory_class/lecture3.pdf. Please see the page 3, the first paragraph under the title "Conditional Φ-risk and classification calibration".
Thanks


text:
Q: PHP Form - Need pastes information in textarea to keep formatting I'm creating a PHP Form and part of the form users must copy and paste an essay into a . When we generate the results of the form all formatting is lost. All I need is for line breaks and/or double spacing to remain as the user sees it when they are submitting the form.
I've read about installing a HTML rich text editor, but I'm new to this and I can't find any straight answers for my situation.
Data entered into the form is received on our SQL and then posted to an HTML document we can download.

A: Your problem is with displaying: Just check the source code of the resulting page.
HTML does nto care about line breaks and also mangles whitespace.
So two easy solution comes up:
Line breaks to

echo str_replace("\n", "
", $myInputText);

This converts the ordinary line breaks to line breaks understood by HTML. This can be done when storing the content - then no changes arte needed to the duisplaying part.
(Or you can put this into the displaying part too, and not change the upload logic.)
Using

echo "
$myInputText
";

This applies all the whitespace formatting to the content, and is better ot put to the displaying part.
Using your comment
If I understood well what you'd like to achieve, this is the easiest:
$HTMLBODY .= "
ESSAY
";  //note the
!
$HTMLBODY .= "

" . $_POST['essay'] . "

";

Also, at the same time, be careful with using unsanitized $POST[''] entries: someone with a bit of hackish instinct might do crazy things to your site...


text:
Q: how can we control EF Database First generated class and property names I have an Oracle database that has all its tables and columns in all Upper-Case.
For example table STUDENT has FIRSTNAME,LASTNAME and DATEOFBIRTH
when i generate classes using EF Database First approach, i get all classes and names in Upper-Case as well.
answer here
How to force pascal case with Oracle's Entity Framework support?
did not helped as it only generates names with only First letter in upper case instead of FirstName or LastName.
I thought of doing it manually. Is there a way i can write something in OnModelCreating so that every time i generate edmx i get the names right?
If i change name after generation its going to override next time i update it from database.

A: ReSharper may be able help with this, though I have not used Re# in a while or the naming convention feature. (see: https://www.jetbrains.com/help/resharper/Inspect_the_Whole_Solution_for_Naming_Style_Compliance.html) Tell it you want UpperCamelCase and run it across the generated code. There may be other plug-ins available with this capability.
EF isn't going to do it as I doubt they'd be trying to determine word boundaries for naming. howwillitknowhowmanywordsareinhere? :)


text:
Q: GIT pull not showing any changes We are using bit bucket as a repository. Below is a scenario we got.

*

*Pull from Branch A (commit already in Develop Branch of A) -> B (git pull origin A)

*Reverted commit in branch B of A (git revert)

*Now i want same commit in branch B, hence creating pull from Develop -> B
But so no changes available to pull.
How do i resolve this situation?
I have tried merge, git pull but still no chances.

A: Remember to run the git fetch --all command to retrieve all changes if there are any, then try again.


text:
Q: AWS/Aurora : is it possible to know if the slaves are correctly used I have a working aurora cluster with a master and a slave.
I use the following code to create a datasource
    val jdbi: Jdbi by lazy {
        val ds = MariaDbDataSource()
        ds.setUrl("jdbc:mysql:aurora://cluster_endpoint/db")
        ds.user = System.getenv("DB_USERNAME")
        ds.setPassword(System.getenv("DB_PASSWORD"))

        val jdbi = Jdbi.create(ds)
        jdbi.installPlugin(SqlObjectPlugin())
        jdbi.installPlugin(KotlinSqlObjectPlugin())
        jdbi
    }

Then, when I am in a readonly operation I do the following :
jdbi.open().use { handle ->
    handle.setReadOnly(true)
    ...
}

How can I be sure that when I do that, queries / connections are correctly routed to the slave ?
I have tried to log the db instance connection
val url = handle.connection.getMetaData().getURL()
val connServer = url.substring(url.indexOf("//") + 2 , url.indexOf("."));

But this always gives me the URL of the cluster...
Is there a way to know if we are talking to the slave or to the master ?

A: Ok, after some more digging, I find the answer burried in mariadb doc at https://mariadb.com/kb/en/mariadb-enterprise/mariadb-maxscale-21-aurora-monitor/#how-aurora-is-monitored (emphasis is mine)
SELECT @@aurora_server_id, server_id FROM information_schema.replica_host_status WHERE session_id = 'MASTER_SESSION_ID';

The node which returns a row with two identical fields is the master. All other nodes are read-only replicas and will be labeled as slave servers.
So in kotlin, with jdbi, you can do :
        //https://mariadb.com/kb/en/mariadb-enterprise/mariadb-maxscale-21-aurora-monitor/#how-aurora-is-monitored
        val sql = "SELECT @@aurora_server_id, server_id FROM information_schema.replica_host_status WHERE session_id = 'MASTER_SESSION_ID'"
        val serverIds = handle.select(sql)
                .map { rs, _ -> Pair(rs.getString(1), rs.getString(2)) }
                .single()
        val serverId = serverIds.first
        val isMaster = serverId == serverIds.second
        val masterOrSlave = if (isMaster) "the master" else "a slave"
        Logger.getLogger(this.javaClass.name).debug("Connected to db instance $serverId which is $masterOrSlave")


text:
Q: How to let a 'charge' be a measure Definiton: If $\mathbb{X}$ is a $\sigma$ algebra of subsets of a set $\mathbb{X}$, then a real-valued (which means it can be positive, negative, or 0) function $\lambda$ defined on $\mathbb{X}$ is said to be a charge in case $\lambda(\emptyset)$=0 and $\lambda$ is countably additive.
Question: If $\mu$ is a charge on $\mathbb{X}$, let $\pi$ be defined for $E \in \mathbb{X}$ by:
$\pi(E)=$ Sup{$\mu(A):A \subset E, A \in \mathbb{X}$ }
Show that $\pi$ is a measure.
=============================
I stuck on how to prove $\pi$ is non negative. My idea is to split $\pi$ into $\pi^+$ and $\pi^-$. Any hint?

A: $\pi(E)=\sup\{\mu(A):A\subset E,\ A\in X\}\ge\mu(\emptyset)=0.$


text:
Q: Is there a PTP (Precision Time Protocol | IEEE 1588) library? I've been tasked with syncing a time critical process for logging data from a PLC with a PTP (Precision Time Protocol, IEEE 1588) time source.
A quick look at the available libraries all turn up nothing but IVI-C and IVI-COM based implementations.
Is there a managed library that supports PTP that I missed, or do I need to find a method to use theIVI-COM library that is designed for LabVIEW in my application?

A: I had reffered, the following answer from this site  http://code.google.com/p/ptpv2d/wiki/Introduction, which i gave me a clear idea on ptpv2d, hope you also get the clear information, about this.
Pls refer this also http://code.google.com/p/ptpv2d/
ptpv2d is GPL licensed open source code of IEEE 1588 version 1, version 2 and IEEE 802.1AS including hardware timestamping for Freescale MPC831x family of processors.

The ptpv2d is a Precision Time
Protocol which has the following
features:

*

*The  User mode application which  runs under standard LINUX, with a
modular design that ensures easy
portation to additional operating
systems.

*An extensive optional print-to-console debug message
function. This message functionality
can be added or omitted at compile
time. If it is included, then the
output level is command-line
selectable. Debug messages are
uniformly formatted for quicker,
easier analysis. The POSIX socket
calls is used to retrive  all
messages. Message handling is
contained in a separate module to
ensure easy portation to any desired
operating system.

*Freescale MPC8313E Ethernet port driver with full support
for PTP version 1 and version 2
message hardware time stamping.

*Ability to adjust the Hardware clock very precisely (as
precise as one part per billion).
Software algorithm for fine (as small
as one part per billion) adjustment of
the Hardware clock .

*Ability to report detected variances from Grandmaster
clock in parts per million

*Command line ability to set four different debug
output levels: none, basic, verbose,
and Message
7.Ability to set Sync/Follow-up transmit time values of
less than one second. This allows for
multiple Sync/Follow-ups per second,
which provides enhanced accuracy and
tracking of the "slave" system to the
"grandmaster" system.

*Additional run time options and support code include:

*Selection of PTP version 1 or version 2 encapsulation
and protocol
10.Selection of IEEE 1588 PTP over IPv4/UDP, IEEE P1588 PTP
over Ethernet (draft 2.2)or IEEE
P802.1AS encapsulation and
protocol(draft 1.0)  User specified
clock period to synthesize other base
clocks, not just at 10 MHz.

These features have gone through
extensive testing using dual
MPC8313E-RDB boards running both PTP
and Ping traffic. On a Freescale
MPC8313E-RDB board running eight
Sync/Follow-up Messages per second, it
will support a plus or minus 50
nanosecond offset from master more
than 99.9% of the time. At 128
Sync/Follow-ups per seconds, the
system will synchronize within 16
nanoseconds of the "grandmaster"
system.

A: Look at http://sourceforge.net/projects/ptpd/
The PTP daemon (PTPd) implements the Precision Time protocol (PTP) as defined by the IEEE 1588 standard. PTP was developed to provide very precise time coordination of LAN connected computers.

A: I've created a IEEE-1588 library some time ago. It was partly difficult especially if you require good sync between clocks. Good ptp library involves a lot of statistics, prediction, and signal processing. The best you can try is ptpd - it's very simple to learn how ptp works, and it will give you a good start.


text:
Q: SQL Selecting count from join returning 0 instead of null result I have a query that gets data and also joins another table (A) and counts the rows in that join table (B). However if the main table (A) is empty I want the query to return nothing. However it is returning a result of null for id and date and an integer value of 0 for users instead of a null row. How do I get an empty result instead of it returning something?
Returning:
id   | date | users
null | null | 0

SQL Code
SELECT
    `sessions`.`id`,
    `sessions`.`date`,
    COUNT( sessions_users.id ) AS users
FROM
    `sessions`
    LEFT JOIN `sessions_users` ON `sessions`.`id` = `sessions_users`.`sessions_id`

A: An aggregate query without a group by clause always returns a single record, regardless of the content of the underlying result set (and even if it is empty).
But, since you have non-aggregated columns in the select clause (sessions.id and sessions.date), your query is missing a group by clause anyway. In non-ancient versions in MySQL, where sql mode ONLY_FULL_GROUP_BY is enabled by default, this is a syntax error.
Consider:
SELECT
    `sessions`.`id`,
    `sessions`.`date`,
    COUNT( sessions_users.id ) AS users
FROM
    `sessions`
    LEFT JOIN `sessions_users` ON `sessions`.`id` = `sessions_users`.`sessions_id`
GROUP BY
    `sessions`.`id`,
    `sessions`.`date`

This will produce one record per session id and date, along with the count of matching records in sessions_users. If there are no records in sessions, the query will return an empty result set.

A: If I understand correctly, instead of NULL, you want something like this:
id   | date | users
     |      | 0

If so, just simply use IFNULL() in your SELECT as such:
SELECT
    IFNULL(`sessions`.`id`,' ') as id,
    IFNULL(`sessions`.`date`,' ') as date,
....

There are also a few other ways to achieve this using just IF() or CASE .. but IFNULL is very straight forward.
BUT if you don't want to see any NULL and 0 values, change your LEFT JOIN to INNER JOIN and you're done.

A: From your description, it sounds like you want an inner join:
SELECT s.id, s.date, COUNT(*) as users
FROM sessions s JOIN
     sessions_users su
     ON su.id = su.sessions_id;


text:
Q: What regression analysis technique to use? I have an independent variable X and dependent variable Y so want too check the impact of X on Y both variables are quantitative ( impact of X quantity on Y quantity ). Also X can be splitted to multiple variable X1,X2,X3... ans i want to check also the impact of X1,X2,X3... on Y (more detailed analysis) so what do you think in both cases the best regression analysis techniques to use ? shoud I just use Simple Linear regression for the fisrt case qnd multiple linear regression for the second case or do you have any better suggestions ?

A: Those certainly seem like reasonable starting points. Of course, you have to check all the assumptions of the model.


text:
Q: Does HCE Service work when screen is locked? I am developing a mobile wallet application and I have a problem that I cannot make payments when screen is locked. The HostApduService not works although I put my mobile phone on the POS terminal. Do you know Google wallet make payments when the screen is locked with no password or password / pattern?

A: In your APDU configuration xml file that you reference in AndroidManifest.xml file, set the property "requireDeviceUnlock" to "false".  See it in this example: https://github.com/handstandsam/HandstandPay/blob/master/app/src/main/res/xml/apdu_config.xml
Example project: https://github.com/handstandsam/HandstandPay


text:
Q: How to get a textbox with its value on page in angularjs? I have an object and that is pushed into a scope variable... but while displaying I need to get a text box with its Name...
The code is,
HTML
<li ng-repeat="textbox in textboxes track by $index">
    Label For Inputfield:
    <input type="text" id="in_{{$index}}" ng-model="$parent.textboxes[$index].Name"/>
   <button class="btn btn-sm btn-default" ng-click="deletetxtbox($index)">-</button>
</li>

JS
var values=[];

angular.forEach($scope.form.fields,function(f){
    if(f.type=="textbox"){
        values.push(f);
    }
});

angular.forEach(values,function(v){
    $scope.textboxes.push(v);
});

What I want to do is, I have an object
$scope.form={
    Name:"sdfsdf",
    fields:{
        Name:"dfsd",
        type:"textbox",
        order:"1"
    }
};

Now the value of the text box i.e., Name must be displayed inside the text box which I have given in the HTML page code.

A: Icycool has right. If you want to have several fields, you should use an array containing your field objects and iterate on it through your ng-repeat.
By the way, if you want to have the Name field displayed inside a text input, use
the value or the placeholder attributes, depending on how you want to display your Name field, like <input value="{{ textbox.Name }}" /> or <input placeholder="{{ textbox.Name }}" />.


text:
Q: Parent module not loaded for Cython library I'm trying out Cython, and I wrote a small module to compile. However, when I compile it, the library is written to a subdirectory. Copying that library out of the subdirectory breaks the importing with this message:
Traceback (most recent call last):
  File "driver.py", line 1, in <module>
    from sum_func import sum_func
  File "sum_func.pyx", line 1, in init cython_fail.sum_func
    from itertools import count
SystemError: Parent module 'sum_func' not loaded, cannot perform relative import

Why is the import broken, or why is the library being written to a subdirectory in the first place?
I posted the whole project to GitHub, but the module is pretty simple:
# sum_func.pyx
from itertools import count

def sum_func(x):
    n = 0
    for i in count():
        n += i
        if n >= x:
            return -i

The setup file is a straight copy from the tutorial:
from distutils.core import setup
from Cython.Build import cythonize

setup(ext_modules=cythonize("sum_func.pyx"))

The driver just calls the library module.
from sum_func import sum_func

print(sum_func(10))
print(sum_func(100))
print(sum_func(1000))

And the __init__.py file is empty.

A: In the process of trimming out all the unrelated code to post this question, I found the problem: the __init__.py file. As mentioned in this question and this one, an __init__.py file will make Cython compile the library into a subfolder. I didn't find those questions at first, because I was looking for my import error message, not the fact that the library was written to a subfolder.
That's fine, because I didn't really need the __init__.py file. I think it was left over from an old version of the project. Deleting it solved the problem.


text:
Q: Get child nodes from an object I have an object with some dynamic keys. I'm able to read the key name, but not the value:
var response = {
    "keyOne": {
        "keyChanged": {
            "keyTwo": {
                "keyINeed": "myData"
            }
        }
    }
}

var myKey = Object.keys(response.keyOne)[0];
var myValue = response.keyOne."something".keyTwo.keyINeed

How can I do it?

A: To achieve this you need to use bracket notation, as you're providing the key of the object in a variable. Try this:

var response = {
  "keyOne": {
    "keyChanged": {
      "keyTwo": {
        "keyINeed": "myData"
      }
    }
  }
}

var myKey = Object.keys(response.keyOne)[0];
var myValue = response.keyOne[myKey].keyTwo.keyINeed; // note the [] here

console.log(myKey)
console.log(myValue);


text:
Q: Typecheck generated code that access dynamically loaded code in Haskell I need a fast way (1000's of typechecks per second) to typecheck generated Haskell source code.
We tried hint which was fast enough except it cannot access dynamically loaded code unless the source code is available which we would not have in some cases. Maybe there is some way to register dynamically loaded code as a package or something since hint can access registered packages it seems?
We tried using the ghc api, but it appears to require the files be on disk and all the file IO required makes it too slow.
We can use haskell-src-exts to generate the code, but we need to typecheck it.

A: Thousands of type checks per second doesn't seem feasible sequentially -- you're doing these concurrently, with some hope for parallelism I hope?
And I assume you are supporting the full GHC type system? So a stripped down type checker (e.g. THIH won't suffice).

*

*Use ghc-api, with bytecode and no optimizations

*Cache everything in memory

*Submit modifications to GHC to ensure it can take FDs from memory buffers, if necessary


text:
Q: Galaxy tab 2 7" does not fit sw600dp? Everywhere in Android documentation I can ready that I have to use sw600dp for 7 inch tablets, but this does not seem to be true, because Galaxy Tab 2 7" has 546dp for its smallest width.
http://www.gsmarena.com/samsung_galaxy_tab_2_7_0_p3100-4543.php
dp = 600 / (170 / 160) = 546
Should I use sw500dp in my layouts instead?

A: Android device pixel densities are classified in buckets:

While the Galaxy Tab 2 screen may actually be 170 dpi, that falls within the range of mdpi which translates to 160 dpi being used in practice for dp calculations. The device should still have a 600dp width.


text:
Q: jQuery events not bind to page items after $.load() I have a base index page and a large repository page which I load needed elements from it with jquery.load() function for the sake of cleaner code and less size. After I load some parts in the base page for example some buttons, all the event handlers which I added to new loaded page items in a js file wont work.
Here is my sample code from js file:
$(document.body).on('click', '.btn', function(){
    var tData = $(this).text();
    console.log(tData)
})

Can anybody help?
Maybe I am wrong in placing all my html code in one place except creating them on the fly,
or I should add a script tag after each part of my html?

A: You wrap your code in the ready method once the jquery js file has loaded.
$(document).ready(function() {
    $(document.body).on('click', '.btn', function(){
       var tData = $(this).text();
       console.log(tData)
    }
});


text:
Q: Rubymine does not detect folder directories in Rails Application This happened right after i did a restart; Ruby mine detects files at root directory but does not detect folders.

What caused this? What should I do to fix it?

A: Not sure what's causing this, but you can close RubyMine, delete .idea folder of your project and reopen it.


text:
Q: SQL Left Join Foreign Key Both Tables I have a query in which I am joining a table of answers to their questions.  Both tables have a foreign key that links back to a user table to determine who asked and who answered the question.
My question is, how can I modify the following query to make product_question.userID AND product_answer.userID show the name of the user from the User table instead of just the ID?
                    SELECT `project_question`.`id` AS question_id, `project_question`.`question`, `project_question`.`userID` AS askedBy,
                           `project_question`.`created` AS question_created, `project_answer`.`id` AS answer_id,
                           `project_answer`.`answer`, `project_answer`.`userID` AS answeredBy,
                           `project_answer`.`accepted`, `project_answer`.`created` AS answer_created
                      FROM `project_question`
                 LEFT JOIN `project_answer`
                        ON `project_question`.`id` = `project_answer`.`questionID`
                     WHERE `project_question`.`projectID` = $args[0]
                       AND `project_question`.`projectPhase` = 2

A: You can use two joins to the same table and aliases to distinguish them:
      SELECT `project_question`.`id` AS question_id,
             `project_question`.`question`,
             q_user.`userName` AS askedBy,
             `project_question`.`created` AS question_created,
             `project_answer`.`id` AS answer_id,
             `project_answer`.`answer`,
             a_user.`userName` AS answeredBy,
             `project_answer`.`accepted`,
             `project_answer`.`created` AS answer_created
        FROM `project_question`
   LEFT JOIN `project_answer`
          ON `project_question`.`id` = `project_answer`.`questionID`
  INNER JOIN `User` AS q_user
          ON `project_question`.`userID` = q_user.`userID`
  INNER JOIN `User` AS a_user
          ON `project_answer`.`userID` = a_user.`userID`
       WHERE `project_question`.`projectID` = $args[0]
         AND `project_question`.`projectPhase` = 2


text:
Q: Interface Misunderstanding I'm trying to increase my productivity and extensibility with Interfaces.  They are quite powerful, but I've hit a snag in either my understanding or implementation.
Hypothetically, if I have a User Interface that I have no control over; but I'm writing a Class Library that will perform a series of logic.  My original thought was something like this:
public interface ISiteForm
{
     public string FirstName { get; set; }
     public string LastName { get; set; }

     // Also any other User Interface Form Fields.
}

Which would be laid out like this, so it could be implemented and referenced by the User Interface.
public class SiteForm : ISiteForm
{
    public SiteForm()
    {
        FormPass();
    }

    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }

    public string LastName
    {
         get { return lastName; }
         set { lastName = value; }
    }

    private string lastName,
    private string firstName,

    public void FormPass(string _lastName, string _firstName)
    {
        // Implementation to assign a value from User Interface into the interface.

        lastName = _lastName;
        firstName = _firstName;
    }
}

My thought was when the Class Library was referenced, they would pass those parameters to the method when it was called.  Then by nature when the class was created; it would assign those variables to the interface.
So then if I had any other portion of the project that required those same variables; I could simply call the interface and adjust the setter value.
My concerns are:

*

*Interfaces by nature don't expect logic

*They are usually Polymorphic, which would lose that specific implementation.

Is that the wrong approach for passing parameters through an interface so those same variables can be used elsewhere?

A: You don't assign anything to the interface, it's an implementation contract. The implementing class contains all the logic.
If you wanted to use the same interface and variables you might want to look at something like Dependency Injection and Inversion of Control.

A: Interfaces aren't for anything but polymorphism.  You should not put any logic in them at all.

A:
Is that the wrong approach for passing parameters through an interface
  so those same variables can be used elsewhere?

Be careful not to confuse object instances with type declarations.  A local variable of type ISiteForm is accessible in the block which it is declared.  For example,
public void M()
{
    ISiteForm s = new SiteForm();
}

If I declared s as a SiteForm the change does not make the object instance s any more accessible to other parts of the program.
An interface does allow us to treat an object uniformly regardless of the underlying type of the object.
E.G.
public void M(ISiteForm s)
{
    var propertyName = s.FirstName;
}

Here, I don't know or care if s is a type of SiteForm or some other type that happens to implement ISiteForm.  The behavior is polymorphic.

Which would be laid out like this, so it could be implemented and referenced by the User
  Interface.

To that point, Interfaces can be used to decouple layers in an n-tier architecture.  For example, you may create an Interfaces.dll.  This DLL can house ISiteForm.  The User interface and Business Logic can  both reference this shared DLL. This design allows loose coupling by allowing otherwise unrelated objects to be passed between layers and helps to avoid circular references.

A: Based on the suggestions, I revisited the solution.  This is how I ended up handling it, I used Dependency Injection: Interface Injection approach.  This methodology provided the decoupled approach I required; while still maintaining the goal of functionality.
I created the following:
public interface ISiteForm
{
     string GetSiteValues(string FirstName, string LastName);
}

This particular interface will act as our Dependency or IDependency.  Then I created the following Class.
public class SiteForm : ISiteForm
{
    // Leave for now.
}

So now at this point we've preconfigured our Interface and Class.  This will act as a our Dependency.
Now to setup our injector.
public interface ISiteFormInjector
{
    void InjectSiteForm(ISiteForm siteDetails);
}

Our injector will be our Dependent or in our case IDependent.  Now we need to update our code so the data injection is physically implemented.
public class SiteContent : ISiteFormInjector
{
    // Call our Dependency.
    ISiteForm _siteDetails;

    public void InjectSiteForm(ISiteForm siteDetails)
    {
         _siteDetails = siteDetails;
    }

    // Properties to Associate our Value.
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string GetSiteValues()
    {
        return _siteDetails.GetSiteValues(FirstName, LastName);
    }
}

And now the values can be injected; obviously with some refactoring it will be able to have the value injected then will pass those variables to other aspects of the application. It follows this form of layout:


text:
Q: Configure WebLogic MDB to listen to Foreign AMQ Server I'm trying to create an MDB(EJB 3.0) on WebLogic 10.3.5. to listen to a Queue on an external AMQ server. After much work and combination of tutorials i get the following error when deploying on webLogic.

[EJB:015027]The Message-Driven EJB is transactional but JMS connection factory referenced by the JNDI name: ActiveMQXAConnectionFactory is not a JMS XA connection factory.

Here is a brief of the work i have done:
I have added the corresponding libraries to my WLS classpath (following this tuturial http://amadei.com.br/blog/index.php/connecting-weblogic-and-activemq) and I have created the corresponding JMS Modules as indicated in the tutorial. I have used ActiveMQConnectionFactory initially and ActiveMQXAConnectionFactory later, I also ignore the jms. notation an just put plain names as testQueue.
Then create a simple MDB with the following structure.
I explicitly defined "connectionFactoryJndiName" property because otherwise it assumes a WebLogic connection factory which is not found, and then raises an error.
@MessageDriven(
        activationConfig = {
                @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
                @ActivationConfigProperty(propertyName = "destination", propertyValue = "testQueue"),
                @ActivationConfigProperty(propertyName = "connectionFactoryJndiName", propertyValue = "ActiveMQXAConnectionFactory")
        },
        mappedName = "testQueue")
public class ROMELReceiver implements MessageListener {

    /**
     * Default constructor.
     */
    public ROMELReceiver() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see MessageListener#onMessage(Message)
     */
    public void onMessage(Message message) {
        System.out.println("Message received");
    }

}

At this point I'm stuck with the error mentioned above. Even though I use ActiveMQXAConnectionFactory instead of simply ActiveMQConnectionFactory, JNDI resources tree in web logic server shows org.apache.activemq.ActiveMQConnectionFactory as class for my configured connection factory.
am i missing something? or is this just a completely wrong way to connect WebLogic whith AMQ?
Thanks in advance.

A: I know its late but i recently i had to do the same thing and encoutered the same error.
This post helped me:
https://community.oracle.com/thread/3903705
Basically it says to add a new parameter in the jndi properties on the foreign server option on the module in weblogic.
xa=true.
Because activemq is not using Xa connections by default.


text:
Q: Unable to run Wildfly 8.1.0 as Service on Windows Server 2012 - Extended Attributes are Inconsistent? I'm attempting to get Wildfly 8.1.0.Final to run as a service on Windows Server 2012. I cd'd into %Wildfly_Home%\bin\service and ran service install in cmd.
It output this:
Using the X86-64bit version of prunsrv
Success

A service named Wildfly was added to my Windows Services. But when I attempt to start it, it tells me this:

Windows could not start the Wildfly on Local Computer. For more information, review the System Event Log. If this is a non-Microsoft service, contact the service vendor, and refer to service-specific error code 255.

In the Windows Event Viewer, it says this:

The Wildfly service terminated with the following service-specific error:
The extended attributes are inconsistent.

What is this talking about? I'm guessing I might need to do something in the system registry since Google turned up a few results of people saying my registry was corrupted. I don't want to just run some automated tool though - that risks just messing up my registry in other ways. I want someone to actually tell me what's wrong so I can actually fix it. I looked over the Wildfly registry entries and it all looked fine to my relatively inexperienced eyes.

A: Copy C:\Windows\system32\findstr.exe to Java\jdk\bin OR Java\jre\bin as applicable.
This resolved my problem.

A: I had the same problem and tried a lot of suggestions, such as:
- moving the Wildfly files to a location which path didn't contain whitespaces
- removing the quotemarks in the Display name field of service.bat (but apparently using the new version of service.bat cited above is equivalent)
- moving findstre.exe to Java\jdk\bin as said above
And the last change I performed before it finally worked was to add to the PATH environment variable the ..\Java\jdk directory as JAVA_HOME, NOT the ..\Java\jdk**\bin** directory as I read somewhere.
Uninstall and reinstalled service between each modification.


text:
Q: Removing else-if-elseif.. in postgresql function I would like to know if and there is some way to get rid code like this:
CREATE FUNCTION parent_function (json json, OUT response_status integer, OUT response json) RETURNS record
    LANGUAGE plpgsql
AS $$

DECLARE
BEGIN
    if <condition> then
      <function_call1(json,response_status,response)>;
      return;
    elsif <condition> then
       <function_call2(json,response_status,response)>;
      return;
    elsif <condition> then
      <function_call3(json,response_status,response)>;
      return;
    end if;
END;
$$

I would like to move these conditions into separate functions where I would like based on what the function returns(there are some output parameters I need) terminate parent function without throwing exceptions and catch them in parent function?
What I would like to achive code like this:
CREATE FUNCTION parent_function (json json, OUT response_status integer, OUT response json) RETURNS record
    LANGUAGE plpgsql
AS $$

DECLARE
BEGIN
    <check_function1(json,response_status,response)>;
    <check_function2(json,response_status,response)>;
    <check_function3(json,response_status,response)>;
END;
$$

After calling message and output parameters set from function terminate further processing. Is it somehow posible?
Thanks,
Lukas

A: you want something like this example?
CREATE OR REPLACE FUNCTION aa_test_check1(  IN test_value integer)
  RETURNS TABLE( problem boolean , problemmessage text ) AS
$BODY$
begin
problem := false;
if $1 <10 then
problem := true;
problemmessage := 'integer is smaller than 10';
end if;
return next;
end;
$BODY$ LANGUAGE plpgsql IMMUTABLE;

CREATE OR REPLACE FUNCTION aa_test_check2(  IN test_value integer)
  RETURNS TABLE( problem boolean , problemmessage text ) AS
$BODY$
begin
problem := false;
if $1 >20 then
problem := true;
problemmessage := 'integer is greater than 20';
end if;
return next;
end;
$BODY$ LANGUAGE plpgsql IMMUTABLE;

CREATE OR REPLACE FUNCTION aa_test_check3(  IN test_value integer)
  RETURNS TABLE( problem boolean , problemmessage text ) AS
$BODY$
begin

problem := false;
if $1 =10 then
problem := true;
problemmessage := 'something is wrong, it cant be 10';
end if;
return next;
end;
$BODY$ LANGUAGE plpgsql IMMUTABLE;

CREATE OR REPLACE FUNCTION aa_test_main(  IN test_value integer)
  RETURNS TABLE( status_id integer , problemmessage text ) AS
$BODY$
declare
 temp_problem boolean;
 temp_problemmessage text;
begin

status_id :=  0;
problemmessage := 'no problem, none at all';

select * from  aa_test_check1($1)
into temp_problem, temp_problemmessage;

if temp_problem then
   status_id :=  1;
   problemmessage := temp_problemmessage;
   return next;
   return;
end if;

select * from  aa_test_check2($1)
into temp_problem, temp_problemmessage;

if temp_problem then
   status_id :=  2;
   problemmessage := temp_problemmessage;
   return next;
   return;
end if;

select * from  aa_test_check3($1)
into temp_problem, temp_problemmessage;

if temp_problem then
   status_id := 3;
   problemmessage := temp_problemmessage;
   return next;
   return;
end if;

return next;

end;
$BODY$
  LANGUAGE plpgsql IMMUTABLE
  COST 100
  ROWS 100;
  select * from aa_test_main(10)


text:
Q: C programming minor issue with interactive menu when input a floating value My program works well with invalid inputs such as char, number out of range, but a problem happens when a floating point value such as 1.2 is entered. The program prints menu again, and asks user for input before printing error message. What I try to fix is don't print menu again, but still struggle. For example,
Make your selection: 1.1
[Here is menu content]
Make your selection: That selection isn't valid. Please try again.
#include <stdio.h>

#define QUIT 0

int menu();

int main(void)
{
    int choice;
    char c;
    choice = menu();
    while(choice != QUIT)   //execute so long as choice is not equal to QUIT
    {
        choice = menu();
    }
}

int menu(void)
{
    int option;

    printf("Text Encoder Service\n\n");
    printf("1.\tEnter name of input file (currently 'Secret.txt')\n");
    printf("2.\tEnter name of output file (currently not set)\n");
    printf("3.\tEnter number of characters data should be shifted (currently +7)\n");
    printf("4.\tEncode the text\n\n");
    printf("0.\tQuit\n\n");
    printf("Make your selection: ");

    while( (scanf(" %d", &option) != 1) /* non-numeric input */
        || (option < 0)               /* number too small */
        || (option > 4))              /* number too large */
    {
        fflush(stdin);                    /* clear bad data from buffer */
        printf("That selection isn't valid. Please try again.\n\n");
        printf("Your choice? ");
    }
    return option;
}

A: An input of 1.1 leads to the following:

*

*The string is read into an internal buffer.

*It is then matched against the given format string.

*On the first non-match, the scanf() call is stopped and it returns the number of successfully scanned values.

Let's test it:
#include <stdio.h>
int main(int argc, char ** argv)
{
    while (1) {
        int option;
        int n = scanf(" %d", &option);
        printf("%d %d\n", n, option);
        if (n <= 0) break;
    }
}

This program reads one line.
Suppose I enter 123 132.
Then the following happens:
* As the format string starts with a space, all leading whitespace is consumed. In this case, there is none.
* Then the 123 is consumed and put into option.
* As the format string is over now, parsing is stopped, n=1 and option=123.
* In the next loop run, the same happens, giving n=1 and option=123.
But: Suppose I enter 123.321 or 123#321.
Then the following happens:
* As the format string starts with a space, all leading whitespace is consumed. In this case, there is none.
* Then the 123 is consumed and put into option.
* As the format string is over now, parsing is stopped, n=1 and option=123.
* In the next loop run, there is no whitespace to skip. .321 resp. #321 is tried to be matched to %d, but these are no valid ints. Thus, we get n=0 and option keeps its old value.
* As no characters are consumed from the input stream (the one used is put back again), the same happens over and over again - that's why I put if (n <= 0) break;.
So you see that the behaviour has nothing to do with floating point, as it doesn't matter if we use . or # to "disturb".
We change our program to
#include <stdio.h>
int main(int argc, char ** argv)
{
    while (1) {
        int option; char c;
        int n = scanf("%d%c", &option, &c);
        printf("%d %d %d %c\n", n, option, c, c);
        if (n <= 0) break;
    }
}

and run it, inputting 4.235#6x7.
Then we get
* n=2, option=4 and c='.' at the first run
* n=2, option=235 and c='#' at the 2nd run
* n=2, option=6 and c='x' at the 3rd run
* n=2, option=7 and c='\n' (newline) at the 3rd run
and are prompted for further input.
This makes you open to the option
(parsed_inputs = scanf("%d%c", &option, &overcount_char)) < 1

and then check what overcount_char contains, whenever parsed_inputs is > 1.

A: I finally could validate floating input. Thanks your advices so much! This is my new code. What else do you think an invalid input?
int menu(void)
{
    int option, parsed_inputs;
    char overcount_char;
    parsed_inputs = 1;

    printf("Text Encoder Service\n\n");
    printf("1.\tEnter name of input file (currently 'Secret.txt')\n");
    printf("2.\tEnter name of output file (currently not set)\n");
    printf("3.\tEnter number of characters data should be shifted (currently +7)\n");
    printf("4.\tEncode the text\n\n");
    printf("0.\tQuit\n\n");
    printf("Make your selection: ");

    parsed_inputs = scanf_s("%d%c", &option, &overcount_char);
    while( parsed_inputs > 1 )              /* number too large */
    {
        if((overcount_char != '\n') || (option < 0) || (option > 4))
        {
            fflush(stdin);                    /* clear bad data from buffer */
            printf("That selection isn't valid. Please try again.\n\n");
            printf("Your choice? ");
            scanf_s("%d%c", &option, &overcount_char);
        }
        else
            break;
    }
    return option;
}

A: I think you should put scanf() before the while loop and explicitly check "option" variable in the while loop.
What happening is that, here scanf() will always return the value 1, because scanf() returns no. of arguments read successfully. Hence this while loop will run forever. For further information check this link->http://www.cplusplus.com/reference/cstdio/scanf/
Hope this helps!


text:
Q: Curl $_GET in function I do have a script:
<?php

    $ch = curl_init($theUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $dirname . $cookie_txt);
    $result = curl_exec($ch);
    parse_str(implode('&', array_slice($argv, 1)), $_GET);

This one is working pretty good. If I now do this:
<?php
function startCurl() {
     $ch = curl_init($theUrl);
     ....
      parse_str(implode('&', array_slice($argv, 1)), $_GET);
 }

 startCurl();

Now the variable $_GET is false. Why? How can I change it. I think $_GET is global.
Thanks for an answer.

A: you can declare a new global variable
$argv is a global variable, but it's not suggest use in here ,you need pass the value for this function


text:
Q: Duplicate key in Hibernate JPA OneTOMany save operation This is my Item class
@Entity
@Table(name = "item", schema = "demo_transaction")
@Transactional
public class Item {
    @Id
    Integer item_id;
    String itemName;
    Integer price;

    @OneToMany(cascade = CascadeType.ALL,fetch= FetchType.EAGER)
    List<Event> events;

Event class:
@Entity
@Table(name = "event", schema = "demo_transaction")
@Transactional
public class Event {
    @Id
    Integer event_id;
String eventName;

As shown  Item can have multiple Events. In typical SQL an FK table would be like this:
item_id event_id
1       10
1       20
2       10
2       20

But when I am trying to save these I am getting constrain violation.
    Event e1=new Event(10,"FirstEvent");
    Event e2=new Event(20,"SecondEvent");
List<Event> lse1=new ArrayList<>();
        lse1.add(e1);
        lse1.add(e2);
        Item item1 = new Item(1,"FirstItem",600,lse1);
List<Event> lse2=new ArrayList<>();
        lse1.add(e1);
        lse1.add(e2);
        Item item2 = new Item(2,"SecondItem",200,lse2);
repo.save(item1);repo.save(item2);

I understand that since eventId is the primary key and I am trying to save
twice that's where the constraint getting violated but how would I
achieve that FK table? Please help

A: What you are trying is not possible with a OneToMany configuration. An item can have many events, but an event can only have one item. You are trying to add the same event to multiple items.
postgres=# \d item_events;
                 Table "public.item_events"
     Column      |  Type   | Collation | Nullable | Default
-----------------+---------+-----------+----------+---------
 item_item_id    | integer |           | not null |
 events_event_id | integer |           | not null |
Indexes:
    "uk_nvp3wmby13pbecx8ikeoae9ep" UNIQUE CONSTRAINT, btree (events_event_id)
Foreign-key constraints:
    "fk98kk1sdgqem8j50mo5avvvmg5" FOREIGN KEY (events_event_id) REFERENCES event(event_id)
    "fkovh11t671qjb2w11sxos7ktvo" FOREIGN KEY (item_item_id) REFERENCES item(item_id)

As you can see the unidirectional OneToMany creates a join table, item_events, and the event_id column has a unique constraint on it to ensure an event can only belong to one item. Without this the relationship becomes a ManyToMany. If you want to add the same event to multiple items you will have to configure the ManyToMany relationship in your entities.

A: @GeneratedValue(strategy = GenerationType.IDENTITY
Add above annotaion to the event_id and item_id. Then it wiil generate unique ids for you.
Then add @JoinColumn(name = "item_id") to event_id field and mappedBy = "item" to inside of OneToMany of the item_id field .Also have to add @ManyToOne for event_id field.
You can do bidirectional OneToMany mapping as follows.
  //for Item change as folllows

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Integer item_id;

    @OneToMany(cascade = CascadeType.ALL,fetch= FetchType.EAGER
     ,mappedBy = "item")
    List<Event> events;

        // for Event change as follows

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Integer event_id;

    @ManyToOne
    @JoinColumn(name = "item_id")
    Item item;


text:
Q: numpy create array of all coordinates I want to create a list of all possible (x,y) values.
For example - for input (x=2,y=3) the output should be:
np.array([
[0,0],
[0,1],
[0,2],
[1,0],
[1,1],
[1,2]])

The order doesn't really matter

A: Quick and dirty:
>>> np.argwhere(np.ones((2, 3)))
array([[0, 0],
       [0, 1],
       [0, 2],
       [1, 0],
       [1, 1],
       [1, 2]])

A: Inspired by Divakar's indices_merged_arr, this should be fast.
def indices_for(m, n):
    i, j = np.ogrid[:m, :n]
    v = np.empty((m, n, 2), dtype=np.uint32)
    v[..., 0] = i
    v[..., 1] = j
    v.shape = (-1, 2)

    return v

>>> indices_for(3, 2)
array([[0, 0],
       [0, 1],
       [0, 2],
       [1, 0],
       [1, 1],
       [1, 2]])

m, n = 10000, 10000
%timeit indices_for(m, n)
607 ms ± 9.12 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit np.argwhere(np.ones((m, n)))
4.69 s ± 225 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


text:
Q: VB NET check SQL server image data type for null or empty I need to check for null value of SQL server image data type ,
here is my code :
    Dim cmd As New SqlCommand("select id_image1 from work_tbl where
    work_id =  12345 ", conn)
    Dim stream As New MemoryStream()
    conn.Open()
    Dim image As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
    stream.Write(image, 0, image.Length)
    conn.Close()
    Dim bitmap As New Bitmap(stream)
    picturebox1.Image = bitmap

I need to stop the procedure with msgbox if my image column is empty .

A: Dim cmd As New SqlCommand("select id_image1 from work_tbl where
work_id =  12345 ", conn)
Dim stream As New MemoryStream()
conn.Open()

if DBNull(cmd.ExecuteScalar())=false
Dim image As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
stream.Write(image, 0, image.Length)
Dim bitmap As New Bitmap(stream)
picturebox1.Image = bitmap

end if
conn.Close()


text: Q: atom unindents tab after self-closing html tag Okay so the Atom text editor is the best thing that ever happened to me but there's something really annoying that keeps happening. Whenever I make a self-closing HTML tag like<br/>, atom auto-un-indents the next line, as if I had just closed an open tag and the code needed to be unindented (which it would be correct in this sense). How can I disable this?


text:
Q: Optimal strategy for selling turnips You have a pile of $N$ turnips that you need to get rid of in $n$ days. The turnip price every day is independently and uniformly distributed in $[0, 1]$. You can sell any amount of turnips every day, but you must sell everything by the last day. What strategy should you employ to maximize your profits?
(Context. This is related to the "stalk market" in Animal Crossing: New Horizons; see edit history.)

A: Following Rob's suggestion to use dynamic programming, I was able to work out the answer for prices following an arbitrary distribution. Here are the details.
The states are $(n, N, x)$ where

*

*$n$ is the number of days remaining,

*$N$ is the number of turnips you've got, and

*$x$ is the current day's price.

Let $V(n, N, x)$ be the maximum profit over all possible strategies starting from the state $(n, N, x)$. The expected maximum profit with $n$ days and $N$ turnips is equal to
$$W(n, N) = \int_{\mathbb{R}} V(n, N, x) \, \mathrm{d}\mu(x) \tag{1}$$
where $\mu(x)$ is the price distribution.
Now, here's the key idea. Regardless of what strategy you're following, at the end of the day you're going to sell some number $M$ of your turnips at the day's price $x$, for a profit of $Mx$, and then have $N\!-\!M$ turnips left over to sell within the next $n\!-\!1$ days, for an expected profit of at most $W(n\!-\!1, N\!-\!M)$. Therefore, the maximum profit satisfies the recurrence relation
$$V(n, N, x) = \max_{0 \leqslant M \leqslant N} \Big\{ Mx + W(n\!-\!1, N\!-\!M) \Big\}. \tag{2}$$
Although the relation (2) seems complicated, it's simplified—and, in fact, solved—by the observation that $V$ is homogeneous in $N$.
Proof. It's clear that $V(0, N, x) = 0$, since there are no days left to sell anything. Note that the zero function is homogeneous. So suppose by induction that for some $n$, the function $V(n, N, x)$ is homogeneous in $N$, i.e., we have $V(n, N, x) = NV(n, 1, x)$ for all $N$ and $x$. Then the function $W(n, N)$ is also homogeneous in $N$, by (1). Now, by the recurrence relation (2) and the homogeneity just established, we have
$$V(n+1, N, x) = \max_M \big\{ Mx + (N - M)W(n, 1)\big\}, $$
which is the maximum of a linear function in $M$ with slope $x - W(n,1)$. If the slope is positive, the function is maximized at the right endpoint $M = N$ with maximum $Nx$; if negative, it's maximized at the left endpoint $M = 0$ with maximum $NW(n,1)$. These two cases can be combined into one expression, yielding
$$V(n+1, N, x) = N \max\{x, W(n,1)\}. \tag{3}$$
Not only does (3) show that $V(n+1, N, x)$ is homogeneous in $N$ (thus completing the proof), it also encodes the optimal strategy: with $n+1$ days left, sell if $x > W(n, 1)$, otherwise hold.
The sequence of cutoffs $\lambda_n := W(n, 1)$ is highly dependent on the particular price distribution $\mu$. Combining (1) and (3) yields the recurrence relation
$$\lambda_{n+1} = \int_{\mathbb{R}} \max\{x, \lambda_n\} \, \mathrm{d}\mu(x) \tag{4}$$
where, of course, $\lambda_0 = 0$. Specializing to the case $\mu \sim U(0, 1)$ from the OP we get $\mathrm{d}\mu(x) = 1_{[0,1]}(x) \mathrm{d}x$, so that
$$\lambda_{n+1} = \int_0^1 \max\{x, \lambda_n\} \, \mathrm{d}x = \frac{\lambda_n^2 + 1}{2}.$$
The first few values are approximately
\begin{array}{c|ccccccc}
n & 0 & 1 & 2 & 3 & 4 & 5 & 6 \\
\hline
\lambda_n & 0 & 0.5 & 0.625 & 0.695 & 0.742 & 0.775 & 0.800
\end{array}
For completeness' sake, I'll also address my original intended application: the Fluctuating pattern in the AC:NH stalk market. There, $\mu \sim U(0.9, 1.4)$ and you have $n = 7$ chances to sell. The cutoffs are
\begin{array}{c|ccccccc}
n & 0 & 1 & 2 & 3 & 4 & 5 & 6 \\
\hline
\lambda_n & 0 & 1.15 & 1.213 & 1.248 & 1.271 & 1.288 & 1.300
\end{array}
and, following the optimal strategy, your expected profit is $W(7, N) \approx 1.31015 N$, just over a 31% return!


text:
Q: trying to use selenium for firefox and running into errors I get the following error:
File "C:\Users\ryanv\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\selenium\webdriver\firefox\service.py", line 44, in __init__
    log_file = open(log_path, "a+") if log_path is not None and log_path != "" else None
PermissionError: [Errno 13] Permission denied: 'geckodriver.log'

when I'm trying to run
browser = webdriver.Firefox()

Could this be because firefox is in the pythonfoundation folder and I have another folder where python is?
I have tried adding geckodriver to path as well as downloading it and putting it into my other python folder however nothing works.

A: in your cmd line type: where python
and put the gecko file in that folder where python is located


text:
Q: When loading, the page goes on the bottom of it I have an issue with my website. My page loads normally in Firefox, but when I use either Chrome or Safari, it goes to the bottom of the page and I don't understand why. I tried putting the following snippet at the beginning of the page, but no luck.
<script>

$(document).ready(function() {
    $(document).scrollTop(0);
});

</script>

Why does the page go to the bottom on loading?

A: When going to your site, I get redirected to http://www.ondinevermenot.fr/#start. That means the page will try to jump to the start element.
However, the start element is absolutely positioned. Therefore, when the page tries to jump down, the start element moves down with it. Therefore the page tries to jump down again. Then the start element moves down more. They keep going down until the bottom of the page, when there is no more room.
To fix it, don't redirect to #start when your page loads.
Because of the strangeness of jumping to something that's absolutely positioned, it's probably handled differently in different browsers.

A: Try to have your image and other contents put inside div and set the box attribute of the div to margin:auto. works well with HTML5.

A: i have an alturnative work around for you and incase you ever need to get to the top of the page - you can use this javascript as an alturnative:
((IJavaScriptExecutor)webapplication).ExecuteScript("window.scrollTo(0, document.body.scrollHeight 0)");

however the other option would be to set a start up property: for example document.start("body.height = 0") something along those lines may work.
preferably id use option one as a code to start the broswer at a set height may not work so well for every browser. hope this helps.

A: I had 2 links to my home page in my footer. When I removed the links from my footer the problem went away.


text:
Q: Unable to execute assembly code located in the program's data segment in WSL This program overrides the return address of the main function to point to a character array of encoded x86-64 assembly instructions. The instructions simply encode a NOP followed by the syscall exit(1).
char shellcode[] = "\x90\x48\x31\xc0\x48\x89\xc7\x48\xff\xc7\x04\x3c\x0f\x05";
void main() {
      long int *ret;
      ret = (long int *)&ret + 2;
      (*ret) = (long int)shellcode;
}

It is compiled with
gcc program.c -o program.exe -fno-stack-protector -z execstack

on a WSL. (The Ubuntu app from the Microsoft Store)
The -z execstack flag should cause the stack, as well as all other writable portions of the program, to be executable.
Since the global character array resides in the .data of the assembly code it should be executable. This is true when running the program on a Linux VM, but apparently not on the WSL?  On WSL, control is still properly redirected to the NOP, but it segfaults if you try to execute that instruction (presumably on code-fetch from a non-executable page). Running gdb shows this after returning from main:
=> 0x8004010 <shellcode>:        nop
   0x8004011 <shellcode+1>:      xor    %rax,%rax
(gdb) si
Program received signal SIGSEGV, Segmentation fault.

What could be causing this inconsistency between WSL and real Linux?  Does WSL enforce strict W^X, overriding even -z execstack?
Are other Windows security features at play? I do not know if it is a WSL 1 or 2, but the uname -a output is:
Linux LAPTOP-M91FQN9V 4.4.0-18362-Microsoft #836-Microsoft Mon May 05 16:04:00 PST 2020 x86_64 x86_64 x86_64 GNU/Linux

What could be preventing the instructions from running, when the same does not occur on a Linux VM?


text:
Q: How to delete/remove/undo DrawString in C# WinForm My form has a background image.  I have some pictureBoxes i am using as buttons. I am attempting to have a MouseEnter/MouseLeave event to display label or pictureBox.
I have been trying various approaches.  I am getting similar results-  The label or picturebox appears fine, but on MouseLeave, label1.Visible = false; causes a very temporary blank box over the background image of the form.  While it is fully functional, it just seems like a very slight lag, but makes the program look bad.
I experimented with the DrawString method.  This seems like it could be a good option, but i cannot figure out how to remove the object on a MouseLeave event.
Is this possible?  If not, is there a better option to accomplish what i am trying to accomplish?
Here is how I am drawing my string (in buttonClick event for testing):
Graphics g = this.CreateGraphics();
string letter = "Yo Dawg!";
g.DrawString(letter, new Font(FontFamily.GenericSansSerif, 20, FontStyle.Regular),
new SolidBrush(Color.Black), 100, 100);

A: You would draw in the paint event, in MouseLeave set a flag, cause a paint with Invalidate() then within paint if the flag is not set don't draw anything.
public partial class TheForm : Form
{
    private Font _font = new Font(FontFamily.GenericSansSerif, 20, FontStyle.Regular);
    private bool _hovering = false;

    public TheForm() {
        InitializeComponent();

        picBox.Paint += new PaintEventHandler(picBox_Paint);
        picBox.MouseEnter += (sender, e) => UpdateText(true);
        picBox.MouseLeave += (sender, e) => UpdateText(false);
    }

    private void picBox_Paint(object sender, PaintEventArgs e) {
        if (_hovering)
            e.Graphics.DrawString("Yo Dawg!", _font, Brushes.Black, 100, 100);
    }

    private void UpdateText(bool show) {
        _hovering = show;
        picBox.Invalidate();
    }
}


text:
Q: Making a file executable on a by the work place locked Mac I have a Macbook pro that I have received from work. I want to run my webscraper with selenium. However the moment I call the webscraper from my Python code I get the following errors:

*

*In a window: "chromedriver" cannot be opened because the developer cannot be verified.
macOS cannot verify that this app is free from malware.
Chrome downloaded this file today at 09:24 from chromedriver.storage.googleapis.com

*In the terminal: selenium.common.exceptions.WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: -9

I have already:

*

*Moved the file (chromedriver executable) to different directories (username/bin, usr/bin, usr/local/bin) that are in my PATH env.

*Tried to unlock execution via mac interface via the instructions in this link: https://support.apple.com/en-us/HT202491

*Changed the file characteristics with "sudo chmod 777 chromedriver"

*Contacted my work ICT department. They don't want to remove the lock.

Is there a way to work around this lock? Help is very much appreciated.

A: Maybe you can find a vulnerability in mac or the softwares that are already installed in your mac. check cvedetails.com, any other website like that is fine, they synchronize their database.
But before doing so, you should know that this is policy is forced with your network admin. It means there is an agent already installed on your mac that is reporting the current status of mac to admin. If you break it then it will report it. You might loose your job.


text:
Q: How do I get the lookup objects field history tracking to show up in the related list of the child object? I can see in my org that someone has a lookup to opportunity and can get the history tracking of opportunity in the related list of the custom object.
I tried to do it for another custom object and it didn't work.
To replicate this in a scratch org I created two custom objects custom object 1 and custom object 2.
Custom object 2 has a lookup to custom object 1 and I made a field "status" on 1 and turned on the field history tracking on it. While creating the objects object 1 didn't have field history tracking turned on and I turned it on but in the real org its turned on from what I can see.
Here is what I can see. As I have field history tracking turned on for both 1 and 2 I can see history object for both in their respective page layouts under the related tabs.
What I want to see is Custom object 1 's history on custom object 2 under the related list but I can't get it to show up. I can see that people have been successful in my org in doing so.


text:
Q: I want to force users to enter a contact role prior to saving new opportunities. Can this be done? I have a basic opportunity object and would like to require sales teams to enter at least one Contact Role in order to save the Opportunity.

A: You could do that if you build a custom UI for entering Opportunity data, such as a Lightning component or Visualforce page, and completely replaced the out-of-the-box user interface. (This would be a pretty large project).
Because Opportunity Contact Role is a child of Opportunity, you cannot use Validation Rules or Apex triggers to require OCRs on the save of Opportunity, as they can't even be created until the Opportunity saves.


text:
Q: A debatable delegate-like event notification pattern I was left with continuing the code of a senior developer, where I came across a coding pattern that was not only bizarre, but got me curious about a lot of things. The pattern, however, that I spoke about had something like this:

*

*There is a UIViewController the view  of which has an instance of extended UIView attached to it as a subview.

*This custom UIView class has a reference of the above-stated UIViewController.

*There are a series of methods defined within the UIViewController that are responsible for handling events at the UIView.

*Since this UIViewController exists as a reference, our custom view calls those event-handling methods through this reference!

In such a system of code, what are the memory implications? How is this any different from the delegate pattern? Under what circumstances using this sort of coding okay?

A: While this pattern is a little curious, I would hesitate to condemn this without more information about what this child view is doing and what it needs to inform the view controller about. There is, admittedly, a faint code smell here, and if I were to hazard a guess, I'd bet that this view is likely doing stuff that one would now generally put in a view controller.
Often, when adding a subview that has any significant complexity (or is likely to be reused in different views), one would consider an iOS 5 feature, "view controller containment" (see the Creating Custom Container View Controllers section of the View Controller Programming Guide or WWDC 2011 video Implementing UIViewController Containment).
If using storyboards, you can achieve much of this using the special "Container View" control introduced with iOS 6, found in Interface Builder's "Object Library" (in the bottom of the right panel in the standard Xcode layout). If doing this programmatically, just make sure to call the appropriate methods listed in the "Managing Child View Controllers in a Custom Container" section of the UIViewController Class Reference.
When using view controller containment, you have a parent view controller (the main view controller) and the child view controller (the view controller that is managing the subview). And in this scenario, it's very common to design a custom protocol by which a child view controller notifies its parent view controller of particular events. But rather than adding your own custom delegate property, you can use the built-in parentViewController property which is automatically populated when you adopt the above "view controller containment" pattern.
Having said all of this, I might let practical concerns drive whether the existing code base needs to be refactored or not. Perhaps the code predates iOS 5, but is a solid implementation of what we might have done back in the day. Bottom line, if it works, is otherwise well written, and has the delineation of responsibilities clearly defined, you might decide to just leave well enough alone. And if it's a little ambiguous (as the absence of a discussion of a protocol might suggest), perhaps just start by introducing a formal protocol between the child view and the view controller to make the interface explicit. Whether a more radical refactoring of the code (to use something like view controller containment) is called for is hard for us to advise on the basis of the limited information provided thus far.


text:
Q: Error connection between Odoo and PHP Drupal I'm trying get data from Odoo 10 using ripcord. Here's my code:
function test_connect(){

    require_once('ripcord/ripcord.php');

    // Login information
    $url = 'http://localhost:30080';
    $url_auth = $url . '/xmlrp/common';
    $url_exec = $url . '/xmlrpc/object';

    $db = 'xxxx';
    $username = 'xxxx@gmail.com';
    $password = 'xxxx';

    // Login
    $common = ripcord::client("$url/xmlrpc/common");

    //$common = ripcord::client($url_auth);
    $uid = $common->authenticate($db, $username, $password, array());

    $models = ripcord::client($url_exec);

    include "config.php";
    $sql = "SELECT so.id as id,
                   so.cust_id,
                   so.numb,
                   p.ktr,
                   p.store_id,
                   so.write_date,
                   p.store_name,
                   p.sales_id
            FROM sales_order so
            INNER JOIN store p on p.store_id = so.store_id
           ";

    $exec = pg_query($sql);

    while ($row = pg_fetch_array($exec)){

        $query = pg_query(
            "SELECT sod.product_id, sod.qty_sales, p.name
                           FROM sales_order_line sod
                           INNER JOIN product p on p.id = sod.product_id
                           WHERE sales_order_id = ".$row['id']
        );

        while ($data = pg_fetch_array($query)) {

            $id = $models->execute_kw($db, $uid, $password,
                'sale.order', 'create',
                array(array(
                    'partner_id' => $row['store_id'],
                    'sales_id' => $row['sales_id'],
                    'order_line' => [array(
                        0, false, array(
                            'product_id' => $data['product_id'],
                            'name' => $data['name'],
                            'qty' => $data['quantity'])
                    )]
                )));

            var_dump($id);

        }
    }
}

Here's my config.php code:
$config = pg_connect("host= 'http://localhost:8010' port='5432' dbname= 'xxxxxx' user='xxxxxx@gmail.com' password='xxxxx' ") or die('Failed');

And I  get errors like this:

Error messageRipcord_ConfigurationException: PHP XMLRPC library is not installed in Ripcord_Client->__construct() (line 132 of D:\usbwebserverlayerfarm\root\sites\all\modules\addon\feed_sync\ripcord\ripcord_client.php).
  The website encountered an unexpected error. Please try again later.

How I can fix it?

A: I had the same problem,
You ned to install XMLRPC library in debian linux
apt-get install php7.0-xmlrpc

If you are using a shared server yo might not be able to install it
I Hope this helps


text:
Q: error CS0117 in Unity I am working in Unity 5.1 as a beginner,
Now i got an error and i've no idea how to solve this:
Assets/SampleAssets/Cameras/Scripts/FreeLookCam.cs(39,32): error CS0117: `UnityEngine.Screen' does not contain a definition for `Cursor'

my script is:
   private void OnDisable()
    {
        Screen.Cursor.lockState = Cursor.visible;
    }

A: Just remove Screen. so the code becomes:
private void OnDisable(){
  Curser.lockState = CursorLockMode.Locked;
}

however, if you want to hide/display the cursor use this:
Cursor.visible = true;
Cursor.visible = false;

A: Cursor class resides in UnityEngine instead of Screen class. So it is unable to find Cursor.lockState. Have a look at this example of doc on how it should be use.


text:
Q: drop down menu will not display outside containing div in IE7 I am tearing my hair out over this, I have a dropdown menu using CSS and jQuery (thanks to Soh Tanaka) and it works perfectly in Firefox, Safari, Google chrome and I.E. 8, but in IE 7 it will not drop down outside the 'Banner div'. It drops below the nav div however. I have moved the nav div higher in the banner the result is the same, menu drops until it reaches the border of the banner div and then vanishes....
Below is the css. This is my first website and I have some limited understanding of what I am doing. The drop down menu includes transparent png's as links (I know, I know...but it's what the Boss wants...) please could someone take a quick scan at the below CSS and let me know what is wroong? Is this some form of the IE z-index bug? i have tried all different combinations of z-index and still I can't get a different result. . The html is below as well.
I set all the z-indexes to 0 out of sheer frustration, I know it won't work as is.
Thankyou in advance
#banner {
    position: relative;
    width: 62.5em;
    height: 12em;
        background-color: #46280A;
         background-image: url('images/includes/banner2.jpg');
    background-repeat: no-repeat;
    background-position: center;
    -moz-box-shadow: -4px 6px 8px #000;
    -webkit-box-shadow: -4px 6px 8px #000;
    box-shadow: -4px 6px 8px #000;
    /* For IE 8 */
    -ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=8,         Direction=225, Color='#000000')";
    /* For IE 5.5 - 7 */
    filter: progid:DXImageTransform.Microsoft.Shadow(Strength=8, Direction=225,     Color='#000000');
        z-index: 1;
}
/*------------------------------------SCROLLER---------------------------------------------*/

#headlines{
    position: absolute;
    top: 1.3em;
    right: 2.75em;
    overflow: hidden;
    height: 2.5em;
    width: 24em;
    background-color: #000000;
    display: block;
    z-index: 3;
}

#news{
    position: relative;
    height: 3.1em;
    line-height: 2.5em;
         font-size: 0.8em
    color: #FFFF99;
    white-space: nowrap;
    overflow: hidden;
    font-family: Georgia,Arial;

}

#scrollerglass{
    position: absolute;
    top: 0.95em;
    right: 2em;
    height: 52px;
    width: 410px;
    border: none;
         padding: 0.2em 0em 0em 0em;
         line-height: 0.7em;
         text-align: center;
    background-image: url('images/includes/scrollerglass.png');
    background-color: transparent;
    background-repeat: no-repeat;
    background-position: center;
    opacity: 20;
    z-index: 10;
 }

#scrollerglass a i {
     visibility: hiddn ;
 }

/-------------------------------------NAVIGATION-----------------------------------------/
#nav   {
    position: absolute;
    top: 5.8em;
    left: 0.2em;
    font-family: trebuchet, sans-serif;
    font-size: 1em;
    line-height: 3.75em;
    text-align: center;
    color: #FFFF00;
    z-index: 3;

}

ul.navlist {
    list-style: none;
    padding: 0em;
    margin: 1em;
    float: left;
    width: 62.5em;
    background: transparent;
    font-size: 1em;
}

ul.navlist li {
    position: relative;                 /*--Declare X and Y axis base for sub navigation--*/
    float: left;
    margin: 0em 1.4em;
    padding: 0em 0.7em 0em 0em;
    z-index: 1;
}

ul.navlist li a{
    display: block;
    text-decoration: none;
    float: left;
         border: 0px solid;
}

ul.navlist li img{
        border: 0px solid;
}

ul.navlist li span {                        trigger styles--*/
    width: 1.2em;
    height: 5.25em;
    float: left;
    background: url(images/links/downlogo.png) no-repeat center top;
}

ul.navlist li span.subhover {                           background-position: center bottom;
    cursor: pointer;
}

ul.navlist li ul.navdrop {
    list-style: none;
    position: absolute;
    float: left;
         top: 5.3em;
    left: -2.4em;
    height: 15.0em;
    width: 11.25em;
    margin: 0;
    padding: 0.5em 0em 0em 0em;
    display: none;                              background-position: center;
    background-image: url('images/includes/slider.jpg');
    background-color: transparent;
    background-repeat: no-repeat;
    -moz-box-shadow: -4px 6px 8px #000;
    -webkit-box-shadow: -4px 6px 8px #000;
    box-shadow: -4px 6px 8px #000;
    /* For IE 8 */
    -ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=8, Direction=225, Color='#000000')";
     /* For IE 5.5 - 7 */
     filter: progid:DXImageTransform.Microsoft.Shadow(Strength=8, Direction=225, Color='#000000');
    z-index:1;
 }

ul.navlist li ul.navdrop li{
    margin: 0em 2.3em 0em 0em;
    padding: 1em 0em 0em 0em;
    width: 8em;
    clear: both;
}

html ul.navlist li ul.navdrop li a {
    border: 0px solid;
         width: 11.25em;
}

 html ul.navlist li ul.navdrop li a:hover {                      background: transparent;

 }

   Whatever we want to promote

                     ------s-c-r-o-l-l-e-r - - - -l-i-n-k-s--------

------s-c-r-o-l-l-e-r - - - -l-i-n-k-s------

A: OK, I've fixed it. The answer is that the drop-down will not display over the 'filter' effect in IE. 7 and below.
Apologies to all you IE 7 users, but it's just not gonna look so pretty for you.

A: Another solution which I found for my dropdown menu is to add to the content Div z-index:-1;

A: I can't tell exactly whats going on just by your css, but I have had a similar problem and it woldn't let me hover unless the drop down section had a background color on it otherwise it would 'see through' it and lose the hover state. You could try that.

A: Please also view your HTML.
However, let's say this is your structure (simplified):

         ...

You have to verify, that #nav's z-index is bigger than that of #content. So:
#nav {
    position:relative;
    z-index:2;
}
#content {
    position:relative;
    z-index:1;
}

Don't forget, that z-index works only on the elements that have position other than static (default);
The idea is that parent of the element that is not shown (parent of the drop-down element), has to have z-index bigger, than the element that "overlaps" the drop-down.
You can read an excellent article on the subject here: http://aplus.rs/lab/z-pos/


text:
Q: Probability of obtaining each number on a dice roll I was just thinking if it really is true that the probability of obtaining each number on a 6-faced fair dice always 1/6? If the die was previously rolled to a 3 for example, would the next die roll not be affected by the fact that it was in that particular orientation when we picked it up for this subsequent die roll?
Does such a bias really exist and can we eliminate it?

A: We assume the act of throwing the die sufficiently randomizes the position so that the previous roll does not matter.  One can conceive of cases where this is not true.  Imagine a die with a reservoir of a viscous liquid inside.  If it sits with $3$ up for a long time, it will be heavy on the $4$ side and more likely to come up $3$.  It is also possible some people are skilled enough to make a die come up preferentially the way they want.   A mathematical die definitely has $\frac 16$ chance of coming up each number.  Whether a particular physical die is perfect in this regard is an experimental question.  You could roll the die a lot and see if numbers repeat more often than chance.


text:
Q: PHP $_POST empty during AJAX post request Goal: Serialize data, send them in HTTP POST request using AJAX, proceed data in PHP (and answer)
Problem: PHP $_POST variable seems to be empty
JS/AJAX
var postData = [cmd, data];
alert(postData = JSON.stringify(postData));

$.ajax({
   url: "./backendTag.php",
   type: "post",
   data: postData,
   dataType: 'json',
   success: function (response) {
      alert(response); // Empty
      //logToServerConsole(JSON.parse(response));
   },
   error: function(jqXHR, textStatus, errorThrown) {
      logToServerConsole("E3"); // Communication Error
      console.log(textStatus, errorThrown);
   }
});

PHP
<?php echo json_encode($_POST);

A: The reason for the same is probably because you are not posting properly in javascript. Before i add the codes, let me add a couple of tips on how to debug in these situations.
First is, you check if the request is properly formed. Inspect the network in browser dev tools.
Second method could be to use var_dump on $_POST to list out all the post parameters and check if they have been recieved in PHP
Now as far as the code goes
here is the javascript
$.ajax({
  method: "POST",
  url: "url.php",
  data: { name: "John Doe", age: "19" }
}).done(function( msg ) {
  alert(msg);
});

and in php you can simply check using
<?php
print $_POST["name"];
?>

which would work perfectly. Notice how the data in javascript is a list, while from what you wrote seems to be json string

A: Apparently we can't pass an array directly after serializing him. The following code resolved the problem. (Split array)
data = JSON.stringify(data);
var JSONdata = {"cmd" : cmd, "data" : data};

$.ajax({
   url: "./backendTag.php",
   type: "post",
   data: JSONata,
   dataType: 'json',

   /* Handlers hidden*/
});

A: JSON content won't be parsed to the $_POST globals. If you want to reach them, try to get from php://input with:
file_get_contents('php://input')

And I suggest giving the content-type during the ajax request:
contentType: 'application/json',

If it's not working, try to set the data as a string, with JSON.Stringify, like the following:
data: JSON.stringify(postData)


text:
Q: change to polar coordinates in a ordinary differential equation I don't know what to do.

write the following system into polar coordinates
$$x'=-ay$$
$$y'=ax$$
with $a\in \mathbb R$

any idea?

A: $\newcommand{\cost}{\cos\theta} \newcommand{\sint}{\sin\theta}$
Let $(x,y) = (r\cos\theta, r\sin\theta)$. Then,
$$
\begin{align}
x' &= r'\cost - r\theta'\sint = -ar\sint\\
x' &= r'\sint + r\theta'\cos = ar\cost
\end{align}
$$
In a matrix form,
$$
\begin{bmatrix}
\cost & -r\sint\\
\sint & r\cost
\end{bmatrix}
\begin{bmatrix}
r'\\ \theta'
\end{bmatrix}
=
ar
\begin{bmatrix}
-\sint\\
\cost
\end{bmatrix}
$$
I think you know what to do after this.
You will get finally, $r' = 0$ and $\theta' = a$, which means that the solution of the ODE draws a circle of radius $r(0)$ with the angular velocity $a$.


text:
Q: MySQL said: Documentation #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version I'm trying to import a SQL file into the database but facing this error. Please help if anyone can solve this error.
SQL query:
CREATE TABLE IF NOT EXISTS `products` (
  `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `details` json NOT NULL,
  `expiration_date` date ,
  `barcode` varchar(125) COLLATE utf8mb4_unicode_ci,
  `name` varchar(125) COLLATE utf8mb4_unicode_ci NOT NULL,
  `bundle_id` bigint(20) UNSIGNED NOT NULL,
  `shelf_id` bigint(20) UNSIGNED DEFAULT NULL,
  `delivery_request_id` bigint(20) UNSIGNED DEFAULT NULL,
  `status` int(11) NOT NULL DEFAULT '0',
  `quantity` int(11) NOT NULL DEFAULT '1',
  `weight` int(10) UNSIGNED NOT NULL,
  PRIMARY KEY (`id`),
  KEY `products_bundle_id_foreign` (`bundle_id`),
  KEY `products_shelf_id_foreign` (`shelf_id`),
  KEY `products_delivery_request_id_foreign` (`delivery_request_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'json NOT NULL,
  `expiration_date` date ,
  `barcode` varchar(125) COLLATE utf8m' at line 5


text:
Q: Sequelize querying both parent model and included model using [Op.or] I want to findAll Bookings where the booking has been paid.
A legacy booking has been paid if the paymentAuthorised: boolean attribute on the Booking table is true.
A new booking has been paid if the paymentAuthorised: boolean attribute on the Payment table is true and type: string attribute on the Payment table is 'booking'.
When I perform the following query it returns an error saying payments.paymentAuthorised not found.
const bookings = await db.Booking.findAll({
    include: [
      {
        model: db.Payment,
        as: "payments",
      },
    ],
    where: {
      [Op.or]: [
        {
          paymentAuthorised: { [Op.eq]: true },
        },
        {
          "$payments.paymentAuthorised$": { [Op.eq]: true },
          "$payments.type$": { [Op.eq]: "booking" },
        },
      ],
    },
    order: [["dateTime", "asc"]],
  });

A: I worked this issue out in the end by logging the generated SQL. You need to add the following parameter: subQuery: false. This is so it generates an SQL query which includes the joins before the where.
const bookings = await db.Booking.findAll({
    include: [
      {
        model: db.Payment,
        as: "payments",
      },
    ],
    where: {
      [Op.or]: [
        {
          paymentAuthorised: { [Op.eq]: true },
        },
        {
          "$payments.paymentAuthorised$": { [Op.eq]: true },
          "$payments.type$": { [Op.eq]: "booking" },
        },
      ],
    },
    subQuery: false,
    order: [["dateTime", "asc"]],
  });


text:
Q: Trying to install Ubuntu for the first time I need help with installing Ubuntu on a different partition on my hp Pavilion 15 Laptop. Installation is always stuck at the install updates page and loads for hours after I try to continue from that page.
Things to note:
I have a separate partition (100 GB) I intend to use for this installation.
I have flashed the ISO image unto a USB already.
I have disabled secure boot.
I intend to use both Windows and Ubuntu on the same PC but in different partitions (I mostly need explanation on how to go about this).
My PC was recently infected by malware and someone recommended Linux as a more secure OS.


text:
Q: Importing from main app in a flask blueprint I'm writing an application with one blueprint. My application uses Flask-SQLAlchemy, so my blueprint needs access to the main app's db object (created by Flask-SQLAlchemy) in order to create its own models.
However, when I try to get the db object with current_app.db, flask gives me the following error:
RuntimeError: working outside of application context

Here is my main __init__.py:
from flask import Flask

from app.uploader import uploader

app = Flask(__name__)

from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)

app.register_blueprint(uploader)

Here's the __init__.py from my uploader blueprint:
from flask import Blueprint

uploader = Blueprint('uploader', __name__,
    template_folder='templates')

from . import views
from .models import *

Here's views.py of the blueprint, where the exception takes place:
from flask import (redirect, render_template, request, send_from_directory,
    session, current_app)
from flask.views import View
from werkzeug import secure_filename

print current_app.db # Exception happens here

And here's the stacktrace:
Traceback (most recent call last):
  File "runtests.py", line 11, in <module>
    import tests
  File "/home/plasmasheep/project/tests.py", line 14, in <module>
    from app import app, db, user_datastore
  File "/home/plasmasheep/project/app/__init__.py", line 6, in <module>
    from app.uploader import uploader
  File "/home/plasmasheep/project/app/uploader/__init__.py", line 6, in <module>
    from . import views
  File "/home/plasmasheep/project/app/uploader/views.py", line 18, in <module>
    print current_app.db
  File "/home/plasmasheep/project/venv/lib/python2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/home/plasmasheep/project/venv/lib/python2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object
    return self.__local()
  File "/home/plasmasheep/project/venv/lib/python2.7/site-packages/flask/globals.py", line 34, in _find_app
    raise RuntimeError('working outside of application context')
RuntimeError: working outside of application context

Simply trying to use from .. import db does not work:
Traceback (most recent call last):
  File "runtests.py", line 11, in <module>
    import tests
  File "/home/plasmasheep/project/tests.py", line 14, in <module>
    from app import app, db, user_datastore
  File "/home/plasmasheep/project/app/__init__.py", line 7, in <module>
    from app.uploader import uploader
  File "/home/plasmasheep/project/app/uploader/__init__.py", line 6, in <module>
    from . import views
  File "/home/plasmasheep/project/app/uploader/views.py", line 17, in <module>
    from .. import db
ImportError: cannot import name db

Nor does from app import db:
Traceback (most recent call last):
  File "runtests.py", line 11, in <module>
    import tests
  File "/home/plasmasheep/project/tests.py", line 14, in <module>
    from app import app, db, user_datastore
  File "/home/plasmasheep/project/app/__init__.py", line 7, in <module>
    from app.uploader import uploader
  File "/home/plasmasheep/project/app/uploader/__init__.py", line 6, in <module>
    from . import views
  File "/home/plasmasheep/project/app/uploader/views.py", line 17, in <module>
    from app import db
ImportError: cannot import name db

A: current_app is only set during (essentially) a request/response cycle.  Normally, you use this only inside views, or stuff that is guaranteed to be called inside views.  You typically use current_app when you don't have access to the app directly, such as if you are using an application factory.  Since you're not using a factory, just import db directly and it should work in your case.
The import error is due to a circular import.  Move the line from app.uploader import uploader to after the definition of db.  See a couple paragraphs into this section of the docs, which mentions importing views after defining any of their dependencies.