Q: How do I get simple scripts which seem to need root priveliges to run via the www-data user? I am programming a small web interface to control samba on Debian (kernel 2.6.32-5-686). I started by writing simple scripts to add users, create folders, etc. They worked fine when run as root. However, when run via the web (apache + php) by using php: shell_exec() some of them didn't work. They look like this:
#!/bin/sh
#archive the userprofile
cp /home/samba/profile/$1 /home/samba/archive/$1
smbpasswd -LU $1 -x
userdel $1
exit 0

I tried using sudo to run the scripts, which doesn't seem to work. I added this line: (jupiter is the servers name)
%sudo jupiter=(ALL)NOPASSWD:/bin/<script>

to the /etc/sudoersfile, gave my www-data user the sudo group, nothing.
Then I read somewhere I should chmod 4755 and chown the scripts. It still didn't work.
At this point I was curious what the problem was and I redirected the STDERR to a file. I ran one of the small scripts, which would call cp, smbpasswdand userdel to delete the user and archive his share. All calls returned the exitcode 1, which AFAIK indicates that something went wrong. STDERR gave me a little clue:
userdel: cannot lock /etc/passwd; try again later.

This seems to be caused by some *.lock files, but there are none in my /etc/ folder.
At this point I got kinda frustrated and tried giving the www-data more root rights by adding it to the root group. Things still didn't work.
So far for my progress, I have no idea what to do next. My question is: How do I get simple scripts which seem to need root privileges to run via the www-data user? I think it might be a problem with the /etc/passwd file, as I can imagine only the root-user has the right to alter it.

A: my answer is only related to the line
sudo jupiter=(ALL)NOPASSWD:/bin/<script>

With this line you allow user sudo to run /bin/<script> on host juptier as any user without authentication. I don't think that you want this.
If i have understood correctly you want the user www-data to execute /bin/<script> as root. In this case the appropriate line looks like
www-data jupiter=(root) NOPASSWD:/bin/<script>

Now you can execute /bin/<script> as www-data with root privileges by invoking
www-data:~ $ sudo /bin/<script>

or via shell_exec("sudo /bin/<script>") in your php-script (I hope you cared about security issues).
For further details look at man sudoers or the online version sudoers.man. For a quick understanding i recommend to take a look at the EXAMPLES section.

A: There's a few different ways ...

*

*use sudo as already described

*configure Apache with the suEXEC feature (might not be an option with php?)

*use a small setuid program that then invokes your code

*and there's more ...

The easiest is probably using sudo, and that's already been described.
A quick summary of the sudo option :

*

*make sure /etc/sudoers doesn't have "Defaults requiretty"

*add this line to that file "apache ALL = NOPASSWD: /path/to/command", which means that "sudo /path/to/command whatever" will by run as root if invoked as apache.  (This assumes that your web server runs as the apache user.)

However, if you do this, let me point out the danger of all of this.  Anybody who can access your page can do whatever it's meant to do -- so with userdel, they can delete users (and possibly all their files), and depending on how the code is written, they may be able to trick it into letting them run any arbitrary command as root.
(Now, if properly configured, sudo can limit what they can do, as can a properly written program (though writing secure setuid, CGI and php (that use shell_exec() as you are) programs can be tricky) but userdel can be pretty destructive by itself.)
So ... if you do this, at the very least make sure that sudo (if you use sudo) is configured to only run the commands that absolutely need to be run, and make sure that your page is not accessible to just anybody -- lock it behind a password in Apache, for example, and be especially wary if it's on the Internet proper rather than behind a corporate firewall (but even then -- don't trust the firewall to make it safe.)  Also make sure that untrusted other people can't add php or CGI programs on this host, because they'll be able to use that line in /etc/sudoers as well.
Since you're using php's shell_exec(), be very careful about the arguments your code feeds to that command.  If you let the user put whatever he wants in there, he can have it do anything.
Suppose your command is "userdel $user" and $user came directly from the user of this web page.  If user="foo ; reboot".  If this was being run as root ... your computer would reboot.  But even if not run as root, he could run code as the apache user that could attempt to get into the machine.
That said, how to properly sanitize your inputs is a longer topic than this simple answer really allows -- I'm not really trying to cover that entire topic, just to touch on it.


Q: Java: changing the order of lines with while-loop I am new to programming and I would like to ask what should I do so that the final value of k  will appear before the values of a, when I try to put it inside the loop it repeats the statement and when I put it before the loop, its value is 0.
    System.out.printf("Input an integer: ");
    int a = in.nextInt();
    int k = 0;

    System.out.print(a);
    while(a > 1)
    {
        if(a % 2 == 0)
            a = a / 2;
        else
            a = 3 * a + 1;
        System.out.printf(", " + a);
        k++;
    }
    System.out.println("\nk = " + k);

    Output:
    Input an integer: 10
    10, 5, 16, 8, 4, 2, 1
    k = 6

A: You could try:
    System.out.printf("Input an integer: ");
    int a = in.nextInt();
    int k = 0;
    String str_a = "";

    System.out.print(a);
    while(a > 1)
    {
        if(a % 2 == 0)
            a = a / 2;
        else
            a = 3 * a + 1;
        str_a += ", " + String.valueOf(a);
        k++;
    }
    System.out.println("k = " + k);
    System.out.println("a = " + str_a);


Q: javascript/jquery: focus() not working I want to focus a special id (in roundcube) by a keyboard shortcut. The html is
   ...

    ...

I tried the following:
 // Strg + Tab, um in Nachrichtenbereich zu kommen
 ...
 else if (event.keyCode == 9 && event.ctrlKey) {
 alert("taste erkannt");
 //document.getElementById("messagetoolbar").focus();
 //$("#messagetoolbar").focus();
 setTimeout(function() { $('#messagetoolbar').focus(); alert("zeit"); }, 3000);
 }
 ...

The first alert and the second alert is shown but no focus on id messagetoolbar. Does anybody have an idea?
Thank you very much.
Edit: I think I should describe it better: I want to mark the first line/email in the email-inbox in roundcube. The inbox is a table with a tr-tag...when I try your solution the first line is dotted, too, but with enter I can't open the mail and with other keys I can't MARK the first line/mail... I think I have to "simulate a left-klick" to get the first line marked...?
Now I tried to use jquery's .trigger. The html of the inbox-Table is

         16.04.2014 13:41

 ...

I tried to use...
 $('#messagelist tr').eq(1).addClass('message selected focused').removeClass('unfocused').trigger("click");

