text:
Q: Create a Multidimensional Array with Codeigniter and MySQL I'm developing internal mailing system using codeigniter, everything done perfetcly like gmail mailing system, except reply.
here i want to show replied message and current message both in single mail(if the mail is replied) like gmail.
Lets say i have threads table, that has a one to many relationship with table messages.
threads

thread_id | msg_id | sender_id | sender_role | receiver_id |
  receiver_role | status

messages

id | subject | body | cdate

Above tables working fine for showing inbox and sent mails.
But now i want to show replied message also along with original message.(like gmail).
for this i'm planning to change the structure of threads table(adding two more fields reply-0 or 1, reply_id)

SELECT  subject ,  body ,  cdate ,  sender_id ,  username AS
  email,  lbs_mails.id AS mail_id,  status ,  sender_role ,
  thread_id FROM (  lbs_mails ) JOIN  lbs_threads ON
  lbs_threads.msg_id =  lbs_mails.id  JOIN  lbs_auth ON
  lbs_auth.uid =  lbs_threads.sender_id  AND role =
  lbs_threads.sender_role WHERE  lbs_threads.receiver_role =  '3'
  AND  lbs_threads.receiver_id =  '1'

An efficient way to retrieve data would be to create a multidimensional array such as:
$inbox = array(
            [subject] => reply to Test Mail
            [body] => reply to Test Mail
            [cdate] => 2014-04-22 17:56:42
            [sender_id] => 2
            [email] => email@email.com
            [mail_id] => 7
            [status] => 1
            [sender_role] => 2
            [reply_id] => array(
                [subject] => reply to Test Mail
                [body] => reply to Test Mail
                [cdate] => 2014-04-22 17:56:42
            )
        )

How can i achieve this, can anyone help me out.
Thanks!

A: I think the easiest option would be for you to make one database call for the message and then a second database call to retrieve associated reply data. Then simply look over the data and combine it into an array.


text:
Q: How to run python script with Automator to see debug/error messages? Currently if I use Run shell script and start python script there:
/usr/bin/python /Users/myuser/script.py "$1"

In case script execution fails due to exception happened, Automator returns the error, which says nothing:
Run Shell Script failed - 1 error
Traceback (most recent call last):

Is there any way to run the shell script to see all debug message (or, to run Terminal and run python script there)?

A: I believe your best way forward is to use the Python debugger with:
import pdb

pdb.set_trace()

inside your py script.
More information here:
https://docs.python.org/2/library/pdb.html

A: When an error occurs, program execution stops and output is overwritten with an abbreviated version of the error (which provides no useful information).
For example, running the buggy code from here will only show you this:

You need to catch all errors to prevent that from happening.
Use try: ... except:
try:
    l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
    reduce(lambda x, y: x.extend(y), l)
except Exception as error:
    print(repr(error))

You will get this printed out:

AttributeError("'NoneType' object has no attribute 'extend'",)

If you want more information, you can just tweak the code:
from sys import exc_info
from traceback import extract_tb
try:
    l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
    reduce(lambda x, y: x.extend(y), l)
except Exception as error:
    print(repr(error))
    print("Line number: ", extract_tb(exc_info()[2])[0][1])

Prints:

AttributeError("'NoneType' object has no attribute 'extend'",)
  ('Line number: ', 5)

redpajama_set_name: RedPajamaStackExchange


text:
Q: jsp not found in SpringMVC and glassfish i am working on project. i did some simple changes and now i am getting following error.
SEVERE: PWC6117: File "D%3A%5CProjects%5CSampradan%5CGV+UI%5Cui%5CGVUI%5Cbuild%5Cweb%5Cjsp%5Cbarcode%5Csearch.jsp" not found

So. i removed all code from jsp and still i am getting error.
my jsp is resides in /jsp/module/search.jsp
my Controller
@RequestMapping(value = "/search", method = RequestMethod.GET)
    public ModelAndView searchBCGenRequest(HttpServletRequest hsr1, HttpServletResponse hsr2, HttpSession session) {

        ModelAndView mv = new ModelAndView();
        mv.setViewName("/module/search");
        System.out.println(mv.getViewName());
        return mv;
    }

it is printing /module/search but after it gives me following error.
SEVERE: PWC6117: File "D%3A%5CProjects%5CSampradan%5CGV+UI%5Cui%5CGVUI%5Cbuild%5Cweb%5Cjsp%5Cbarcode%5Csearch.jsp" not found


text:
Q: Cannot query an alias table I'm doing something like:
SELECT T1.NAME, T2.DATE
    FROM T1
INNER JOIN
(
    SELECT * FROM OTHERTABLE
) AS T2 ON T2.USERID = T1.USERID

Which works, but if I query the alias table, I get an error saying that T2 is an invalid object name.
Example:
SELECT
T1.NAME,
T2.DATE,
CASE
    WHEN EXISTS (SELECT TOP 1 1 FROM T2 WHERE T2.THISFIELD = T1.THISFIELD) THEN 'HELLO'
    ELSE 'BYE'
END AS COMMENT -- THIS ALSO FAILS
    FROM T1
INNER JOIN
(
    SELECT * FROM OTHERTABLE
) AS T2 ON T2.USERID = T1.USERID
WHERE (SELECT COUNT(*) FROM T2) > 0

I thought that's what I did, "create" T2. Is there any way I can use T2 like such ?
My goal is to scrape all the related data from OTHERTABLE once because I'll have many CASE in the SELECT clause depending whether data exists in T2 or not. I don't want to do EXISTS for every field since that'll launch a new query in a huge table everytime.

A: Your query using a sub-query of SELECT * FROM OTHERTABLE which doesn't make sense. You can modify it like;
SELECT
T1.NAME,
T2.DATE,
...

FROM T1
    JOIN OTHERTABLE T2 ON T2.USERID = T1.USERID
WHERE (SELECT COUNT(*) FROM OTHERTABLE ) > 0

You cannot use a sub-query multiple times in the same query. Instead use a Common Table Expression (CTE) for that purpose. T2 is a CTE in the following example.
;WITH T2 AS
(
   SELECT UserId, col1, col2, [Date]
   FROM OtherTable
)
SELECT T1.NAME, T2.DATE
FROM T1
    JOIN T2 ON T2.USERID = T1.USERID
WHERE (SELECT COUNT(*) FROM T2) > 0


text:
Q: RegEx issue - No delimiter I have the next log string :
E.....@..@:......F....2...148.277.90.903 - - [15/Nov/2015:16:10:00] "GET

How is it possible to separate the IP address (note that it is no have delimiter)
I tried unsuccessfully the next regex:
(\S+)(\d+\.\d+\.\d+\.\d+) - - \[(.*)] \(.*)

A: Use word boundary anchors and don't forget to escape the dots:
\b\d+\.\d+\.\d+\.\d+\b

Note that this doesn't do any error checking. It will simply look for four integers separated by dots.

A: I'd probably do this:
(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})

...that is, one to three digits separated by literal periods.  Or if you want to be minimalist and mysterious:
(\d{1,3}(?:\.\d{1,3}){3})

See https://regex101.com/r/dW3mT1/1 (which is an awesome tool that everyone should be using).


text: Q: Arrays and showing as undefined My project is to make a class report based on the amount of students and marks. In my project I need to show student names and marks, the average, and the lowest and highest grade in the class. In my code, when I get to the part where I post the class report, the last student's name and mark is read as undefined and undefined. It then affect my average which is read as NaN and lowest and highest mark. If anyone could fix my code that would be amazing! An explanation on what I did wrong is greatly appreciated as well.


text:
Q: JavaScript to clear SharePoint Text Filter box on focus I am using the following code to clear default value which is "Keyword ...." from a SharePoint text filter box. I put in an alert at line 10 but it doesn't pop-up. Do you any reason why it would not clear the Text Box when a user clicks inside the box to type something.
<script type="text/javascript">
    // Clears text box on click or focus
    var TextBoxID = document.getElementById("ctl00_m_g_22e9e7dd_3da6_4f0b_bc1c_0874742c6012_SPTextSlicerValueTextControl");
    TextBoxID.focus(function()
    {
        if(this.value == "Keyword ....")
        {
            alert('test line 10');
            $(this).val("");
        }
    });
</script>

A: It looks like you may have an error in your jQuery selector.
Should that have been $('#'+searchID).focus(...)?
If not, I was mislead by the reuse of "searchID" as a local variable and the name of a class on an element.

A: Try something like this?
HTML
Search Box: <input onclick="clearPlaceholder();" id="ctl00_m_g_22e9e7dd_3da6_4f0b_bc1c_0874742c6012_SPTextSlicerValueTextControl" type="text" name="fname" value="Keyword..."><br>

JS
function clearPlaceholder(){
    var TextBoxID = document.getElementById("ctl00_m_g_22e9e7dd_3da6_4f0b_bc1c_0874742c6012_SPTextSlicerValueTextControl");

    TextBoxID.value = "";
}

http://jsfiddle.net/z5h6H/2/

A: Here is the code that solved the issue. I needed to clear the value in the text field when user click inside the text box.
<script type="text/javascript">
// Clears text box on click or focus
var TextBoxID = document.getElementById('ctl00_m_g_22e9e7dd_3da6_4f0b_bc1c_0815182c6012_SPTextSlicerValueTextControl');
    TextBoxID.onfocus = function(){
        if(this.value == 'Keyword ....')
        {
            TextBoxID.value="";
        }
    };
</script>


text:
Q: Thyme leaf and Bootstrap changing button color I have a SpringBoot w/Thymeleaf & Bootstrap project.  I have a form that does some lengthy processing on the server.  As this is can be a long process, I would like to:
1) Change the button color/text as a visual indicator that something is happening
2) Disable the button so another file cannot be uploaded until the process completes.
Here is my code so far:
<form action="search" th:action="@{/search}" th:object="${search}"
                  method="post">
.....
<input type="submit" class="btn btn-success" value="Search"/>
 </form>

And my controller:
 @RequestMapping(value = "/search", method = RequestMethod.POST)
    public String search(@ModelAttribute Search search, Model model, Authentication authentication) {

   List<> found = sdnService.findMatches( search );
   model.addAttribute( "results", found );
   return "search";
}

I have seen some examples on changing the button color with javascript, but that only handles setting it the first time, now resetting it when the results come back.
Can anyone help me with this?


text:
Q: Matplotlib - plt.show() on chart object I've got a really simple example here. I'm making a plot from an ax object returned from a function:
import matplotlib.pyplot as plt

x = ['a', 'b', 'c']
y = [1, 2, 3]

def make_plot():

    fig, ax = plt.subplots()
    ax.set_title('test bar chart')

    return ax

chart = make_plot()
chart.bar(x, y)

plt.show()               #why does this show the chart?

My question is about plt.show() at the end. Obviously, this shows the output of the chart. But why?  To me it does not seem like plt.show() is tied to anything. I have my chart object, which contains my chart with all its parameters and whatnot. But how does plt.show() know to interact with this?  It would seem more intuitive to have something like chart.show(), as chart is the class instance.

