text:
Q: Trying to compile Cyberduck and ant error I am trying to compile Cyberduck from SVN on MacOSX, I have run make to get the xcode project and tried to run 'build and compile' from the GUI and everything seemed to went well until getting that error :
/Users/chmouel.boudjnah/tmp/cyberduck/build-mac.xml:187:0 /Users/chmouel.boudjnah/tmp/cyberduck/build-mac.xml:187: Problem: failed to create task or type scp
Cause: Could not load a dependent class com/jcraft/jsch/UserInfo
       It is not enough to have Ant's optional JARs
       you need the JAR files that the optional tasks depend upon
       Ant's optional task dependencies are listed in the manual.

Action: Determine what extra JAR files are needed, and place them in one of:
        -/usr/share/ant/lib
        -/Users/chmouel.boudjnah/.ant/lib
        -a directory added on the command line with the -lib argument

Do not panic, this is a common problem.
The commonest cause is a missing JAR.
This is not a bug; it is a configuration problem
Total time: 5 minutes 4 seconds

I have add this file ~/.ant/lib/ant-jsch.jar and still no luck. Do you know if I am missing some files or some environment variable ?
Cheers,

A: You need jsch-0.1.42.jar jar in your classpath

A: Copy the dependencies for Ant from /lib/ext to ~/.ant/lib/.jar*. This is documented in the Readme.


text:
Q: Proper place to declare variables used by many functions? I've been writing C for years now, but I've never learned how to structure things. I've just made giant programs in one file and used global scope for variables that are modified by multiple functions. I'm trying to break away from this and group my functions in separate files. The biggest problem I've had is with variable scope.
For example, one variable needs to be written to by two separate functions in different files and read by two more. I could declare it in main.c and make it an extern in the others, but I know globals are frowned upon and it seems sloppy.
So, is there a logical, "correct" place to declare it? Should it have something like get/set functions? Or is this problem indicative of me poorly dividing my functions?
Thanks.

A: Stop thinking in terms of variables and start thinking of values. Pass values to functions that need them, only pass them what they need, and gather related values in structs to reduce the number of arguments when needed. Let functions return their result instead of writing it into a global. This is the way to organize programs in any language, including C. (See Pike's Notes, especially rule 5: "data dominates".)
Using getters and setters on global variables can buy you some safety, but it doesn't solve the real problems with global state. You still need to figure out which parts of the program are using which data and make sure they're touching the data in the right order.

A: Allocate the variable dynamically using malloc and pass the pointer to the variable to the functions (or pass by reference if you are using C++).
You can define the variable as extern in a header file and include that file wherever needed, as mentioned by @pala.
For the functions which will only read the value pointed by the pointer, you can define it as 'pointer to constant'. This will avoid accidental updation of the content by that function.
If you are sure that the address of the memory location also will remain constant in the function you can define 'constant pointer to a constant'. Check this page for on const pointer and pointer to constant.
Returning updated value of a function is also OK, but if there are many functions updating the variable it would be difficult to manage.
If you have multiple threads updating a common variable, make sure you use mutex or semaphore to avoid synchronization issues.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why don't negative root answer count when using derivatives? I was completing the question,

Find $f'(2)$ if $f(x)= \sqrt{3x-2}$.

When I was calculating it as $1.5/\sqrt4$, I got the answers, $3/4$ and $-3/4$ but $-3/4$ wasn't counted in the answers. Why is that?

A: Hints:

*

*the real square root function $\,y = \sqrt{x}\,$ denotes the positive root of $\,y^2 = x\,$, by definition;

*the derivative, whenever it exists, is a function; it cannot take two different values at any point;

*$\;\sqrt{3x-2}\,$ is obviously increasing on $\,[\frac{2}{3}, \infty)\,$, so its derivative can never be negative.

A: The square root is commonly taken to be a function $\sqrt{\cdot}$ such that
$$ \sqrt{\cdot}: [0,\infty) \to [0,\infty) $$
meaning that we take the non-negative square root.
Unfortunately this nuance isn't always clarified in texts but knowing now is better than never.


text:
Q: What does $\arg(z-3)= \frac{-3\pi}{4}$ mean? How to visualize it? What does $\arg(z-3)= \frac{-3\pi}{4}$ mean? How to visualize it?
I can't seem to visualize what it looks like. Could someone please teach me this.
I'm currently trying to solve this question and want to break it down into pieces to understand the whole question:
Question: If $\arg(z-3)= \frac{-3\pi}{4}$ and $\arg(z+3)=\frac{-\pi}{2}$, find $z$.

A: People have given you a nice graphical approach above - I'll try to give a slightly more in depth explanation of this approach, as well as give you another approach.
So, the argument of a complex number is essentially just the angle the number makes with regards to the positive real axis:

notice a negative angle means we go round clockwise, whereas a positive angle means we go round anti-clockwise.
Now, ${z-3}$ essentially means "take the complex number $z$, and then go left three units". When this is done, we are told the angle it makes with the positive real axis is ${-\frac{3\pi}{4}}$:

We don't know the magnitude of ${z-3}$, but all complex numbers with an angle of ${-\frac{3\pi}{4}}$ must lie somewhere on that line. So ${z-3}$ lies on that line. We don't know where, but it does somewhere. By moving the line across to the right ${3}$, we will have a line on which ${z}$ must lie:

We can apply exactly the same logic with the information ${\arg(z+3)=\frac{-\pi}{2}}$:

Moving this line left three, we will get a line again on which $z$ must lie:

And so now we have two lines which we know $z$ must lie on both. The intersection of these lines should then tell us what the value of $z$ is! This is because $z$ needs to satisfy being on both lines:

So now simply find the equation that represents both of the lines in question, and use some nice algebra to find out where they intersect. If you are struggling with this stage, upon request I can also explain how to do this.

Another quick (and a naughty) way to arrive at the answer is to set up a system of Algebraic equations. If ${z=x+iy}$, then you have
$${\arg((x-3) + iy) = \frac{-3\pi}{4}}$$
So what? Well, if ${z=x+iy}$, then ${\frac{y}{x}}$ will give you the tangent of the acute angle that the complex number makes with the pos/neg real axis (whether it's positive or negative depends on the quadrant the number lies in). Since ${-\frac{3\pi}{4}}$ is half way between ${-\frac{\pi}{2}}$ and ${-\pi}$, the acute angle it will make with the axis is ${\frac{\pi}{4}}$ (you can refer to the diagrams above once again to see what I mean):

So
$${\frac{y}{x-3}=\tan\left(\frac{\pi}{4}\right)=1}$$
Now, using
$${\arg((x+3)+iy)=-\frac{\pi}{2}}$$
will lead to a slight problem, since you will end up saying something like
$${\frac{y}{x+3}\stackrel{?}{=}\tan\left(\frac{\pi}{2}\right)}$$
(but - ${\tan(x)}$ "blows up to infinity" at ${x=\frac{\pi}{2}}$).
What's the solution to this? Well a bit of thought will lead you to ${x=-3}$. Now, subbing in ${x=-3}$ into the first equation gives
$${\frac{y}{-6}=1}$$
Which gives us ${y=-6}$. Hence ${z=x+iy=-3-6i}$.

A:
Can you see what's going on here? You can look up how to draw diagrams of points and lines in the complex plane.
To break it into pieces, think about what $\arg(u) = \theta$ means.

A: so the argument is simply the angle the complex number makes with the real axis when plotted on an argand diagram (note that a negative angle means you go clockwise from the positive real axis). In general arg(Z-a) is a half line starting at the point a. I have done a sketch to hopefully show this.

A: If $z=r e^{i\theta}$, then $\text{Arg}(z)= \theta + 2k\pi$, where $-\pi<\text{Arg}(z)\le \pi$.
So, $$\begin{aligned}
\text{Arg}(z-3)= -\frac{3\pi}{4} &\Longrightarrow z-3 = r_1 e^\frac{-{i 3 \pi}}{4} \Longrightarrow z= 3+ r_1 e^\frac{-{i 3 \pi}}{4} \\
\text{Arg}(z+3)= -\frac{\pi}{2} &\Longrightarrow z+3 = r_2 e^\frac{-{i  \pi}}{2}\Longrightarrow z = -3 + r_2 e^\frac{-{i  \pi}}{2}\\
\end{aligned}$$
The first equation implies that $z$ lies on a ray starting from the point $3$ and directed at an angle $-\frac{3\pi}{4}$ (shown in yellow).  The second equation implies that $z$ lies on a ray starting from the point $-3$ and directed at an angle $-\frac{\pi}{2}$ (shown in blue).  The intersection is the point $z=-3-6i = \sqrt{45} e^{i \tan^{-1} 2 - i\pi}.$ (The green ray starts at the origin and ends at our point $z=-3-6i$.  It has magnitude $\sqrt{45}$ and argument $(\tan^{-1}-\pi)$.)

A: Note that $\operatorname{Arg}(z-3)=-\frac{3\pi}4$ is
$$x+i y-3=re^{\frac{-3\pi}{4}i }= -\frac r{\sqrt2}  -\frac r{\sqrt2} i
$$
which leads to $x-3=  -\frac r{\sqrt2},\>\>\>y = -\frac r{\sqrt2} $, or
$$y=x-3$$
Thus, $\operatorname{Arg}(z-3)=-\frac{3\pi}4$ represents a line. Similarly, $\operatorname{Arg}(z+3)=-\frac{\pi}2$ represents $x=-3$. The two lines intersect at $z= -3-6i$.


text:
Q: Function is called twice in nodejs When I run this as server, and goto localhost:8080 'Saved!' is printed twice in console. And also 'Honey Bee' is appended twice in mynewfile1.txt Why is that?
var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write('Hello World!');

    fs.readFile('head.html', function (err, data) {
        res.write(data);
        res.end();
    });

    fs.appendFile('mynewfile1.txt', 'Honey Bee', function (err) {
        if (err) throw err;
        console.log('Saved!');
    });
}).listen(8080);

A: It's because your browser makes an additional request to fetch favicon.ico. Use curl to make a single HTTP request:
curl http://localhost:8080

A: If you put a return statement at the end of the function, it won't run more than once.
content = "
This is content written to a file
";
file_name = "html/fs_test_file.html";
fs.appendFile(file_name, content,
    (err) =>
    {
        if (err) throw err;
        console.log("File created");
        return;
    });


text:
Q: malformedXML: During update: outerTab:j_idt185 not found; iframe id="JSFFrameId" I have a form with a PrimeFaces selectOneMenu which, when the user selects an option, I want to refresh a DataTable in the same form with different data. When I select an option I get a Javascript popup that says "malformedXML: During update: outerTab:j_idt185 not found" with no DataTable refresh and on inspecting the source I see an invisible iframe at the bottom of the page with id="JSFFrameId" that contains an element <partial-response> that in turn contains an element <update id="outerTab:j_idt185" ...> and this contains an element <![CDATA[

]]>. I think this references my <messages> tag, but nothing in the backing bean creates a message, and I do see an element in the page source

 where the messages should be, so the messages tag is indeed rendered. I can find no element with an ID containing "j_idt185" and apparently neither can some Javascript.