...but it doesn't work: It adds an removes the classes but doesn't really focus the line  :-( With "buttons" it works.
EDIT AGAIN: I think the file list.js of roundcube is important for that question. There I found the following:
/**
 * Set focus to the list
 */
focus: function(e)
{
  var n, id;
  this.focused = true;

  for (n in this.selection) {
    id = this.selection[n];
    if (this.rows[id] && this.rows[id].obj) {
      $(this.rows[id].obj).addClass('selected').removeClass('unfocused');
    }
  }

  // Un-focus already focused elements (#1487123, #1487316, #1488600, #1488620)
  // It looks that window.focus() does the job for all browsers, but not Firefox (#1489058)
  $('iframe,:focus:not(body)').blur();
  window.focus();

  if (e || (e = window.event))
    rcube_event.cancel(e);
},

Does anybody know how to modify or use referring to my question? Thank you!

A: Add tabindex=0 attribute to the div you want to foucs and you will be able to set focus on the div using .focus()

A: You can not focus controls like div, span etc. You can move to that div if required using book marks.

A: Do you want to highlight the div then you can use the jquery and following code to give highlight effect.
$("div").click(function () {
  $(this).effect("highlight", {}, 3000);
});

A: Good morning,
I've read a few times now, that one can't focus table rows but only can focus elements, which accepts input by the user. Otherwise I think there must be a way to simulate a click on a table row by jquery/javascript!  I tried the following:
document.onkeydown = function(event) {
  ...
  else if (event.keyCode == 9 && event.ctrlKey) {
   $('#messagelist tr').on('click', function () {
    alert('I was clicked');
    });
    $('#messagelist tr').eq(1).click();
  }
...
}

The alert is shown! But the row isn't "marked"!?


Q: remove code duplication in java with custom getter This question isnt about selenium, but java in general
I have the scenario below, while trying to setup an automation framework using selenium and page object model -
public class SigninPage {

    WebDriver driver;

    private By emailInputSelector = By.id("user_email");
    private By passwordInputSelector = By.id("user_password");
    private By signinBtnSelector = By.xpath("//input[@value='Log In']");
    private By errorDivSelector = By.xpath("//div[@role='alert']");
    private By headerLinksSelector = By.className("nav-link");

    public SigninPage(WebDriver driver) {
        this.driver = driver;
    }

    public WebElement emailInput() {
        return driver.findElement(emailInputSelector);
    }

    public WebElement passwordInput() {
        return driver.findElement(passwordInputSelector);
    }

    public WebElement signinBtn() {
        return driver.findElement(signinBtnSelector);
    }

    public WebElement errorDiv() {
        return driver.findElement(errorDivSelector);
    }

    public List<WebElement> headerElement() {
        return driver.findElements(headerLinksSelector);
    }

}

as you can see, all my methods like headerElement() etc are doing the same thing - driver.findElement(selector) or sometimes driver.findElements(selector)
I want to remove this code duplication, like lombok provides @Getter.
What is my best bet to achieve this?


Q: What do I need to style for the page after wp_get_archives? http://summitcoach.web.dmitcapstone.ca/
Just a development server for now, but on the blog page I have links for monthly archives but they go to some page I believe is date.php and I just want the posts to display as they do on the blog page, but only for that month. For some reason I can't find a single thing online about this.
Thanks.

A: According to the Template Hierarchy, archives are usually displayed using the theme's archive.php file, although other template pages might be used instead (see the image on that page).
So, you would need to change your theme's archive.php file, or change the font-page.php or home.php template (again, see the image on the above page).
I suspect that the home.php template file is set up differently than the archive.php template. Change the archive.php file to match what you need.
Of course, Child Themes are the best to do this change, as you don't want to change a theme's files - any changes will be overwritten with a theme update.


Q: HTML5 Dynamic Video Background here is my code

$("body").prepend("
<video loop muted autoplay class='fullscreen-bg__video' ><source src='https://www.iresearchservices.com/wp-content/uploads/2018/03/bgvideo.mp4' type='video/mp4'></video>
")

and its working fine. but what i need is, I want to call a function say remove-pre-loader(), once the video is loaded.
i have a per-loader screen, i want to remove the pre-loader once the video is loaded.

A: You can use loadeddata or canplaythrough event to check whether the browser has loaded the current frame of the audio/video. See a full list of possible video events here

$("body").prepend(
  "
<video loop muted autoplay class='fullscreen-bg__video' ><source src='https://www.iresearchservices.com/wp-content/uploads/2018/03/bgvideo.mp4' type='video/mp4'><source src='https://www.iresearchservices.com/wp-content/uploads/2018/03/bgvideo.mp4' type='video/mp4'><source src='https://www.iresearchservices.com/wp-content/uploads/2018/03/bgvideo.mp4' type='video/mp4'></video>
"
);
$(".fullscreen-bg__video").on("loadeddata", function () {
        alert("Video Loaded")
    });
.fullscreen-bg {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: hidden;
    z-index: -100;
}

.fullscreen-bg__video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

@media (min-aspect-ratio: 16/9) {
  .fullscreen-bg__video {
    width: 100%;
    height: auto;
  }
}

@media (max-aspect-ratio: 16/9) {
  .fullscreen-bg__video {
    width: auto;
    height: 100%;
  }
}
@media (min-aspect-ratio: 16/9) {
  .fullscreen-bg__video {
    height: 300%;
    top: -100%;
  }
}

@media (max-aspect-ratio: 16/9) {
  .fullscreen-bg__video {
    width: 300%;
    left: -100%;
  }
}


Q: Ubuntu 16.04 LAN is not detected I am using Ubuntu 16.04 LTS with i3 desktop environment. My ifconfig command shows the following output-
docker0   Link encap:Ethernet  HWaddr 02:42:49:4f:16:2a
          inet addr:172.17.0.1  Bcast:172.17.255.255  Mask:255.255.0.0
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

eno1      Link encap:Ethernet  HWaddr b0:5a:da:d9:a8:24
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:1652 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1652 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:124400 (124.4 KB)  TX bytes:124400 (124.4 KB)

wlo1      Link encap:Ethernet  HWaddr 48:e2:44:00:86:ed
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

Few days ago, I have updated my kernel and my system was unable to detect LAN. To solve that, I found a solution from askubuntu as-
Solution 1
nmcli networking off && nmcli networking on

Now it worked fine for some days. Then I probably have updated my system(I forgot) and it stopped working. Again I found another solution to detect LAN.
Solution 2
sudo service network-manager restart

Then it worked perfectly fine. I don't know, after some days, Solution 2 stopped working. So I found some random solution from internet, and it worked.
Solution 3
sudo ifconfig eno1 down
sudo ifconfig wlo1 down
sudo ifconfig docker0 down
sudo ifconfig lo down
sudo service network-manager restart

And after some days, it stopped working. Now I had to restart my system for LAN to work. And again that solution was for only some days. Now I am unable to find any other solutions which will keep my LAN port working. My system info is-
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.6 LTS
Release:    16.04
Codename:   xenial

I have explained the whole scene, because I had no idea about where the problem is. And I had tried every random solution from internet, as long as it was working. Please try to guess the actual problem, because it is getting worse day by day. If you need any other info, do mention in the comment section.
PS- I am sure it is a software problem. I have dual boot, and in windows, LAN is working perfectly fine.


Q: configuring Nagios with check_by_ssh I am trying to configure Nagios to use "check_by_ssh" plugin, to monitor if the service "mpg123" is running on a remote Linux computer.

*

*I have Configured passwordless login between Nagios server & client

*Defined the command to check if the process is running.

/usr/local/nagios/etc/objects/check_music.cfg
define command {
        command_name    check_music
        command_line    $USER1$/check_by_ssh -H $HOSTADDRESS$ -C "pgrep mpg123 > /dev/null && echo YES || echo NO"
}

*

*Created the host definition file

/usr/local/nagios/etc/objects/client002.cfg
define host{
        use                     linux-server
        host_name               client002
        alias                   Client002
        address                 192.168.1.52
        }

define service{
        use                    generic-service
        host_name              client002
        service_description    Music
        check_command          check_music
        }

*

*Configured Nagios to know where to look for these files

/usr/local/nagios/etc/nagios.cfg
cfg_file=/usr/local/nagios/etc/objects/client002.cfg
cfg_file=/usr/local/nagios/etc/objects/check_music.cfg

My problem is that under Services in Nagios, I get a message saying:
Remote command execution failed: Could not create directory '/home/nagios/.ssh'.


Q: Weak star topology on a finite dimensional space coincides with the standart topology I want to show that if $X$ is a finite dimensional normed space, then $*$-weak topology on $X^*$ coincides with the standard topology.
First of all, if $X$ is finite dimensional then $\mbox{dim}X = \mbox{dim}X^*$ and $X^*$ is also finite dimensional. Denote by $\tau^*$ the weak star topology on $X^*$ and by $\tau$ its standard topology. To show that they coincide means to show that $\tau = \tau^*$.
Why $\tau^* \subseteq \tau$? It is obvious directly from the definition of $*$-weak topology that every $U \in \tau^*$ is an open subset in ordinary meaning because we want every $ev_x\colon X^*\to \mathbb{C}$ be a continuous map and that inclusion takes place even in infinite dimensional case.
But why $\tau \subseteq \tau^*$ and how should I use that $X^*$ is finite dimensional? Can someone show me a proof of this inclusion?

A: Without loss of generality we can assume that $X = \mathbb K^n$. It suffices to show that each element of a base of $\tau$ is also in $\tau^\ast$. As a base we can use sets of the form $U = \prod_{i=1}^n(a_i,b_i)$ with $a_i<b_i$ for each $i$. Let $\pi_i\in X^\ast$ be the $i$-th canonical projection. Then $U = \bigcap_{i=1}^n {\pi_i}^{-1}(a_i,b_i)$, hence $U\in \tau^\ast$.


Q: Wordpress - Display array data of a child I've used the wordpress plugin - advanced custom field and would like to show an array of a child, here's my code:
I'm using this code to show the custom fields data from a specific page ID's children:
<?php $args = array(
    'depth'        => 0,
    'child_of'     => 411 );
$pages = get_pages(array('child_of'));

foreach($pages as $post)
{
setup_postdata($post);
$fields = get_fields();
if($fields->company_name != "") : ?>

<?php echo $fields->company_name; ?>

<?php else : ?>
<?php endif; ?>
<?php
}

wp_reset_query();
?>

This is the code I'm using to show the checkbox data of the page itself (i.e it's not a parent/child):
<?php $catNames = array( 'branding','creative','development','exhibition','packaging','print','seo','social_media','usability','web','advertising','campaign','content','feasibility','publishing','research','strategy');

    foreach($catNames as $name){
        if(in_array($name, get_field('categories') )){
            echo ''.ucwords($name).'';
        }
    }
?>

I want to combine the two together so underneath the H2 tag in the first code box I want to show the checkbox data of the child, how can this be done?
UPDATE:
When I add the checkbox code to the child code, I can't get the data to display, it's either blank or has an error.
This is the page I'm working on. The first thumbnail has been hardcoded, the second and third thumbnails should pick up the tags with the code above but it doesn't.

A: This will show the checkboxes that have been ticked (much simpler!!):
                    <?php
$categories = get_field('categories');
$elements = array();
foreach($categories as $category) {
    //do something
    $elements[] = '' . $category .'';
}
echo implode(',', $elements);
?>

A: Try this code:
<?php $args = array(
    'depth'        => 0,
    'child_of'     => 411 );
$pages = get_pages(array('child_of'));
$catNames = array( 'branding','creative','development','exhibition','packaging','print','seo','social_media','usability','web','advertising','campaign','content','feasibility','publishing','research','strategy');
foreach($pages as $post){
    setup_postdata($post);
    $company = get_field('company_name',$post->ID);
    if( $company != "") {
       echo '
'.$company.'
';
       foreach($catNames as $key => $val){
            if(in_array($val, get_field('categories',$post->ID) )){
                echo ''.ucwords($val).'';
            }
        }
    }
}
wp_reset_query();
?>


Q: Normal distance Recently, I saw a paper "G. H. Darwin, Periodic Orbits" and I don't undertand the concept of "normal displacement $\delta$p".
"...
Now suppose that x, y are the coordinates of a point on an orbit,  and that x + $\delta$ x, y + $\delta$ y are the coordinates of a point on an adjacent orbit. Then if we put
$\delta$p = $\delta$x cos $\phi$ + $\delta$y sin $\phi$
$\delta$s = -$\delta$x sin $\phi$ + $\delta$y cos $\phi$
$\delta$p, $\delta$s as are the distances, measured along the outward normal and along the arc of the unvaried orbit, from the original point x, y to the adjacent point x + $\delta$x, y +$\delta$y."
$\phi$ is a angle between outward normal and x-axis. Someone can help me to understand.
Appreciate.

A: I searched online to find a copy of the paper you're referring to at Periodic Orbits - 1485881980, with the particular section you're asking about being on page $36$. My understanding is that the "normal displacement $\delta p$" is basically the perpendicular change in distance between a periodic orbit $s$ and a

... path which varies by infinitely little from that of the periodic orbit.

as stated on page $35$ in that paper.
Although you didn't explicitly ask for clarification of the equations, you included a copy of them so I assume you may want to understand them. I'm also explaining them below so you can see how the various aspects interact. The following diagram illustrates what the author is talking about.

Here, the center is far off the lower-left corner of the diagram, the red line indicates the periodic orbit and the green line the infinitesimally perturbed orbit. $ABDE$ is a rectangle, with $EC$ being parallel to the $x$-axis. Also, $A(x,y)$ is a point on the periodic orbit and $D(x + \delta x, y + \delta y)$ is a point on the perturbed orbit. In addition, $AB$ and $ED$ is normal to the periodic orbit at $A$, with length $\delta p$, plus $AE$ and $BD$ are parallel to the periodic orbit arc at $A$, with length $-\delta s$. Note this assumes the orbit is counter-clockwise, so this is why the graph uses $-\delta s$ instead of $\delta s$.
Note that, as shown, $\angle DEC = \phi$, so $\angle CEA = \frac{\pi}{2} - \phi$. To make things somewhat simpler, horizontally and vertically translate $ABDE$ so $A$ is at the origin, i.e., $x = y = 0$. To convert from $(x,y)$ co-ordinates to $(p,-s)$ co-ordinates requires a counter-clockwise rotation of $\frac{\pi}{2} - \phi$, so $D(\delta x, \delta y)$ will then be mapped to $D'(-\delta s, \delta p)$. The formula for converting from $(x,y)$ by a counter-clockwise rotation of $\theta$ to $(x',y')$ is, as given in the Two Dimensions section of Wikipedia's article on Rotation:
\begin{align}
x'&=x\cos \theta -y\sin \theta \\
y'&=x\sin \theta +y\cos \theta \tag{1}\label{eq1}
\end{align}
For the case here, $\theta = \frac{\pi}{2} - \phi$, $x = \delta x$, $y = \delta y$, $x' = -\delta s$ and $y' = \delta p$. Thus, the first equation of \eqref{eq1} becomes
\begin{align}
-\delta s & = \delta x \cos\left(\frac{\pi}{2} - \phi\right) - \delta y \sin\left(\frac{\pi}{2} - \phi\right) \\
& = \delta x \sin\phi - \delta y \cos\phi \tag{2}\label{eq2}
\end{align}
Multiplying both sides by $-1$ gives
$$\delta s = - \delta x \sin\phi + \delta y \cos\phi \tag{3}\label{eq3}$$
The second equation of \eqref{eq1} becomes
\begin{align}
\delta p & = \delta x \sin\left(\frac{\pi}{2} - \phi\right) + \delta y \cos\left(\frac{\pi}{2} - \phi\right) \\
& = \delta x \cos\phi + \delta y \sin\phi \tag{4}\label{eq4}
\end{align}
As you can see, \eqref{eq3} and \eqref{eq4} match the $2$ equations you're asking about.


Q: How can I get a regex to check that a string only contains alpha characters [a-z] or [A-Z]? I'm trying to create a regex to verify that a given string only has alpha characters a-z or A-Z. The string can be up to 25 letters long. (I'm not sure if regex can check length of strings)
Examples:
1. "abcdef" = true;
2. "a2bdef" = false;
3. "333" = false;
4. "j" = true;
5. "aaaaaaaaaaaaaaaaaaaaaaaaaa" = false; //26 letters
Here is what I have so far... can't figure out what's wrong with it though
Regex alphaPattern = new Regex("[^a-z]|[^A-Z]");
I would think that would mean that the string could contain only upper or lower case letters from a-z, but when I match it to a string with all letters it returns false...
Also, any suggestions regarding efficiency of using regex vs. other verifying methods would be greatly appreciated.