A: Good question! chart is an Axes created when you call plt.subplots(). Pyplot is what's called a "stateful" API. When you make calls to plt.* functions, it changes the internal state of pyplot and that can affect future calls. When you call plt.subplots(), it knows that there is a newly created Figure with newly created subplot Axes inside it.
Similarly, if you call plt.plot(), it has a stored record of what the most recent axes are, and plots the data on that plot.
Take a look at the pyplot sourcecode and you can see how it has a global manager variable that it uses to store the current plot, and updates that manager when you create a plot.
Additionally, there is Figure.show(). If you want to work around pyplot, it looks something like this


text:
Q: Probability of at least one boolean random variable being true in a network of positively-correlated boolean variables My question
I have a set of $N$ random boolean variables $X_1, \ldots, X_N$ (each can be $1$ or $0$). For every $i \in [1, N]$, I know that
$$P(X_i = 1) = p^*$$
Now, I know that the variables are positively correlated, i.e., for every $i, j \in [1, N]$ I have:
$$P(X_i = 1 | X_j = 1) \geq p^*$$
$$P(X_i = 1 | X_j = 0) \leq p^*$$
(but I can't find an expression for those conditional probabilities)
Is the probability of at least one variable being $1$ larger or smaller than if they were independent?
The extreme case
Consider the case where all the variables are completely correlated, so that for every $i, j \in [1, N]$
$$P(X_i = 1 | X_j = 1) = 1$$
$$P(X_i = 1 | X_j = 0) = 0$$
Then the probability $p$ of at least one random variable being $1$ is $p = p^*$ (either all of them are $1$ or none is).
While in the case where they are completely independent, i.e.,
$$P(X_i = 1 | X_j = 1) = p^*$$
$$P(X_i = 1 | X_j = 0) = p^*$$
I have
$$p = 1 - (1 - p^*)^N$$
and since $(1 - p^*) < 1 \implies (1 - p^*)^N < (1 - p^*)$ I have
$$p > p^*$$
So in the limiting case I know that being positively correlated makes the probability of at least one variable being $1$ smaller. Is this true for any positive correlation?


text:
Q: Major Upgrade - .exe file not reinstalled I have a .msi file created by a program called MSICREATE and doctored using orca as follows...
InstallExecuteSequence Table
* added FindRelatedProducts with sequence 410
* added RemoveExistingProducts with sequence 1450

InstallUISequence Table
* added FindRelatedProducts with sequence 200

PropertyTable
* added RemovePreviousVersions TRUE
* added SECURECUSTOMPROPERTIES SOLARUPGRADE
* had a existing UpgradeCode with guid created by MSICREATE
* had a existing ProductVersion 12.2.12.0 created my MSICREATE

Added a Upgrade Table
* UpgradeCode same value as Upgrade in Property Table
* VersionMin null
* VersionMax 99.12.31
* Attributes 1
* ActionProperty SOLARUPGRADE (same value as SECURECUSTOMPROPERTIES in Property Table)

I also assigned a new PackageCode and a new ProductCode so the new msi had different values of PackageCode, ProductCode, and ProductVersion than the previously installed product.
When I run this msi with the product previously installed, the old product is deleted, a new program files directory created and all the files except the .exe reinstalled from the new .msi.  A repair will cause the .exe to be created.  If the new msi is installed AFTER removing the old product (using control panel add/remove programs), all files including the .exe are installed.
The msiexec log file is mywebspace.wisc.edu/mdorl/msilog/log3.log
The .msi is mywebspace.wisc.edu/mdorl/msilog/sbl_Major_Upgrade.msi
The only things that looks weird to me are the following lines from the log.  The first, second, and fourth are files that do get installed, the third is the .exe file that does not get installed. NOTE THE NULL ACTION ON THIS ENTRY.
Action start 8:04:41: InstallValidate.
MSI (s) (18:F4) [08:04:41:671]: Feature: _MainFeature; Installed: Absent;   Request: Local;   Action: Local
MSI (s) (18:F4) [08:04:41:671]: Component: _24A30964F6B6462282E161248AF15827; Installed: Absent;   Request: Local;   Action: Local
MSI (s) (18:F4) [08:04:41:671]: Component: _7B95B32E33EB4F699B44D53CA5BC22B5; Installed: Absent;   Request: Local;   Action: Local
MSI (s) (18:F4) [08:04:41:671]: Component: _2FBD153583AF40C09EB9920149F7C7B7; Installed: Absent;   Request: Local;   Action: Null
MSI (s) (18:F4) [08:04:41:671]: Component: _38A400D7DB76479CA0EC6D643D5793CD; Installed: Absent;   Request: Local;   Action: Local

A: If you look in the log at the line 603 you will find the following:
MSI (s) (18:10) [08:04:41:827]: Disallowing uninstallation of component: {ADC6C3E9-A0CF-4AFC-9998-7B9449C8EA10} since another client exists
MSI (s) (18:10) [08:04:41:827]: Disallowing uninstallation of component: {F74907E7-607E-49D1-B613-D63A36ADB020} since another client exists
MSI (s) (18:10) [08:04:41:827]: Disallowing uninstallation of component: {B1FE4023-E176-42BC-92C3-15B8E50CFBB0} since another client exists
MSI (s) (18:10) [08:04:41:827]: Disallowing uninstallation of component: {E6F5DF5D-3460-4B44-8743-48787E68A2C1} since another client exists
This can happen if the same components are shared between multiple packages installed on the same machine. Windows Installer keeps a refcount for the components and does allow removing them until all the applications that use them are removed.
If you encounter this on your test/development machine I recommend testing on a clean VM, to ensure no other previous tests affect this one.
Also, if you know you have used the same components in packages for other applications please edit them, making sure each component has an unique GUID for each package.

A: A keyfile is used by Windows Installer to detect the component, along with its GUID, here are more details:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa370561(v=vs.85).aspx
As you suspected, Windows Installer is also checking the file version, which I assumed you correctly incremented in the new version. Here are the rules followed by it:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa368599(v=vs.85).aspx
You need to have the version column from the File table for the EXE set to a higher value then of the one already existent on the machine, otherwise Windows Installer will decide its better to keep the old one, because it has a higher version.

A: For the sake of putting some closure to this item, here's what I've discovered and what I did to fix things.
1) I'm still fuzzy on the meaning of versioned/unversioned file.  I guess all .exe files ar versioned.  I suppose this means that such files need corresponding versions in the File table.
2) I now understand the file table version need have no connection to the ProductVersion.
3) I have been using illegal ProductVersion Eg. 2012.02.16.  I switched to using something like 12.2.16.
4) I set the .exe VS_VERSION_INFO FILEVERSION in Visual Studio and added the same value to File table Version field.
Now, all files are replaced when I do a major upgrade.

A:
The entries in the file table ALL have no version. Why are the non .exe files treated differently and reinstalled?

I suppose the other files have their version increased. Windows Installer should apply the versioning rules on all the files from the package.

So this means it's impossible for a user to install an older version of a product using a major upgrade msi?

I don't see a solution if you want to keep the version smaller in the new package. Except of course, custom actions.

And what constitutes a legal version? In one place I see 255.255.65535 and in another I see 65535.65535.65535.65535

Both of them are correct version numbers. The latter value is usually set to a file to make sure it replaces any other existing file from the machine, i.e. its the highest version number allowed by the OS.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa368596(v=vs.85).aspx


text:
Q: The given key was not present in the dictionary when using text inputs for ajax/json calls Hey guys I ran into an unfamiliar issue and am curious if anybody knows a solution for it.  I would like to start by saying thank you in advance for taking the time to read.  So my problem is that when I am making a ajax/json call to my web api it works fine if it is just clicking a button.  If the call is used in a form and gets values from input fields it fails and gives me the error "The given key was not present in the dictionary".
This works fine to get all users:
$(function () {
            var $users = $("#users");
            $("button[name='getAllUsers']").click(function () {
                $.ajax({
                    type: 'GET',
                    url: "/api/Users",
                    contentType: "json",
                    success: function (data) {
                        $users.html("");
                        $users.append("
First Name	Last Name	Email
");
                        $.each(data, function (index, item) {
                            $users.append("
" + item.FirstName + "	" +
                                                  "" + item.LastName + "	" +
                                                  "" + item.Email + "	");
                        });
                    }
                });
            });
        });

<button name="getAllUsers">Get Users</button>

And this does not work when I try to get a single user by id:
$(function () {
            var $users = $("#users");
            $("#getForm").submit(function (event) {
                var id = $('#getuserId').val();
                $.getJSON('/api/Users' + id)
               .done(function (data) {
                   $users.html("");
                   $users.append("
First Name	Last Name	Email
");
                   $.each(data, function (index, item) {
                       $users.append("
" + item.FirstName + "	" +
                                             "" + item.LastName + "	" +
                                             "" + item.Email + "	");
                   });
               });
               });
            });

<form action="/api/Users" id="getForm">
                <input type="text" name="getuserId" placeholder="User ID">
                <input type="submit" value="Get User">
            </form>

Any advice on how to fix this would be greatly appreciated!

A: You are missing a trailing slash in your URI:
$.getJSON('/api/Users' + id)

For the id 50 would make a GET request to: /api/Users50. It should be:
$.getJSON('/api/Users/' + id)

Which would result in api/Users/50.


text:
Q: Flip animation with text only works on Firefox, any way to make it cross browser? I'm trying to create a simple flip animation with an image and text, when hovered the image will flip and show the text, which was previously hidden.
What I have now works and it's what i want, problem is, it only works in Firefox for some reason.
The code is pure html + CSS, I provided a jsfiddle with the issue reproduced. Try it on Firefox and then Edge or chrome to see my problem.

    .Features-logo {
      height: 40vmin;
      pointer-events: none;
      -webkit-user-select: none;
      -khtml-user-select: none;
      -moz-user-select: none;
      -o-user-select: none;
      user-select: none;
    }

    .flip-card {
      width: 40vmin;
      height: 40vmin;
    }

    .flip-card-inner {
      position: relative;
      width: 100%;
      height: 100%;
      text-align: center;
      transition: transform 0.6s;

    }

    .flip-card:hover .flip-card-inner {
      transform: rotateY(180deg);
    }

    .flip-card-front,
    .flip-card-back {
      position: absolute;
      width: 100%;
      height: 100%;
    }

    .flip-card-front {
      background-color: white;
      color: black;
    }

    .flip-card-back {
      background-color: white;
      color: red;
      transform: rotateY(180deg);
      backface-visibility: hidden;
      top: 40%;
    }

BORK

Would like this animation to work in all modern browsers but I'm a bit lost!
Thank you in advance!

A: You need to consider transform-style: preserve-3d; on the parent element and also backface-visibility: hidden; on the front element (not only the back one). Also better use top:0 for the back element and consider something else to position the text inside. Doing so you will be sure the back element will fully cover the front one.
Not all the properties are needed in some browsers but this will make sure it will work the same in all the browsers

.Features-logo {
  height: 40vmin;
  pointer-events: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -o-user-select: none;
  user-select: none;
}

.flip-card {
  width: 40vmin;
  height: 40vmin;
}

.flip-card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.6s;
  transform-style:preserve-3d;
}

.flip-card:hover .flip-card-inner {
  transform: rotateY(180deg);
}

.flip-card-front,
.flip-card-back {
  position: absolute;
  top:0;
  width: 100%;
  height: 100%;
}

.flip-card-front {
  background-color: white;
  color: black;
  backface-visibility: hidden;
}

.flip-card-back {
  background-color: white;
  color: black;
  transform: rotateY(180deg);
  backface-visibility: hidden;
  display:flex;
  align-items:center;
  justify-content:center;
}

BORK

If you want to keep the image, remove backface-visibility from the image and the background from the text:

.Features-logo {
  height: 40vmin;
  pointer-events: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -o-user-select: none;
  user-select: none;
}

.flip-card {
  width: 40vmin;
  height: 40vmin;
}

.flip-card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.6s;
  transform-style:preserve-3d;
}