The "outerTab" in the IDs is a PrimeFaces TabView that contains all this stuff.
A page refresh causes the update to happen and the DataTable shows the correct data for the selected SelectOneMenu option.
I have found several posts by balusC where some element that is updated by an ajax call has a rendered value that makes it not render and therefore unable to be found when the update is called for. The target of my update (the DataTable) has no rendered attribute and is visible all the time, so this is a different problem. Other posts speak to a bug in earlier versions of PrimeFaces (I am using 6.1). I cannot figure out why this error occurs.
@Kukeltje kindly pointed me to several posts showing that using an encoding type of multipart/form-data in a file-upload component or a form submit can cause this problem but my page has neither of these.
Here is an excerpt of my page:

    <h:form id="facilitatorTestsForm">

        Tests for which event?

            <f:selectItem itemLabel="All Tests" itemValue="" />
            <f:selectItems value="#{testBean.facilitatorEvents}" var="event" itemValue="#{event.id}" itemLabel="#{event.name}"  />
            <f:ajax update="facilitatorTests" />

#{index + 1}

<h:outputText value="#{test.name}" />

<h:outputText value="#{test.tester.fullname}" />

<h:outputText value="#{test.manager.fullname}" />

<h:outputText value="#{test.event.name}" />

<h:outputText value="#{test.functionalArea.name}" />

<h:outputText  value="#{test.completionDate == null ? 'Not Completed' : test.completionDate}"><f:convertDateTime pattern="M/d/yyyy hh:mm a" /></h:outputText>

<... a few dialogs with conditional rendering ...>
    </h:form>

I have tried different targets for the selectOneMenu update attribute and it does not change the behavior so I believe it is correct.
Primefaces 6.1
Mojarra JSF API & IMPL 2.2.4
EL 3.0.0
Tomcat 7
Is this a JSF bug? Thanks for any help you can offer.

A: Found the solution. Thanks to @Kukeltje for staying with me through this even if he did downvote my question for not having enough info :)
It comes back to @BalusC's posts about not rendering the target of an ajax update. In this case I had several PrimeFaces TabView tabs containing
 tags with autoUpdate="true", and the tabs are shown/hidden depending on the role of the user. When I removed autoUpdate="true" from these messages tags the problem went away. Apparently every time I did an ajax post, even if I had partial submit limited to rendered subelements of the current visible tab, autoUpdate causes JSF to try to update the messages tags in the unrendered tabs and of course they cannot be found.