A: /// <summary>
/// Checks if string contains only letters a-z and A-Z and should not be more than 25 characters in length
/// </summary>
/// <param name="value">String to be matched</param>
/// <returns>True if matches, false otherwise</returns>
public static bool IsValidString(string value)
{
    string pattern = @"^[a-zA-Z]{1,25}$";
    return Regex.IsMatch(value, pattern);
}

A:
The string can be up to 25 letters long.
  (I'm not sure if regex can check length of strings)

Regexes ceartanly can check length of a string - as can be seen from the answers posted by others.
However, when you are validating a user input (say, a username), I would advise doing that check separately.
The problem is, that regex can only tell you if a string matched it or not. It won't tell why it didn't match. Was the text too long or did it contain unallowed characters - you can't tell. It's far from friendly, when a program says: "The supplied username contained invalid characters or was too long". Instead you should provide separate error messages for different situations.

A: The regular expression you are using is an alternation of [^a-z] and [^A-Z]. And the expressions [^…] mean to match any character other than those described in the character set.
So overall your expression means to match either any single character other than a-z or other than A-Z.
But you rather need a regular expression that matches a-zA-Z only:
[a-zA-Z]

And to specify the length of that, anchor the expression with the start (^) and end ($) of the string and describe the length with the {n,m} quantifier, meaning at least n but not more than m repetitions:
^[a-zA-Z]{0,25}$

A: Regex lettersOnly = new Regex("^[a-zA-Z]{1,25}$");

*

*^ means "begin matching at start of string"

*[a-zA-Z] means "match lower case and upper case letters a-z"

*{1,25} means "match the previous item (the character class, see above) 1 to 25 times"

*$ means "only match if cursor is at end of string"

A:
I'm trying to create a regex to verify that a given string only has alpha
  characters a-z or A-Z.

Easily done as many of the others have indicated using what are known as "character classes".  Essentially, these allow us to specifiy a range of values to use for matching:
(NOTE: for simplification, I am assuming implict ^ and $ anchors which are explained later in this post)
[a-z]   Match any single lower-case letter.
ex: a matches, 8 doesn't match
[A-Z]   Match any single upper-case letter.
ex: A matches, a doesn't match
[0-9]   Match any single digit zero to nine
ex: 8 matches, a doesn't match
[aeiou] Match only on a or e or i or o or u.
ex: o matches, z doesn't match
[a-zA-Z]  Match any single lower-case OR upper-case letter.
ex:  A matches, a matches, 3 doesn't match
These can, naturally, be negated as well:
[^a-z]  Match anything that is NOT an lower-case letter
ex: 5 matches, A matches, a doesn't match
[^A-Z]  Match anything that is NOT an upper-case letter
ex: 5 matches, A doesn't matche, a matches
[^0-9]  Match anything that is NOT a number
ex: 5 doesn't match, A matches, a matches
[^Aa69] Match anything as long as it is not A or a or 6 or 9
ex: 5 matches, A doesn't match, a doesn't match, 3 matches
To see some common character classes, go to:
http://www.regular-expressions.info/reference.html

The string can be up to 25 letters long.
  (I'm not sure if regex can check length of strings)

You can absolutely check "length" but not in the way you might imagine.  We measure repetition, NOT length strictly speaking using {}:
a{2}  Match two a's together.
ex:  a doesn't match, aa matches, aca doesn't match
4{3}  Match three 4's together.
ex:  4 doesn't match, 44 doesn't match, 444 matches, 4434 doesn't match
Repetition has values we can set to have lower and upper limits:
a{2,}  Match on two or more a's together.
ex:  a doesn't match, aa matches, aaa matches, aba doesn't match, aaaaaaaaa matches
a{2,5} Match on two to five a's together.
ex:  a doesn't match, aa matches, aaa matches, aba doesn't match, aaaaaaaaa doesn't match
Repetition extends to character classes, so:
[a-z]{5}  Match any five lower-case characters together.
ex:  bubba matches, Bubba doesn't match, BUBBA doesn't match, asdjo matches
[A-Z]{2,5}  Match two to five upper-case characters together.
ex:  bubba doesn't match, Bubba doesn't match, BUBBA matches, BUBBETTE doesn't match
[0-9]{4,8}  Match four to eight numbers together.
ex:  bubba doesn't match, 15835 matches, 44 doesn't match, 3456876353456 doesn't match
[a3g]{2}  Match an a OR 3 OR g if they show up twice together.
ex:  aa matches, ba doesn't match, 33 matches, 38 doesn't match, a3 DOESN'T match
Now let's look at your regex:
[^a-z]|[^A-Z]
Translation:  Match anything as long as it is NOT a lowercase letter OR an upper-case letter.
To fix it so it meets your needs, we would rewrite it like this:
Step 1:  Remove the negation
[a-z]|[A-Z]
Translation: Find any lowercase letter OR uppercase letter.
Step 2:  While not stricly needed, let's clean up the OR logic a bit
[a-zA-Z]
Translation: Find any lowercase letter OR uppercase letter.  Same as above but now using only a single set of [].
Step 3:  Now let's indicate "length"
[a-zA-Z]{1,25}
Translation: Find any lowercase letter OR uppercase letter repeated one to twenty-five times.
This is where things get funky.  You might think you were done here and you may well be depending on the technology you are using.
Strictly speaking the regex [a-zA-Z]{1,25} will match one to twenty-five upper or lower-case letters ANYWHERE on a line:
[a-zA-Z]{1,25}
a matches, aZgD matches, BUBBA matches, 243242hello242552 MATCHES
In fact, every example I have given so far will do the same.  If that is what you want then you are in good shape but based on your question, I'm guessing you ONLY want one to twenty-five upper or lower-case letters on the entire line.  For that we turn to anchors.  Anchors allow us to specify those pesky details:
^ beginning of a line
(I know, we just used this for negation earlier, don't get me started)
$ end of a line
We can use them like this:
^a{3}  From the beginning of the line match a three times together
ex:  aaa matches, 123aaa doesn't match, aaa123 matches
a{3}$  Match a three times together at the end of a line
ex:  aaa matches, 123aaa matches, aaa123 doesn't match
^a{3}$  Match a three times together for the ENTIRE line
ex:  aaa matches, 123aaa doesn't match, aaa123 doesn't match
Notice that aaa matches in all cases because it has three a's at the beginning and end of the line technically speaking.
So the final, technically correct solution, for finding a "word" that is "up to five characters long" on a line would be:
^[a-zA-Z]{1,25}$
The funky part is that some technologies implicitly put anchors in the regex for you and some don't.  You just have to test your regex or read the docs to see if you have implicit anchors.

A: Do I understand correctly that it can only contain either uppercase or lowercase letters?
new Regex("^([a-z]{1,25}|[A-Z]{1,25})$")

A regular expression seems to be the right thing to use for this case.
By the way, the caret ("^") at the first place inside a character class means "not", so your "[^a-z]|[^A-Z]" would mean "not any lowercase letter, or not any uppercase letter" (disregarding that a-z are not all letters).


Q: How to list files and file sizes of a zip archive? Suppose I have a ZIP archive myfiles.zip. To list the files inside the ZIP file, I could do zip -sf myfiles.zip, which results in:
Archive contains:
  files/mypic.jpg
  files/myvideo.mp4
Total 2 entries (12345678 bytes)

Is there a way to list these files together with their file sizes? For example:
Archive contains:
  files/mypic.jpg  1234
  files/myvideo.mp4  456789
  ...

A: You can use command like:
unzip -lv myfiles.zip

Here is example output of this command:
# unzip -lv zz.zip
Archive:  zz.zip
 Length   Method    Size  Cmpr    Date    Time   CRC-32   Name
--------  ------  ------- ---- ---------- ----- --------  ----
      94  Defl:N       79  16% 02-18-2020 08:53 7be876f8  z1
     539  Defl:N      218  60% 02-18-2020 08:54 34711128  z2
    3234  Defl:N      250  92% 02-19-2020 14:06 46aba2a1  z3
--------          -------  ---                            -------
    3867              547  86%                            3 files


Q: How to set unique for specific field from specific table? I have this where i have all features from database:
$features = Feature::all();

User can add new additional feature that will be added in this table, but i want to validate so if user enter something that is already in databse to get a message. So name need to be unique. Any suggestion how can i do that?
I tried this but it save it anyway.
 $this->validate($request, [
        'name' => 'unique:features',
    ]);

A: From the docs

unique:table,column,except,idColumn
The field under validation must be unique in a given database table. If the column option is not specified, the field name will be used.
Specifying A Custom Column Name:
'email' => 'unique:users,email_address'

You may need to specify the column to be checked against.

A:  $feauturescheck= Feauture::where('Columname', '=',Input::get('input'))->count();


Q: is there Material increment/decrement Button implementation for Android? is there by any chance a Material design implementation for increment/decrement button ? image for illustration

A: No, but it's quite simple to implement, you only need a linear layout with horizontal orientation, containing a button, a textview and another button.
Have an internal value to count and then associate a callback to your buttons, where you add/substract your counter and update the textview, like this:
substractButton.setOnClickListener(v -> {
  count--;
  countTextView.setText(count);
});
sumButton.setOnClickListener(v -> {
  count++;
  countTextView.setText(count);
});


Q: JSOUP parse for android force closes I am trying to use JSOUP to get the menu data from a website (http://hdh.ucsd.edu/mobile/dining/locationdetails.aspx?l=11) but whenever I try to fetch the links, my android app crashes. What is the reason? This is the code I have
public class SixthFragment extends Fragment {

String url = "http://hdh.ucsd.edu/mobile/dining/locationdetails.aspx?l=11";
ProgressDialog mProgressDialog;
String MENU;
String HOURS;
TextView textview;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_sixth, container, false);
    textview = (TextView) rootView.findViewById(R.id.textView10);

    new JSOUP().execute();
    return rootView;

}

public class JSOUP extends AsyncTask<Void, Void, Void>{
    ProgressDialog dialog;

    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        dialog = new ProgressDialog(getActivity());
        dialog.setMessage("loading...");
        dialog.show();

    }

    @Override
    protected Void doInBackground(Void... params){
        try{

            Document document = Jsoup.connect(url).get();
            Elements elements = document.select("a[href]");
            //HOURS = elements.text();
            System.out.println(elements.size());
            for(int i = 0; i<elements.size(); i++){

                MENU += "\n" + elements.get(i).text();
                System.out.println(i);

            }

        }

        catch (Exception e){

        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result){
        dialog.dismiss();

        textview.setText(MENU);
        super.onPostExecute(result);
    }

}

}

And my error shows up as this
11-28 13:48:59.175 23230-23230/com.lamdevs.tritonbites E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.lamdevs.tritonbites, PID: 23230
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.lamdevs.tritonbites.fragments.SixthFragment$JSOUP.onPostExecute(SixthFragment.java:82)
at com.lamdevs.tritonbites.fragments.SixthFragment$JSOUP.onPostExecute(SixthFragment.java:43)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Which I don't understand because elements has a size of 61 when I output the size of elements. Also, is there a way to get the breakfast, lunch, and dinner separately? Thank you

A: Please post your layout XML R.layout.fragment_sixth. Probably you're referring to a wrong id, which causes de NullPointerException.

To get each "Breakfast", "Lunch" and "Dinner" separately, you can simply iterate through the last three <div> tags inside the HTML element with id MainContent_divDailySpecials (I did find that id looking at the website DOM structure through Chrome Developer Tools inspector).
So, as a start, simply grab that element with
Document document = Jsoup.connect(url).get();
Element parentDiv = document.getElementById("MainContent_divDailySpecials");

and from there on you can iterate backwards to get the last three children of that div. (Please keep in mind that if, in any point in time, the structure of that page changes your code will break).

A: Looking at the error log you attached ..
java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.lamdevs.tritonbites.fragments.SixthFragment$JSOUP.onPostExecute(SixthFragment.java:82)

It talks about a NullPointerException on a TextView in SixthFragment Line 82 i.e. textview.setText(MENU);
The textview is initialized (textview = (TextView) rootView.findViewById(R.id.textView10);) which looks okay.
So, make sure you have a TextView with id textView10 in your layout fragment_sixth.


Q: How to change Ruby and Rails version for the Rails base Docker image? Docker base image rails provides a full environment for Ruby on Rails. It pulls from the ruby upstream image. The rails base image specifies Ruby and Ruby on Rails versions.
What if we want to use different Ruby and Ruby on Rails versions?
Do we edit our Dockerfile in our project folder? Or, do we ssh into the machine, and install the ruby version we want and then build our own image?
Further details:
The rails base image documentation says that your doc file can simply be one line of code:
FROM rails:onbuild

This line of code pulls from the rails image on Docker Hub. This image has its own Dockerfile. The first line of this Dockerfile is FROM ruby:2.2.
Just to restate the question, what is the best way to create a container based off of the rails image, with different Ruby and Ruby on Rails versions? If possible, some sample code might be helpful for understanding how to do this.

A: I assume you want a docker image that is suiteable for plenty of rails apps.
I do not know docker at all, but maybe ignore what Docker offers to you, and do it yourself:
Create an image with all great ruby versions, maybe 1.9 and 2.3,
but i think you should just stick with latest ruby.

Use https://github.com/rbenv/rbenv to provide a ruby env

Every Rails applications usually ships with a Gemfile.
In production releases, the gem versions are locked in the Gemfile.lock file.
In case the gems need an update, you will need to update the app code and then the gems with
bundle install

So i think it´s not possible to have a docker "one-fits-all" image for plenty of rails apps nicely.
Something i do when installing productive rails apps is to install their gems in the app folder.
bundle install --path vendor/bundle

This puts the gem apps inside their vendor directory. I see no big chance here either to make update life easier.

As i never tried docker, or even visited their website, my post might be useless (sry)
I hope i understood your intentions, at least.


Q: How can I download the oldest file of an FTP server? How can I download the oldest file of an FTP server?
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://192.168.47.1/DocXML");
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential("Igor", "");

FtpWebResponse response = (FtpWebResponse)request.GetResponse();

Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);

string names = reader.ReadLine();

textBox12.Text = names;

A:
How can I download the oldest file of an FTP server?

Using WebRequestMethods.Ftp.ListDirectoryDetails
This will issue an FTP LIST command with a request to get the details on the files in a single request. This does not make things easy though because you will have to parse those lines, and there is no standard format for them.
Depending on the ftp server, it may return lines in a format like this:
08-10-11  12:02PM       <DIR>          Version2
06-25-09  02:41PM            144700153 image34.gif
06-25-09  02:51PM            144700153 updates.txt
11-04-10  02:45PM            144700214 digger.tif

Or
d--x--x--x    2 ftp      ftp          4096 Mar 07  2002 bin
-rw-r--r--    1 ftp      ftp        659450 Jun 15 05:07 TEST.TXT
-rw-r--r--    1 ftp      ftp     101786380 Sep 08  2008 TEST03-05.TXT
drwxrwxr-x    2 ftp      ftp          4096 May 06 12:24 dropoff

Or even another format.
This blog post "Sample code for parsing FtpwebRequest response for ListDirectoryDetails" provides an example of handling several formats.
If you know what the format is, just create a custom minimal line parser for it.
Using WebRequestMethods.Ftp.ListDirectory with WebRequestMethods.Ftp.GetDateTimestamp
This is easier, but the downside is that it requires you to submit several requests to find out the last modification dates for the directory entries.
This will get you a list of file and directory entries with names only, that is easier to parse.
public static IEnumerable<string> ListDirectory(string uri, NetworkCredential credentials)
{
    var request = FtpWebRequest.Create(uri);
    request.Method = WebRequestMethods.Ftp.ListDirectory;
    request.Credentials = credentials;
    using (var response = (FtpWebResponse)request.GetResponse())
    using (var stream = response.GetResponseStream())
    using (var reader = new StreamReader(stream, true))
    {
        while (!reader.EndOfStream)
            yield return reader.ReadLine();
    }
}

Then for each file you can get the last modification date by issuing a request per file:
public static DateTime GetLastModified(string fileUri, NetworkCredential credentials)
{
    // error checking omitted
    var request = FtpWebRequest.Create(fileUri);
    request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
    request.Credentials = credentials;
    using (var response = (FtpWebResponse)request.GetResponse())
        return response.LastModified;
}

Now you can simply do the following to get a list of files with their last modification date.
var credentials = new NetworkCredential("Igor", "");
var filesAndDates = ListDirectory("ftp://192.168.47.1/DocXML", credentials)
    .Select(fileName => new {
        FileName = fileName,
        LastModified = GetLastModified("ftp://192.168.47.1/DocXML/" + fileName, credentials)
    })
    .ToList();
// find the oldest entry.
var oldest = filesAndDates.OrderBy(x => x.LastModified).FirstOrDefault();


Q: is SICP still recommended? I have some experience with python, I asked for a new language, and said that i am having a hard time implementing what I have learned. they suggested I learn SICP. Saying it uses a great language and teaches great programming fundamentals.
But I notice it was published in 1984. Do you guys recommend it, or have I been trolled? :p
Thanks.

A: Yes, SICP is still a great book! The second edition, which is available online, as of 1996. Although, if you just want to learn Scheme instead of fundamental computer science, you might be better off with Teach Yourself Scheme in Fixnum Days.

A: I strongly encourage you to check out the book How to Design Programs.  It focuses on the fundamentals of programming, not on the specific language, but it also uses Scheme as its language.  It's also available free online.
You can also check out the current release of the second edition, which is in preparation (or the less-stable but more up-to-date current draft).

A: Firstly, you're loooking at the first edition. The second edition is from 1996.
You should VERY MUCH tackle the book. I've gone through about half and my mind is blown. I can't begin to explain how amazing it is. Not only will you develop an appreciation for elegance in programming, but you'll see the line blurred between coding and computer science.
Don't approach this book like a programming book. Approach it as if you want to learn the fundamentals of computation and computer science using programming as a means of expression.

A: SICP is one of the best books I've read for learning how to write programs well.  I never used scheme outside of the work I did in that book, but it's well worth your time.


Q: Normalize samples with ffmpeg I am writing application for music analysis. I wrote resampling module relying on ffmpeg. Currently, I have AV_SAMPLE_FMT_S16 but later I have converting to float, which can be time consuming.
Because I need samples to be in some reasonable interval I need to do some kind of normalization, for AV_SAMPLE_FMT_FLT samples.
So, how I can normalize samples which I get when I select AV_SAMPLE_FMT_FLT. Ideal interval would be -n to n, where n is greater than equal of 1.f

A: Given that AV_SAMPLE_FMT_FLT is already normalised to the -1 .. 1 range, we can multiply each sample by your 'n' value to have it scaled between -n .. n


Q: error on string literal jsp So I want to create charts from jsp using fusioncharts. I'd choose fusioncharts then JFree, canvasjs or any other because I'd experiences using it in php language. It should be no problem in jsp because jsp and php are literally same, mapping above html, with only differences is their syntax. However, as I've done the code, it return String literal is not properly closed by a double-quote error on sql statement. Please help me because I am a beginner to jsp and java environment. Thank you.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*" %>
<%@page import="java.util.*" %>
<%@page import="com.google.gson.*" %>
<%@page import="readConfig.readConfig" %>

<%
String hostdb = readConfig.getProperties("conUrl");              // MySQl host
String userdb = readConfig.getProperties("dbUser");              // MySQL username
String passdb = readConfig.getProperties("dbPass");                 // MySQL password
String driver = readConfig.getProperties("dbDriver");           // MySQL driver

DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection con = DriverManager.getConnection(hostdb , userdb , passdb);

%>

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Creating Charts with Data from a Database - fusioncharts.com</title>

    <%@page import="fusioncharts.FusionCharts" %>

    <%
        Gson gson = new Gson();

        String sql= "SELECT m.month,IFNULL(x.cnt, 0) AS cnt FROM
(SELECT 1 AS month UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) AS m
LEFT JOIN (SELECT DATE_FORMAT(date, '%c') as month, COUNT(*) AS cnt FROM ssl_sales where YEAR(date)=2017 AND status_ssl='new' GROUP BY month) AS x ON m.month = x.month
ORDER BY m.month DESC";

        PreparedStatement pt=con.prepareStatement(sql);
        ResultSet rs=pt.executeQuery();

        Map<String, String> chartobj = new HashMap<String, String>();

        chartobj.put("caption", "Top 10 most populous countries");
        chartobj.put("showValues", "0");
        chartobj.put("theme", "zune");

        ArrayList arrData = new ArrayList();
        while(rs.next()) {
            Map<String, String> lv = new HashMap<String, String>();
            lv.put("label", rs.getString("Monthly"));
            lv.put("value", rs.getString("New Demand"));
            arrData.add(lv);
        }

        rs.close();

         Map<String, String> dataMap = new LinkedHashMap<String, String>();

         dataMap.put("chart", gson.toJson(chartobj));
         dataMap.put("data", gson.toJson(arrData));

        FusionCharts columnChart= new FusionCharts(
                    "column2d",
                    "chart1",
                    "500","300",
                    "chart",
                    "json",
                    gson.toJson(dataMap)
                );

        %>

        <%=columnChart.render()%>

error on eclipse terminal
Mar 27, 2018 2:07:17 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [/registration] threw exception [Unable to compile class for JSP:

An error occurred at line: 78 in the jsp file: /dashboard.jsp
String literal is not properly closed by a double-quote
75:
76:
77:             // Form the SQL query that returns the number of sales in 2017
78:             String sql= "SELECT m.month, IFNULL(x.cnt, 0) AS cnt FROM
79:     (SELECT 1 AS month UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) AS m
80:     LEFT JOIN (SELECT DATE_FORMAT(date, '%c') as month, COUNT(*) AS cnt FROM ssl_sales where YEAR(date)=2017 AND status_ssl='new' GROUP BY month) AS x ON m.month = x.month
81: ORDER BY m.month DESC";

Stacktrace:] with root cause
org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: 78 in the jsp file: /dashboard.jsp
String literal is not properly closed by a double-quote
75:
76:
77:             // Form the SQL query that returns the number of sales in 2017
78:             String sql= "SELECT m.month, IFNULL(x.cnt, 0) AS cnt FROM
79:     (SELECT 1 AS month UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) AS m
80:     LEFT JOIN (SELECT DATE_FORMAT(date, '%c') as month, COUNT(*) AS cnt FROM ssl_sales where YEAR(date)=2017 AND status_ssl='new' GROUP BY month) AS x ON m.month = x.month
81: ORDER BY m.month DESC";

A: in Java String literals are not allowed  more than one line .
so you can do using '+' like
String sql= "SELECT m.month,IFNULL(x.cnt, 0) AS cnt FROM "+
" (SELECT 1 AS month UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) AS m "+
" LEFT JOIN (SELECT DATE_FORMAT(date, '%c') as month, COUNT(*) AS cnt FROM ssl_sales where YEAR(date)=2017 AND status_ssl='new' GROUP BY month) AS x ON m.month = x.month "+
" ORDER BY m.month DESC";

or write it in one line
String sql="SELECT m.month,IFNULL(x.cnt, 0) AS cnt FROM (SELECT 1 AS month UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) AS m LEFT JOIN (SELECT DATE_FORMAT(date, '%c') as month, COUNT(*) AS cnt FROM ssl_sales where YEAR(date)=2017 AND status_ssl='new' GROUP BY month) AS x ON m.month = x.month ORDER BY m.month DESC";


Q: Python: Modify the internal behavior of a function by using decorator I'm learning to use python decorator.
def my_dcrtr(fun):
    def new_fun():
        return fun()
    return new_fun

I realize the decorated function 'fun' acts like a black box inside the decorator. I can choose to use fun() or not at all inside new_fun. However, I don't know whether I can break into 'fun' and interact with fun's local scope inside the new_fun?
e.g. I'm trying to make a toy Remote Procedural Call (RPC) with python.
def return_locals_rpc_decorator(fun):
    def decorated_fun(*args, **kw):
        local_args = fun(*args, **kw)
        # pickle the local_args and send it to server
        # server unpickle and doing the RPC
        # fetch back server results and unpickle to results
        return rpc_results

    return decorated_fun

@return_locals_rpc_decorator
def rpc_fun(a, b, c=3):
    return locals() # This looks weird. how can I make this part of the decorator?

print(rpc_fun(2, 1, 6))

In this example, I try to get rpc_fun's argument list at runtime with the 'locals()' command. Then send it to server to execute. Instead of letting rpc_fun returns its locals(), is it possible to use the decorator to retrieve decorated function's argument space?

A: You can use function annotations for Python3:
def return_locals_rpc_decorator(fun):
   def decorated_fun(*args, **kw):
      local_args = fun(*args, **kw)
      print(local_args)
      fun_parameters = fun.__annotations__
      final_parameters = {a:list(args)[int(b[-1])-1] for a, b in fun_parameters.items() if a != 'return'}
      return final_parameters
   return decorated_fun

@return_locals_rpc_decorator
def my_funct(a:"val1", b:"val2", c:"val3") -> int:
    return a + b + c

print(my_funct(10, 20, 30))

Output:
60
{'a': 10, 'b': 20, 'c': 30}

In this way, you are using the wrapper function decorated_fun to access the decorated function's parameters and further information specified by the annotation. I changed the parameter descriptions in the annotations so that each string value would end in a digit that could be used to index args. However, if you do not want to change the parameter descriptions in the annotations, you can sort via ending character.
Edit: the code in the body of my_funct is executed when called in the wrapper function (decorated_fun), since the args, declared in the scope of decorated_fun is passed to and unpacked in local_args.


Q: Balance between use of Ajax on $.ready() and loading data already I have a page which has several independent sections. Data is to be populated in each section by different queries to the database.
In order to lower the page load time, I have ajaxified the loading of each section (following the Amazon.com philosophy).
In order to load each section of the page, I make an ajax call on $.ready() method in my page which in turn fetches data from the database.
In all 6 requests are made to the (same) server which completely generate the sections.
Now, I'm not sure if I am overburdening the server by making 6 requests each time the page is requested. Any suggestions?
(I use Struts/Hibernate/Jsp/jQuery)

A: You can always queue your ajax calls so they happen 1 at a time.  There are jquery plugins to help with this:
http://www.protofunc.com/scripts/jquery/ajaxManager/
To me however, 6 calls does not seem too bad, as long as they dont generate a lot of server activity (hard db queries, file handling, etc...)

A: alternatively, you can start all your queries as soon as the page is requested, and save the results up for the ajax calls. This needs asynchronous execution on the server, and you need to make sure that the ajax response program can wait for the sql completion too.
If you query the same data in several of your 6 queries, this might be worth it. If tables are different for each, this might be really counterproductive (depending on your database engine, and cluster architecture).
However, if database stress and response time is a concern, caching techniques and other optimisations usually work better (memcache by example). But again this depends strongly on your database engine.


Q: Constructor parameter in configuration class required a bean of type 'StratusAuthenticationEntryPoint' that could not be found Parameter 0 of constructor in ResourceServerConfiguration required a bean of type 'StratusAuthenticationEntryPoint' that could not be found.
I am using spring boot 2.6.6
Here is the code:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(100)
//@Import({ApiPermissionEvaluator.class})
public class ResourceServerConfiguration extends WebSecurityConfigurerAdapter {

    private final StratusAuthenticationEntryPoint securityAuthenticationEntryPoint;

    public ResourceServerConfiguration(StratusAuthenticationEntryPoint securityAuthenticationEntryPoint) {
        super();
        this.securityAuthenticationEntryPoint = securityAuthenticationEntryPoint;
    }
}

error message:
            ***************************
        APPLICATION FAILED TO START
        ***************************

        Description:

        Parameter 0 of constructor in com.stratus.security.config.ResourceServerConfiguration required a bean of type 'com.stratus.security.config.StratusAuthenticationEntryPoint' that c
        ould not be found.

        Action:

        Consider defining a bean of type 'com.stratus.security.config.StratusAuthenticationEntryPoint' in your configuration.

A: *

*Add @Component over Class of StratusAuthenticationEntryPoint that a bean created by spring ioc

*verify if the ComponentScan path contains Class of StratusAuthenticationEntryPoint


Q: Maven build war doesn't work properly on Tomcat 7 I've been working on a web app that and here's me configuration before I get started telling my story.
Configuration: IntelliJ IDEA 11 + Java 7 + (Maven + Jetty 8.0.1).
When I clean and build my app on intelliJ, everything works as expected and nothing goes wrong; pages load, rendering are perfectly fine. Then I use -mvn clean package command to build my project so I'll test my app on Tomcat 7.
However, when I deploy my application to Tomcat, some pages aren't as I saw on my maven build: renderings doesn't work properly, styling is a little bit deprecated and so on...
Even some pages doesn't load fully when I check on firebug.
I wish someone encountered a similar issue; this thing is making me crazy... If you need any logs or anything just name it.
Thank you.

A: Apperently, there's always nuances that you miss sometimes and browsers keep extensive data of the pages you browser. I've just cleared all of my browsers caches and now everything works perfectly!.. So if you encounter something similar, be sure to clear your browser cache.


Q: How do I determine the start and end of instructions in an object file? So, I've been trying to write an emulator, or at least understand how stuff works. I have a decent grasp of assembly, particularly z80 and x86, but I've never really understood how an object file (or in my case, a .gb ROM file) indicates the start and end of an instruction.
I'm trying to parse out the opcode for each instruction, but it occurred to me that it's not like there's a line break after every instruction. So how does this happen? To me, it just looks like a bunch of bytes, with no way to tell the difference between an opcode and its operands.

A: For most CPUs - and I believe Z80 falls in this category - the length of an instruction is implicit.
That is, you must decode the instruction in order to figure out how long it is.

A: If you're writing an emulator you don't really ever need to be able to obtain a full disassembly. You know what the program counter is now, you know whether you're expecting a fresh opcode, an address, a CB page opcode or whatever and you just deal with it. What people end up writing, in effect, is usually a per-opcode recursive descent parser.
To get to a full disassembler, most people impute some mild simulation, recursively tracking flow. Instructions are found, data is then left by deduction.
Not so much on the GB where storage was plentiful (by comparison) and piracy had a physical barrier, but on other platforms it was reasonably common to save space or to effect disassembly-proof code by writing code where a branch into the middle of an opcode would create a multiplexed second stream of operations, or where the same thing might be achieved by suddenly reusing valid data as valid code. One of Orlando's 6502 efforts even re-used some of the loader text — regular ASCII — as decrypting code. That sort of stuff is very hard to crack because there's no simple assembly for it and a disassembler therefore usually won't be able to figure out what to do heuristically. Conversely, on a suitably accurate emulator such code should just work exactly as it did originally.


Q: What does QFE_Richmond actually mean? I am developing a VBA add-in for Excel that uses the RefEdit control.
One of my testers pointed out that he couldn't use keyboard shortcuts while selecting cells. And I found the solution to this problem here: http://support.microsoft.com/kb/291110
Set the magical value QFE_Richmond to 1 in the Excel section of HKEY_CURRENT_USER.
This solution works great.
My question is why?
What is the significance of the "QFE_Richmond" variable? Where did it come from? Why do you need this obscure flag to fix a simple glitch that has persisted at least through Excel 2010 and at least as far back as 2003?  Does this flag do anything else?
And is it safe to automatically make this change for the users of my add-in, even though it globally affects their Excel settings?

A: The obvious answer seems to be that they either forgot to apply it in each version or they don't consider it important enough to make default because it is on the border of being considered a bug or a usability preference because it has an easy workaround(i.e. using the GUI instead of shortcuts). I wouldn't think applying the hotfix would hurt anything - they wouldn't make it available if that were the case.
Changing QFE_Richmond registry key to 1 is a to enable a hotfix.
http://support.microsoft.com/?kbid=291110
"Typically, hotfixes are made to address a specific customer situation and may not be distributed outside the customer organization."
In addition, the RefEdit control seems to have alternatives:
http://peltiertech.com/WordPress/refedit-control-alternative/
Which have been recommended because it has compatability issues:
http://peltiertech.com/WordPress/unspecified-painfully-frustrating-error/
So you could probably presume that MS has some gaps in their quality control for the RefEdit feature.
Good Luck.
EDIT/ADDITION:
By the way,
QFE stands for Quick Fix Engineering


Q: Assign a new column in pandas in a similar way as in pyspark I have the following dataframe:
df = pd.DataFrame([['A', 1],['B', 2],['C', 3]], columns=['index', 'result'])

index
result

A
1

B
2

C
3

I would like to create a new column, for example multiply the column 'result' by two, and I am just curious to know if there is a way to do it in pandas as pyspark does it.
In pyspark:
df = df\
.withColumn("result_multiplied", F.col("result")*2)

I don't like the fact of writing the name of the dataframe everytime I have to perform an operation as it is done in pandas such as:
In pandas:
df['result_multiplied'] = df['result']*2

A: Use DataFrame.assign:
df = df.assign(result_multiplied = df['result']*2)

Or if column result is processing in code before is necessary lambda function for processing counted values in column result:
df = df.assign(result_multiplied = lambda x: x['result']*2)

Sample for see difference column result_multiplied is count by multiple original df['result'], for result_multiplied1 is used multiplied column after mul(2):
df = df.mul(2).assign(result_multiplied = df['result']*2,
                      result_multiplied1 = lambda x: x['result']*2)
print (df)
  index  result  result_multiplied  result_multiplied1
0    AA       2                  2                   4
1    BB       4                  4                   8
2    CC       6                  6                  12


Q: Python dictionary printing first word behaviour I'm learning python and am on the topic of dictionaries. I wrote the following dictionary:
Team={
    ('projectmanager','Asma'): 'Sara',
    ('ba','Richard'): 'Steve',
    ('tester','Asma'): 'Rob',
    'developer1': 'Misbah',
    'developer2': 'Mariam'
}

I then wrote the following code:
for k,v in Team.items():
    profile=type(k)
    print('engTeam => {1} {0}'.format(k[0][0],profile))

The output I get is:
Team => <class 'str'> e
Team => <class 'str'> d
Team => <class 'tuple'> i
Team => <class 'str'> m
Team => <class 'tuple'> b
Team => <class 'str'> s
Team => <class 'tuple'> p
Team => <class 'str'> e
Team => <class 'str'> a

I don't understand why the first character of all non-tuple entries are being printed. If I think about it k[0][0] in my mind means get me the first element of the dictionary then the first sub element. But the non-tuple words don't have a sub element so the output should be blank, shouldn't it? Also k[0][0] should be printing the whole first word in the tuple e.g. 'projectmanager' instead of the first character of the first tuple word. What am I missing in understanding what k[0][0] means and what it is doing?

A:
If I think about it k[0][0] in my mind means get me the first element of the dictionary then the first sub element.

No, k is the key of a given key-value pair. You are iterating over the items, which are those pairs:
for k,v in Team.items():

Each key-value pair is assigned to the names k and v there.
Given that you have two different types of keys in your dictionary, strings and tuples, your type() information shows you exactly that; you print a series of <class 'str'> and <class 'type'> for those keys.
So if k is a tuple, then k[0] is the first element in that tuple and k[0][0] is the first character of that first element:
>>> k = ('projectmanager', 'Asma')
>>> type(k)
<class 'tuple'>
>>> k[0]
'projectmanager'
>>> k[0][0]
'p'

For strings, k[0] would be the first character. But a single character is a string too. A string of length 1, so getting the first element of that string is still a string, again of length 1:
>>> k = 'developer1'
>>> type(k)
<class 'str'>
>>> k[0]
'd'
>>> type(k[0])
<class 'str'>
>>> len(k[0])
1
>>> k[0][0]
'd'

You wouldn't get an empty value here.

A: Consider,
First case- key, k is set to be a to be tuple. For instance ('projectmanager','Asma'). Hence obviously k[0][0] will print out p
Second case (the more tricky one) when k is set to be a string, k[0] is the first element of string. k[0] is hence a string of length 1. Doing
k[0][0] would access the first element of k[0] which is inturn the same as k[0] is a string of length 1.For example when k  is 'developer1' ,k[0] is'd' and k[0][0]  is hence 'd'
Hope this helps, good luck


Q: How to detect if a particular command has executed in terminal I need to detect if a particular command has run. for example if I do a git push I need to execute a build script in my fedora machine. Is there any way to do this.? we can use any facility in linux. Any help will be greatly appreciated.

A: You can try using "alias", try this link http://www.cyberciti.biz/tips/bash-aliases-mac-centos-linux-unix.html


Q: pkg-config file openmp dependency I want to write a pkg-config for a library that uses openmp internally.
My .pc file reads
prefix=/usr/local
exec_prefix=/usr/local
libdir=${exec_prefix}/lib
includedir=${prefix}/include

Name: LightFEM
Description:
Version: 1.0.0

Requires: openmp
Libs: -L${libdir} -lLightFEM
Cflags: -I${includedir}

However pkg-config returns the following error
Package openmp was not found in the pkg-config search path.
Perhaps you should add the directory containing `openmp.pc'
to the PKG_CONFIG_PATH environment variable
Package 'openmp', required by 'LightFEM', not found

How sould I write my .pc file ?


Q: Los caracteres anchos de C++ no se imprimen correctamente en la consola Este es un problema que vengo arrastrando desde que empecé a programar en c++ y se resume en que los caracteres anchos no se editan correctamente al usar un índice:
#include <iostream>
#include <cstring>

int main(){

    std::wstring cadena = L"Hoy es un d?a muy lindo";

    cadena[11]=wchar_t(L'í');

    std::wcout << cadena << std::endl;

}

la salida que obtengo en la consola es la siguiente:

El resultado que esperaba es la vocal i con tilde pero obtengo una Y con tilde que desconozco de que idioma es. No se si es la consola que no imprime correctamente los caracteres no ascii o es la codificación interna de los wstring.
Por alguna extraña razón las cadenas no ascii me funcionan fatal, nunca logro hacer nada con ellas y estoy por abandonar el lenguaje c++ ya que estoy acostumbrado al unicode utf8 de python y no encuentro una solución similar para ese tipo de codificación.


Q: Kafka logfile location Just to make some things clear: I'm talking about the process logfile that contains the stdout and stderr messages.
This is my systemd unit file:
[Unit]
Description=Apache Kafka server
Documentation=http://kafka.apache.org
Requires=network.target remote-fs.target
After=network.target remote-fs.target

[Service]
Type=simple
PIDFile=/var/run/kafka.pid
User=kafka
Group=kafka
Environment="JAVA_HOME=/usr/lib/jvm/jre"
Environment="KAFKA_LOG4J_OPTS=-Dlog4j.configuration=file:/var/log/kafka"

ExecStart=/opt/kafka/bin/kafka-server-start.sh /opt/kafka/config/server.properties
ExecStop=/opt/kafka/bin/kafka-server-stop.sh
Restart=on-failure
SyslogIdentifier=kafka

[Install]
WantedBy=multi-user.target

Note that I added the KAFKA_LOG4J_OPTS environment variable.
However, that doesn't seem to do anything. This is the output, when I try to start my service:
Feb 11 00:55:30 kafka01 kafka[4047]: mkdir: cannot create directory ‘/opt/kafka/bin/../logs’: Permission denied
Feb 11 00:55:30 kafka01 kafka[4047]: OpenJDK 64-Bit Server VM warning: Cannot open file /opt/kafka/bin/../logs/kafkaServer-gc.log due to No such file or directory
Feb 11 00:55:30 kafka01 kafka[4047]: log4j:WARN No appenders could be found for logger (kafka.Kafka$).
Feb 11 00:55:30 kafka01 kafka[4047]: log4j:WARN Please initialize the log4j system properly.

So, can please someone tell me the correct way to change the location of the kafka log file? KAFKA_LOG4J_OPTS doesn't work, KAFKA_LOG_DIR doesn't work either (=I was hoping kafka implemented this similar to zookeeper). The kafka documentation doesn't tell me either.

A: For other unfortunate lads like my, you need to modify LOG_DIR environment variable (tested for Kafka v0.11).
If you open script kafka-server-start or /usr/bin/zookeeper-server-start, you will see at the bottom that it calls kafka-run-class script. And you will see there that it uses LOG_DIR as the folder for the logs of the service (not to be confused with kafka topics data).

A: As eddyP23 mentioned in previous response... kata-run-class uses LOG_DIR
However there is logic in it to use Script directly parent folder if LOG_DIR variable is not set.
So if your scripts are in kafka/bin folders where you are starting kafka... then logs will be present in kafka/log

A: Maybe not actually the answer to the questions but I've arrived here searching for where kafka stores application logs, not producers/consumers data. IMO calling this data logs is really bad naming.
I've deployed a Kafka cluster on GCP Kubernetes engine and I wanted to view the logs of the application and here is how I did it.
1- Get the pods
    > kubectl get pods
    NAME      READY   STATUS    RESTARTS   AGE
    kafka-0   1/1     Running   0          32m
    kafka-1   1/1     Running   0          32m
    kafka-2   1/1     Running   0          32m
    zk-0      1/1     Running   0          23h
    zk-1      1/1     Running   0          23h
    zk-2      1/1     Running   0          23h

2- Connect to one of the Kafkas pods with interactive command
> kubectl exec -it kafka-0 /bin/bash

3- Echo $, in command line type echo $ and press the tab button several times ...
you will get a list of all defined environment variables, search for $KAFKA_HOME
or just type
> cd $KAFKA_HOME

You will get to:
/opt/kafka$ ls -al
total 68
drwxr-xr-x 1 kafka kafka  4096 Aug  2 09:37 .
drwxr-xr-x 1 root  root   4096 Jun 26  2017 ..
-rw-r--r-- 1 kafka kafka 28824 Apr 21  2017 LICENSE
-rw-r--r-- 1 kafka kafka   336 Apr 21  2017 NOTICE
drwxr-xr-x 1 kafka kafka  4096 Jun 26  2017 bin
drwxr-xr-x 1 kafka kafka  4096 Jun 26  2017 config
drwxr-xr-x 1 kafka kafka  4096 Jun 26  2017 libs
drwxr-xr-x 2 kafka kafka  4096 Aug  2 09:37 logs
drwxr-xr-x 1 kafka kafka  4096 Jun 26  2017 site-docs

The log directory is what I was looking for ...


Q: What is the difference between /ʌɪ/ and /aɪ/ in English? Is there any difference between the two diphthongs in English IPA transcriptions?
If I search a word in the Cambridge dictionary, it gives /aɪ/ for both UK English and US English.
For example, the word "night" is transcribed as /naɪt/ in Cambridge English dictionary for both UK and US English.
But Lexico (powered by Oxford) gives /nʌɪt/ for "night".
In Cambridge dictionary, I can hear a slight difference between UK and US pronunciation but the IPA symbols are the same.
Dictionary.com also has /aɪ/.
Is there any difference between them? Or can I use /ʌɪ/ and /aɪ/ interchangeably?

A: If you click on the U.S. pronunciation in Lexico, it gives /naɪt/ (https://www.lexico.com/en/definition/night).
They represent the same phoneme, and you can pronounce it either way (although it might confuse people if you are not consistent).
The Oxford lexicographers think that [nʌɪt] is becoming the prestigious pronunciation in the U.K., but that the standard pronunciation in the U.S. is still [naɪt]. If you're trying to sound British, you can use the pronunciation [nʌɪt]. If you're trying to speak American English or world English, you should probably use [naɪt]. Much of the rest of the world still uses /naɪt/, although this varies — Australians
pronounce it [nɑɪt].
The Cambridge lexicographers haven't bothered changing the pronunciation symbols. There is something to be said for consistency—changing pronunciation symbols confuses people. And even Oxford isn't consistent about changing the symbol when pronunciations change — no dictionaries seem to have changed their IPA symbol for the vowel in nut, even though hardly anybody actually pronounces it [nʌt] anymore.
Many Americans have what is known as "Canadian raising", and use /ʌɪ/ before an unvoiced consonant and /aɪ/ before a voiced consonant, so they would say [nʌɪt] (night) but [raɪd] (ride). Since Americans usually use the same pronunciation for /t/ and /d/ after a stressed syllable and before a vowel, this vowel distinguishes between writer /rʌɪɾər/ and rider /raɪɾər/.

A: The notations /ʌɪ/ and /ɑɪ/ represent a contrastive phonemic difference
that some native speakers of English produce and perceive between
certain minimal pairs.
For those speakers, the following are minimal
pairs differing only in that the first word has the /ʌɪ/ phoneme
but the second word has the /ɑɪ/ phoneme:

*

*writer–rider

*hire–higher

*shire–shyer

*lyre–liar

*bier–buyer

*idle–idol

*ˈhigh school–high ˈschool

Because those are minimal pairs for those speakers, that proves that for
them, /ʌɪ/ versus /ɑɪ/ is a phonemic distinction not merely a phonetic one,
because changing the sound changes the word in their minds.
This is the phenomenon that has generally come to be known as Canadian
raising but it is by no
means strictly Canadian.  Most native speakers throughout North America
make this phonemic distinction, as do some from Northern Ireland.
For such speakers, the raised diphthong /ʌɪ/ occurs in such words as
tight, dice, mice, ice, bison, writer, spider, tiger, kind, hire, fire,
tire, dire, mire, lyre, bier, sire, shire, choir, pliers, Ireland, inquire,
entire, expire, idle, ˈhigh school. However, not all such speakers
necessarily have the raised variant in all those terms just listed.
Similarly, for those speakers with this phonemic contrast, the unraised
diphthong /ɑɪ/ is (often) found in such words as dyed, dyes, dyer, ire,
ion, dine, pine, bind, buys, prize, surmise, rider, scythe, horizon,
higher, sigher, shyer, buyer, liar, denier, Oscar Mayer, idol, high
ˈschool.
However, if you are referring to allophonic phonetic renditions for the
same pair of phonemes, then this requires narrow phonetic transcriptions with
complex notation that only specialists are apt to understand.
If so, then the /ʌɪ/ phoneme of
ice can variously
— depending on the speaker, region, and utterance — be any of
[ʌɪ], [ʌ̈ɪ], [äɪ], [ɑ̟i], [äɛ̝̈], [ɐi], [ɐɪ], [ə̠i], [ɛ̈i].
Here are the technical decoded details of what each of those phonetic
allophones of the /ʌɪ/ phoneme means:
[ʌɪ]:
 ʌ      open-mid back unrounded vowel           U+028C  LATIN SMALL LETTER TURNED V
 ɪ      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I

[ʌ̈ɪ]:
 ʌ̈      open-mid back unrounded vowel           U+028C  LATIN SMALL LETTER TURNED V
        centralized                             U+0308  COMBINING DIAERESIS
 ɪ      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I

[äɪ]:
 ä      open front unrounded vowel              U+0061  LATIN SMALL LETTER A
        centralized                             U+0308  COMBINING DIAERESIS
 ɪ      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I

[ɑ̟i]:
 ɑ̟      open back unrounded vowel               U+0251  LATIN SMALL LETTER ALPHA
        advanced                                U+031F  COMBINING PLUS SIGN BELOW
 i      close front unrounded vowel             U+0069  LATIN SMALL LETTER I

[äɛ̝̈]:
 ä      open front unrounded vowel              U+0061  LATIN SMALL LETTER A
        centralized                             U+0308  COMBINING DIAERESIS
 ɛ̝̈      open-mid front unrounded vowel          U+025B  LATIN SMALL LETTER OPEN E
        raised                                  U+031D  COMBINING UP TACK BELOW
        centralized                             U+0308  COMBINING DIAERESIS

[ɐi]:
 ɐ      near-open central vowel                 U+0250  LATIN SMALL LETTER TURNED A
 i      close front unrounded vowel             U+0069  LATIN SMALL LETTER I

[ɐɪ]:
 ɐ      near-open central vowel                 U+0250  LATIN SMALL LETTER TURNED A
 ɪ      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I

[ə̠i]:
 ə̠      mid-central vowel                       U+0259  LATIN SMALL LETTER SCHWA
        retracted                               U+0320  COMBINING MINUS SIGN BELOW
 i      close front unrounded vowel             U+0069  LATIN SMALL LETTER I

[ɛ̈i]:
 ɛ̈      open-mid front unrounded vowel          U+025B  LATIN SMALL LETTER OPEN E
        centralized                             U+0308  COMBINING DIAERESIS
 i      close front unrounded vowel             U+0069  LATIN SMALL LETTER I

Compare that set with phonetic realizations of the /ɑɪ/ phoneme of
nine, which can
be any of [ɑɪ], [ɑˑɪ], [äɪ], [ɑ̈ˑɪ], [ɑ̈ˑɪ̠], [ɑ̟ˑɪ], [äˑɐ], [äˑe̞],
[äˑɛ̝̈], [äˑi], [äˑɪ], [ɐˑiˑ], [ɐ̟ˑɪ̠], [ɐˑɪˑ], [ɐi], [ɐiˑ], [ɐɪ],
[æˑi], [ɛ̈ˑiˑ], [ɛ̈ĭɪ̠], [ɜ̟ˑiˑ], [ɔ̟ɪ], [ʌ̈ɪ], [ə̟ɪ̝].
Here are the technical decoded details of what each of those phonetic allophones of the /ɑɪ/ phoneme means:
[ɑɪ]:
 ɑ      open back unrounded vowel               U+0251  LATIN SMALL LETTER ALPHA
 ɪ      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I

[ɑˑɪ]:
 ɑˑ     open back unrounded vowel               U+0251  LATIN SMALL LETTER ALPHA
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON
 ɪ      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I

[äɪ]:
 ä      open front unrounded vowel              U+0061  LATIN SMALL LETTER A
        centralized                             U+0308  COMBINING DIAERESIS
 ɪ      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I

[ɑ̈ˑɪ]:
 ɑ̈ˑ     open back unrounded vowel               U+0251  LATIN SMALL LETTER ALPHA
        centralized                             U+0308  COMBINING DIAERESIS
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON
 ɪ      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I

[ɑ̈ˑɪ̠]:
 ɑ̈ˑ     open back unrounded vowel               U+0251  LATIN SMALL LETTER ALPHA
        centralized                             U+0308  COMBINING DIAERESIS
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON
 ɪ̠      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I
        retracted                               U+0320  COMBINING MINUS SIGN BELOW

[ɑ̟ˑɪ]:
 ɑ̟ˑ     open back unrounded vowel               U+0251  LATIN SMALL LETTER ALPHA
        advanced                                U+031F  COMBINING PLUS SIGN BELOW
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON
 ɪ      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I

[äˑɐ]:
 äˑ     open front unrounded vowel              U+0061  LATIN SMALL LETTER A
        centralized                             U+0308  COMBINING DIAERESIS
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON
 ɐ      near-open central vowel                 U+0250  LATIN SMALL LETTER TURNED A

[äˑe̞]:
 äˑ     open front unrounded vowel              U+0061  LATIN SMALL LETTER A
        centralized                             U+0308  COMBINING DIAERESIS
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON
 e̞      close-mid front unrounded vowel         U+0065  LATIN SMALL LETTER E
        lowered                                 U+031E  COMBINING DOWN TACK BELOW

[äˑɛ̝̈]:
 äˑ     open front unrounded vowel              U+0061  LATIN SMALL LETTER A
        centralized                             U+0308  COMBINING DIAERESIS
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON
 ɛ̝̈      open-mid front unrounded vowel          U+025B  LATIN SMALL LETTER OPEN E
        raised                                  U+031D  COMBINING UP TACK BELOW
        centralized                             U+0308  COMBINING DIAERESIS

[äˑi]:
 äˑ     open front unrounded vowel              U+0061  LATIN SMALL LETTER A
        centralized                             U+0308  COMBINING DIAERESIS
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON
 i      close front unrounded vowel             U+0069  LATIN SMALL LETTER I

[äˑɪ]:
 äˑ     open front unrounded vowel              U+0061  LATIN SMALL LETTER A
        centralized                             U+0308  COMBINING DIAERESIS
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON
 ɪ      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I

[ɐˑiˑ]:
 ɐˑ     near-open central vowel                 U+0250  LATIN SMALL LETTER TURNED A
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON
 iˑ     close front unrounded vowel             U+0069  LATIN SMALL LETTER I
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON

[ɐ̟ˑɪ̠]:
 ɐ̟ˑ     near-open central vowel                 U+0250  LATIN SMALL LETTER TURNED A
        advanced                                U+031F  COMBINING PLUS SIGN BELOW
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON
 ɪ̠      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I
        retracted                               U+0320  COMBINING MINUS SIGN BELOW

[ɐˑɪˑ]:
 ɐˑ     near-open central vowel                 U+0250  LATIN SMALL LETTER TURNED A
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON
 ɪˑ     near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON

[ɐi]:
 ɐ      near-open central vowel                 U+0250  LATIN SMALL LETTER TURNED A
 i      close front unrounded vowel             U+0069  LATIN SMALL LETTER I

[ɐiˑ]:
 ɐ      near-open central vowel                 U+0250  LATIN SMALL LETTER TURNED A
 iˑ     close front unrounded vowel             U+0069  LATIN SMALL LETTER I
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON

[ɐɪ]:
 ɐ      near-open central vowel                 U+0250  LATIN SMALL LETTER TURNED A
 ɪ      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I

[æˑi]:
 æˑ     near-open front unrounded vowel         U+00E6  LATIN SMALL LETTER AE
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON
 i      close front unrounded vowel             U+0069  LATIN SMALL LETTER I

[ɛ̈ˑiˑ]:
 ɛ̈ˑ     open-mid front unrounded vowel          U+025B  LATIN SMALL LETTER OPEN E
        centralized                             U+0308  COMBINING DIAERESIS
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON
 iˑ     close front unrounded vowel             U+0069  LATIN SMALL LETTER I
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON

[ɛ̈ĭɪ̠]:
 ɛ̈      open-mid front unrounded vowel          U+025B  LATIN SMALL LETTER OPEN E
        centralized                             U+0308  COMBINING DIAERESIS
 ĭ      close front unrounded vowel             U+0069  LATIN SMALL LETTER I
        extra-short                             U+0306  COMBINING BREVE
 ɪ̠      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I
        retracted                               U+0320  COMBINING MINUS SIGN BELOW

[ɜ̟ˑiˑ]:
 ɜ̟ˑ     open-mid central unrounded vowel        U+025C  LATIN SMALL LETTER REVERSED OPEN E
        advanced                                U+031F  COMBINING PLUS SIGN BELOW
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON
 iˑ     close front unrounded vowel             U+0069  LATIN SMALL LETTER I
        half-long                               U+02D1  MODIFIER LETTER HALF TRIANGULAR COLON

[ɔ̟ɪ]:
 ɔ̟      open-mid back rounded vowel             U+0254  LATIN SMALL LETTER OPEN O
        advanced                                U+031F  COMBINING PLUS SIGN BELOW
 ɪ      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I

[ʌ̈ɪ]:
 ʌ̈      open-mid back unrounded vowel           U+028C  LATIN SMALL LETTER TURNED V
        centralized                             U+0308  COMBINING DIAERESIS
 ɪ      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I

[ə̟ɪ̝]:
 ə̟      mid-central vowel                       U+0259  LATIN SMALL LETTER SCHWA
        advanced                                U+031F  COMBINING PLUS SIGN BELOW
 ɪ̝      near-close near-front unrounded vowel   U+026A  LATIN LETTER SMALL CAPITAL I
        raised                                  U+031D  COMBINING UP TACK BELOW

However, for speakers who have merges in minimal pairs like hire–higher, you
should not use different phonemes since those speakers do not make such a distinction.
Dictionaries do not try to represent narrow phonetics. They present broad phonemic
transcriptions, virtually always choosing just one of either  /ʌɪ/ or /ɑɪ/, and then pretending that everyone says only that version, belying the existence of minimal pairs.

A: I wouldn’t take tchrist’s answer at face value. As a native speaker of Standard American English (in the Pennsylvania to Colorado belt, so truly the standard) these are at best phonetic differences, certainly not phonemic (plus several of the examples given are clearly triggered by context or simply wrong). Almost none of the examples are truly minimal pairs in my dialect of English, as they assert. Anyway the IPA is for transcribing phonetic rather than phonemic pronunciations so this is ultimately meaningless.


Q: Google Spreadsheet node.js move a row or sort table Edit: I saw that I am not using the official google api. This is a package based on v3 of the google api. Here is the npm that I currently use.
I saw that google api v4 exists and has many more features than the npm package I currently use, would it be possible with the official v4 api? What would I need to change to use this api?

Is it possible to move a row to a specific row (number)?
If not, can I custom sort the entire table again?
This is how I access the table:
const GoogleSpreadsheet = require("google-spreadsheet");
const { promisify } = require("util");
const creds = require("./client_secret.json");
const doc = new GoogleSpreadsheet("XXXXXXXXXXXXXXXX");
const tt = promisify(doc.useServiceAccountAuth)(creds);
const info = await promisify(doc.getInfo)();
const sheet = info.worksheets[0];

And now I want to edit/update a row, and because the order should be different now if I change the column cell where my table is sorted by, I want to move the row somewhere else. this is how I modify a row:
var row = await promisify(sheet.getRows)({
        offset: 1,
        query: 'id = ' + userId
});

//This row has now a different value and should have a different row number
row[0].role= "value";

//This will update the row, but only on its current position.
promisify(row[0].save)();

Pseudo code (how it should look like, row[0] has no attribute that indicates the position):
//row[0] role was "" and now "member", the row should be where the other member rows are
row[0].index = IndexOf(AllRows.where(x => x.role == "member")) + 1


Q: How do I change the width of a ScrollBar? I would like to change a TFrame's ScrollingBar width.
I know I could change all ScrollingBars in the system by:
SystemParametersInfo(SPI_SETNONCLIENTMETRICS,....

But how do I do it for a specific WinControl?

A: A lot of the code within Delphi depends on the width of scrollbars to be the fixed system setting so you can't alter the width without breaking the control. (Not without rewriting the TControlScrollBar and related controls in the VCL.)
You could, of course, hide the default scrollbars of the control and add your own TScrollbar components next to it.The standard TScrollBar class is a WinControl itself, where the scrollbar is taking the whole width and height of the control. The TControlScrollBar class is linked to other WinControl to manage the default scrollbars that are assigned to Windowed controls. While the raw API could make it possible to use a more flexible width, you'd always have the problem that the VCL will just assume the default system-defined width for these controls.

This also shows the biggest difference between both scrollbar types: TScrollBar has it's own Windows handle while TControlScrollBar borrows it from the related control.

A: You can try something like this:
  your_frame.HorzScrollBar.Size := 50;
  your_frame.HorzScrollBar.ButtonSize := your_frame.HorzScrollBar.Size;

A: procedure TForm1.FormCreate(Sender: TObject);
var NCMet: TNonClientMetrics;
begin
     FillChar(NCMet, SizeOf(NCMet), 0);
     NCMet.cbSize:=SizeOf(NCMet);
     // get the current metrics
     SystemParametersInfo(SPI_GETNONCLIENTMETRICS, SizeOf(NCMet), @NCMet, 0);
     // set the new metrics
     NCMet.iScrollWidth:=50;
     SystemParametersInfo(SPI_SETNONCLIENTMETRICS, SizeOf(NCMet), @NCMet, SPIF_SENDCHANGE);
end;


Q: How to find MLE for multinomial distribution and expectation of $X_1$ and $X_2$? There are 3 types of flowers that can grow from planting a seed.
$$P(\text{Daisy}) = \theta_1$$
$$P(\text{Rose}) = (1-\theta_1)\theta_2$$
$$P(\text{Sunflower}) = (1-\theta_1)(1-\theta_2)$$
the total number of flowers at the end is $n.$ If $X=(X_1, X_2, X_3)$ is the number of daisies, roses and sunflowers respectively, find the MLEs for $\theta_1$ & $\theta_2$ and $E[X_1]$ and $E[X_2]$ in term of the parameters $\theta_1$ & $\theta_2$.
I am aware that this is a multinomial distribution but i sont know how to go about finding the estimators for the parameters since there are 2 of them.

A: The likelihood for the outcome $(X_1,X_2,X_3)=(x_1,x_2,x_3)$ is
$$
\binom n{x_1,x_2,x_3}\theta_1^{x_1}(1-\theta_1)^{x_2}\theta_2^{x_2}(1-\theta_1)^{x_3}(1-\theta_2)^{x_3}\;,
$$
so the derivative of the log likelihood with respect to $\theta_2$ is
$$
\frac{x_2}{\theta_2}-\frac{x_3}{1-\theta_2}\;.
$$
Setting this to $0$ yields the MLE for $\theta_2$, $\frac{x_2}{x_2+x_3}$, which shouldn’t surprise us, since we effectively have a subexperiment with $x_2$ of the $x_2+x_3$ big flowers being roses, where we don’t care about the daisies.
The same calculation for $\theta_1$ yields
$$
\frac{x_1}{\theta_1}-\frac{x_2+x_3}{1-\theta_1}
$$
and thus the MLE $\frac{x_1}{x_1+x_2+x_3}=\frac{x_1}n$ for $\theta_1$, again not surprising, since for the proportion of daisies we don’t care about the distinction between the two types of big flowers.


Q: NullPointerException in Silk4J Object Map Editor when pressing the Tab key After creating a new Silk4J Object Map entry manually (right click, "Insert new") and enter the item name, I press the Tab key to move to the Locator path input field.
In this case, a series of "Object not set to an instance of an object" error messages appear. Eventually, Eclipse crashes. Doing some debugging, I found out that Eclipse crashes due to a StackOverflowException.
I can move to the locator path column using the mouse, but since I'm used to do things by keyboard, I'd really like to find a fix. How can I make the Tab key work as expected?
I am using Silk4J 16 Hotfix 2.

A: Doing some more debugging, I found out that Silk4J for Eclipse (Java) actually uses a WPF user interface (.NET).
While preinstalled by Windows, I never needed .NET on my machine, so I never installed any updates for it.
Installing the latest .NET updates, the problem was gone. In my case I updated to .NET 4.5.2.


Q: Can resistors be used to bring a heating element within range? I have a replacement 24V/60W desoldering gun I would like to modify for use on my Aoyue Int958A+ soldering station. My 968A+ has a smoke absorber which has enough suction to double as a solder vacuum. Mapping the pins is relatively straightforward.
During my measurements, however, I found the desoldering gun's heat sensor resistance was significantly lower than my soldering iron's (see table below). When I briefly heated the tip of the gun with a torch lighter, I noticed the resistance steadily climb to around 6 ohms. Could this be a thermistor instead of a thermocouple? Also, is it possible to correct the resistance range by adding a ~50 ohm resistor in series with the heat sensor?

Desoldering Gun Pinouts
PIN WIRE    PURPOSE
1   Black   Heat Sensor
2   Blue    Heat Sensor
3   Red     Heating Element
4   Red     Heating Element
5   White   Trigger switch
6   White   Trigger switch
7   CENTER  Vibration sensor (unused)

Resistance Measurements
Pins 1 & 2              1 to 2  Ω
Pins 4 & 5              1 to 2  Ω
Pin 3 & solder tip      Below 2  Ω

Soldering Iron Port Pinouts
PIN WIRE    PURPOSE
1   Blue    Heating element
2   Green   Heating element
3   Yellow  Case ground
4   Red     Heat Sensor
5   Black   Heat Sensor
6   Unused

Resistance Measurements
Pins 1 & 2              2.3 to 3.5  Ω
Pins 4 & 5              43 to 58  Ω
Pin 3 & solder tip      Below 2  Ω

A:
Could this be a thermistor instead of a thermocouple?

Could be either, thermocouples usually put out microvolts. If it's a thermocouple, you'll see the voltage vary by a small amount with temperature.

Also, is it possible to correct the resistance range by adding a ~50
  ohm resistor in series with the heat sensor?

It's possible to correct for one temperature point with a resistor, but if your adding a resistor to a thermistor, this will shift the entire curve up and will not be equivalent. This will most likely cause problems for the control circuitry, and the temperature display. Your best bet is to find an equivalent temperature sensor and swap it out.