.flip-card:hover .flip-card-inner {
  transform: rotateY(180deg);
}

.flip-card-front,
.flip-card-back {
  position: absolute;
  top:0;
  width: 100%;
  height: 100%;
}

.flip-card-front {
  background-color: white;
  color: black;
}

.flip-card-back {
  color: black;
  transform: rotateY(180deg);
  backface-visibility: hidden;
  display:flex;
  align-items:center;
  justify-content:center;
}

BORK


text:
Q: Do microwaves (photons) lose energy as they heat? I understand that microwaves are able to heat water because their alternating electromagnetic fields flip water molecules (dipoles) up and down which increases the waters kinetic energy (thus increasing temperature).
Doesn't that mean the microwave photons are then losing energy due to law of the conservation of energy?
In other words, if I took a single microwave photon (~30 cm wavelength) and passed it through a cup of water, would it come out the other side with a larger wavelength (because it lost energy interacting with the H2O's)?

A: First, lets calculate the energy per photon for a 30 cm radiation:
$$E = \frac{hc}{\lambda} = \frac{(6.62\times10^{-34}\ {\rm Js})(3\times10^8\ {\rm m/s})}{30\times10^{-2}\ {\rm m}} = 6.62\times10^{-25}\ {\rm J}$$
That means that a 1000 W microwave oven is producing in the neighborhood of $1.5\times10^{27}$ photons per second (or $6.1\times10^{26}$ photons per second at the more typical microwave oven wavelength of 12 cm), and the energy associated with each individual photon is miniscule.
When the water absorbs energy from the electromagnetic wave, it absorbs whole photons rather than taking only part of the energy from a photon. The vast number of photons involved in the interaction means that the energy in the EM wave can essentially change continuously (the water can absorb 10% of the energy or 10.01% or 10.10203910% of the energy without having to only "partially absorb" a photon).

A: Typically, the microwave photon is absorbed by a water molecule, so any re-radiation you get out the other side wouldn't be the same photon anymore.

A: http://www.businessinsider.com/how-do-microwaves-work-2014-6
"The positively charged end of the water molecule tries to align itself with the microwave's electric field while the negatively charged end points the other way. But because the field reverses 2.5 billion times a second, Mickey's ears and face are being twisted back and forth rapidly."
(The molecule as illustrated in the referenced text resembles the rounded head and ears of Mickey Mouse)
What you get isn't so much a LONGER wavelength compared to the energy being absorbed, so much as a SHORTER wavelength (infrared) produced by the action described above (the dipoles of the water molecules twisting rapidly back and forth).  A microwave photon may do this many times, being reflected and re-entering the water or food being heated until it is heated to the desired temperature.  The interior of the microwave oven is a tuned cavity. Any foodstuffs heated in there detune the cavity, and if it is working properly and the rest of the interior of the microwave oven is relatively clean, it is quite efficient (60-70%).   Some energy loss is also dissipated in the magnetron in the form of heat, which is once again, a shorter wavelength than the microwaves that do the actual cooking..


text:
Q: How to distinguish these two ID requests when joining tables? SQL noob here. I have a database of soccer matches that I am trying to learn/practice SQL with.
In one table (called "Match") there is the match_api_id, date, home_team_api_id, away_team_api_id, home_team_goal, away_team_goal.
In another table (called "Team") there is the team_api_id, team_long_name.
Right now I am trying to do a query to show the ID of the match, the date, the home team's name, and the away team's name.
SELECT M.match_api_id, M.date, T.team_long_name, T.team_long_name
FROM Match M
JOIN Team T ON (M.home_team_api_id = T.team_api_id)
JOIN Team T ON (M.away_team_api_id = T.team_api_id)
LIMIT 10

This code worked when I only used one join (the first one) to show the home team's name. However, when I add the second join it gives me the ambiguous column name error. How do I alter this code so that I can also display the away team's name?

A: YOu need different table aliases.  Otherwise T is ambiguous:
SELECT M.match_api_id, M.date, TH.team_long_name, TA.team_long_name
FROM Match M JOIN
     Team TH
     ON M.home_team_api_id = TH.team_api_id JOIN
     Team TA
     ON M.away_team_api_id = TA.team_api_id;
LIMIT 10


text:
Q: Can GetFileAttributesExA return stale information on an SMB3 mount? I'm trying to figure the root cause of an issue in a single-threaded Python program that essentially goes like this (heavily simplified):
# Before running
os.remove(path)

# While running
if os.path.isfile(path):
    with open(path) as fd:
        ...

I'm essentially seeing erratic behavior where isfile (which uses stat, itself using GetFileAttributesExA under the hood in Python 2.7, see here) can return True when the file doesn't exist, failing the next open call.
path being on an SMB3 network share, I'm suspecting caching behavior of some kind. Is it possible that GetFileAttributesExA returns stale information?
Reducing SMB client caching from the default (10s) to 0s seems to make the issue disappear:
Set-SmbClientConfiguration -DirectoryCacheLifetime 0 -FileInfoCacheLifetime 0

(Note: The correct fix here is to try opening the file and catch the exception, of course, but I'm puzzled by the issue and would like to understand the root cause.)


text:
Q: Reading Json object with inside array This is my JSON result:
{
  "@odata.context": "http://wabi-west-europe-redirect.analysis.windows.net/v1.0/collections/washington/workspaces/37380bc1-dd47-4c95-8dbd-5efecafc8b26/$metadata#reports",
  "value": [
    {
      "id": "6ea77895-f92a-4ca6-90f7-cdade3683cd6",
      "modelId": 0,
      "name": "america",
      "webUrl": "https://app.powerbi.com/reports/6ea77895-f92a-4ca6-90f7-cdade3683cd6",
      "embedUrl": "https://embedded.powerbi.com/appTokenReportEmbed?reportId=6ea77895-f92a-4ca6-90f7-cdade3683cd6",
      "isOwnedByMe": true,
      "isOriginalPbixReport": false,
      "datasetId": "3f1f480c-4a8c-4756-87eb-fc29f5d76de3"
    },
    {
      "id": "ce558be6-aaf9-4bee-b344-6db7754e572b",
      "modelId": 0,
      "name": "dency",
      "webUrl": "https://app.powerbi.com/reports/ce558be6-aaf9-4bee-b344-6db7754e572b",
      "embedUrl": "https://embedded.powerbi.com/appTokenReportEmbed?reportId=ce558be6-aaf9-4bee-b344-6db7754e572b",
      "isOwnedByMe": true,
      "isOriginalPbixReport": false,
      "datasetId": "5264cf84-214a-4c33-8f8e-f421d8ce1846"
    }
  ]
}

In PHP im getting into
$response = json_decode($aboveresult);

But My problem is the value is in array.I want to get both the array value like id,modelId,Name,...
Please help me.
I tried $response['value'].But its showing error like Cannot use object of type stdClass as array

A: json_decode() accepts a second parameter, which is by default false. If you pass true, the function will return you an associative array instead of an instance of stdClass and you can work with it the way you tried before.

A: You have to change:
$response = json_decode($aboveresult,true);

When you mentioned the second parameter as true you will get the ASSOCIATIVE array

A: Try this
echo "
";
$json_data = json_decode($json);  //$json = your json string

print_r($json_data->value);

foreach($json_data->value as $value) {
    echo 'ID: '.$value->id .'
';
    echo 'modelId: '.$value->modelId .'
';
    echo 'name: '.$value->name .'
';
}


text:
Q: Как разбить проверить каждое число на четность цифр входящих в это число Есть коллекция чисел , и нужно удалить те числа в состав которых входят четные цифры .Например число 22 состоит из двух двоек и его надо удалить так как обе цифры четные, а вот число 23 состоит из 2 и 3 его не нужно удалять, я попробовал сделать цикл но ничего не получилось
import java.util.ArrayList;
import java.util.List;

public class numers {
    public static void main(String[] args) {
        List<Object> numbers = new ArrayList<>();
        numbers.add(13);
        numbers.add(24);
        numbers.add(68);
        numbers.add(22);
        numbers.add(28);
        numbers.add(10);

        for (int i = 0; i <= numbers.size() - 1; i++) {
            int a =(Integer) numbers.get(i);
            while (a > 0) {
                a = a % 10;
                if (a % 2 == 0) {
                    System.out.println(a);
                    numbers.remove(i);
                    i--;
                    break;

                }

            }

        }
    }
}

Получилось что то типо такого
 for (int i = 0; i <= numbers.size() - 1; i++) {
                        int a = (Integer) numbers.get(i);
                        String s = String.valueOf(Integer.valueOf(a));
                        if(!s.contains("1")&&!s.contains("3")&&!s.contains("5")&&!s.contains("7")&&!s.contains("9")){
                            numbers.remove(i);
                            i--;
                        }

A: Есть решение:
public static void main(String[] args) {
        // TODO Автоматически созданная заглушка метода
        List<Integer> numbers = new ArrayList<>();
        numbers.add(13);
        numbers.add(24);
        numbers.add(68);
        numbers.add(22);
        numbers.add(28);
        numbers.add(10);

        List<Integer> removeNum = new ArrayList<>();
        // Проверка:
        for (int i = 0; i < numbers.size(); i++) {
            int Num = 0;
            String[] testNum = numbers.get(i).toString().split("");
            for (int j = 0; j < testNum.length; j++) {
                if (Integer.parseInt(testNum[j]) % 2 == 0) {
                    Num += 1; // Num = Num + 1;
                }
            }
            if (Num == testNum.length) {
                removeNum.add(numbers.get(i));
            }
        }
        for (int i = 0; i < removeNum.size(); i++) {
            numbers.remove(removeNum.get(i));
        }

        // Вывод на экран:
        for (int i = 0; i < numbers.size(); i++) {
            System.out.println(numbers.get(i));
        }
    }

A: Упрощенный вариант с использованием List::removeIf, упоминавшимся в предыдущем ответе на сходную задачу:
List<Integer> mutableInts = new ArrayList<>(Arrays.asList(13, 24, 68, 22, 28, 10, 91));

// с регуляркой
mutableInts.removeIf(n -> String.valueOf(n).matches("[02468]+"));
// -> [13, 10, 91]

// с "просмотром" цифр из строки
mutableInts.removeIf(n -> String.valueOf(Math.abs(n))
    .chars() // символы строки
    .map(Character::getNumericValue) // преобразовать в цифровое значение
    .allMatch(d -> (d & 1) == 0)
);

Аналогичное решение, использующее разбиение числа на цифры:
mutableInts.removeIf(
    n -> IntStream.iterate(Math.abs(n), d -> d > 0, d -> d / 10)
        .map(d -> d % 10) // получить цифру
        .allMatch(d -> (d & 1) == 0) // проверить на четность
);

Или же определяется функция-предикат:
// class MyClass
public static boolean allEvens(int n) {
    int m = Math.abs(n);
    while (m > 0) {
        if ((m % 10 & 1) == 1) {
            return false;  // нашлась "нечётная" цифра
        }
        m /= 10;
    }
    return true;
}

которая и вызывается через ссылку: mutableInts.removeIf(MyClass::allEvens);


text:
Q: Diophantine equations whose coefficients are increasing sequences of integers I needed (for my research) to solve a Diophantine equation, in particular,
$$ 2 a + 3 b + 4 c + 5 d = 12 .$$
And I could easily solve it
(for example, on solution is $a=2, b=1, c=0, d=1$).
But this made me wonder if such equations, with their coefficients increasing sequences of
natural numbers, are a special case of Diophantine equations that are always explicitly solvable,
despite the negative solution to Hilbert's 10th problem.

A: Linear Diophantine equations are always solvable decidable (in linear time).  If the coefficients are $a_1, a_2, ... a_n$ then the numbers that can appear on the RHS are precisely the multiples of $\text{gcd}(a_1, ... a_n)$, and one can find solutions using the extended Euclidean algorithm.


text:
Q: rank of matrices 3 How can we prove the following:
If a matrix $A \in \mathbb{C}^{n\times n} $ is invertible, then
$\begin{bmatrix}
        A & I  \\
        I & X\\
        \end{bmatrix} \in  \mathbb{C}^{2n\times 2n}$ has the same rank as $A$ if and only if $X=A^{-1}.$
I would appreciate any hints or ideas to show this.

A: $\pmatrix{I & 0\cr -I & A\cr} $ is invertible, its inverse being $\pmatrix{I & 0\cr A^{-1} & A^{-1}\cr}$, so the rank of $\pmatrix{A & I\cr I & X}$ is the same as the rank of
$$ \pmatrix{I & 0\cr -I & A\cr} \pmatrix{A & I\cr I & X} =\pmatrix{A & I\cr 0 & AX-I}$$
But that would have greater rank than that of $A$ if some entry of $AX-I$ is nonzero.

A: If $A$ is invertible, then you can reduce $A$ to $I$ by elementary row operations: $EA=I$.
Performing the same operations on
$\begin{bmatrix} A & I \\ I & X\\ \end{bmatrix}$
gives
$\begin{bmatrix} I & E \\ I & X\\ \end{bmatrix}$
and then
$\begin{bmatrix} I & E \\ 0 & X-E\\ \end{bmatrix}$.
If any entry in $X-E$ is nonzero, then the last matrix has rank larger than $n$.
Therefore, $X-E=0$ and so $X=E=A^{-1}$.


text:
Q: Find combination of numbers such that their addition is closest to a number? I have a column named Orders. I want to cluster them into groups in such a way sum of orders in a cluster is close to 300. Below is the input.
**Orders**
100
198
50
40
215
296

The output should look like
Orders  Group
100     1
198     1
50      2
40      2
215     2
296     3

This is just a sample data. In Real the data is pretty huge. Can this be done using R.

A: Results
Below are functions that tackle the problem, firstly though here are the results
find_grouping(orders, 300L)
#      orders group
# [1,]    100     1
# [2,]    198     1
# [3,]     50     2
# [4,]     40     2
# [5,]    215     2
# [6,]    296     3

allocate_groups(orders, 300L, 3L)    # third argument <-> max. num. of groups
#      orders group
# [1,]    100     3
# [2,]    198     3
# [3,]     50     2
# [4,]     40     2
# [5,]    215     2
# [6,]    296     1

# bigger vector
set.seed(123)
orders <- sample(1:300, 15)
find_grouping(orders, 300L)
#       orders group
#  [1,]     87     2
#  [2,]    236     2
#  [3,]    122     3
#  [4,]    263     4
#  [5,]    279     5
#  [6,]     14     9
#  [7,]    156     6
#  [8,]    262     7
#  [9,]    162     8
# [10,]    133     8
# [11,]    278     9
# [12,]    132    10
# [13,]    196     1
# [14,]    165    10
# [15,]     30     7
allocate_groups(orders, 300L, 3L)
#       orders group
#  [1,]     87     1
#  [2,]    236     2
#  [3,]    122     3
#  [4,]    263     3
#  [5,]    279     1
#  [6,]     14     2
#  [7,]    156     3
#  [8,]    262     3
#  [9,]    162     2
# [10,]    133     1
# [11,]    278     2
# [12,]    132     2
# [13,]    196     1
# [14,]    165     1
# [15,]     30     3

with the data orders = c(100L, 198L, 50L, 40L, 215L, 296L).

Edit: New Function
Considering the added constraint of wanting to specify the number of groups, here comes a new function
create_groups <- function (orders, num, group_num) {
  orders
  groups <- rep(list(NA_integer_), group_num)
  for (k in sort(orders, decreasing = TRUE)) {
    sums <- vapply(1:group_num, function (s) as.integer(sum(groups[[s]], na.rm = TRUE)), integer(1))
    index <- ifelse(any(sums + k <= num), which(sums + k <= num)[which.min(abs(sums[which(sums + k <= num)]+k - num))], NA_integer_)
    index <- ifelse(is.na(index), which.min(sums), index)
    groups[[index]] <- append(groups[[index]],k)
    groups[[index]] <- groups[[index]][!is.na(groups[[index]])]
  }
  groups
}
allocate_groups <- function (orders, num, group_num) {
  groups <- create_groups(orders, num, group_num)
  g <- rep(seq_along(groups), sapply(groups, length))
  out <- cbind(orders, group = g[match(orders, unlist(groups))])
  out
}
# results above

The added constraint actually makes the problem somewhat simpler: There are (at most) n drawers that we want to fill with orders and any total sum should be as close to num as possible.

The Function
Here is the full code of the function
find_grouping <- function (orders, num) {
    combs2 <- RcppAlgos::comboGeneral(orders, 2L, constraintFun = 'sum')
    combs2 <- cbind.data.frame(combs2,close=abs(num - combs2[,3]))
    out <- integer(length(orders))
    skip <- NA_integer_
    group <- 1L
    for (k in seq_along(out)) {
      val1 <- orders[k]
      if (val1 %in% skip) next
      ind1 <- (.subset2(combs2,1L) == val1) | (.subset2(combs2,2L) == val1)
      ind2 <- (which.min(.subset2(combs2, 4L)[ind1]))
      ind3 <- which(ind1)[ind2]
      val2 <- .subset2(combs2, 3L)[ind3]
      if (abs(num-val1) <= abs(num-val2)) {
        out[k] <- group
        group  <- group + 1L
        next
      }
      intList <- as.integer(combs2[ind3,1:2])
      ordersRemain <- setdiff(orders, intList)
      if (abs(num-val2) <= abs(num-val2-min(ordersRemain))) {
        skip <- c(skip, intList)
        out[orders %in% intList] <- group
        group <- group + 1
        next
      }
      val3 <- val2
      cond <- FALSE
      while (!cond) {
        toAdd <- which.min(abs(num - (val2 + ordersRemain)))
        val3 <- val3 + ordersRemain[toAdd]
        intList <- c(intList, ordersRemain[toAdd])
        ordersRemain <- ordersRemain[-toAdd]
        cond <- abs(num-val3) <= abs(num-val2-min(ordersRemain))
      }
      skip <- c(skip, intList)
      out[orders %in% intList] <- group
      group <- group + 1
    }
    cbind(orders,group=out)
}

 Explanation
The first step was to generate all combinations (of 2) of orders
 using RcppAlgos::comboGeneral (it is a rather fast method)
# num
combs <- RcppAlgos::comboGeneral(orders, 2L, constraintFun = 'sum')
combs <- cbind.data.frame(combs,close=abs(num - combs[,3])) # check how far from num are the combinations
#      1   2   3 close
# 1  100 198 298     2
# 2  100  50 150   150
# 3  100  40 140   160
# 4  100 215 315    15
# ...

From here on now there are several approaches. I opted for a loop where in each iteration I find the best combinations (i.e. closest to num) for the current value orders[k], remember then given combination (e.g. 100;198) and assign the combination a group value.

A: This solves a variant of the problem you posed in which the group sum may not exceed the target sum.
library(BBmisc); library(dplyr);
bin.capacity <- 305
df <- data.frame(Orders = c(100,198,50,40,215,296)) %>%
  mutate(Group = BBmisc::binPack(Orders,bin.capacity))
> df
  Orders Group
1    100     3
2    198     3
3     50     2
4     40     2
5    215     2
6    296     1

for bin.capacity = 300:
> df
  Orders Group
1    100     3
2    198     3
3     50     2
4     40     4
5    215     2
6    296     1


text:
Q: Is the System.Timers.Timer.Enabled property thread safe and so can it be accessed from the timer's Elapsed event? I have an Elapsed method in which I have a while loop. If the timer is disabled/stopped from another thread, I would like this loop to stop. Can I rely on the timer's Enabled property in the Elapsed method for this or should I create a "volatile bool timerEnabled" variable just to be sure. My testings show that it's OK, but I'd like to be sure of this before putting it in production.
This is what I'm trying to achieve (not actual code but close)
private volatile bool isElapsedAlreadyRunning

void myTimer_Elapsed(object sender, ElapsedEventArgs e)
{
    if (!isElapsedAlreadyRunning)   // to prevent reentrance
    {
        isElapsedAlreadyRunning = true;
        try
        {
            while (myTimer.Enabled && some other condition)
            {
                do stuff
            }
        }
        finally
        {
            isElapsedAlreadyRunning = false;
        }
    }
}

myTimer.Start() and myTimer.Stop() are in other methods that can be called frrom other threads

I'm using the System.Timers.Timer class
If you have any other comment or see any pitfall in this design feel free to comment :)
Thanks

Edit :
Man, threading is hard. Based on the answers and other stackoverflow questions (this answer particularly) this would be the way to do it (I hope this time it's OK)
public class NoLockTimer : IDisposable
{
    private readonly System.Timers.Timer _timer;

    private bool _isTimerStopped = false;
    private readonly object _isTimerStoppedLock = new object();

    public NoLockTimer()
    {
        _timer = new System.Timers.Timer { AutoReset = false, Interval = 1000 };

        _timer.Elapsed += delegate
        {
            try
            {
                while (!IsTimerStopped && some other condition)
                {
                    // do stuff
                }
            }
            catch (Exception e)
            {
                // Do some logging
            }
            finally
            {
                if (!IsTimerStopped)
                {
                    _timer.Start(); // <- Manual restart.
                }
            }
        };

        _timer.Start();
    }

    public void Stop()
    {
        IsTimerStopped = true;
        if (_timer != null)
        {
            _timer.Stop();
        }
    }

    private bool IsTimerStopped
    {
        get
        {
            lock (_isTimerStoppedLock)
            {
                return _isTimerStopped;
            }
        }
        set
        {
            lock (_isTimerStoppedLock)
            {
                _isTimerStopped = value;
            }
        }
    }

    public void Dispose()
    {
        Stop();
        if (_timer != null)
        {
            _timer.Dispose();
        }
    }
}

A: No, this is not safe.  The Elapsed event handler is called on a threadpool thread.  You cannot predict when that thread actually calls your method, it depends on what other TP threads are running in the process.  Having two calls in flight at the same time is technically possible.  Which makes the volatile keyword on the isElapsedAlreadyRunning variable not nearly good enough to ensure that the method is thread-safe, you must use the lock keyword or Monitor.TryEnter() instead.
This problem disappears when you set the Timer's AutoReset property to false.  Be sure to restart the timer in a finally block, another nasty problem with the Timer.Elapsed event is that exceptions get swallowed without diagnostic.  System.Threading.Timer is an all-around better timer with fewer surprises like this.
The Timer.Enabled property has a similar problem, you'll always see it late.

A: Your guard with isElapsedAlreadyRunning is obviously not thread-safe.
But you can simply replace it with a lock(...) { ...} statement.


text:
Q: Running Bib file I'm relatively new in Latex and now I want to use bibtex function in my paper.
here is how it"s constructed:
\documentclass[12pt]{article}
\usepackage{amsmath}
\usepackage{afterpage,lscape}
\usepackage{natbib}

\begin{document}
Imperfections in credit market influence the labor market \cite{einstein}.

\newpage
\setcounter{secnumdepth}{0}
\pagenumbering{roman}
\bibliography{Reference}
\bibliographystyle{plain}
\nocite{*}

\end{document}

where my bib file is "Reference.bib" and has the following content:
@article{einstein,
    author =       "Albert Einstein",
    title =        "{Zur Elektrodynamik bewegter K{\"o}rper}. ({German})
        [{On} the electrodynamics of moving bodies]",
    journal =      "Annalen der Physik",
    volume =       "322",
    number =       "10",
    pages =        "891--921",
    year =         "1905",
    DOI =          "http://dx.doi.org/10.1002/andp.19053221004"
}

I'm running Latex, however there is no output of the bibliography in pdf and the citations are with question marks.
Also I have tried to run my bib file separately and it's not creating "bbl" extension file (I'm not sure if it's necessary for creating pdf).
Also when I"m running my bib file separately here is the Console Output I'm getting:
 " This is pdfTeX, Version 3.1415926-2.5-1.40.14 (MiKTeX 2.9)
entering extended mode
("C:/Users/Anushmush/Desktop/Labor Search/Reference.bib")
*"

Is this what I need to get?
Could you please help me figure out what is the mistake I'm making here?
Thank you very much


text:
Q: show last post from each category I have two models Post and Category
// migration post
public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('body');
        $table->string('image');
        $table->integer('category_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories');
        $table->timestamps();
    });
}