The way I found this was to put id attributes EVERYWHERE, on every element in my forms. Then the Javascript error pointed me to a named (id'd) element, rather than one with an automatically assigned ID that I could not trace, and when I saw "autoUpdate" the light bulb came on. Moral: put ids on EVERYTHING.
I hope this helps someone with the same symptom to look for autoUpdate everywhere.
And @Kukeltje you were right that my post had inadequate information - without the enclosing tab tags with their rendered attributes you could not have seen the problem. Since they were in another template that ui:includes the forms I did not think they were relevant. Wrongo!


text:
Q: force popup to display on the top of the page I have a popup that gets fired when I hover over a link in an iframe embedded inside the main page.
Currently that popup is rendering on the iframe and gets clipped. I want the popup to display on the top and not in the frame.

A: As far as I can see, this can't be done in a reliable and simple way.
You would have to display the popup in the parent frame, because that's the only one that can hover above your iframe. If the popup is bound to the mouse position, the amount of effort required to cross-calculate the correct positions and transfer them to the parent frame is huge and awfully complicated.


text:
Q: why mediaplayer getcurrentposition returns lower than before? I'm trying to make a seekbar which shows playback position And I found something weird. The value of current position it not inscreasing. It should be increased by asc.
Log
D/RecordingFragment: #@ current_position: 0
D/RecordingFragment: #@ current_position: 0
D/RecordingFragment: #@ current_position: 0
D/RecordingFragment: #@ current_position: 5
D/RecordingFragment: #@ current_position: 15
D/RecordingFragment: #@ current_position: 27
D/RecordingFragment: #@ current_position: 37
D/RecordingFragment: #@ current_position: 49
D/RecordingFragment: #@ current_position: 61
D/RecordingFragment: #@ current_position: 73
D/RecordingFragment: #@ current_position: 84
D/RecordingFragment: #@ current_position: 96
D/RecordingFragment: #@ current_position: 108
D/RecordingFragment: #@ current_position: 118
D/RecordingFragment: #@ current_position: 129
D/RecordingFragment: #@ current_position: 141
D/RecordingFragment: #@ current_position: 153
D/RecordingFragment: #@ current_position: 165
D/RecordingFragment: #@ current_position: 177
D/RecordingFragment: #@ current_position: 188
D/RecordingFragment: #@ current_position: 199
D/RecordingFragment: #@ current_position: 210
D/RecordingFragment: #@ current_position: 221
D/RecordingFragment: #@ current_position: 232
D/RecordingFragment: #@ current_position: 243
D/RecordingFragment: #@ current_position: 254
D/RecordingFragment: #@ current_position: 145 <- why?
D/RecordingFragment: #@ current_position: 156
D/RecordingFragment: #@ current_position: 168
D/RecordingFragment: #@ current_position: 180
D/RecordingFragment: #@ current_position: 191
D/RecordingFragment: #@ current_position: 203
D/RecordingFragment: #@ current_position: 217
D/RecordingFragment: #@ current_position: 228
D/RecordingFragment: #@ current_position: 239
D/RecordingFragment: #@ current_position: 250
D/RecordingFragment: #@ current_position: 262
D/RecordingFragment: #@ current_position: 274
D/RecordingFragment: #@ current_position: 285
D/RecordingFragment: #@ current_position: 296
D/RecordingFragment: #@ current_position: 308
D/RecordingFragment: #@ current_position: 320
D/RecordingFragment: #@ current_position: 332
D/RecordingFragment: #@ current_position: 343
D/RecordingFragment: #@ current_position: 354
D/RecordingFragment: #@ current_position: 365

Here is Fragment code
    // update position in every 10ms
    private fun updateCurrentPosition() {
        timer = Timer("current_position", false).schedule(0, 10) {
            Log.d(LOG_TAG, "#@ current_position 타이머: ${player.currentPosition}")
            recordingViewModel.currentPosition.postValue(player.currentPosition)
        }
    }

Observing code
recordingViewModel.currentPosition.observe(this, Observer { position ->
            if(position != null) {
                sbPlayingControll.progress = position
            }
        })

Audio file format (it's recorded audio file from MediaRecorder
            setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
            setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB)
            setAudioSamplingRate(1000 * 16)
            setAudioEncodingBitRate(1000 * 128)

A: It happens because you must be streaming live content and the manifest refresh happens periodically, and with each manifest refresh, some of the chunks in the manifest will get removed from the top and some new chunks will get added at the bottom.
getCurrentPosition() returns the absolute position of the player for that particular manifest. so it reduces slightly on each manifest refresh.
#EXTM3U
    #EXT-X-VERSION:3
    #EXT-X-TARGETDURATION:7
    #EXT-X-MEDIA-SEQUENCE:8779957
    #EXTINF:6.006,
    index_1_8779957.ts?m=1566416212
    #EXTINF:6.006,
    **index_1_8779958.ts?m=1566416212**. -- current position
    #EXTINF:5.372,
    index_1_8779959.ts?m=1566416212
    #EXT-OATCLS-SCTE35:/DAlAAAAAsvhAP/wFAXwAAAGf+/+AdLfiP4AG3dAAAEBAQAAXytxmQ==
    #EXT-X-CUE-OUT:20.020
    #EXTINF:0.634,
    index_1_8779960.ts?m=1566416212
    #EXT-X-CUE-OUT-CONT:ElapsedTime=0.634,Duration=21,SCTE35=/DAlAAAAAsvhAP/wFAXwAAAGf+/+AdLfiP4AG3dAAAEBAQAAXytxmQ==
    #EXTINF:6.006,
    index_1_8779961.ts?m=1566416212
    #EXT-X-CUE-OUT-CONT:ElapsedTime=6.640,Duration=21,SCTE35=/DAlAAAAAsvhAP/wFAXwAAAGf+/+AdLfiP4AG3dAAAEBAQAAXytxmQ==

after manifest refresh
#EXTM3U
    #EXT-X-VERSION:3
    #EXT-X-TARGETDURATION:7
    #EXT-X-MEDIA-SEQUENCE:8779957
    #EXTINF:6.006,
    **index_1_8779958.ts?m=1566416212**. -- updated current position
    #EXTINF:5.372,
    index_1_8779959.ts?m=1566416212
    #EXT-OATCLS-SCTE35:/DAlAAAAAsvhAP/wFAXwAAAGf+/+AdLfiP4AG3dAAAEBAQAAXytxmQ==
    #EXT-X-CUE-OUT:20.020
    #EXTINF:0.634,
    index_1_8779960.ts?m=1566416212
    #EXT-X-CUE-OUT-CONT:ElapsedTime=0.634,Duration=21,SCTE35=/DAlAAAAAsvhAP/wFAXwAAAGf+/+AdLfiP4AG3dAAAEBAQAAXytxmQ==
    #EXTINF:6.006,
    index_1_8779961.ts?m=1566416212
    #EXT-X-CUE-OUT-CONT:ElapsedTime=6.640,Duration=21,SCTE35=/DAlAAAAAsvhAP/wFAXwAAAGf+/+AdLfiP4AG3dAAAEBAQAAXytxmQ==


text:
Q: Как сделать чтобы таймер выполнил действие после его отсчета unit Unit1;
interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,Registry,
  Dialogs, ExtCtrls;

type
  TForm1 = class(TForm)
    Timer1: TTimer;
    procedure Timer1Timer(Sender: TObject);
  end;

var
  Form1: TForm1;
  reg: TRegistry;
  sec : Integer;

implementation
{$R *.dfm}

procedure TForm1.Timer1Timer(Sender: TObject);
  procedure formclose;
  begin
    form1.close
  end;
begin
  Application.Run;
  reg:=TRegistry.Create;
  reg.RootKey:=HKEY_CURRENT_USER;
  reg.Openkey('HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVerson\Policies\System',True);
  reg.WriteString('RegistryTools','1');
  reg.CloseKey;
  reg.Free;
end;

end.

Пытаюсь сделать так, чтоб после открытия программы не надо было нажимать на кнопку в форме, а таймер сам после его окончания блокировал диспечер.
Но, как бы я не пытался, таймер выводит пустую форму, а диспечер не блокируется


text:
Q: C, read by line I'm making a RPG game in C, and I need to read from a single file. Having multiple files is very tedious. Like "health.dat", "energy.dat", "money.dat" etc. I want to put them into one "data.dat", is this possible?
I just want to read specific line from a file
If line 1 has "number 1", then it should go to the "a" variable, line 2 should go to the "b" variable, etc.
Many thanks.

A: It is possible.
you can use the array of pointers in the fgets function.
       char *fgets(char *s, int size + 1, FILE *stream);

fgets (array,size + 1,stream);
where array is *array[size];

A: You can achieve what you describe using the fgets function as follows:
#include <stdio.h>
#include <stdlib.h>
const int MAX_LENGTH = 256;

int main (void)
{
    // Open the file
    FILE* file = fopen ("data.dat", "r");

    // Read the lines
    char a[MAX_LENGTH];
    fgets (a, MAX_LENGTH - 1, file);
    char b[MAX_LENGTH];
    fgets (b, MAX_LENGTH - 1, file);
    // ...

    // Close the file
    fclose (file);
    return EXIT_SUCCESS;
}

Set the MAX_LENGTH variable to the maximum expected length of a line in your file. You should also test fopen and fgets for returning NULL, as both are error conditions.


text:
Q: The implementation of HOG Descriptor I am trying to implement the Hog Descriptor using java without using Hog descriptor which is implemented in opencv, but I have the following questions:

*

*Are HOG Detector and HOG Descriptor the same?

*After we extract interest points or key points from an image from what do we extract HOG descriptor? Form the whole image or from the interest points / key points which we detected before from image.

*When we compute the gradient do we divide the image into blocks before or after we compute the image gradient?
Regards
Thanks in advance

A: Well,

*

*I haven't used HoG specifically but judging from other descriptors, usually they are not the same. The actual feature is the descriptor while the detector as you can guess it is used to detect (to locate) the feature.

*There is no point in finding interesting points and then extract features from the whole image. (Again) I don't know how HoG exactly work but usually either you extract features from the whole image or first detect interesting points and then extract from them. (Some features cannot be extracted from the whole image though).

*Judging from the answers in wikipedia the usual approach involves the calculation of the local features and then use the blocks to group the cells together into larger, spatially connected blocks to improve illumination etc robustness, so first you calculate HoG on cell level and then use the block to groug them together.


text:
Q: Cant mail a couple of variables and strings So I am developing a script that will eventually be run as a shell to detect ip address changes by comparing the current ip (
//get_ip.php
<?php
$current_ip = file_get_contents('http://www.ipaddresscheck.comlu.com/ip.php');
?>

)
(if anyone is interested, http://www.ipaddresscheck.comlu.com/ip.php  will return ONLY the public IP of your machine/ router)
to the latest one recorded in mysql.  Right now, I can't even email out a fake old IP and a real current ip. When i try to email the old and new IPs, it will only work I i put the old ip variable in the spot for the current or nothing at all.  it should say
The old IP adresss was --- ".$old_ip."
The new IP address is  --- ".$current_ip."

but that won't work.  the only thing that works is
The old IP adresss was --- ".$old_ip."
The new IP address is  --- ".$old_ip."

or
The old IP adresss was --- ".$old_ip."
The new IP address is  ---

<?php
//Get IP
include 'get_ip.php';
//Connect to SQL
mysql_connect('localhost','root','root');
//Select database
mysql_select_db("ip_changes") or die(mysql_error());
//Get Date Info
$date = date("D M Y");
$time = date("H i s");
//Generate SQL query
$sql="INSERT INTO ip (date, time, current_ip)
VALUES ('$date', '$time', '$current_ip')";
//Execute SQL
mysql_query($sql);
//$sqlcurrent = mysql_query(SELECT current_ip FROM ip ORDER BY id DESC LIMIT 1);
echo $current_ip;
$new_ip = $current_ip;
//Send Mail
$old_ip = '192.168.0.1';
$to = "justinmarmorato@gmail.com";
$subject = "IP Address Change";
$message = "Hello! This is an automated message from the IPMS.  An IP address chamge has been
detected.
//Right here, I can only send out $old_ip, and nothing else.  The date and time at the bottom does work.
The old IP adresss was --- ".$old_ip."
The new IP address is  --- ".$old_ip."
The IP address change was detected at ---". $date. ' , '. $time;
$message1 = 'Old IP:'.$old_ip.
'New IP:'.$current_ip;
$from = "no-reply@http://mar-remote-net.dns2.us";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo 'Old IP:'.$old_ip.
'New IP:'.$current_ip;
?>

any suggestions?

A: No doubt, that it doesn't work, because you are using a wrong variable name:
$message = "Hello! ...";
//why is it called message1?
$message1 = 'Old IP:'.$old_ip. 'New IP:'.$current_ip;

//here you are sending $message
mail($to,$subject,$message,$headers);

A: I figured it out...
$finalmessage = <<< EOT
    Hello! This is an automated message from the IPMS. An IP address change has been detected.

    Old IP	New IP	Time Detected

    $old_ip	$new_ip	$date  $time

EOT;


text:
Q: Why are some JavaScript constructors not functions? Clarification:
"JavaScript constructor" should be more properly be written as "javascript constructor" to emphasize that the constructors considered are not just the native JavaScript language constructors, such as Object, Array, Function, etc. but also others, extrinsic to the JavaScript language definition but intrinsic to a browser, such as XMLHttpRequest, The word "JavaScript" is meant to indicate these constructors are expressed and accessed using JavaScript.
some references:

*

*Using a Constructor Function in Working with Objects - MDN Docs

*"constructor
Specifies the function that creates an object's prototype"
in Object - MDN Docs

*an example: "... calling the Worker() constructor ..."
Worker - MDN Docs

*What are the predefined primitive constructors?

*Where are constructors such as, `new Image()` and `new Option()`, documented?

*Where is the Documentation for all of the Javascript HTML Element Constructors?
Rhetorically, there are references to constructor functions but NOT constructor objects!
(Facetiously, this is because Objects ARE functions, and Functions are objects!
Why in JavaScript is a function considered both a constructor and an object?
More specifically, objects, or is that obj-eggs?, ARE, ignoring literal instances, instantiations of functions and functions are Object instances of Functions. It is arguable that functions are fundamental to the existence of objects as evidenced by the fact
7. Functions
       precedes
8. Working with Objects
in the MDN docs JavaScript Guide. That section 8, I object!, provides the details needed to create objects using constructors and function instantiations!)
Why are constructors that interface the DOM not functions?
javascript:
  alert([
    "using browser environment:  \n"+window.navigator.userAgent,
     Option, Image, Audio,
       Storage, XMLHttpRequest, Worker, FileReader,
   ] . join("\n\n"));

shows us:

using browser environment:
  Mozilla/5.0 (X11; U; Linux i686; en-US;
  rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3
[object Option]
[object Image]
[object Audio]
[object Storage]
[object XMLHttpRequest]
[object Worker]
[object FileReader]

but ...
javascript:
  alert([
             XPCNativeWrapper,
  ].join("\n\n"));

(which produces

function XPCNativeWrapper() {
      [native code] }

)
and JavaScript language constructors ARE functions.
javascript:
  alert([
    "using browser environment:  \n"+window.navigator.userAgent,
             Array, Boolean, Date, Function,
               Number, Object, RegExp, String,
                 Error, Iterator,
  ].join("\n\n"));

gives us:

using browser environment:
  Mozilla/5.0 (X11; U; Linux i686; en-US;
  rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3
function Array() {
      [native code] }
function Boolean() {
      [native code] }
function Date() {
      [native code] }
function Function() {
      [native code] }
function Number() {
      [native code] }
function Object() {
      [native code] }
function RegExp() {
      [native code] }
function String() {
      [native code] }
function Error() {
      [native code] }
function Iterator() {
      [native code] }

A: First:

Objects ARE functions

No, the are not:
> a = function() {}
  function () {}
> a instanceof Object
  true
> b = {}
  Object
> b instanceof Function
  false

The toString method (which is what gets called when you do string concatenation) is not a reliable way to get information about an object. If I use typeof, I get the following:
using browser environment:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:5.0.1) Gecko/20100101 Firefox/5.0.1

function

function

function

object

function

function

function

So you see, most of them, apart form Storage, are actually functions (why it does not work for Storage, I don't know).
Also keep in mind that the DOM interface can behave differently than native JavaScript objects.
On the other hand, in Chrome the toString method gives this:
[object Function]

[object Function]

[object Function]

function Storage() { [native code] }

function XMLHttpRequest() { [native code] }

function Worker() { [native code] }

function FileReader() { [native code] }

A: When you alert those values the browser engine is alerting value.toString() so we are talking about why does Function.prototype.toString behave in a strange manner.
The ES5.1 specification states :

15.3.4.2 Function.prototype.toString ( )
  An implementation-dependent representation of the function is returned. This representation has the  syntax of a FunctionDeclaration.
Note in particular that the use and placement of white space, line terminators, and
  semicolons within the representation String is implementation-dependent.
The  toString function is not generic; it throws a  TypeError exception if its  this value is not a Function object. Therefore, it cannot be transferred to other kinds of objects for use as a method.

Clearly ES5 states that toString returns an implementation specific string.
If you read the ES Harmony proposals page it states :

function to string – greater specification for problematic Function.prototype.toString (markm, allen)

Here are some more resources :

*

*ES:Harmony proposal for Function.prototype.toString

*ES:Harmonye strawman proposal for Function.prototype.toString

*ES-discuss mail archive about Function.prototype.toString
Basically it's a known issue that toString on function objects (and especially host objects that are also functions) is undefined behaviour. The TC39 committee is already working on standardizing this.
As you can see the host objects are proposed to be standardized in strawman so it's in the air whether that makes it into ES6. However function objects living in ECMA land should have a standardized toString method in ES6 as defined on the harmony proposals page.

A: The question might actually be paraphrased as:
"Do JavaScript (ECMAScript) language conventions apply to and qualify other components of the browser such as the programming objects that interface the DOM?"
The original question uses objects that are supposedly of type Function and used as constructors. The examples shows a dichotomy exists with the programming environment and the DOM interface in how they are represented.
If there is this actual dichotomy, is it made explicit?
This may be the actual issue. If so, the original question should be preceded by this to direct attention to the real problem.
references:

*

*W3C HTML 5 specification

*W3C WebIDL interface definition language specification

*W3C DOM

*Mozilla JavaScript technologies overview

*Mozilla DOM

*Mozilla ECMAScript references

*ecma262-5.com
ECMAScript language constructor details:

*

*4.3.4 constructor

*13.2.2   [[Construct]]

*15.3.4.5.2 [[Construct]].

*"every built-in constructor has the Function prototype object"
quoting section 15   Standard Built-in ECMAScript Objects

*"it is expected that the computational environment of an ECMAScript program will provide ... certain environment-specific host objects, whose description and behaviour are beyond the scope of this specification"
quoting section 4   Overview


text:
Q: react native pormise.all with deviceinfo and geolocation I am building my first react native application and I am using DeviceInfo (react-native-device-info) and geolocation API.
DeviceInfo.getMACAddress(mac => console.log(mac);

and
navigator.geolocation.getCurrentPosition(position => console.log(position)

both of them are returning promise. How to merge them with something like promise.all()

A: Well, I studied your code but what you're doing isn't called a promise, you're objectively giving a callback to the function instead of using .then to resolve the promise.
Check the API of GetMacAddress here also the getCurrentPosition doesn't use promises, it uses callbacks instead, it's api is here.
What you can do to use Promise.all is that, you can wrap getCurrentPosition to a promise and then use promise.all with the DeviceInfo.
wrap getposition to a promise:
const getPosition = (options) => {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(resolve, reject, options);
  });
}

now use Promise.all like this:
const getData = async () => {
        const [macAddress, currentPos] = await Promise.all([
            DeviceInfo.getMACAddress(),
            getPosition(),
        ]);

        // use macAddress and currentPosition here.
}

Now the macAddress and currentPos are the outputs of the getMACAddress and getCurrentPosition function.
If you're not using an async function, then you can do the following:
Promise.all([
    DeviceInfo.getMACAddress(),
    getPosition(),
]).then((macAddress, pos) => {
    // access macAddress and pos in this func
}).catch((error) => {
    // access any error here
})


text:
Q: Create a variable whose shape is only determined at run time I am trying to create the inputs to an RNN cell which has takes

*

*An input tensor x of dimensions batch_size x time_step x n_classes

*An initial hidden state tensor h of dimensions batch_size x hidden_state_size
The problem now is that I am unsure how to use tf.get_variable(...) to create h such that it has a shape of ? x hidden_state_size where ? is the current batch size.
I don't have this problem with x as I am able to define x like so:
x = tf.nn.embedding_lookup(self.pretrained_embeddings, self.input_placeholder)
x = tf.reshape(x, (-1, self.max_length, Config.n_features * Config.embed_size))

So the batch_size is automatically inferred from tf.reshape
So x.get_shape() would give me (?, max_length, n_features * embed_size)
The only workaround I have to create h is the following:
 # x_ is of shape (max_length, batch_size, n_features * embed_size)
 x_ = tf.unstack(x, axis = 1)

 # h is of shape (batch_size, n_features)
 h = tf.get_variable("h", tf.shape(x_[0]), initializer =
 tf.constant_initializer(0.0))

Then h.get_shape() would give the desired (?, n_features * embed_size) which by chance is equal to my hidden_state_size. The problem with this workaround is that this only works if the hidden_state_size is equal to n_features * embed_size which may not always be the case.
Is there a way such that I can define the hidden tensor h so that it can have a shape of (?, hidden_state_size) without the error:

ValueError: Shape of a new variable (pred/h) must be fully defined,
  but instead was (?, 300)

A: Silly me I could have just done something like:
h = tf.zeros(shape = (tf.shape(x)[0], n_features * embed_size))


text:
Q: How to get a better error message from Meteor in the case of an invalid DB update on a 'unique' indexed field? I've set a unique index on one of my Meteor.users fields:
Meteor.startup(function() {
  Meteor.users._ensureIndex('profile.uri', {unique: 1, sparse: 1});
});

I'm allowing users to edit this field via a front-end form.
When they attempt to update it to something already taken by another user, the app - as it should - throws an error and prevents the update.
However, the error I'm getting is just a blank 500 Internal server error:

M…r.m…e.errorClass {error: 500, reason: "Internal server error",
  details: undefined, message: "Internal server error [500]", errorType:
  "Meteor.Error"}

Which… isn't hugely useful for client-side error reporting.
How can I get Meteor to return a more precise error message so that I can appropriately interpret the cause of the error and report it to the user?
Naturally if I apply an error message specific to that error ("URI already taken") to the 500 response then it'll show for any 500 error, which could end up causing confusion if something else is causing it.

A: There may be one temporary solution. Update through a method, and check in the body of that method if the specific field already exists in the collection.
I guess you could also do that in a update allowing hook.
Yes, it is doing again what is already done by the DB (except the DB is probably doing it better).
I can't see any other solution to have the right error message.
Meteor.methods({
  updateProfileUri : function(newUri) {
    if(!this.userId) {
      throw new Meteor.Error('user not signed-in');
    }

    check(newUri, String);

    //If another user already uses this URI
    if( Meteor.users.findOne({ _id: { $ne: this.userId }, 'profile.uri' : uri }) ) {
      throw new Meteor.Error('uri already taken');
    }

    updateUriOfUser(this.userId, newUri);
  }
});


text:
Q: Is it possible to add Custom class in to the popupWindow in Android I am creating custom keyboard. This keyboard created with custom class without xml usage. This is purely customized class for Keyboard. I did not use xml. Now I want to add the custom class in to the popup.
instead  View customView = layoutInflater.inflate(R.layout.popup,null); Can I use my Custom class?
My class will be like following:
public class CustomKeyboard extends LinearLayout {
//Creating layouts and buttons for Keyboard
}

I want to add my CustomKeyboard in popupWindow. Please give me some ideas for this issue.

A: Inflate view mean nothing but adding new view to the parent view. So we can directly add the view instead of inflating views.
CustomKeyboard custKeyboard = new CustomKeyboard(context);
//View customView = layoutInflater.inflate(R.layout.popup,null);//No need to use this.
View customView = custKeyboard;// Instead we can use this.


text:
Q: CloudKit CKShare URL Goes Nowhere I have successfully saved a CKShare URL to CloudKit, and I can see that the user is INVITED in the CloudKit Dashboard. My Mac app emailed the URL to that person, but when they click it, all they see it this screen on icloud.com:

Clicking OK makes everything disappear so all you see is the background on the web page.
My understanding is that the URL is supposed to open my Mac app where it will fire userDidAcceptCloudKitShareWith in my app delegate. But it does nothing.
Could this be because my app is in development and not in the Mac App Store yet? Do I need a custom URL scheme to get it to open my app?
Documentation on this stuff is pretty sparse. I'd love any help someone can provide.

A: I have since learned that you must specify a fallback URL for your CloudKit container. In cases where the app isn't installed (or isn't recognized, which seems to be the case when doing dev builds in Xcode like I am), CloudKit will forward share URL to somewhere you specify. They append the unique share ID to the URL so that you can process it on your own web page.
In the CloudKit dashboard, go to Environment Settings... and you'll see this popup:

I have it redirect to https://myapp.com/share/?id= and on my web page where it redirects to, I do a $_GET['id'] to grab the id. I then do another redirect to my application using a custom URL scheme and pass the share ID (e.g. myapp://abc123 where abc123 is the share ID).
In my app delegate, I receive the URL like this:
func application(_ application: NSApplication, open urls: [URL]) {
  if let url = urls.first, let shareId = url.host{
    fetchShare(shareId) //<-- sharedId = abc123
  }
}

I then use CKFetchShareMetadataOperation to look up the URL of the share and CKAcceptSharesOperation to accept it like this:
func fetchShare(shareId: String){
  if let url = URL(string: "https://www.icloud.com/share/\(shareId)"){
    let operation = CKFetchShareMetadataOperation(shareURLs: [url])

    operation.perShareMetadataBlock = { url, metadata, error in
      if let metadata = metadata{
        //:::
        acceptShare(metadata: metadata)
      }
    }
    operation.fetchShareMetadataCompletionBlock = { error in
      if let error = error{
        print("fetch Share error: \(error)")
      }
    }
    CKContainer.default().add(operation)
  }
}

func acceptShare(metadata: CKShareMetadata){
  let operation = CKAcceptSharesOperation(shareMetadatas: [metadata])

  operation.acceptSharesCompletionBlock = { error in
    if let error = error{
      print("accept share error: \(error)")
    }else{
      //Share accepted!
    }
  }
  CKContainer.default().add(operation)
}

I think there are easier ways to work through this using NSItemProvider and NSSharingService, but I'm doing a lot of custom UI and wanted to have full control of the share workflow.
I hope this helps someone. :)


text:
Q: How to flip geom_curve (arrow) in ggplot2? I can't seem to make arrows concave. I have tried many adjustments to the angle argument in geom_curve
Reproducible example
library(ggplot2)
library(dplyr)
set.seed(123)
data.frame(x = runif(200)* 1000, y = runif(200)* 1000) %>%
  ggplot(aes(x, y)) +
  geom_point() +
  geom_curve(
  aes(x = 200, y = 300, xend = 500, yend = 400),
  arrow = arrow(length = unit(0.03, "npc"), type="closed"), colour = "#EC7014", size = 1.2, angle = 90)

The arrow above is convex - the goal is to make the arrow the shape of a rainbow (concave). I have altered angle and start/end points but all the resulting arrows are still convex
Practical Example
Here the arrows point to the pink parts of the bars - the bottom arrow looks fine, but the top one would look better if it could be made concave

A: I think you want the curvature parameter. Positive values have a counter-clockwise curl, and negative values a clockwise curl. Here's a reprex:
library(ggplot2)

ggplot() +
  geom_text(aes(x = -5, y = 5, label = "Some text"), size = 10, hjust = 0) +
  geom_rect(aes(xmin = 0, xmax = 5, ymin = 2.5, ymax = 7.5)) +
  geom_curve(aes(x = -2.5, y = 5.5, xend = -1.25, yend = 6),
             arrow = arrow(length = unit(0.03, "npc"), type="closed"),
             colour = "#EC7014", size = 1.2, curvature = -0.3, angle = 90) +
  geom_curve(aes(x = -2.5, y = 4.5, xend = -1.25, yend = 4),
             arrow = arrow(length = unit(0.03, "npc"), type="closed"),
             colour = "#EC7014", size = 1.2, curvature = 0.3, angle = 90)

Created on 2020-05-09 by the reprex package (v0.3.0)


text:
Q: Windows command forfiles to copy subdirectories Using the forfiles Windows command, I wnat to copy a directory and every subdirectory. To do so, I´ve tried this:
forfiles /S /P  %myDirectoryPath% /C "CMD /C xcopy @path %NewPath% /Y /V /E"

But all files included in the subdirectories are copied in the same folder as the files of the main directory.
How can I solve it?
Thanks.

A: You should be able to use xcopy to copy the directory tree
xcopy %myDirectoryPath% %NewPath% /t /e

Alternatively use robocopy
robocopy %myDirectoryPath% %NewPath% /e /create


text:
Q: HTML code shows as text in template I have a template like:
{% extends "index.html" %}

{% block content %}
{% if post %}

 Post id: {{post.id}}

    Post title: {{post.post_title}}
    Post: {{post.post_body | safe}}

{% endif %}

{% endblock content %}

my post.post_body is
 Hello World!

The problem is, when the page is rendered code tags also shows up, they are not rendering as HTML tags. If i check rendered html, i see:

 Hello World!

How can i render those tags as HTML tags?

A: Instead of using safe filter, you should wrap variable with tags {% autoescape off %} and {% endautoescape %}.


text:
Q: JQuery / WebKit / CSS transitions for cross browser panel animation As an avid user of JQuery I was alarmed when on the admin panel on iOS effects such as slide were slow and jerky unlike native iOS software.
I've found several mobile libraries including JQuery mobile and JQtouch. Neither however provide cross browser support.
Is their a way of having my existing JQuery effects default to a mobile version if it detects an iOS browser. And would it be possible for a brief explanation of how it works.
Many Thanks,
Marvellous

A: I use code like this:
speed = 500;

var vP = "";
var transitionEnd = "transitionEnd";
if ($.browser.webkit) {
    vP = "-webkit-";
    transitionEnd = "webkitTransitionEnd";
} else if ($.browser.msie) {
    vP = "-ms-";
} else if ($.browser.mozilla) {
    vP = "-moz-";
    transitionEnd = "transitionend";
} else if ($.browser.opera) {
    vP = "-o-";
    transitionEnd = "oTransitionEnd";
}

function animate(object, cssProperties, callback, ms) {
    if (!ms) {
        ms = speed;
    }

    if (Modernizr.csstransitions) {
        object.css(vP+"transition", "all "+ms+"ms ease-in-out");

        object.css(cssProperties);

        if ($.isFunction(callback)) {

            object.bind(transitionEnd,function(){
                object.unbind(transitionEnd);
                callback();
            });

        }

    } else {
        if ($.isFunction(callback)) {
            object.animate(cssProperties, ms, callback);
        } else {
            object.animate(cssProperties, ms);
        }
    }
}

Then for simple cases:
animate($("#someID"),{"left":"100px"});

or for complex ones that need a vendor prefix:
var cssArgs = {};
cssArgs[vP+"transform"] = "translate(100px,0px)";

animate($("#someID"),cssArgs);

If I'm doing some sliding, the I'd recommend using transform3d and a translate of say (100px,0,0). On iOS that will be hardware accelerated.
I use Modernizr to check what I can do, with something like this:
function slide(gallery_chunk, sliderWidth) {
    if (Modernizr.csstransforms3d && Modernizr.csstransitions) {
        var cssArgs = {};
        cssArgs[vP+"transform"] = "translate3d("+gallery_chunk*-sliderWidth+"px,0px,0px)";

        animate($("#gallery_content #thumbnails"),cssArgs);
    } else if (Modernizr.csstransforms && Modernizr.csstransitions) {
        var cssArgs = {};
        cssArgs[vP+"transform"] = "translate("+gallery_chunk*-sliderWidth+"px,0px)";

        animate($("#gallery_content #thumbnails"),cssArgs);
    } else {
        animate($("#gallery_content #thumbnails"),{"left":gallery_chunk*-sliderWidth+"px"});
    }
}

That example is from an image slider, so I'm sending it the width and the chunk (i.e. page 0,1 or 2).
Hopefully that should give you some ideas!

A: I'm not aware of a super-easy way to do this.  But you could use modernizr to figure out if the browser is css-transition friendly, and then do something like this:
function slideMeUp(elementID) {
    if (Modernizr.csstransitions) {
        $(elementID).removeClass('slidDown').addClass('slidUp');
    } else {
        $(elementID).slideUp(500);
    }
}
And then the magic would take place in the css, which gets a bit redundant, but ought to do the trick.  The benefit of using the transition-transform-scale properties is that it works REALLY smoothly on iOS.

.sliders  {
  -moz-transition: -moz-transform 0.5s ease-out;  /* FF4+ */
  -o-transition: -o-transform 0.5s ease-out;  /* Opera 10.5+ */
  -webkit-transition: -webkit-transform 0.5s ease-out;  /* Saf3.2+, Chrome */
  -webkit-transform-origin: 50% 0%;  /* halfway across, at the top */
  -moz-transform-origin: 50% 0%;  /* halfway across, at the top */
  -o-transform-origin: 50% 0%;  /* halfway across, at the top */
  transition: transform 0.5s ease-out;
  transform-origin: 50% 0%;  /* halfway across, at the top */
}
.slidUp {
    -webkit-transform: scale(1,0);  /* full width, zero height */
    -moz-transform: scale(1,0);  /* full width, zero height */
    -o-transform: scale(1,0);  /* full width, zero height */
    transform: scale(1,0);  /* full width, zero height */
}

.slidDown {
    -webkit-transform: scale(1,1);  /* full width, full height */
    -moz-transform: scale(1,1);  /* full width, full height */
    -o-transform: scale(1,1);  /* full width, full height */
    transform: scale(1,1);  /* full width, full height */
}


text:
Q: Custom Tabs shortcode i'v spent a whole day trying to make a shortcode for the tabs that i made.I'v seen here a lot of codes, which i tried to add to functions.php but cant figure it out how to make it work for my case. Most of them are dynamical like tab 1, tab 2 and you add anything. But i want let's say 5 which would be always the same. So the titles would be the same and would have icon above it. This I would insert it inside wp posts. I'v made a nice style for it, and dont want to use plugin.
This is my html

Home

Deals

Upload

Work

Settings

1

2

3

4

5

So any pointers, especially for function.php code?
Thanks

A: A shortcode, is a function that gets run when the code is inserted into the content of a post. The code is enclosed with square brackets like "[code-word]". So drop this in your functions.php file:
function my_tabs(){
     echo ("Hello world!");
}
add_shortcode( 'my_tabs', 'my_tabs' );

Then add the text "[my_tabs]" to any post to display "Hello world!". Change "Hello world!" to anything you want.


text:
Q: matrix differentation I want to find the derivative of the $f:X→(X′X)^{-1}$ where $X$ is a $m×n$ matrix.
Now I know that the differential of $d(X^{−1})=−X^{−1}(dX)X^{−1}$. Can I use this directly to get the differential for the function I want to differentiate above?
Any derivations of this differential and derivative would be appreciated.

A: As long as the matrix for the given linear transformation on Euclidean space is nonsingular, I don't see why not. Some clear and detailed discussions can be found here. I particularly recommend Richard Schoonhoven's wonderful response,I think you'll find it exactly what you're looking for.
Hey,why waste a perfectly good answer someone worked hard posting?


text:
Q: Android 6.0 permission.GET_ACCOUNTS I'm using this to get permission:
if (ContextCompat.checkSelfPermission(context, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(context, Manifest.permission.GET_ACCOUNTS)) {

    } else {
        // No explanation needed, we can request the permission.
        ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.GET_ACCOUNTS}, PERMISSIONS_REQUEST_GET_ACCOUNTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
}

But the pop up dialog for permission asks user for access Contacts!?!?
In pre 6.0 in Play Store with
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>

request is named Identity and explains I need it to get device account.

A: Fortunately this will change in Android N
http://developer.android.com/preview/behavior-changes.html#perm

The GET_ACCOUNTS permission is now deprecated. The system ignores this
  permission for apps that target Android N.

A: That is because of Permission Groups. Basically, permissions are placed under different groups and all permissions from that group would be granted if one of them is granted.
Eg. Under "Contacts" , there is write/read contacts and get accounts, so when you ask for any of those, the popup asks for Contacts permissions.
Read through: Everything every Android Developer must know about new Android's Runtime Permission

EDIT 1
Just thought i'l add the related(not to get accounts but permissions and groups) Oreo update info:
source: https://developer.android.com/about/versions/oreo/android-8.0-changes.html#rmp

Prior to Android 8.0 (API level 26), if an app requested a permission
  at runtime and the permission was granted, the system also incorrectly
  granted the app the rest of the permissions that belonged to the same
  permission group, and that were registered in the manifest.
For apps targeting Android 8.0, this behavior has been corrected. The
  app is granted only the permissions it has explicitly requested.
  However, once the user grants a permission to the app, all subsequent
  requests for permissions in that permission group are automatically
  granted.

A: In Marshmallow all dangerous permissions belong to permission groups.
The permission android.permission.GET_ACCOUNTS belongs to CONTACTS group
You can find more information about dangerous permission and their groups here:
https://developer.android.com/guide/topics/security/permissions.html#normal-dangerous

A: GET_ACCOUNTS was moved into the CONTACTS permission group in Android 6.0. While the API has us provide permissions, the user (for Android 6.0 at least) is prompted for permission groups. Hence, the user will be given the same prompt for GET_ACCOUNTS as the user would get for READ_CONTACTS or WRITE_CONTACTS.

A: I got your question wrong first. On this page http://developer.android.com/guide/topics/security/permissions.html#perm-groups, your can see that GET_ACCOUNTS refers to the permission group contacts. Because of that your are prompted for contact permission.

A: If your using the GET_ACCOUNTS permission to ask the user to select a particular account type on the device(Google in my case), you can use the AccountPicker class which doesn't require any special permissions
Intent intent = AccountPicker.newChooseAccountIntent(null, null,
                    new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE},
                    false, null, null, null, null);
try {
    startActivityForResult(intent, REQUEST_ACCOUNT_PICKER);
} catch (ActivityNotFoundException e) {
    // This device may not have Google Play Services installed.
}

You'll need Google Play services auth in your gradle dependencies
implementation com.google.android.gms:play-services-auth:16.0.1

This avoids the Contacts permission popup for me


text:
Q: pandas filter entries by date have a dataframe with a key named 'date'. first few entries look like this:
0    02.01.2013
1    03.01.2013
2    05.01.2013
3    06.01.2013
4    15.01.2013

Now i want to use pandas to filter out all the rows that are for example not 2014 as a date.
i looked through tutorials and find the following :
mask = transactions['date'][9]==4
trans=transactions[mask]

but that does not work since
transactions['date'][9]

gives me the 9th data entry but not the 9th digit of the date.
Can someone help a newb along ?

A: df
         date
0  02.01.2013
1  03.01.2013
2  05.01.2013
3  06.01.2014
4  15.01.2014

Convert the column to datetime using pd.to_datetime, and test the dt.year attribute -
m = pd.to_datetime(df.date).dt.year != 2014
m

0     True
1     True
2     True
3    False
4    False
Name: date, dtype: bool

Use the mask to filter on df -
df = df[m]

If the datetime column is the index, you'd instead need to convert the df.index -
m = pd.to_datetime(df.index).year != 2014


text:
Q: TypeError on Angular9 "Cannot read properties of undefined (reading 'dispatchEvent') I am following a lesson about Angular in course on Udemy and in console I have this error
Uncaught TypeError: Cannot read properties of undefined (reading 'dispatchEvent')
at :2:27
this is the code from the app component

import { Component, OnInit } from '@angular/core';

declare global {
  interface Document {
    monetization?:any;
  }
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']

})
export class AppComponent implements OnInit{
  title = 'web-monetization';
  monetized=false;

  ngOnInit() {
      if (document.monetization){
        document.monetization.addEventListener('monetizationstart', ()=> {
          this.monetized=true;
        });
      }
  }

  pay() {
    const event =new Event('monetizationstart');
    document.monetization.dispatchEvent(event);
  }

}

Some coding tutorial <button class="button is-link" (click)="pay()">Simulate payment</button>

        The first example

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius metus quis dapibus lacinia. Proin faucibus faucibus nunc, non eleifend metus rutrum quis. Nullam molestie turpis id eros vulputate eleifend.

        const text= 'Here is text for the first example'; console.log(text);

        You Need Monetization to see the code

        The second part

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius metus quis dapibus lacinia. Proin faucibus faucibus nunc, non eleifend metus rutrum quis. Nullam molestie turpis id eros vulputate eleifend.

        const text= 'Here is text for the first example'; console.log(text);

        You Need Monetization to see the code

I am sure to have copied the rigth instruction so I don't know why I see the error

A: In pay method you don't have a check if monetization is available like you have in ngOnInit. In your browser monetization is undefined. See these states here :-
https://webmonetization.org/docs/api/#states
You can add a pollyfill :- https://www.npmjs.com/package/web-monetization-polyfill


text:
Q: Difference between correctly  / incorrectly classified instances in decision tree and confusion matrix in Weka I have been using Weka's J48 decision tree to classify frequencies of keywords
in RSS feeds into target categories. And I think I may have a problem
reconciling the generated decision tree with the number of correctly classified
instances reported and in the confusion matrix.
For example, one of my .arff files contains the following data extracts:
@attribute Keyword_1_nasa_Frequency numeric
@attribute Keyword_2_fish_Frequency numeric
@attribute Keyword_3_kill_Frequency numeric
@attribute Keyword_4_show_Frequency numeric
...
@attribute Keyword_64_fear_Frequency numeric
@attribute RSSFeedCategoryDescription {BFE,FCL,F,M, NCA, SNT,S}