// migration category
public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

How can I display only the last post from each category in home page?

A: Hiren was close, but you need to go from the category since your post is owned by the category
$category->posts()->latest()->first();

Alternatively you could work backwards:
$post = Post::latest()->whereHas('category', function($q) use($category_id) {
    return $q->where('id', $category_id);
})->first();

For this to work you'll need to define your model relationships:
Category Model needs this function:
public function posts()
{
    return $this->hasMany(App\Post::class);
}

Post Model needs this function:
public function category()
{
    return $this->belongsTo(App\Category::class);
}

To respond to Alexey Mezenin, we can just pass a callback to with() to define which posts we want to pull in for each category, performing the correct eager load.
Category::with(['posts' => function($q) {
    return $q->latest()->first();
})->get();

A: An Eloquent solution for loading categories with latest post is to create an additional hasOne() relationship in the Category model:
public function latestPost()
{
    return $this->hasOne(Post::class)->latest();
}

And then use eager loading:
Category::with('latestPost')->get();

This will generate just 2 queries to DB.

A: public function up()
{
    Schema::create('news', function (Blueprint $table) {
        $table->increments('id');
        $table->string('slug')->unique();
        $table->unsignedInteger('author_id');
        $table->unsignedInteger('category_id');
        $table->string('subject');
        $table->text('short');
        $table->text('content');
        $table->integer('view')->default(0);
        $table->integer('status')->default(0);
        $table->string('image');
        $table->timestamps();

        $table->foreign('author_id')
              ->references('id')->on('users')
              ->onDelete('cascade');
        // $table->foreign('category_id')
        //       ->references('id')->on('categories')
        //       ->onDelete('cascade');
    });
    // Schema::enableForeignKeyConstraints();
}
public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name')->unique();
        $table->timestamps();
    });
}