@data
0,0,0,34,0,0,0,0,0,40,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,13,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,BFE
0,0,0,10,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,BFE
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,BFE
...
20,0,64,19,0,162,0,0,36,72,179,24,24,47,24,40,0,48,0,0,0,97,24,0,48,205,143,62,78,
0,0,216,0,36,24,24,0,0,24,0,0,0,0,140,24,0,0,0,0,72,176,0,0,144,48,0,38,0,284,
221,72,0,72,0,SNT
...
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,S

And so on: there's a total of 64 keywords (columns) and 570 rows where each one contains the frequency of a keyword in a feed for a day. In this case, there are 57 feeds for
10 days giving a total of 570 records to be classified. Each keyword is prefixed
with a surrogate number and postfixed with 'Frequency'.
My use of the decision tree is with default parameters using 10x validation.
Weka reports the following:
Correctly Classified Instances         210               36.8421 %
Incorrectly Classified Instances       360               63.1579 %

With the following confusion matrix:
=== Confusion Matrix ===

   a   b   c   d   e   f   g   <-- classified as
  11   0   0   0  39   0   0 |   a = BFE
   0   0   0   0  60   0   0 |   b = FCL
   1   0   5   0  72   0   2 |   c = F
   0   0   1   0  69   0   0 |   d = M
   3   0   0   0 153   0   4 |   e = NCA
   0   0   0   0  90  10   0 |   f = SNT
   0   0   0   0  19   0  31 |   g = S