in contoller:
    $latestpostlist = News::whereIn('created_at',function($query){
            $query->select(DB::raw('max(created_at)'))
                      ->from('news')
                      ->groupBy('category_id');
    })->get();

in your case news will be post. this query worked for me


text:
Q: Unity3d request user authorisation (OSX) So basically my Unity program would need to modify hosts file on OSX and that need admin privilege. And i got the following Exception:
UnauthorizedAccessException: Access to the path "/private/etc/hosts" is denied.

How do I pop a "XXX wants to make changes: Enter your password to allow this." window just like the screenshot I attached below?
I did some Google but i couldn't find anything useful.
Any suggestion would be appreciated.

A: Did some more research, the only solution I can think off right now is to write a native plugin using apple's Authorization service, and call it from Unity program.
But if there's a more Unity way of doing it, please don't hesitate to add it as an answer.
EDIT_1: Progress update and a note to my future self.
A native plugin for OSX is suffixed .bundle, I wrote it in C++(since the official example is in c++), but it dont have access to authorization service. And i don't know how to setup OC for a bundle project.  Now I'm trying an alternative to create a command-line tool application for OS X and run it as an external process from Unity3d.  Good news is now i can use swift to write it !
.
EDIT_2: Progress update and a note to my future self.
The commandline tool written in OC did work. I can simply open command line tool using Process.start(name, argument) in Unity3d.


text:
Q: Caret going next to text rather than the span on contenteditable div When using the contenteditable attribute on a div and have inserted a HTML element span in, for some reason the caret goes inside the space next to the text:

To replicate, hit backspace to remove the question mark at the end on the example I provided

.pill {
    background-color:  #EEEEEE;
    border: none;
    color: black;
    padding: 0px 4px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    margin: 4px 2px;
    cursor: pointer;
    border-radius: 5px;
    font-weight: bold;
    font-size:0.8em;
    z-index:100;
}

    is your email still Email?


text:
Q: Getting DNS for Load Balancer in GCP In Google Kubernetes Engine, I created a Load Balancer (External IP Address). I can access it using the IP address. However, I want to get a domain name. ( I am not asking about buying my own domain and adding DNS records ). I am not able to find how to get the url.
For eg. in Azure, in Azure Kubernetes Service, I created a Load Balancer and added a label. So, I can get a url like http://<dns_label_which_i_gave>.<region_name>.cloudapp.azure.com. So, for trial purpose, I don't have to pay for a domain and I can get an easy to read domain name.
How to get the same in GCP Load Balancer?

A: With Google Cloud you can't do this. The Load balancer expose an IP and you have to create a A record in your registrar to make the link.


text:
Q: Run Java Code after a Method Return? I have a web service that is based on Java classes. Is it possible to run code after an acknowledge message has been returned within Java method of the called operation.
To understand better, this is the workflow:

*

*Call a specific operation (method) of my web service

*Start processing

*Sent an ack that the processing has been started (this is done be a return value)

*Continue processing

Threads do not work, since the threads need to be terminated before the return of the method.
Does anybody has an idea how to implement this scenario or an alternative to it?
Thanks in advance.

A: You will need to use Threads for this, as you are splitting program flow into two; the returning path and the processing path are separating and running alongside each other.
If you need the acknowledgement for the method start to be sent by the return of the method then why can't your service providing methods look as simple as something like this?
public Acknowledgement someService() {
  new Thread(new SomeServiceRunnable()).start();
  return new Acknowledgement();
}

The service will be started, then the method will return (thus notifying that the process has started) whilst the processing continues until the thread ends...
Am I missing something here about what you need to achieve?
Hope this helps.
EDIT:
It seems that some answers have been engineered to address problems which I did not see as being presented as part of the question. Here are some assumptions I made when making my answer, presented so that anyone reading this answer might have a better idea of when it might not apply to their particular situation:
This is for a situation where you want only to acknowledge that a service has conceptually speaking begun execution. The acknowledgement can give no information about the success of any part of this execution or its initialisation, only that it has conceptually started, that is to say that the Associated Runnables run() will be called at some point.
Of course if you want the execution to start and the caller to return, then the significance of the acknowledgement will necessarily be limited by just exactly how much of the task waited to be executed before returning, here no waiting is done and the acknowledgement is returned immediately, and so no extra information can be given.

A: How about invoking a callback method to the client.
See the workflow

*

*Call a specific operation (method) of my web service

*Start processing

*Call a method on the client, sending an acknowledgement.

*Continue processing

A:
Threads do not works, since the threads need to be terminated before
  the return of the method.

Wrong. Threads share variables, and thus can share data between threads with no need to return from the thread. Taking your example:

Call a specific operation (method) of my web service

Spawn new thread for this

Sent an ack that the processing has been started (this is done be a return value)

No, don't do it by return value. The new thread sends a message to whatever class you want (calls a method, changes a variable...). With this you can signal anything you want to any thread you want. Just beware of racing conditions, and use "synchronized" keyword when needed!

Continue processing

The new thread continues to process, as does the main one.

A: The answer to your problem is creating a thread:
public boolean beginWorkAndSendAck(){
    Thread t = new Thread(){
        public void run(){
            //Do something here
        }
    }
    t.start();
    return true;
}

The thread will carry on after the 'main' thread dies away. The problem you may be referring to, is if the web-service shuts down the process after the ack is sent. The thread should keep going, as java doesn't shut down its process unless all threads are done.
If it isn't working, it might the web service is doing some voodoo - closing the java process or somesuch. I'd suggest looking into creating a new process with java, here: http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html which would require a separate application to perform the job you need.

A: Thread t = new Thread(){
    public void run(){
              //task to complete after sending acknowledge
    }
};
t.start();
//prepare acknowledgement code and return;
return new ResponseEntity<>(HttpStatus.OK);

task inside run() method will keep on running even after return.

A: Maybe you're looking for an asynchronous Web service invocation:
http://today.java.net/pub/a/today/2006/09/19/asynchronous-jax-ws-web-services.html


text:
Q: mysql - measure amount of write System : Centos 6.4, PerconaDb/MySQL 5.5.31
Im running relatively small mysql database with some 30 databases, total amount of 12Gb, but heavy on reads, updates and writes (texts, posts, user data and user actions are being CRUD evenly during the day). Its a typical relational db, no data warehouse or so.
Currently, its running on some two HDD array (not sure about specs, its hosted) giving the disks quite tough time, with 25% IO utilization, avg 700 IOPS, 5Mbps (according to Newrelic monitoring agent on the server). The whole MySQL server is doing some 540 queries per second, average.
Im considering putting it on separate disk array, and Im considering use SSD for it. Either classic SSD disks, or SSD PCI card.
As there are technical limits of how much data can be written to SSD, before the chips wear out, I'd like to calculate / estimate the amount of time the disks will be good before need to be replaced.
My questions are :