The tree is as follows:
Keyword_22_health_Frequency <= 0
|   Keyword_7_open_Frequency <= 0
|   |   Keyword_52_libya_Frequency <= 0
|   |   |   Keyword_21_job_Frequency <= 0
|   |   |   |   Keyword_48_pic_Frequency <= 0
|   |   |   |   |   Keyword_63_world_Frequency <= 0
|   |   |   |   |   |   Keyword_26_day_Frequency <= 0: NCA (461.0/343.0)
|   |   |   |   |   |   Keyword_26_day_Frequency > 0: BFE (8.0/3.0)
|   |   |   |   |   Keyword_63_world_Frequency > 0
|   |   |   |   |   |   Keyword_31_gaddafi_Frequency <= 0: S (4.0/1.0)
|   |   |   |   |   |   Keyword_31_gaddafi_Frequency > 0: NCA (3.0)
|   |   |   |   Keyword_48_pic_Frequency > 0: F (7.0)
|   |   |   Keyword_21_job_Frequency > 0: BFE (10.0/1.0)
|   |   Keyword_52_libya_Frequency > 0: NCA (31.0)
|   Keyword_7_open_Frequency > 0
|   |   Keyword_31_gaddafi_Frequency <= 0: S (32.0/1.0)
|   |   Keyword_31_gaddafi_Frequency > 0: NCA (4.0)
Keyword_22_health_Frequency > 0: SNT (10.0)

My question concerns reconciling the matrix to the tree or vice versa. As far as
I understand the results, a rating like (461.0/343.0) indicates that 461 instances have been classified as NCA. But how can that be when the matrix reveals only 153? I am
not sure how to interpret this so any help is welcome.
Thanks in advance.

A: The number in parentheses at each leaf should be read as (number of total instances of this classification at this leaf / number of incorrect classifications at this leaf).
In your example for the first NCA leaf, it says there are 461 test instances that were classified as NCA, and of those 461, there were 343 incorrect classifications. So there are 461-343 = 118 correctly classified instances at that leaf.
Looking through your decision tree, note that NCA is also at other leaves. I count 118 + 3 + 31 + 4 = 156 correctly classified instances out of 461 + 3 + 31 + 4 = 499 total classifications of NCA.
Your confusion matrix shows 153 correct classifications of NCA out of 39 + 60 + 72 + 69 + 153 + 90 + 19 = 502 total classifications of NCA.
So there is a slight difference between the tree (156/499) and your confusion matrix (153/502).
Note that if you are running Weka from the command-line, it outputs a tree and a confusion matrix for testing on all the training data and also for testing with cross-validation. Be careful that you are looking at the right matrix for the right tree. Weka outputs both training and test results, resulting in two pairs of matrix and tree. You may have mixed them up.


text:
Q: CompletableFuture solution to Reactor (or Akka) solution I have the following method using CompletableFuture like this:
public AClass aMethod() {

    CompletableFuture<SomeClassA> someClassAFuture =
        CompletableFuture.supplyAsync(() -> someMethodThatReturnsA());
    CompletableFuture<SomeClassB> someClassBFuture =
        CompletableFuture.supplyAsync(() -> someMethodThatReturnsB());
    CompletableFuture<SomeClassC> someClassCFuture =
        CompletableFuture.supplyAsync(() -> someMethodThatReturnsC());

    CompletableFuture.allOf(someClassAFuture, someClassBFuture, someClassCFuture).join();

    return new AClass(someClassAFuture.join(), someClassBFuture.join(), someClassCFuture.join());
}