*

*Is it premature optimization ? I cannot rewrite all apps using all the databases, all are indexed as well as possible, I'm no newbie in this, but I accept there might be things to consider and change.

*How can I measure the amount of data written by MySQL ? to estimate how long it will probably live on the SSD. Does it even apply on this amount of data, should I care about it at all ?

*Do you have any experience with running MySQL on SSD, any best practice to share in here ?


text:
Q: Django Form Processing With Custom Widget I am implementing a star rating system, and I am having trouble getting the form to validate. I am using a custom widget (see code below), and this plugin http://plugins.krajee.com/star-rating. When a rating is selected, I am setting the value on the input to be the value of the rating. I want this value on the input to be the value that is cleaned and validated by the form, but right now the form always prompts back that rating is a required field. How do I get my django form to accept the value of the input on this custom widget as the value to validate?
class StarRatingsWidget(forms.Widget):

    def render(self, name, value, attrs=None):
        return mark_safe('<input id="id_star_rating" type="number" class="rating" min=0 max=5 step=0.5 data-size="xs" data-glyphicon="false" data-show-caption="false" >')

A: Turns out I needed to provide a correct name for my widget, per django form standards, and implement the value_from_datadict method to return the value of the widget.
class StarRatingsWidget(forms.Widget):

    def render(self, name, value, attrs=None):
        return mark_safe('<input name="%s" id="id_rating" type="number" class="rating" value=0 min=0 max=5 step=0.5 data-size="xs" data-glyphicon="false" data-show-caption="false" >' % name)

    def value_from_datadict(self, data, files, name):
        return float(data[name])


text:
Q: Does AtomicLong's compareAndSet ensure threadsafety This is in continuation to my previous question - Refactoring synchronization blocks keeping ordering of execution intact
I have a synchronized block in one the functions which I want to do away with, having something else to reduce contention and improve performance.
public CallCompletion startCall()
{
  long currentTime;
  Pending pending = null;
  long lastStartTime = _lastStartTime.get();

  currentTime = _clock.currentTimeMillis();
  synchronized (_lock)
  {
      _lastStartTime = currentTime;
      _tracker.getStatsWithCurrentTime(currentTime);
      _sumOfOutstandingStartTimes += currentTime;

      _callStartCountTotal++;
      _tracker._callStartCount++;
      if (_callStartsInLastSecondTracker != null) _callStartsInLastSecondTracker.addCall();
      _concurrency++;
      if (_concurrency > _tracker._concurrentMax) {
        _tracker._concurrentMax = _concurrency;
      }
      pending = checkForPending();
  }
  if (pending != null)
  {
    pending.deliver();
  }
  return new CallCompletionImpl(currentTime);
}

I am trying to replace with an AtomicLong for _lastStartTime:
public CallCompletion startCall()
{
  long currentTime;
  Pending pending = null;
  long lastStartTime = _lastStartTime.get();

  currentTime = _clock.currentTimeMillis();
  //synchronized (_lock)
  //{
    if (_lastStartTime.compareAndSet(lastStartTime, currentTime)) {
      System.out.println("Inside atomic if -->" + Thread.currentThread().getName());
      //_lastStartTime = currentTime;
      _tracker.getStatsWithCurrentTime(currentTime);
      _sumOfOutstandingStartTimes += currentTime;

      _callStartCountTotal++;
      _tracker._callStartCount++;
      if (_callStartsInLastSecondTracker != null) _callStartsInLastSecondTracker.addCall();
      _concurrency++;
      if (_concurrency > _tracker._concurrentMax) {
        _tracker._concurrentMax = _concurrency;
      }
      pending = checkForPending();
      System.out.println("Leaving atomic if -->" + Thread.currentThread().getName());
    }
 // }
  if (pending != null)
  {
    pending.deliver();
  }
  return new CallCompletionImpl(currentTime);
}

However, although most threads enter and exit the compareAndSet block sequentially, there are a few threads which gets messed up:
Inside atomic if -->pool-1-thread-3
Inside atomic if -->pool-1-thread-2
Leaving atomic if -->pool-1-thread-2
Leaving atomic if -->pool-1-thread-3

Not sure if my logic is correctly synchronising the execution or where I am doing wrong. Any help will be appreciated.


text:
Q: Adding custom options to my opencart product Well I have developed an open cart website and now I want some custom options with the product information
For example I want to buy some icecream.
Custom options would be lets say 3 different flavors.
Vanilla/Strawberry/Chocolate
For that also each flavor would have individual options. Lets say i want to buy vanilla then i have to buy a cone. If i want to buy strawberry then i have to buy a bar and if i want to buy chocolate then i have to buy a cup.
Its same as in buying a dreamweaver. If i buy a professional level dreamweaver then i would have to specify how many users and so forth and would have to purchase a license as well. Same as that.
I didnt found any options to add such feature in the admin panel. The only feature I found was to add the attribute.
Any help?

A: If you are talking about dependent options, then this is not a feature of OpenCart. By default, options are unaware of each other, so If Option X = 1, Option Y will not vary based on that choice, and vice versa. There is an extension available (commercial) that does what you want


text:
Q: Mocking a Groovy Service with Spring Boot I am testing a Spring Boot application that I am writing in Groovy, and I want to mock out one of the @Components.
Were I using plain Java, I would just mock it out with Mockito in a test @Configuration, but that doesn't work with groovy in versions <2.0 (see https://github.com/mockito/mockito/issues/72 ) and in versions > 2.0, it breaks with Spring (see https://github.com/spring-projects/spring-boot/issues/6520). Now I'm looking for a workaround--other libraries, a different test design, all are fine.
Here is a standalone example that illustrates what I'm going for (see comment in test):
package testing

import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.stereotype.Component
import org.springframework.test.context.junit4.SpringRunner

@SpringBootApplication
public class TheguildRegisterApplication {

    public static void main(String[] args) {
        SpringApplication.run(tech.theguild.TheguildRegisterApplication.class, args);
    }
}

class Account {
    String firstName
    String lastName
}

@Component
class AccountService {

    List<Account> getAllAccounts() {
        return [
                new Account(firstName: "John", lastName: "Doe"),
                new Account(firstName: "Sally", lastName: "Smith")
        ]
    }
}

@RunWith(SpringRunner.class)
@SpringBootTest
class MockTesting {

    @Autowired AccountService accountService

    @Test void test1() {

        // Create Mock Data
        List<Account> accounts = [
                [firstName: "The Cat", lastName: "In The Hat"]
        ].collect {d -> d as Account}

        //
        // Replace the data in AccountService here with a mock
        //

        Assert.assertEquals(accountService.getAllAccounts().size(), 1)

    }
}

Thanks!


text:
Q: Get top videos on facebook/twitter My requirement is to get the list of top N videos being shared on facebook, twitter.
When i say top, i mean it would be based on likes, shares, tweets, retweets etc.
The question from where I am coming is the way how youtube provides a list of top N videos through its api.
I need to get similar information for facebook and twitter.
Can somebody suggest ?
Thanks.

A: I have never asked myself how to do this, but would proceed in the following way, based on the Video URL:
Twitter: search for all tweets with that URL using the search API and count the number of tweets(?). A previe of the results can be found in the search tool on Twitter (this is a sample query with a random video https://twitter.com/search?q=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTD7oMzfA9fY&src=typd)
Facebook: make a query to the graph API, and search for shares/likes of the video url. You have many discussions here on SO that address how to to that. Examples are here How do you get the total likes for a URL (Likes and Shares)? and here How to get share counts using graph API (Facebook). For Twitter, you may refer to the Developers site?
Shortcomings: this solution, albeit simple, is not exhaustive. If you are planning to count shares and the "social buzz" of Youtube videos, bear in mind that Youtube has different urls for one video, and that the query on both Twitter and Facebook is based on the actual URL shared. Twitter users tend to post shortened urls, so it may be difficult to count the tweets about a video with the url only.


text:
Q: Column 'RowIdent' does not belong to table I am trying to add a row to a DataTable using the following code:
for (int i = 0; i < datesCount; i++
{
    // Populate payments table with existing data
    DataRow newPaymentRow = PaymentsMadeDataTable.NewRow();
    newPaymentRow["Date"] = datesSplit[i];
    newPaymentRow["Description"] = descSplit[i];
    newPaymentRow["Amount"] = Convert.ToDecimal(amountSplit[i]);
    // Add row to data table
    PaymentsMadeDataTable.Rows.Add(newPaymentRow);
}

I am receiving the following Error, "Column 'RowIdent' does not belong to table".
What could be causing this error?


text:
Q: Moving a node and it's related siblings into a new parent I'm attempting copy an element and it's related siblings (where they exist in such an order) into a new shared parent but I'm struggling to do this - my XSLT knowledge is limited.
Given the following XML (which can be considered HTML):
<root>

    <heading />
    <content />
    <image />

    <heading />

    <image />

    <heading />
    <content />
    <image />

</root>

I am attempting to create this structure:
<root>

    <wrapper>
        <heading />
        <content />
        <image />
    </wrapper>

    <heading />

    <image />

    <wrapper>
        <heading />
        <content />
        <image />
    </wrapper>

</root>

This is the start of my stylesheet, first copying each node into the output:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:output method="html" encoding="UTF-8" />

    <xsl:template match="node()">
        <xsl:copy>
            <xsl:copy-of select="@*" disable-output-escaping="yes" />
            <xsl:apply-templates select="node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="//heading[following-sibling::content][following-sibling::image]">
    </xsl:stylesheet>

</xsl:stylesheet>

But after this I'm unsure (conceptually) how to handle the next stage. I need to move each set of <heading />, <content /> and <image /> nodes into a new element.
Any help is much appreciated.

A:
I need to move each set of <heading />, <content /> and <image />
  nodes into a new element.

Would something like this work for you?
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="heading[following-sibling::*[1][self::content] and following-sibling::*[2][self::image]]">
    <wrapper>
        <xsl:copy-of select=". | following-sibling::*[1] | following-sibling::*[2]"/>
    </wrapper>
</xsl:template>

<xsl:template match="content[preceding-sibling::*[1][self::heading] and following-sibling::*[1][self::image]]"/>
<xsl:template match="image[preceding-sibling::*[1][self::content] and preceding-sibling::*[2][self::heading]]"/>

</xsl:stylesheet>


text:
Q: How to pass an object as props to a child Functional Component in React.js? I have this code with a config file testType:
import React, { Component } from 'react';
import Select from "./components/Select/Select";

class App extends Component {
  state = {
    testType : [
      {value : "test1", name : "Test1"},
      {value : "test2", name : "Test2"},
    ]
  }
    render() {
        return (
            <>
              <Select {...this.state.testType}/>
              <Select {...this.state.testType}/>
            </>
            );
    }
}
export default App;

Which I use to pass as props to a Select Component, below is the code for it Select.js :
import React from "react";
const selectoption = (props) => (
<select className="custom-select">
    <option value={props.value}>{props.name}</option>
</select>
);

export default selectoption;

But it does not work, I don't see the props test1 and test2 in the select element.

A: The problem in your code is when you are doing <Select {...this.state.testType}/> the below is the data that will be received as prop in the Select component. So basically the array is getting converted to below format in the Select component.
{
  "0": {
    "value": "test1",
    "name": "Test1"
  },
  "1": {
    "value": "test2",
    "name": "Test2"
  }
}

So, instead of spreading it that way if it's being passed as list={[...this.state.testType]} then the passed array can be accessed in Select component as props.list or in the component itself it can be spread like const Select = ({ list }) => {...}. The passed list can be looped through using Array.map and then render all the options.

const { Component, Fragment } = React;

class App extends Component {
  state = {
    testType: [
      { value: "test1", name: "Test1" },
      { value: "test2", name: "Test2" }
    ]
  };
  render() {
    return (
      <Fragment>
        <Select list={[...this.state.testType]} />
        <Select list={[...this.state.testType]} />
      </Fragment>
    );
  }
}

const Select = ({ list }) => (
  <select className="custom-select">
    {list.map(option => (
      <option key={option.value} value={option.value}>{option.name}</option>
    ))}
  </select>
);

ReactDOM.render(<App />, document.getElementById("react"));

For more info about rendering list elements in React please refer here.

A: I hope you are doing well.
I've just read your descriptions carefully.
Data you have passed through props is an array of objects.
So in the selectoption components the "prop" is an array of objects.
You cannot find "value" and "name" of this props.
You must map this array to get data of each options.
Or you can change the code like this.
<Select {...this.state.testType[0]}/>
<Select {...this.state.testType[1]}/>

A: Thank you for your vote.
I am a dedicated and reliable Full-Stack Developer with over 10 years of experience in Web Development.
I have strong skills and experience with React,Vue,Angular Frontend Development and Backend Development with RESTful APIs using Node.js and Laravel.
I can help you with my strong development skills.
You will be happy with my quality of code and fast delivery.
I am full time available and I can overlap at least 8 hrs a day in your timezone.


text:
Q: dropdownlist doesn't lost his selected value but listbox does I have 2 user control one has dropdownlist other listbox, on main page there is a button when I click to button page goes postback and get user controls from session add controls on page. and I can get selected items from drop down list but list box cant sync with viewstate I guess.
what did I try;
binding session uc in page init, adding listbox datavalue and datatext, viewstate enable for listbox(which is default also i guess)
if you think logic is right so I must be doing something wrong in my code let me know I will try to paste it here in a simplified version.

A: Here's code that does what you're trying to do, maybe you're not doing something correct and you can spot something to help you out.
  protected void Page_Load(object sender, EventArgs e)
        {
            var newListBox = new ListBox();
            newListBox.ID = "ANewId";
            newListBox.Items.Add("1");
            newListBox.Items.Add("2");
            newListBox.SelectedIndexChanged += LstBoxChanged;
            Panel1.Controls.Add(newListBox);
        }

        private void LstBoxChanged(object sender, EventArgs e)
        {
            var newListBox = sender as ListBox;

            if (newListBox != null && newListBox.SelectedItem != null)
            {
                Label1.Text = newListBox.SelectedItem.Text;
            }
        }

Hope this helps.


text:
Q: How to show submenu bar on sidebar when mouse over? How to show submenu bar on sidebar when mouse over and close when mouse leave?  can anyone help me to solve this problem? I am newbie on using jquery.
JS CODE not working
$(function(){
    $('.nav').hover(function(){
        $(this).animate({width:'200px'},500);
    },function(){
        $(this).animate({width:'35px'},500);
    }).trigger('mouseleave');
});

HTML

Setting

 Add Account

 Update User

        </ul

Documents in Process

 Incoming Products

 Document Validation

A: css:
.nav{
    width:35px;
    -webkit-transition:width 500ms ease-out;
    transition:width 500ms ease-out;
}
.nav:hover{
    width:200px;
}

see css transitions
see css pseudoclass :hover

greetings timotheus

A: Using pure CSS you can achieve the same.
 .nav li ul{display:none;}
 .nav li:hover ul{display:block;}

DEMO

A: Your selector is wrong
You are selecting
#nav

this selects elements with id="nav"
try using
#sidebar > .nav

To select elements with class="nav" as you have (but only direct children of the sidebar).
Alternatively, use CSS
Something like this.
ul.nav li ul {
  height: 0px;
  transition: height 500ms;
  background-color: red;
  overflow: hidden;
}

ul.nav li:hover ul {
  height: 200px;
}

A: Of course you can achieve it with CSS, but if you want to make your javascript to work:
$('#sidebar > .nav > li').hover(function () {
    $(this).find('.nav').show(500);
}, function () {
    $(this).find('.nav').hide(500);
});

jsfiddle DEMO


text:
Q: How to build a machine learning model for a multi-label classification problem, in which part of training data contains output which is not exact? I have a dataset, which contains input and output labels. For most of the data, the output labels are certain. For instance, some data belongs to type A, some data belongs to type B,  some data belongs to type C, some data belong to type D. But there is some special data, which contains only fuzzy information: we only know that these special data does not belong to type A or type B, in other words, it belongs either type C or type D.
So for this type of dataset, how can we employ machine learning method, such as XGBoost etc. to train a classification model? Is there any mature method to deal with this?

A: The simplest way is to put all those "special data" into a new category named "E" (ideally new category should be -1).
Then the ML model learns those as records that cannot be classified into your known categories based on your training data.
A complex way is to have 4 separate target values.

*

*Probability of A: P(A)

*Probability of B: P(B)

*Probability of C: P(C)

*Probability of D: P(D)

So for the "special data" where you know that it's not A or B, the values of these fields will be:
P(A):0, P(B):0, P(C):0.5, P(D):0.5
If you have some sort of probability function in your training data, use those instead of equal possibility.
Then predict the probabilities for all 4 using regression and you have more granular outputs.
The outputs with highly skewed probabilities can be put into definite classes and the outputs with a more even distribution can show that the output is also a case of "special data".


text:
Q: Win7 widget: RSS/Feed Headlines has stop symbol when hovering
As you can see from the picture I get a stop symbol (PrtScn doesn't capture cursor, so I edited that in) & no images load. This happens on multiple different feeds, so I have trouble believing that's the cause, as it happens with the default-included feeds as well. Things I have tried without sucess:

*

*Disabled all firewall+AV's

*Restart

*Run sidebar.exe as Admin

Not sure what is causing this, maybe the microsoft recent article saying widgets are a security concern & how to disable (as well as their site deactivation for additional widgets)

A: Derp. Internet Explorer being offline causes this. I had gone offline to check a .mht file I had created worked successfully. I noticed after I opened internet explorer to click a link & it had the same icon
Once again: IE being offline is the cause, it now is working. Hopefully this helps someone else who gunks things up


text:
Q: "No singleton value available for A" when A is clearly a singleton I can't figure out why this code wouldn't compile and fail with a:

No singleton value available for A
where:    A is a type variable with constraint >: ("yo" : String) and <: Singleton

case class Wrapper[A <: Singleton](a: A)(using ValueOf[A])

def test[A <: Singleton](blabla: Wrapper[A]): Unit = ()

test(Wrapper("yo"))

Is this expected or a bug in Scala 3?
Note that if I extract Wrapper("yo") then it works:
case class Wrapper[A <: Singleton](a: A)(using ValueOf[A])

def test[A <: Singleton](blabla: Wrapper[A]): Unit = ()

val value = Wrapper("yo")
test(value)


text:
Q: How to pass Event (e) and variables with event listeners? I have an event listener like this:
div.addEventListener('mouseover',function(){bubble_info.call(data);},false);

function bubble_info(e,info){
  //get e.pageX etc
  //do stuff with info
}

This problem is in bubble_info the variable e holds the info of data and info is undefined
How do i make sure i can get e and info correctly?

A: Event Object has many useful properties and methods.
div.addEventListener('mouseover',function(event){
    bubble_info(event, info);
    // you can pass additional params that can be used in your handler
},false);

function bubble_info(event, info){
  // you can access type of event from event object's properties
  console.log(event.type);
  console.log(info); // your additional parameter.
};

addEventListener Documentation
Use call only if you need to pass reference of this (current) object.
It's syntax will be ...
FunctionName.call(thisArg, arguments-list, ...);

call Documentation

A: Try this (you don't need the call unless you're passing a specific this reference - which you're missing in your code anyway):
div.addEventListener(
  'mouseover',
  function(event) {
    bubble_info( event, dataYouWant );
  },
  false
}

For reference, a .call() should look like this: bubble_info.call( this, event, etc )


text:
Q: Creating a generator function that lists the sum of all previous integers Sum of the integers:
keep adding the next integer
0 + 1 + 2 + 3 + 4 + 5 + ...
so the sequence is:
0, 1, 3, 6, 10, 15 .....
I am having trouble with this generator problem. What would be the best implementation of this?

A: itertools.accumulate does this for you:
from itertools import accumulate

for i in accumulate(range(6)):
    print(i)

0
1
3
6
10
15

A: This is how I would go about implementing such a generator:
def integer_running_sum(n):
    running_total = 0
    for integer in range(n):
        running_total += integer
        yield running_total

for total in integer_running_sum(6):
    print(total)

# 0
# 1
# 3
# 6
# 10
# 15


text:
Q: Why Octave crash when I minimize the window and sometimes automatically? I have the latest version of Octave 7.3.0. and I'm using a widows 10 computer.
Octave crashes when I try to minimize the window size and work while keeping it in the left half of the screen, and sometimes automatically while working. Every time when I try to do this, this app crashes.  What can I do to overcome this?


text:
Q: Passing Jquery value to thymeleaf I have a Jquery code like this
$(document).ready(function(){
    $('#viewModal').on('show.bs.modal',function(e){
        $('.row-select input:checked').each(function() {
            var i = $(this).closest("tr").index()-1;
            alert(i);
        })
    })
})

and I have program which use thymeleaf like this :
<label th:each="dataBarangModel:${ListDataBarangModel[i].kodeBarang}" th:text="${dataBarangModel}"></label>

How to pass value  in variable i in jquery code to variable i in thymeleaf code ?


text:
Q: Gruntjs - Watch/Browsersync doesn't reload php So I am using grunt to help me develop sites.
For last two weeks I am having issues with Browsersync/Watch.
When I am making changes to a php files, browsersync doesn't detect any changes. Even, when I am reloading the site manually, source code is not updated. Most funny part is, this code gets updated after "some time" or when I am restarting grunt.
watch: {
    php: {
        files: ['*.php', '**/*.php'],
    }
},
// Run Browser Sync
browserSync: {
    default_options: {
        bsFiles: {
            src: [
                "**/*.php",
                "*.php",
            ]
        },
        options: {
            watchTask: true,
            proxy: 'g.test',
        }
    }
}

Does anyone had familiar issue?

A: Do you have a  body  tag in your PHP files?
Also, when running grunt, do you have a script (like one below) injected under body?

<script id="__bs_script__">
//<![CDATA[document.write("<script async src='/browser-sync/browser-sync-client.js?v=2.26.7'><\/script>".replace("HOST", location.hostname));
//]]>
</script>


text:
Q: alert dialog box having list of item In my android application, when i click on text view, i want to display an alert dialog box which contain list of items. How is it possible. kindly guide.
i code it as:
cus_name_txt = (TextView)findViewById(R.id.cus_name_txta);
    cus_name_txt.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Onclick_click1(cus_name_txt);
            // TODO Auto-generated method stub

        }
    });

    contact_no_txt = (TextView)findViewById(R.id.contact_no_txta);

    attend_by_txtbx = (EditText)findViewById(R.id.attend_by_txt);
    attend_by_txtbx.setText(My_Task.attend_by_txt);

    ticket_no_txt = (TextView)findViewById(R.id.ticket_no_txta);

    task_detail_txt = (TextView)findViewById(R.id.task_detail_txt);

How can i get the alert box of list of items by clicking on textView. Please guide. I'll be thankful to u

A: Put following code in onClick of textView:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Color Mode");

ListView modeList = new ListView(this);
String[] stringArray = new String[] { "Bright Mode", "Normal Mode" };
ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, stringArray);
modeList.setAdapter(modeAdapter);