This code has a deadlock problem when T threads simultaneously enter the method if there are less threads in the fork join pool than T * 3 (because none of the allOf calls can complete, and they will not return to the pool the currently taken threads).
The only way I have found to solve this was to limit the simultaneous threads inside the method (using Spring's @Async annotation with a thread executor) or increasing the threads in the fork join pool.
I would like some better solution where I can completely forgot about the thread pool size. How can I rewrite this using Reactor or Akka?

A: The implementation in Akka futures would be something like (completely untested):
Future< SomeClassA > f1 = future(() -> someMethodThatReturnsA(), system.dispatcher());
Future< SomeClassB > f2 = future(() -> someMethodThatReturnsB(), system.dispatcher());
Future< SomeClassC > f3 = future(() -> someMethodThatReturnsC(), system.dispatcher());

List<Future<Object>> futures = Arrays.asList(f1, f2, f3);

return sequence(futures).map((results) ->  new AClass(results.get(0),results.get(1),results.get(2)));

Some extra work could be required to parse the futures result before create AClass. Note that you are returning a Future< AClass > now in the aMethod
Though, the problem with your code is that it's blocking. Did you try to join all the CompletableFutures using thenApply and thenCompose to return a CompletableFuture<AClass>?


text:
Q: Retrieving Json from url success but no data shown on table I tried running the code and I have successfully retrieve the json from the url as there is an alert success returned. However, when I try to retrieve the data, there is no result from the json file. Anyone can help me with this please?

$.ajax({
    type: "GET",
    url: 'https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood&key=YOUR-API-KEY',
 dataType: "json",
    success: function(data){
    drawTable(data);
 alert("Success!");
    }
});

function drawTable(data) {
   for (var i = 0; i < data.length; i++) {
        drawRow(data[i]);
    }

}

function drawRow(rowData) {
   var row = $("
")
    $("#personDataTable").append(row);
    row.append($("" + rowData.lat + "	"));
    row.append($("" + rowData.lng + "	"));

}
table {
  border: 2px solid #666;
    width: 100%;
}
th {
  background: #f8f8f8;
  font-weight: bold;
    padding: 2px;
}
<!DOCTYPE html>

    <title>Json to HTML</title>
   <meta charset="utf-8">

     <link rel="stylesheet" href="css/table.css">

        Lat
        Lng

I have edited to add in the json data that I am trying to retrieve, I keep receiving a success connect to the webpage but there's no data that's retrieved.
{
   "geocoded_waypoints" : [
  {
     "geocoder_status" : "OK",
     "place_id" : "ChIJa147K9HX3IAR-lwiGIQv9i4",
     "types" : [ "amusement_park", "establishment", "point_of_interest" ]
  },
  {
     "geocoder_status" : "OK",
     "place_id" : "ChIJzzgyJU--woARcZqceSdQ3dM",
     "types" : [ "amusement_park", "establishment", "point_of_interest" ]
  }
   ],
   "routes" : [
  {
     "bounds" : {
        "northeast" : {
           "lat" : 34.1373841,
           "lng" : -117.9220826
        },
        "southwest" : {
           "lat" : 33.8151707,
           "lng" : -118.3575585
        }
     },

A: As other users commented, you should first check that the data you get from the api is correct. An alert saying that you reached that point is not a guarantee that you have the data you require. If on the other hand you have the correct data please consider this solution
Based on the data structure that you try to draw in the table I think it could be something like this:
[
    {
        "lat": 123,
        "lng": 456,
    }, {
        "lat": 789,
        "lng": -456,
    }, {
        "lat": 321,
        "lng": 956,
    }
]

Surely there will be more data but I imagine these are the relevant data in your case. If this is the case, one way to do it can be as follows:

const dataset = [
    {
        lat: 123,
        lng: 456,
    }, {
        lat: 789,
        lng: -456,
    }, {
        lat: 321,
        lng: 956,
    }
];

function drawTable(dataset) {
    const rows = dataset.map(drawRow).join('');

    document.querySelector('#root').innerHTML = `

                    Latitude
                    Longitude

                ${rows}

`;
}

function drawRow(data) {
    return `

        ${data.lat}
        ${data.lng}

`;
}

// This call to the function in your example would be within the callback success in your ajax method
drawTable(dataset);
table {
    border: 2px solid #666;
    width: 100%;
}

th {
    background: #f8f8f8;
    font-weight: bold;
    padding: 2px;
}

A: The problem is with improper understanding and usage of jQuery. First, your ajax is wrong. I mean, you literary have "YOUR-API-KEY" at the end of the link, so I have no idea how and why do you say that the data is successfully retrieved? But, let's say that it is, and let's say that you parsed JSON and/or manipulated data in a way that you end up with something like this:
data = [{lat: latValue0, lng :lngValue0}, {lat: latValue1, lng : lngValue1}, ...]

I mean, this is from what I've seen in your code: data[i].lat and data[i].lng
So, with that huge IF out of our minds, the actual process of drawing the table rows could be done like this:
function drawTable(data) {
  let table = $("#personDataTable");

  data.forEach(row => {
    table.append(`<tr><td>${row.lat}</td><td>${row.lng}</td></tr>`)
  });
}

That's it. You don't need much more. If you're not familiar with ES6 syntax, You can go to Babel's website and paste ES6 code on the left, and watch what it compiles to on the right. Btw, forEach() is preferred over "classical" for loop. They are doing the same job, but you have much less syntax and less room for error.
Btw, your mistake with jQuery's .append() was confusing appending strings with appending another element on the page which you select with $. Read more about it here.
Further reading:

*

*MDN: Template Literals (Template Strings)

*MDN: Arrow Functions

*MDN: Array.prototype.forEach


text:
Q: how character sets are stored in strings and wstrings? So, i've been trying to do a bit of research of strings and wstrings as i need to understand how they work for a program i'm creating so I also looked into ASCII and unicode, and UTF-8 and UTF-16.
I believe i have an okay understanding of the concept of how these work, but what i'm still having trouble with is how they are actually stored in 'char's, 'string's, 'wchar_t's and 'wstring's.
So my questions are as follows:

*

*Which character set and encoding is used for char and wchar_t? and are these types limited to using only these character sets / encoding?

*If they are not limited to these character sets / encoding, how is it decided what character set / encoding is used for a particular char or wchar_t? is it automatically decided at compile for example or do we have to explicitly tell it what to use?

*From my understanding UTF-8 uses 1 byte when using the first 128 code points in the set but can use more than 1 byte when using code point 128 and above. If so how is this stored? for example is it simply stored identically to ASCII if it only uses 1 byte? and how does the type (char or wchar_t or whatever) know how many bytes it is using?

*Finally, if my understanding is correct I get why UTF-8 and UTF-16 are not compatible, eg. a string can't be used where a wstring is needed. But in a program that requires a wstring would it be better practice to write a conversion function from a string to a wstring and the use this when a wstring is required to make my code exclusively string-based or just use wstring where needed instead?

Thanks, and let me know if any of my questions are incorrectly worded or use the wrong terminology as i'm trying to get to grips with this as best as I can.
i'm working in C++ btw

A: *

*They use whatever characterset and encoding you want. The types do not imply a specific characterset or encoding. They do not even imply characters - you could happily do math problems with them. Don't do that though, it's weird.

*How do you output text? If it is to a console, the console decides which character is associated with each value. If it is some graphical toolkit, the toolkit decides. Consoles and toolkits tend to conform to standards, so there is a good chance they will be using unicode, nowadays. On older systems anything might happen.

*UTF8 has the same values as ASCII for the range 0-127. Above that it gets a bit more complicated; this is explained here quite well: https://en.wikipedia.org/wiki/UTF-8#Description

*wstring is a string made up of wchar_t, but sadly wchar_t is implemented differently on different platforms. For example, on Visual Studio it is 16 bits (and could be used to store UTF16), but on GCC it is 32 bits (and could thus be used to store unicode codepoints directly). You need to be aware of this if you want your code to be portable. Personally I chose to only store strings in UTF8, and convert only when needed.

A:
Which character set and encoding is used for char and wchar_t? and are these types limited to using only these character sets / encoding?

This is not defined by the language standard. Each compiler will have to agree with the operating system on what character codes to use. We don't even know how many bits are used for char and wchar_t.
On some systems char is UTF-8, on others it is ASCII, or something else. On IBM mainframes it can be EBCDIC, a character encoding already in use before ASCII was defined.

If they are not limited to these character sets / encoding, how is it decided what character set / encoding is used for a particular char or wchar_t? is it automatically decided at compile for example or do we have to explicitly tell it what to use?

The compiler knows what is appropriate for each system.

From my understanding UTF-8 uses 1 byte when using the first 128 code points in the set but can use more than 1 byte when using code point 128 and above. If so how is this stored? for example is it simply stored identically to ASCII if it only uses 1 byte? and how does the type (char or wchar_t or whatever) know how many bytes it is using?

The first part of UTF-8 is identical to the corresponding ASCII codes, and stored as a single byte. Higher codes will use two or more bytes.
The char type itself just store bytes and doesn't know how many bytes we need to form a character. That's for someone else to decide.
The same thing for wchar_t, which is 16 bits on Windows but 32 bits on other systems, like Linux.

Finally, if my understanding is correct I get why UTF-8 and UTF-16 are not compatible, eg. a string can't be used where a wstring is needed. But in a program that requires a wstring would it be better practice to write a conversion function from a string to a wstring and the use this when a wstring is required to make my code exclusively string-based or just use wstring where needed instead?

You will likely have to convert. Unfortunately the conversion needed will be different for different systems, as character sizes and encodings vary.
In later C++ standards you have new types char16_t and char32_t, with the string types u16string and u32string. Those have known sizes and encodings.

A: Everything about used encoding is implementation defined. Check your compiler documentation. It depends on default locale, encoding of source file and OS console settings.
Types like string, wstring, operations on them and C facilities, like strcmp/wstrcmp expect fixed-width encodings. So the would not work properly with variable width ones like UTF8 or UTF16 (but will work with, e.g., UCS-2). If you want to store variable-width encoded strings, you need to be careful and not use fixed-width operations on it. C-string do have some functions for manipulation of such strings in standard library .You can use classes from codecvt header to convert between different encodings for C++ strings.
I would avoid wstring and use C++11 exact width character string: std::u16string or std::u32string

A: As an example here is some info on how windows uses these types/encodings.

*

*char stores ASCII values (with code pages for non-ASCII values)

*wchar_t stores UTF-16, note this means that some unicode characters will use 2 wchar_t's

If you call a system function, e.g. puts then the header file will actually pick either puts or _putws depending on how you've set things up (i.e. if you are using unicode).
So on windows there is no direct support for UTF-8, which means that if you use char to store UTF-8 encoded strings you have to covert them to UTF-16 and call the corresponding UTF-16 system functions.


text:
Q: WIFI driver isues. Wifi and boot up lag Ubunti 20.04 recent update I have been using 20.04 for a few week. I have dabbled with Ubuntu trying to make it my go to operating system - I have used command line a little, i am by no means well versed in it's use and can only do very basic operations so please keep any response simple.
20.04 was working ok up until the most recent update 4 days ago (apx), however, since the latest update I am having problem with WIFI. There is no WIFI button in the OS. The only network settings available are Ethernet wired and USB tether, when I connect my Samsung s8 Active through USB type C.
WIFI card is a Broadcom 802.21 CARD (the machine is old, (it's a HP Pro Book 6460b);
driver is :- Broadcom 802.11 Linux STA source bcmwl-kernel-source(propriety).
(found in software & update in the (gnome gui window)
**I tried updating & upgrading.
**I saw a tutorial mentioning driver validation failure so i tried
sudo mokutil --disable-validation

which returned
sudo mokutil --disable-validation command not found
**sudo lshw -C network

returned

  *-network
       description: Ethernet interface
       product: 82579V Gigabit Network Connection
       vendor: Intel Corporation
       physical id: 19
       bus info: pci@0000:00:19.0
       logical name: enp0s25
       version: 04
       serial: a0:b3:cc:28:2e:3c
       capacity: 1Gbit/s
       width: 32 bits
       clock: 33MHz
       capabilities: pm msi bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=e1000e driverversion=3.2.6-k firmware=0.13-4 latency=0 link=no multicast=yes port=twisted pair
       resources: irq:31 memory:d4700000-d471ffff memory:d472a000-d472afff ioport:4060(size=32)
  *-network UNCLAIMED
       description: Network controller
       product: BCM43224 802.11a/b/g/n
       vendor: Broadcom Inc. and subsidiaries
       physical id: 0
       bus info: pci@0000:24:00.0
       version: 01
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list
       configuration: latency=0
       resources: memory:d4400000-d4403fff
  *-network
       description: Ethernet interface
       physical id: 2
       bus info: usb@2:1.2
       logical name: usb0
       serial: fa:18:b5:c7:6a:cd
       capabilities: ethernet physical
       configuration: broadcast=yes driver=rndis_host driverversion=22-Aug-2005 firmware=RNDIS device ip=192.168.42.150 link=yes multicast=yes
mike@mike-HP-ProBook-6460b:~$ ^C
mike@mike-HP-ProBook-6460b:~$ sudo lshw -C network
  *-network
       description: Ethernet interface
       product: 82579V Gigabit Network Connection
       vendor: Intel Corporation
       physical id: 19
       bus info: pci@0000:00:19.0
       logical name: enp0s25
       version: 04
       serial: a0:b3:cc:28:2e:3c
       capacity: 1Gbit/s
       width: 32 bits
       clock: 33MHz
       capabilities: pm msi bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=e1000e driverversion=3.2.6-k firmware=0.13-4 latency=0 link=no multicast=yes port=twisted pair
       resources: irq:31 memory:d4700000-d471ffff memory:d472a000-d472afff ioport:4060(size=32)
  *-network UNCLAIMED
       description: Network controller
       product: BCM43224 802.11a/b/g/n
       vendor: Broadcom Inc. and subsidiaries
       physical id: 0
       bus info: pci@0000:24:00.0
       version: 01
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list
       configuration: latency=0
       resources: memory:d4400000-d4403fff
  *-network
       description: Ethernet interface
       physical id: 2
       bus info: usb@2:1.2
       logical name: usb0
       serial: fa:18:b5:c7:6a:cd
       capabilities: ethernet physical
       configuration: broadcast=yes driver=rndis_host driverversion=22-Aug-2005 firmware=RNDIS device ip=192.168.42.150 link=yes multicast=yes

regarding the display I have not even started trouble shooting that yet - there is a ton on lag, the OS doesn't crash but the screen remains black and back lit then I must ctrl + alt del to switch into the GUI.
Thank in advance -
N.B
mike@mike-HP-ProBook-6460b:~$ sudo rfkill list all
0: hp-wifi: Wireless LAN
    Soft blocked: no
    Hard blocked: no
mike@mike-HP-ProBook-6460b:~$ sudo dpkg -s bcmwl-kernel-source | grep Status
Status: install ok installed
mike@mike-HP-ProBook-6460b:~$ dmesg | grep wl
[    0.000000] DMI: Hewlett-Packard HP ProBook 6460b/161D, BIOS 68SCE Ver. F.67 02/13/2018
mike@mike-HP-ProBook-6460b:~$


text:
Q: Django: how to annotate based on another annotation, or perform operations on an annotation So I am making something that organizes a school schedule. The school in question is organized in a way that the classes stay together in the same room and the teacher moves, the schedule is different every day, and not all the teachers or the classes are in the building in at the same time, and some of the teachers are very picky about when they teach.
I have these models:
class Teacher(models.Model):
    christian_name = models.CharField(max_length=200)
    family_name = models.CharField(max_length=200)
    ...

class TeacherAvailableHour(models.Model):
    teacher = models.ForeignKey('Teacher')

class Requirement(models.Model):
    ...
    teacher = models.ForeignKey('Teacher')
    per_week = models.PositiveIntegerField()
    ...

So the thing I am trying to do is make a schedule for the pickiest teachers first, namely the ones with the smallest ratio between when they can teach (total "TeacherAvailableHour"s) and the number of hours they are required to teach (the sum of all of the teacher's "Requirement.per_week").
In other words, I need to "order_by" that ratio. I can't think of how to do it. Tried this:
Teachers=Teacher.objects.annotate(availability=(Count('teacheravailablehour') / Sum('requirement__per_week')).order_by('availability')

That blows up with an error, of course. I've also tried something like a double annotation:
Teachers=Teacher.objects.annotate(availability=Count('teacheravailablehour')).annotate(required=Sum('requirement__per_week')).annotate(availRatio=(('availability') / ('required')).order_by('-availRatio')

What is the best way to do this? Is this even possible?

A: You cannot calculate such a ratio using the annotate method. You need to use the extra() method provided by the QuerySet API. While lookups using extra are not advisable as they are not portable across DB engines, they are sometimes the best (or only) option for doing such complex queries.
Assuming all the models you are referencing are in an app named schedules, and you have not modified table names using the db_table attribute in your models' metaclasses, the lookup would be something like this:
availability_sql = "(select count(*) from schedules_teacheravailablehour where schedules_teacheravailablehour.teacher_id=schedules_teacher.id) * 1.0"
required_hrs_sql = "(select sum(per_week) from schedules_requirement where schedules_requirement.teacher_id=schedules_teacher.id)"
Teacher.objects.extra(select={"ratio":"%s/%s" %(availability_sql, required_hrs_sql)}).order_by("-ratio")


text:
Q: Passing argument from view to controller I am working on MVC application. I am trying to pass argument from view through JQuery to controller using JSON. the return type is working fine but when I pass argument it fails. following is the code
VIEW
<script type="text/javascript">
    $(document).ready(function () {
        $("#ClientList").change(function () {
            $.ajax({
                url: '@Url.Action("GetClientData", "Home")',
                type: 'Post',
                dataType: 'json',
                data: { clientID: $("#CientList").val() },
                contentType: 'application/json; character=utf-8',
                success: function (data) {
                    if (data.success) {
                        document.getElementById("ClientName").value = data.clientName
                    }
                    else {
                        alert('invalid ID' + data.success);
                    }
                }
            });
        });
    });

CONTROLLER
[HttpPost]
        public JsonResult GetClientData(string clientID)
        {
            Client client = Client.GetClient(Convert.ToInt32(clientID));
            if (client != null)
            {
                return Json(new { success = true, clientName = client.ClientName });
            }
            return Json(new { success = false });

        }

If I take out the argument from controller code. It works fine but it fails when method is accepting arguments. Any suggestions?

A: <script type="text/javascript">
    $(document).ready(function () {
        $("#ClientList").change(function () {
            var selectedClientID = { clientID: $("#ClientList").val() };
            $.ajax({
                url: '@Url.Action("GetClientData", "Home")',
                type: 'Post',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify(selectedClientID),
                success: function (data) {
                    if (data.success) {
                        document.getElementById("ClientName").value = data.clientName;
                        document.getElementById("ClientAddress").value = data.clientAddress;
                        document.getElementById("ClientContactNumber").value = data.clientContact;
                    }
                    else {
                        alert('invalid ID' + data.success);
                    }
                }
            });
        });
    });
</script>

This works perfectly


text:
Q: Inserting "line break" inside block element I'm trying to insert what I assume to be a line break in a css block element. I've tried the simple
 tag and tried adjusting a heading element (h3 e.g.) with margins, padding, etc to fit inside the block with no luck.
This is an example of what I wish to achieve http://imgur.com/oA5RSHo and this is what I have so far. http://jsfiddle.net/3q7on4v2/ it's pretty close in my opinion, but not like I want it yet. any help is appreciated

 Tonight

E Notisia

Mercee

Last Call

Unu-Unu

.nav {
list-style-type: none;
margin-top: 0px;
padding: 0;
overflow: hidden; }

.nav a{
display: block;
width: 200px;
height:60px;
font-weight: bold;
color: #ffffff;
background-color: #323643;
text-align: center;
line-height:60px;
padding: 4px;
text-decoration: none;
border-left: 1px solid #818181;}

.nav a:hover {background-color: #404452; }
.nav li{ float: right; }
h1 {
color: #F2F2F3;
display: inline-block;
margin-top: 15px;
margin-bottom: 0;
padding: 0; }
#bg { background-color: #323643; }

A: I updated the jsfiddle code. So have a look. You will see I added a span within the h1 tag and styled the span to be smaller font and you could do a different color what ever you want.
You might just need a wrapper around it at this point everything floats to the right.

E Notisia

Mercee

Last Call

Unu-Unu

Tonight
    test

ul{padding:0; margin:0;}
ul li{padding:0; margin:0;}

.nav {
 list-style-type: none;
 margin-top: 0px;
 padding: 0;
 overflow: hidden;
    float:right;
}

.nav a{
 display: block;
 width: 200px;
 height:60px;
 font-weight: bold;
 color: #ffffff;
 background-color: #323643;
 text-align: center;
 line-height:60px;
 padding: 4px;
 text-decoration: none;
 border-left: 1px solid #818181;
}
.nav a:hover {background-color: #404452; }
.nav li{
 float: right;
}
h1 {
 color: #F2F2F3;
 display: inline-block;
 padding: 5px 10px;
    float:right;
    margin:0;
}
h1 span{ font-size:12px; display:block;}
.clear{ clear:both;}
#bg { background-color: #323643; margin:0; padding:0; }


text:
Q: How to create mongodb oplog for database? Recently I purchased cluster account from MongoDB atlas. I had checked UI and MongoDB documentation but don't know create oplog db. And how to create a connection string for oplog?

A: Oplog collection is automatically created and maintained by mongoDB and is created under the local database. It is used internally by mongoDB to maintain the various nodes in sync in a replica set. Assume you have a three node replica set, one primary and two secondary. When a write operation happens in the primary, the event is logged in oplog collection and is used internally to replicate the same change in the secondary nodes.
So to use oplog you will need a MongoDB server configured as a replica set. Standalone instances of mongoDB do not have oplog as there is no need for replication in this case.
However, you may start a standalone instance as a replica set by using the command,

*

*Start Mongo server in replica mode.

*

*mongod --dbPath <path_to_data_file> --replSet rs0

*Initiate the replica set.(Execute from mongo shell)

*

*rs.initiate();

A: oplog is a mongodb replication feature. If you have choose replication cluster, you have it in the database named "local". See the collections in "local" database.


text:
Q: Probability of following numbers in a sequence (parking spots problem) I am trying to teach myself some probability and statistics (any book recommendation is more than welcome).
Here's a little problem I tried to solve and I just need some help to complete certain details. The problem goes as follows :
There's 12 aligned parking spots and 8 cars. Each car choose its spot randomly. We observe that all the 4 empty spots are following each other, is it surprising ?
My attempt :
I numbered the parking spots from 1 to 12, I then figured out how many different combination exists for the cars to park. I would say ${12 \choose 8}=495$. I then tried to count all the combinations where the empty spots are following themselves. If I now write all the empty spots down, I get :
$$ (1,2,3,4), (2,3,4,5),...,(9,10,11,12). $$
A total of 9 different combinations. So I would guess that the probability of finding a combination with the 4 empty spots following themselves is
$$ \frac{9}{495}=\frac{1}{55} \approx 0.018.$$
Is my reasoning correct ? Also I am having trouble to describe the sample space $\Omega$ for this model.
Thanks a lot for your help.

A: Yes, your reasoning is correct. The sample space of all possible empty spaces would be something like: $$\Omega=\{(a_1,a_2,a_3,a_4):(a_1,a_2,a_3,a_4)\in \mathbb N, 1\leq a_1 \lt a_2 \lt a_3 \lt a_4 \leq 12 \}$$


text:
Q: What is the null hypothesis in a multivariate Granger causality test (MVGC) test? What is the null hypothesis in a multivariate Granger causality test?
Is it that one series does not cause any of the n-series, or that n-series do not cause one particular series?

https://stackoverflow.com/questions/44967016/multivariate-grangers-causality describes how to implement the software. I have no idea what these software do.
Maybe https://arxiv.org/pdf/1002.0299.pdf explains it better, but I have no idea what the null hypothesis of MVGC from it.


text:
Q: Gmail gadget to the right Is it possible to set the position for my gadget to the right, when I'm on a mail overview.
Something similar to Rapportive gadget.
I tried using canvas, default view ... ate the whole Google doc ...
EDIT : My code
<?xml version="1.0" encoding="UTF-8" ?>

<Module>
  <ModulePrefs height="100" title="Navigation">
    <Require feature="views" />
  </ModulePrefs>
  <Content type="html" view="home">
    <![CDATA[

My Home view

features ...

    ]]>
  </Content>
  <Content type="html" view="canvas">
    <![CDATA[

canvas view

    ]]>
  </Content>
  <Content type="html" view="DEFAULT">
    <![CDATA[

Default view

    ]]>
  </Content>
</Module>


text:
Q: FSCalendar column line separator I using fscalendar and I see that a new column separator in days cell.
These lines does't appear in iPhone 7 but in iPhone XS yes.

If somebody has a solution for this issue I appreciate you because I'm crazy with this problem.
Thanks in advance!

A: I solve it!... in my code, I changed backgroundColor property of cell.titleLabel object. I comment this lines and column separator line is go out!
Regards!


text:
Q: Fermi's golden rule (transition rate) for two widely separated states My problem has to do with quantum (e.g. electronic) transitions of a single particle between two orthogonal states. I know, for example, that light can couple two orthogonal states in a Hydrogen atom and cause transitions from one state to the other. The electron transition rate going from the 1s state to the 2p in the presence of monochromatic radiation (frequency $\omega $) can be computed from Fermi's golden rule, and is proportional to the factor
$ < 1s|\sin \omega t|2p > $.
The term between the bra and the ket is interaction Hamiltonian ${H_I}\left( {r,t} \right) = {H_I}\left( t \right) \propto \sin \omega t.$  In this specific example, ${H_I}$ is independent of the position variable $r$, though in general ${H_I}$ might depend on r.
In my problem, I wish to consider transitions between two states that are widely separated in space. Not only are these states orthogonal, but they exist in physically distinct regions of space. IOW, if ${\psi _1}\left( r,t \right)$ and ${\psi _2}\left( r,t \right)$ are the spatial representations of the two states, then at $ t = 0 $
${\psi _1}\left( r,0 \right)\;\psi _2^*\left( r,0 \right) = 0$
for all values of $r$, by construction.
In the presence of an interaction Hamiltonian $ {H_I}\left( {r,t} \right) $, Fermi's golden rule says the transition rate is proportional to
$ \[ < {\psi _1}|{H_I}|{\psi _2} > \quad  = \quad \int\limits_{{\rm{all \ space}}} {{\psi _1}\left( r,t \right)\;H\left( {r,t} \right)} \;{\psi _2}\left( r,t \right)\;dr\] $.
My question has two parts:
1)  In the special case ${H_I}\left( {r,t} \right) = {H_I}\left( t \right)$, the transition probability is zero when $ t=0 $. I believe that the transition probability remains zero for all subsequent times (but I can't prove it). Is this correct?
2)  In the case where ${H_I}$ does depend on $r$, I think the transition probability can be greater than zero. Is this correct?  Or is the transition probability always zero even in this case? I am having trouble deciding between these two options.
If the answer in part 2) is that transitions are allowed, then could someone provide an example of an interaction Hamiltonian that makes the transition rate nonzero?
Thank you.


text:
Q: Rails 3 data errors with link_to I've been searching for a while for a solution, but haven't been able to find out what is wrong with my code.
I'm trying to delete an item using an ajax call on an event page, but it doesn't seem to work.
<%= link_to 'X', { :controller => 'items', :action => 'destroy', :id => item.id }, :method => :delete, :confirm => 'Are you sure you want to delete this item?', :remote => true %>

X

I believe everything looks right, however, the data attributes don't seem to work. No confirmation occurs when I click this and instead it calls the 'show' action for the controller, so the data-method is not working either.
The weirdest part is that I something else on the page that generates the confirmation messages.
<%= link_to image_tag("trashcan.png"), @event, :confirm => 'Are you sure you want to delete this event?', :method => :delete %>

I've tried changing the 'X' in the first one to an image (in case an image_tag did the trick) - no luck. However, when I changed the link_to to a button_to it did delete, but not confirmation which I assume button does not support. So I'm not sure if I maybe has some javascript error somewhere else, which I assume to not be the case since it works in the other case or maybe I'm missing something somewhere.
Edit:
I forgot to mention I also have a comment for each item and that works as well...
<%= link_to 'X', [comment.item, comment], :confirm => 'Are you sure?', :method => :delete, :remote => true %>
X

A: Fixed it, the problem was I had a div behind these links where I bound an click event to and in which I also called event.stopPropagation() thus prevented the data calls to be made.


text:
Q: Inherit event handlers Im trying to write abstract class for different reports.
I have a method
protected Tuple<byte[], string, string> RenderReport()

which has such lines
var localReport = new LocalReport { ReportPath = _reportLocalFullName };
...
localReport.SubreportProcessing += localReport_SubreportProcessing;

Derived class must write own code in the localReport_SubreportProcessing.
I'm not sure how to make inheritance here. Can someone help ?

A: Rather than having a method:
private void localReport_SubreportProcessing(...) {...}

consider instead:
protected virtual void OnSubreportProcessing(...) {...}

Now your subclasses can simply use:
protected override void OnSubreportProcessing(...) {...}

A: You can call a common method, which you override in your base class.
So in localReport_SubreportProcessing, call ProcessSubreport
private void localReport_SubreportProcessing(object sender, EventArgs e)
{
    this.ProcessSubreport();
}

protected virtual void ProcessSubreport()
{ }

And override it in your deriving class:
protected override void ProcessSubreport()
{ }

A: Try like below.
public abstract class BaseReport
{
  ......
  protected Tuple<byte[], string, string> RenderReport()
  {
    var localReport = new LocalReport { ReportPath = _reportLocalFullName };
    ...
    localReport.SubreportProcessing += localReport_SubreportProcessing;
    ...
  }

  protected abstract void LocalReport_SubreportProcessing(object sender, EventArgs e);
}

public class DerivedReport1 : BaseReport
{
  protected override void LocalReport_SubreportProcessing(object sender, EventArgs e)
  {
    // Report generation logic for report1.
  }
}

public class DerivedReport2 : BaseReport
{
  protected override void LocalReport_SubreportProcessing(object sender, EventArgs e)
  {
    // Report generation logic for report2.
  }
}