builder.setView(modeList);
final Dialog dialog = builder.create();

dialog.show();

Or
Dialog dialog = new Dialog(**Your Context**);
  dialog.setContentView(R.layout.**Your Layout File**);
  dialog.show();

In this layout file you can make your layout as per your requirements. When you want to use ListView from your Dialog Layout file then you have to write
  ListView listView = (ListView)**dialog**.findViewById(R.id.**Your ListView Id**)

A: If you want to show the progressBar Before loading of the List in alert dialog, then use AsyncTask for that.
e.g.:
private class LoadingTask extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute(){
               super.onPreExecute();
               progressDialog.show();
        }

        @Override
        protected String doInBackground(String... str) {
            String response = "";
                    // Call Web Service here and return response

            response = API.getDealsByCategory(str[0], str[1]);
                    // e.g.: above is my WebService Function which returns response in string
            return response;
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            System.out.println("result is: "+result);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    progressDialog.dismiss();
                }
            }).start();

        // SHOW THE ALERT DIALOG HERE.....
        }
    }

Call AsyncTask as like below :
LoadingTask task = new LoadingTask();
task.execute("YOUR_PARAMETER","YOUR_PARAMETER");
//==============================
Just put below code in the Post Excution of the AsyncTask and you will get what you want.
final CharSequence[] items = {"","50","100","150","200","250","300","350","400","450","500","550","600","650","700","750","800","850","900","1000"};
        AlertDialog.Builder builder = new AlertDialog.Builder(getParent());
        builder.setTitle("Select Country");
        //builder.setI
        builder.setItems(items, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int item) {
                //Toast.makeText(getApplicationContext(), con.get(item).getCountrName(), Toast.LENGTH_SHORT).show();
                selectDistanceTV.setText(items[item]);
                System.out.println("Item is: "+items[item]);
                /*CONTRY_ID = con.get(item).getCountryId();
                stateET.requestFocus();*/
           }
        });
        AlertDialog alert = builder.create();
        alert.show();

Hope it will help you.
If you need more help on how to use AsyncTask then see here:Vogella
Comment me for any query.
Enjoy Coding... :)

A: You can pass list of items in an String Array and display it in AlertBox..
For Example:
private void SingleChoice() {

String[] selectFruit = new String[] {"Apple","orange","mango"};
 Builder builder = new AlertDialog.Builder(this);
 builder.setTitle("Single your Choice");
 builder.setItems(selectFruit, new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
     Toast.makeText(MainActivity.this,
         selectFruit[which] + " Selected", Toast.LENGTH_LONG)
         .show();
     dialog.dismiss();
   }
 });
 builder.setNegativeButton("cancel",
     new DialogInterface.OnClickListener() {
       @Override
       public void onClick(DialogInterface dialog, int which) {
         dialog.dismiss();
       }
     });
 AlertDialog alert = builder.create();
 alert.show();

}

A: button.setOnClickListener(new OnClickListener()
    {

        public void onClick(View arg0)
        {
            new AlertDialog.Builder(MainActivity.this)

            .setSingleChoiceItems(arrClientName,0, new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog, int which)
                {
                    name.setText(arrClientName[which]);

                }
            })
            .setPositiveButton("Ok", new DialogInterface.OnClickListener()
            {
                       public void onClick(DialogInterface dialog, int id)
                       {

                       }
            })
            .show();

        }
    });


text:
Q: How to show where a funcion is differetiable? I mean what is the basic technique on functions which are defined like
$h(x)$= {$f(x)$ if $x$$\in$$[a,b]$ and $g(x)$ if $x$$\in$$[c,d]$}.
An example:$f(x)$={$x$*$cos({1\over x})$ if $x$ is not $0$ and $0$ if $x=0$}.

A: In your example (and in most examples of this type), it is easy to see that $f|_{\mathbb{R} \setminus \{0\}}$ is differentiable (chain rule, ...). This means that $f$ is differentiable at $x$ for every $x \in \mathbb{R} \setminus \{0\}$. For this conclusion it is essential that $\mathbb{R} \setminus \{0\}$ is an open set.
For the remaining point $x=0$ you use the definition of differentiability, i.e. you write down the difference quotient
$$ \frac{f(x_0 + h) - f(x_0)}{h},$$
where in your example $x_0 = 0$ and determine whether the limit $h\rightarrow 0$ of this quotient exists.
In many examples it is useful to consider the cases $h \downarrow 0$ and $h \uparrow 0$ seperately.
Pro tip: If you know that $f|_{[c,d]} = g|_{[c,d]}$ for some differentiable function $g : \mathbb{R} \rightarrow \mathbb{R}$ (actually, $g : U \rightarrow \mathbb{R}$ with $c$ in the interior of $U$ suffices), then you know
$$\lim_{h \downarrow 0} \frac{f(c + h) - f(c)}{h} = \lim_{h \downarrow 0} \frac{g(c + h) - g(c)}{h} = g'(c).$$
An analogous calculation can be made for $h \uparrow 0$ if $f|_{[a,c]} = u|_{[a,c]}$ for some differentiable function $u$ similar to $g$ above. Here we assumed $a < c < d$.
The function $f$ is thus differentiable in $c$ iff $u'(c) = g'(c)$.


text:
Q: Useful scripts for Sikuli Thanks to Lifehacker I came across Sikuli which is described as:

Sikuli is a visual technology to
  search and automate graphical user
  interfaces (GUI) using images
  (screenshots). The first release of
  Sikuli contains Sikuli Script, a
  visual scripting API for Jython, and
  Sikuli IDE, an integrated development
  environment for writing visual scripts
  with screenshots easily. Sikuli Script
  automates anything you see on the
  screen without internal API's support.
  You can programmatically control a web
  page, a desktop application running on
  Windows/Linux/Mac OS X, or even an
  iphone application running in an
  emulator.

As this looks very promising, perhaps complementary to AutoHotKey I'm curious what scripts you guys will come up with. Especially since this program is portable and could solve "simple" Super User problems.

Example script from their
  documentation:

*

*setThrowException(True)

*setAutoWaitTimeout(10000)

*switchApp("System Preferences.app")

*click()

*click()

*click()

*click()

*wait()

*type("192.168.0.1\t")

*type("255.255.255.0\t")

*type("192.168.0.254\t")

*click()

A: I just found somce new examples on their blog. Sikuli seems extremely useful for GUI controlled software, such as anti-virus software

or controlling your OS, such as changing themes and power settings

A: Basically you can do everything with Sikuli and maybe even more that you can do with scripts or Terminal.
This could be useful for basic user, but if you can do the same thing with a simple script, what would be the utility ? (in the way that a normal user won't make the script itself but rather ask someone who knows more than him to give him a fully functional script)
So if you're looking for useful scripts especially for Sikuli, any useful Automator, AppleScript, shell scripts or whatever languages ported to Sikuli.
Some examples, scripts for :

*

*Changing User-Agent in Safari

*Setting up a proxy server or turning it off

*Locking the screen

*Changing screen resolution if you have several monitors

*Changing to graphic card (for MacBook Pro with double cards)

*Activating or changing order of network interfaces

*Turning bluetooth on and connecting to iPhone for network tethering

*Choosing the boot volume

I tried to choose actions that should not be easy to do without Sikuli.


text:
Q: 503 Service unavailable error in Openshift PHP5.3 application I am trying to deploy a  codeigniter application on openshift with haproxy scaling enabled. I am using PHP 5.3 catridge. I am getting 503 No server is available to handle this request error. I tried googling a lot but I couldn't get a precise solution for this. Have already tried to restart the application, but of no use.

A: If you're still having issues I would check out this CodeIgniter OpenShift quickstart here https://github.com/openshift/CodeIgniterQuickStart. If anything you can take a look and see how this quickstart developer went about building it and then apply it to your application.


text:
Q: i had an interview and they ask me and i didn't know the answer i get a answer The question is write a pseudo code that returns true if a given one way linked list reads the same in both directions and false otherwise. In addition we know the size of the list stored in a variable n. The expected solution should have computational complexity O(n) and memory complexity O(1).
example : 1->2->3->3->2->1  return true
example : 1->2->3->1->2->3  return false

A: It is possible to reverse a one way linked list, doing a single pass(see the end of this answer). The restriction on the additional memory is quite constraining in this task, so the best approach I figured is a bit hacky.

*

*Iterate over the list and reverse the part that comes after its center(namely after position n/2) using the algorithm I mentioned above. Save a pointer to the last element in the list - you'll need it for step 2.

*Simultaneously iterate over the list from the beginning to position n/2 and the reversed portion(from n to n/2). The elements that you iterate over in both portions should match. For this you need two variables - one iterating over the first portion and one for the second(and one to remember how many elements you've already processed).

*Reverse back the second half of the list so that the list is not changed at the end.

Overall I meet the requirements of the task.
The algorithm to reverse a one-way linked list goes like this(using c++ as example):
struct node {
  node* next;
  int data;
};

// reverses a one-way list and returns pointer to the new list head
node* reverse(node* c) {
  node* prev = NULL;
  node* cur = c;
  // I assume the list is NULL terminated;
  while (cur) {
    node* temp = cur->next;
    cur->next = prev;
    prev = cur;
    cur = temp;
  }
  return prev;
}


text:
Q: Antonym of copypasta Is there any antonym for "copypasta", preferably in the context of computer programming?
I can't think of anything more concise than "written from scratch".
Neither Wiktionary or Urban Dictionary lists any antonyms, though the latter has a self-demonstrating entry of what copypasta is, with the top definition duplicated twice.

A: Original is the antonym of copypasta.

A: OC for "original content".
Urban Dictionary also defines it as "original character". But in the context of chan threads and memes, the antonym of "copypasta" is "OC" for "original content".