text:
Q: How to track Email read duration using php? I Want to track how many seconds user spends on a mail sent via me.
I have used a php script for it.
<?php
// Time the request
$st = time();
$t = $st;
$ft = $st + 30;
ignore_user_abort(true);
set_time_limit(0);
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
syslog(LOG_ERR,"URL : ".$actual_link);

while($st < $ft)
{
    // Did the connection fail?
    echo "HI \n";
    flush();
    ob_flush();
     if(connection_status() != 0)
        {
          $duration1 = time() - $t;
          syslog(LOG_ERR,"SKIM : User Stopped For TIME: ".$duration1);
          break;
         }

    // Sleep for 1 seconds
    sleep(1);
    $st = $st + 1;
}
if($st >= $ft)
{
   $duration = $st - $t;
   syslog(LOG_ERR,"READ : User Stopped For TIME: ".$duration);
 }
?>

It is invoked via HTML in the content of mail like

Now the time duration of reading the mail shows always mostly 23 seconds irrespective of the time duration  I take to read it. I tried closing the mail before after too but no effect. Although the script works perfect when I try it on a webpage on local server.I tried for Gmail only.

A: Probably your are talking about this
<?php
session_start();
$_SESSION['start'] = time();

/*here goes the code of email*/

$_SESSION['end'] = time();
echo "Start:".$_SESSION['start']."--"."End:".$_SESSION['end']."
";
echo "Total Execution time is : ".date("H:i:s",$_SESSION['end']-$_SESSION['start']);

?>

A: There's no way you can do what you want. Gmail caches all the images in a mail, so I suppose that after 23 seconds of not receiving anything it just timed out the request by itself


text:
Q: Bug when evaluating a string in JavaScript I have a string calc, which represents an operation (for example, "2/2")
I want my code to evaluate the string and return the result.
When the string is invalid and cannot be evaluated (for example, "2.2.2", I want to return null.
This is my code so far:
    const result = eval(calc);

    if (result === undefined){
      return null;
    } else {
      return result;
    }

My bug is: when the string is invalid as an operation and cannot be evaluated, I don't get null. Instead, the program throws an error.
How can I get null instead of an error?

A: Use try/catch
try {
    result = eval(calc);
    return result;
} catch (e) {
    return null;
}

A: Using eval() is often not necessary and can lead to security and performance problems. There is likely a better solution available. I advise you to explain your use case more detailed so we can help you find a better solution.
If you really want to do this you can use a try catch statement since an exception will be thrown when the code can't be evaluated.

console.log(myEval("2.2.2"));
console.log(myEval("2/2"));

function myEval(str) {
  try {
    return eval(str);
  } catch {
    return null
  }
}

A: eval() will return an error when it cannot parse the command correctly.
When you use try and catch you can return null when an error occurred.
try{
  const result = eval(calc);
  return result;
}
catch (error){
  return null;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add a circular progress icon inside the chip view I want to add a circular progress icon like

Inside a chip view in android. Some thing like this as the end product

Excuse the background of the progress bar indicator. I am not able to find any thing regarding this. Any suggestion?

A: You can achieve this behaviour by setting programmatically the ChipIcon using an androidx.swiperefreshlayout.widget.CircularProgressDrawable if you want to align the loading indicator in the left side of your Chip or you can use the CloseIcon if you want to align it on the right side of the Chip.
Align CircularProgressDrawable on the left side of chip:
1.In your chip xml layout define the chipIconSize and padding attributes based on your needs like below:
<com.google.android.material.chip.Chip
    android:id="@+id/chip"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Chip"
    app:chipIconSize="25dp"
    app:iconStartPadding="5dp"
    app:iconEndPadding="5dp"
    app:chipBackgroundColor="@android:color/holo_blue_bright" />

2.Create programmatically your CircularProgressDrawable like below:
CircularProgressDrawable cpDrawable = new CircularProgressDrawable(this);
cpDrawable.setStyle(CircularProgressDrawable.DEFAULT);
cpDrawable.setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);
cpDrawable.start();

3.And set the above CircularProgressDrawable to your ChipIcon like below:
chip = findViewById(R.id.chip);
chip.setChipIcon(cpDrawable);
chip.setChipIconVisible(true);

Align CircularProgressDrawable on the right side of chip:
1.In your chip xml layout define the closeIconSize and closeIcon paddings attributes based on your needs like below:
<com.google.android.material.chip.Chip
    android:id="@+id/chip"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Chip"
    app:closeIconSize="25dp"
    app:closeIconStartPadding="5dp"
    app:closeIconEndPadding="5dp"
    app:chipBackgroundColor="@android:color/holo_blue_bright" />

2.Create programmatically your CircularProgressDrawable like above and set it on Chip CloseIcon like below:
 chip = findViewById(R.id.chip);
 chip.setCloseIcon(cpDrawable);
 chip.setCloseIconVisible(true);

Results will be like below:

A: I created a layout using relative layout, you can check this i hope you get this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="80dp"
    android:background="@drawable/dummy_bg"
    android:splitMotionEvents="true">

    <TextView
        android:id="@+id/tvlabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="30dp"
        android:text="Electronics"
        android:textColor="@color/black"
        android:textSize="25sp" />

    <ProgressBar
        android:id="@+id/progrressciruclar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_toRightOf="@+id/tvlabel" />
</RelativeLayout>

also create this dummy_bg in your drawables folder and paste the following code
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF"/>
    <stroke android:width="3dp"
        android:color="#FFFFFF" />
    <corners android:radius="50dp"/>
    <padding android:left="0dp"
        android:top="0dp"
        android:right="0dp"
        android:bottom="0dp" />
</shape>


text:
Q: Which is the fastest way to clear a memory block (or a SDL surface)? I'm currently developing a project with SDL. It basically draws and moves images (surfaces) on the screen.
To move an image without leaving a trail, you must first clear the screen surface, pretty much like glClear(), and I'm currently doing it with a simple for loop iterating over the surface's pixels (also drawing a black box on the surface or memset).
While the previous solutions work fine for small surfaces, they get increasingly slower as the surface grows bigger so i was looking for the fastest way I could clear (zero) a memory block.
Also, a friend pointed out that using SIMD instructions could do the work really fast but the last time I've done ASM was on a 8085, any insight on this could also be useful.

A: You should try memset, the implementation should be highly optimized to take advantage of whatever instructions are available on your system.

A: The fastest way is to use memset.
memset(ptr, 0, length);

This automatically uses SIMD on architectures that support it*.  You are not going to beat it.  It is already memory bound, so it's writing zeroes as fast as the processor can spit them out.  I don't know who told you that memset is slower for larger blocks, but you should stop listening to that person.
*There are some toolchains that don't give you a fast memset.  It is unlikely that you are using one.


text:
Q: Extract data from one file and save to another I'm running ansible playbook task using shell command to extract data from file based on regex match and save it to another file.
I tried using awk and sed but not able to get the regex working.
awk '$NF == "-m.comment.*\""' iptable.txt" > file1.txt

sed 's/\/.*' iptable.txt > file2.txt

I need to save any content from -m comment till the double quotes. to file1.txt and remaining content to file2.txt. If the line doesnot have comment field, then it should be saved only to file2.txt.
-P INPUT ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p icmp -m state --state NEW -m comment --comment "Echo Request" -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m comment --comment "tcp" -j ACCEPT

Expected output:
cat file1.txt
-m comment --comment "Echo Request"
-m comment --comment "tcp"

cat file2.txt
-P INPUT ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p icmp -m state --state NEW -j ACCEPT
-A INPUT -p tcp -m state --state NEW -j ACCEPT

A: With GNU awk for the 3rd arg to match():
awk 'match($0,/(.*)(-m.comment.*")(.*)/,a) {
    print a[2] " > foo"
    print a[1] a[3] " > bar"
}' file
-m comment --comment "Echo Request" > foo
-A INPUT -p icmp -m state --state NEW  -j ACCEPT > bar

With any awk:
awk 'match($0,/-m.comment.*"/) {
    print substr($0,RSTART,RLENGTH) " > foo"
    print substr($0,1,RSTART-1) substr($0,RSTART+RLENGTH) " > bar"
}' file

Just change " > foo" to > "foo" and ditto for bar to really write to new files.
If that's not exactly what you need then edit your question to clarify your requirements and provide more truly representative sample input/output.
Oh and when you wrote:
$NF == "-m.comment.*\""

There's nothing wrong with -m.comment.*\" as a regexp per-se BUT == is telling awk to do a literal string comparison, not a regexp comparison.
Given your updated question, just tweak the above to:
awk 'match($0,/(.*)(-m.comment.*")(.*)/,a) {
    print a[2] " > foo"
    print a[1] a[3] " > bar"
    next
}
{ print $0 " > bar" }' file
-P INPUT ACCEPT > bar
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT > bar
-m comment --comment "Echo Request" > foo
-A INPUT -p icmp -m state --state NEW  -j ACCEPT > bar
-m comment --comment "tcp" > foo
-A INPUT -p tcp -m state --state NEW  -j ACCEPT > bar


text:
Q: ASP.NET: Getting System.Web.HttpUnhandledException in production env I am trying to host a website developed in ASP.NET 4 Webforms. While it is running just fine in my Visual Studio 2012, it isn't at remote IIS (version 7.5).
Here is the stacktrace of the exception:-
Exception of type 'System.Web.HttpUnhandledException' was thrown.
   at System.Web.UI.Page.HandleError(Exception e)
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
   at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
   at System.Web.UI.Page.ProcessRequest()
   at System.Web.UI.Page.ProcessRequest(HttpContext context)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Can anybody please help me with this issue?


text:
Q: Add CSS to Active class This might be an easy go for the designers but I'm finding it hard to apply a CSS styling to it.

Some Text

Pls tell me the CSS class for it to apply style when it is having active class.

A: To apply a style to the whole li:
.labelRow.active {
  /* your styles*/
}

for just the span:
.labelRow.active span {
  /* your styles*/
}

note the lack of space between .labelRow and .active.

A: This is the selector you would use.
.labelRow.active {
  /* styles here */
}

A: if the .labelRow.active{} try li .active{}


text:
Q: ImageButton not aligning to center Given the following markup for a GridView column, why are my image buttons showing up as left aligned?
<ItemStyle HorizontalAlign="Center" Width="55px" />
<ItemTemplate>
    <asp:ImageButton ID="removeButton" runat="server"
        ImageUrl="~/Images/Icons/x-m.png"
        CommandArgument='<%# Eval("ResourceId") %>'
        AlternateText="Remove Button"
        onclick="removeButton_Click" />
</ItemTemplate>

A: Can you use css?  You might have better luck styling using the following css.
Lets say width of x-m.png is 25px;
.X { width: 55px; }
.Y { display: block; margin: 0 auto;  width: 25px; }

<ItemStyle cssClass="X" />
<ItemTemplate>
        <asp:ImageButton ID="removeButton" runat="server"
        ImageUrl="~/Images/Icons/x-m.png"
        CommandArgument='<%# Eval("ResourceId") %>'
        AlternateText="Remove Button"
        onclick="removeButton_Click"
        cssClass="Y"/>
</ItemTemplate>


text:
Q: spotify web api with java I want to make some searches in spotify database only for learning purpose of rest app.
I'm stuck on the first point of
https://developer.spotify.com/documentation/general/guides/authorization-guide/
Authorization Code Flow
to login in spotify with java app:
package spotify;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/*
    1) https://developer.spotify.com/dashboard/applications
*/

public class SpotifyMain {

    static final String CLIENTID = "blablablablablablablabla";
    static final String CLIENTSECRET = "blablablablablablablabla";
    static final String REDIRECTURL = "https://github.com/blablablablablablablabla"; //whiltelisted set inside spotify

    public static void main(String[] args) {
        try {
            String url_auth =
            "https://accounts.spotify.com/authorize?"
            + "client_id="+CLIENTID+"&"
            + "response_type=code&"
            + "redirect_uri="+REDIRECTURL+"&"
            + "scope=user-read-private%20user-read-email&"
            + "state=34fFs29kd09";

            System.out.println(url_auth);

            URL url = new URL(url_auth);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
            conn.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

I get error 406.
The url I think is correct because if I put that url inside a browser it displays correctly that the app want to access some resources.
If I put that url inside postman the error changes in 400 bad request...
Am I missing something?
thanks

A: Try removing this line:
conn.setRequestProperty("Accept", "application/json");

HTTP 406 Error is "Not Acceptable" meaning the server has generated a reply that it can't return as the requested Accept content type.

A: You are trying to open a webpage (HTML) via code and you set
conn.setRequestProperty("Accept", "application/json");

This will not work for auth. You should open the link in the browser, let the user sign in and take the code from the redirect url.


text:
Q: {{if}} of jQuery template not working in visual studio I have code as follows
<select id="TaskStatusDropdown">
    <option value="1" {{if TaskStatus == 1}}selected="selected"{{/if}}>Not Started</option>
    <option value="2">Pending</option>
    <option value="3">Complete</option>
</select>

The problem is that the {{if}} is not working, i.e. i get message in visual studio that "Attribute name must be followed by = sign and value. If the value is in quotation marks, the quotation marks must match"
Is this anything specific to visual studio or do i have the syntax incorrect?

A: In you code you do not have the closing tag for if condition. So you should close the if condition like this
{{if}} {{/if}}

A: This message is just a validation warning because the template is not html valid.
You can move it to a script tag with type text/x-jquery-tmpl but you'll lose the syntax highlight
<script type="text/x-jquery-tmpl" id="TaskStatusDropdown">
   <select>
      <option value="1" {{if TaskStatus == 1}}selected="selected"{{/if}}>Not Started</option>
      <option value="2">Pending</option>
      <option value="3">Complete</option>
   </select>
</script>

or just ignore the message. There is no type in VS for the jQuery template syntax.
If the condition in the template is not working that means there is something wrong with other things. So paste code with .tmpl call and in which files do you keep template (.cshtml, .html)? Is it in <script> tag or not?


text:
Q: Cannot run nvidia-settings after switching to Power Saving Mode I'm on ubuntu 18.04.
I installed nvidia-driver-390 through my Software & Updates and it started Performance mode, which I don't need for the most of the time so I switched to Power Saving mode, it hang for a while and told me to reboot and so I did. But now I can't start nvidia-settings to turn performance mode back on, I get following errors when trying to run sudo nvidia-settings
ERROR: NVIDIA driver is not loaded

ERROR: Unable to load info from any available system

While I'm pretty sure it should start in some kind of poor-mode with limited options.
Did I do something wrong or is that a bug? How do I switch between modes?

A: This is because when you are switching to power saving mode, nvidia-settings is creating a file called /etc/modprob.d/blacklist-nvidia.conf. This file should be cleared when you switch mode back to nvidia, which is not happening in 18.04.
If you wish to switch to nvidia again, you will have to manually remove this file and reboot. only switching to nvidia from nvidia-settings wont work in 18.04. There is an bug raised for this here. There are also some said fixes for this out there, but none has worked for me.
I am struggling with similar nvidia card issues on 18.04, due to some internal changes in the drivers, switch to wayland, and other things it seems like a mess on 18.04. There was chat that some of these should be fixed in 18.10, it not a very long wait, so look forward to it. :)

A: I am facing the same issue. After selecting Intel (Power Saving mode) and doing restart. I am getting same error. But I cannot /etc/modprob.d/blacklist-nvidia.conf


text:
Q: Mysterious auth failure only with MongoDB client on remote machines I can connect and authenticate normally using mongo client locally on the db server. I can not remotely. I can connect from a remote host, but db.auth always fails with the correct credentials that work locally, and also work remotely using the pymongo client. So this works:
> python
> import pymongo, config
> pymong.MongoClient(host=config.database_host)['live'].collection_names()

Yet this does not!
> mongo db.example.com/live
> db.auth('live', 'secret')
0
>

However, locally from the db server, the exact same thing does work, so I'm certain I'm using the right syntax and credentials :-(. What could possibly be going on here? In the server log I see:
2016-10-09T04:44:21.368+0000 I ACCESS   [conn22763]  authenticate db: live { authenticate: 1, nonce: "xxx", user: "live", key: "xxx" }
2016-10-09T04:44:21.368+0000 I ACCESS   [conn22763] Failed to authenticate live@live with mechanism MONGODB-CR: AuthenticationFailed: MONGODB-CR credentials missing in the user document

Perhaps it's a client version issue?

A: I already answered it in the original post. It was a simple major version number mismatch between mongo client and server. This took me many hours to figure out because the error is straight up completely wrong, not to mention not even reported from the client I was trying, so had to dig it out of server logs.


text:
Q: Difficulties retrieving List within List> I am having trouble with the below code:
foreach (var result in results)
{
    foreach (int individualresult in result)
    {
         //Operation
    }
}

'results' is a List<List<int>> and I am trying to retrieve each integer from each list within the 'results' list of lists (sorry if that's confusing), however when I run the code no errors are received but it doesn't get any further than the first line.
I've put it in a 'try catch' and it doesn't pick up any exceptions or errors so I am flummoxed as to why it isn't working. Additionally I have tried changing var to List<int> but that didn't change anything either.
Any and all help will be appreciated. Thanks

A: Try this code in a Console-Application and check the Output. I assume that ether your results is empty or that each individual List in your results is empty.
Console.WriteLine("Start");
if (results == null || !results.Any())
    Console.WriteLine("No result received!");

foreach (var result in results)
{
    Console.WriteLine("new result-set");
    if (result == null || !result.Any())
        Console.WriteLine("    Result: Empty list!");

    foreach (var individualresult in result)
    {
        Console.WriteLine("   Result: " + individualresult);
    }
}
Console.WriteLine("End");
Console.Readline();

A: See this example it might help you
    class Program
{

    static void Main(string[] args)
    {

        List<int> list1d = new List<int>();
        List<List<int>> list2d = new List<List<int>>();

        for (int i = 0; i < 10; i++)
        {
            list1d = new List<int>();
            for (int j = 0; j < 10; j++)
            {
                list1d.Add(i * j + i);
            }
            list2d.Add(list1d);
        }

        foreach (var result in list2d)
        {

            foreach (var i  in result)
            {
                Console.WriteLine(i);
            }

        }

        Console.ReadKey();
    }
}


text:
Q: Silverlight WCF issue with cross-domain policy file Ive seen a number of threads on this issue but none have worked for me. I have a simple silverlight application. I consume a WCF service. When I call a method GetOrderList from the service I get the following error:
An error occurred while trying to make a request to URI 'https://testserver2.mydomain.org/ORDERNET/WCFServices/OrderService/OrderService.svc'. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details.
Here is my code:
public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            ServiceReference1.ServiceClient sc = new ServiceReference1.ServiceClient();
            sc.GetOrderListAsync("testuser");
            sc.GetOrderListCompleted += new EventHandler<ServiceReference1.GetOrderListCompletedEventArgs>(sc_GetOrderListCompleted);
        }

        void sc_GetOrderListCompleted(object sender, ServiceReference1.GetOrderListCompletedEventArgs e)
        {
            var RESULT = e.Result;
        }
    }

This is my client access policy file that I put on my wwwroot:
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
<policy>
      <allow-from http-request-headers="*">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

When I run fiddler, it finds the "clientaccesspolicy.xml" with a 200 OK (text/xml) so I know is finding the file.
What could be the issue? Do I have an invalid policy file? If I create a console application and consume the service, I can call the method with thno problem.
Any ideas?

A: <?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="SOAPAction">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

Silverlight Cross Domain Web Service Access Error - This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place
thanks.....

A: I had similar issue but with service having http protocol, which was solved using .clientconfig file.

A: I notice you are using HTTPS (https://testserver2.mydomain.org/ORDERNET/WCFServices/OrderService/OrderService.svc)
Have you tried explicitly adding a https://* uri to your cross domain policy file:
<domain uri="https://*"/>

If you need to support http, then add both:
<domain uri="http://*"/>
<domain uri="https://*"/>


text:
Q: Updates table missing in Joomla 3 Joomla 3.x comes with a handy Update Joomla extension, this updates any extensions on the site including the Joomla core. Unfortunately on some installs (primarily one's migrated from Joomla 1.5 to Joomla 3.x) the "#__updates" table is missing from the database.

A: After spending hours trawling the internet, I worked out the missing tables and have written the following MySQL query which solves this issue:
DROP table IF EXISTS #__updates;
CREATE TABLE `#__updates` (
  `update_id` int(11) NOT NULL AUTO_INCREMENT,
  `update_site_id` int(11) DEFAULT '0',
  `extension_id` int(11) DEFAULT '0',
  `name` varchar(100) DEFAULT '',
  `description` text NOT NULL,
  `element` varchar(100) DEFAULT '',
  `type` varchar(20) DEFAULT '',
  `folder` varchar(20) DEFAULT '',
  `client_id` tinyint(3) DEFAULT '0',
  `version` varchar(32) DEFAULT '',
  `data` text NOT NULL,
  `detailsurl` text NOT NULL,
  `infourl` text NOT NULL,
  `extra_query` VARCHAR(1000) DEFAULT '',
  PRIMARY KEY (`update_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Available Updates';

A: I had the same problem, more than once (with new installed Joomla 3.x). Joomla reported x_updates doesn't exist.
The query provided here faulted with x_updates already exists. Only after adding DROP table IF EXISTS 'x_updates'; before the code the table was created.
This may mean some plugins have to be reinstalled in Joomla and other work using this plugins is lost.

A: Just look at the original code, it's rather simple and it takes 2 minutes.
--
-- Table structure for table `#__updates`
--

CREATE TABLE IF NOT EXISTS `#__updates` (
  `update_id` int(11) NOT NULL AUTO_INCREMENT,
  `update_site_id` int(11) DEFAULT 0,
  `extension_id` int(11) DEFAULT 0,
  `name` varchar(100) DEFAULT '',
  `description` text NOT NULL,
  `element` varchar(100) DEFAULT '',
  `type` varchar(20) DEFAULT '',
  `folder` varchar(20) DEFAULT '',
  `client_id` tinyint(3) DEFAULT 0,
  `version` varchar(32) DEFAULT '',
  `data` text NOT NULL,
  `detailsurl` text NOT NULL,
  `infourl` text NOT NULL,
  `extra_query` VARCHAR(1000) DEFAULT '',
  PRIMARY KEY (`update_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Available Updates';


text:
Q: Create NSManagedObject Subclass... make a new Error in my project i want to add a class for my entity by Editor\Create NSManagedObject Subclass... menu . but when i added it , the project made an error , this is the message:
Multiple commands produce '/Users/mohsenkhodadadzadeh/Library/Developer/Xcode/DerivedData/walk-fcnteanemrfigmfaalqkvwigvwqc/Build/Intermediates.noindex/walk.build/Debug-iphonesimulator/walk.build/Objects-normal/x86_64/WalkEntity+CoreDataProperties.o':
1) Target 'walk' (project 'walk') has compile command for Swift source files
2) Target 'walk' (project 'walk') has compile command for Swift source files

Multiple commands produce '/Users/mohsenkhodadadzadeh/Library/Developer/Xcode/DerivedData/walk-fcnteanemrfigmfaalqkvwigvwqc/Build/Intermediates.noindex/walk.build/Debug-iphonesimulator/walk.build/Objects-normal/x86_64/WalkEntity+CoreDataClass.o':
1) Target 'walk' (project 'walk') has compile command for Swift source files
2) Target 'walk' (project 'walk') has compile command for Swift source files

i changed that build system to Legacy Build system in  File->Project settings . but it diden't work yet
this project made with xcode9 and i develope it with xcode 10 now

A: Select the xcdatamodeld file in the project navigator, select the entity and press ⌥⌘3 – in Xcode 13 ⌥⌘4 – to show the Data Model Inspector.
If you created the class manually the Codegen popup must be set to Manual/None otherwise the class file is created implicitly.

A: In Xcode 11
1.Remove info list from Build Phases > Copy Bundle Resources
2.Remove Created Subclass from Build Phases > Compile Sources
Than Run if its not working use legacy build settings
From: File > Project Settings > build settings > legacy build settings


text: Q: OpenNMS Name OID to Numeric OID translation in Java I am using OpenNMS for the first time, and I simply want to take a fully resolved OID like sysContact.0 and get its dot numeric representation and vice versa.


text:
Q: Apply Periodic Boundary to PDE (Fourier Transform) Use Fourier Transform to solve the BVP:
\begin{cases}
u_t + a u_x - b u_{xx} = 0, & \mbox{for } x \in [-1,1] \\
u(x,0) = f(x) \\
u(x+2,t) = u(x,t)
\end{cases}
I solved the problem (attached); however, I do not know how to apply the periodic boundary condition. I know how to do it with separation of variable, but not for any Integral Transform method. Please help. Thank you.

A: The way I view the use of the FT using periodic BCs is that the problem is really about expressing the solution in terms of Fourier series with the "transform" being the Fourier coefficients.
The periodic BC's imply that
$$u(x,t) = \sum_{n=-\infty}^{\infty} c_n(t) e^{i n \pi x} $$
where
$$f(x) = \sum_{n=-\infty}^{\infty} c_n(0) e^{i n \pi x} $$
Thus,
$$c_n(t) = \frac12 \int_{-1}^1 dx \, u(x,t) \, e^{-i n \pi x} $$
Now,
$$u_t + a u_x - b u_{xx} = 0 $$
implies that
$$c_n'(t) + (i n \pi a +n^2 \pi^2 b) c_n(t) = 0 $$
or
$$c_n(t) = c_n(0) e^{-i n \pi a t} e^{-n^2 \pi^2 b t} $$
where
$$c_n(0) = \frac12 \int_{-1}^1 dx \,f(x) e^{-i n \pi x}$$
The solution to the equation is therefore
$$u(x,t) = \sum_{n=-\infty}^{\infty} c_n(0) e^{i n \pi (x-a t)} e^{-n^2 \pi^2 b t}$$
If $f(x) \in \mathbb{R}$, then $c_{-n}(0) = c_n(0)^*$ and

$$u(x,t) = c_0(0) + 2 \sum_{n=1}^{\infty} \left [\operatorname{Re}{[c_n(0)]} \cos{[n \pi (x-a t)]}+\operatorname{Im}{[c_n(0)]} \sin{[n \pi (x-a t)]}\right ] e^{-n^2 \pi^2 b t}$$


text:
Q: how to get all variable and type data in class and method using java I have a class and i want to find all variable and type data.
for e.g
class ex
{
    String A,B;
    public void method()
    {
        int a;
        double C;
        String D;
    }
}

so i want output like this
A : String
B : String
a : int
C : double
D : String

A: You can use the methods Class.getDeclaredMethods() and Class.getDeclaredFields() from the Reflection API to list a class methods and attributes.
for (Method m : ExampleClass.class.getDeclaredMethods()) {
    System.out.println(m.getName() + ": " + m.getGenericReturnType());
}

for (Field f : ExampleClass.class.getDeclaredFields()) {
    System.out.println(f.getName() + ": " + f.getType());
}

But you can not normally access the local variables information. In Java 8, you have access to the methods parameters using the method Method.getParameters(). So you could do:
for (Method m : ExampleClass.class.getDeclaredMethods()) {
    for (Parameter p : m.getParameters()) {
        System.out.println(p.getName() + ": " + p.getType());
    }
}

The parameter names are not stored by default in the .class files though, so the parameters will be listed as arg0, arg1, etc. To get the real parameter names you need to compile the source file with the -parameters option to the javac compiler.

A: check reflection, you can get all the info of a class on runtime

A: You can use reflection to get A and B for sure. But you can't get same info for other local variables.


text:
Q: Reducing nonlinear equations to obtain simplified form Apologies in advance if my question has been posed in a nonstandard way.
I am currently reading a journal article that contains the following two equations:
$\lambda_{u}\cos \gamma_{T}-(\lambda_{v}\cos\psi_{T}+\lambda_{w}\sin\psi_{T})\sin\gamma_{T}=0$
$-\lambda_{v}\sin\psi_{T}+\lambda_{w}\cos\psi_{T}=0$
Using the above two equations, the author states that the following three results can be obtained:
$\sin\gamma_{T}=\lambda_{u}/\lambda_{V}\\ \cos\gamma_{T}\cos\psi_{T}=\lambda_{v}/\lambda_{V}\\
\cos\gamma_{T}\sin\psi_{T}=\lambda_{w}/\lambda_{V}$
where $\ \lambda_{V}=\sqrt{\lambda_{u}^{2}+\lambda_{v}^{2}+\lambda_{w}^{2}}$. After several attempts at deriving these results, I have unfortunately not been able to obtain these results. I would be extremely grateful if someone could kindly take a look at the above relationships and advise whether these results can indeed be obtained.
Many thanks.

A: Write your two equations in the following form:
cosψ·λv + sinψ·λw = cotγ·λu
-sinψ·λv + cosψ·λw =   0
and solve them to get
λv = cotγ·λu·cosψ
λw = cotγ·λu·sinψ
It follows that λV = λu·√(1+cot²γ) = λu/sinγ,whence the values
of the the ratios λu/λV, λv/λV, λw/λV follow readily.

A: Let $\theta=\gamma_T$ be the azimuthal angle and $\phi=\psi_T$ the axial angle in a spherical coordinate system $(r,\theta,\phi)$. Let $\boldsymbol{\lambda}=-\lambda_v\mathbf{\hat{x}}-\lambda_w\mathbf{\hat{y}}+\lambda_u\mathbf{\hat{z}}$ where $\{\mathbf{\hat{x}},\mathbf{\hat{y}},\mathbf{\hat{z}}\}$ are the Cartesian unit vectors. Then the two given equations are
$$\begin{align}\boldsymbol{\lambda}\cdot\mathbf{\hat{r}}&=0\\
\boldsymbol{\lambda}\cdot\boldsymbol{\hat{\phi}}&=0
\end{align}$$
which implies
$$\begin{align}
\boldsymbol{\hat{\lambda}}=\pm\boldsymbol{\hat{\theta}}
\end{align}$$
where the $\{\mathbf{\hat{r}},\boldsymbol{\hat{\theta}},\boldsymbol{\hat{\phi}}\}$ are the spherical-coordinate unit vectors and $\boldsymbol{\hat{\lambda}}$ is the unit vector in the $\boldsymbol{\lambda}$ direction. The results you give correspond to $\boldsymbol{\hat{\lambda}}=-\boldsymbol{\hat{\theta}}\text{.}$


text:
Q: Alchemist potion on Undead When an Alchemist uses their non-coven potion on other factions, then a Wolfpack member will become either a normal Werewolf or a Shape Shifter, and a Village member will become either a Villager, Lycan, Sleepwalker, Insomniac, or Stalker.  Vampires and familiars are not affected by the potion.
But if an Alchemist targets an Undead player with their purge potion, what role does the Undead player become?

A: An Undead player will become either a Wight or a Ghoul.

A: Actually, believe it or not, but an undead purged by the alchemist was once turned into a villager role. Would love to hear an update from the mods if this no long happens anymore.
Source: A spud I hosted long ago. Can't remember the number right now, but I'll update the answer once I check the archives.


text:
Q: preg_replace to change text start with '@' and end with '@\n' i have s string such as this :
@
String mystr = "test@example.com"
String mystr = test@@@@::example.com;
@

i want to change first '@' to [code] and secont last '@' to [/code].
after first and last '@' we have space or '\n'.
this code is not work for me :
$text = preg_replace('#[@](.|)(.*?)[@\n]#',"'
$2
'",$text);

A: I'd say easiest way is non-regexp way:
$splitted = str_split($your_string, "@");
$first = array_shift($splitted);
$last = array_pop($splitted);

$result = "[code]" . implode("@", $splitted) . "[/code]";

Or something similar, whatever you see best.

A: If you want to consider the newlines in the subject string, you need to add to add the 'm' modifier to the regexp and maybe 's' too.
This snippet does what you're asking:
<?php
$test = <<<END
@
String mystr = "test@example.com"
String mystr = test@@@@::example.com;
@

END;

echo preg_replace('/@\s(.*)@\s/sm', "\n$1\n", $test);
?>

Output:

String mystr = "test@example.com"
String mystr = test@@@@::example.com;

If there's more than one pair of '@' in the input string, then the regexp should include the 'U' modifier:
<?php
$test = <<<END
@
String mystr = "test@example.com"
String mystr = test@@@@::example.com;
@

@
String mystr2 = "test2@example.com"
String mystr2 = test@@@@2::example.com;
@

END;

echo preg_replace('/@\s(.*)@\s/smU', "\n$1\n", $test);
?>

Output:

String mystr = "test@example.com"
String mystr = test@@@@::example.com;

String mystr2 = "test2@example.com"
String mystr2 = test@@@@2::example.com;


text:
Q: How to Save a Coda Object in R I'm unsure of how to save a coda (mcmc.list) object in R. Others have asked similar questions, but I found that the answers given were not particularly clear. Ideally I'd like to save the coda object as an R.data file or a text file (e.g., csv), so that I can reimport it and analyze the JAGS chains without having to rerun the model (which takes about 30 minutes on my computer). Right now my coda object "coda.samples" looks like this:
str(coda.samples)
List of 3
 $ : mcmc [1:3334, 1:1094] 0.904 0.977 0.927 0.945 0.905 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:3334] "2001" "2011" "2021" "2031" ...
  .. ..$ : chr [1:1094] "alpha[1,1]" "alpha[2,1]" "alpha[1,2]" "alpha[2,2]" ...
  ..- attr(*, "mcpar")= num [1:3] 2001 35331 10
 $ : mcmc [1:3334, 1:1094] 0.824 0.866 0.839 0.832 1.032 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:3334] "2001" "2011" "2021" "2031" ...
  .. ..$ : chr [1:1094] "alpha[1,1]" "alpha[2,1]" "alpha[1,2]" "alpha[2,2]" ...
  ..- attr(*, "mcpar")= num [1:3] 2001 35331 10
 $ : mcmc [1:3334, 1:1094] 0.956 0.944 0.895 0.809 1.064 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:3334] "2001" "2011" "2021" "2031" ...
  .. ..$ : chr [1:1094] "alpha[1,1]" "alpha[2,1]" "alpha[1,2]" "alpha[2,2]" ...
  ..- attr(*, "mcpar")= num [1:3] 2001 35331 10
 - attr(*, "class")= chr "mcmc.list"

As you can see, it's a list of three matrices that contain 3334 estimates of 1094 parameters (i.e., 3 chains of length 3334). I'd like to store this coda object so that I can call it back into R without having to rerun the model over again each time. I also want to preserve the fact that there are three unique chains.

A: This is the script I use when saving chains from MCMCglmm. Replace the OBJECT with the name of your coda object (e.g. the name of the model as made in MCMCglmm), and replace FILEPATH with a suitable save destination.
save(OBJECT, file= "FILEPATH")
model = load("FILEPATH")

Handy Tip: I also wrap my models in switches using if and else - this can be combined to make a useful system that either runs and saves the script, or loads a previous run (setting runmod to y or n, and choosing loaddate to get the right file. For example:
runmod = "y"
loaddate = "2017-01-12"

NITT = 130000
BURN =  30000
THIN =    100

# Model
if(runmod=="n"){
model4.1 = MCMCglmm(cbind(BWT_F, BWT_M, TAR_F, TAR_M) ~ trait-1,
        random = ~us(trait):animal + us(trait):BYEAR + us(trait):MOTHER,
        rcov = ~us(trait):units,
        family = rep("gaussian", times = 4),
        pedigree = Ped,
        data = Data,
        burnin = BURN,
        nitt = NITT,
        thin = THIN,
        prior = prior4.1)
        save(model4.1, file=paste0("FILEPATH......",NITT,"_",Sys.Date(),".rda"))
}else{
model41 = load(paste0("FILEPATH......",NITT,"_",loaddate,".rda"))
}


text:
Q: PHPMailer does not give error message? Im creating a little Email Script at the Moment with PHPMailer + SMTP Authentication. I tried now sending an E-Mail using a wrong Passwort - but it still gives back "true" for success... anyone have any idea?`
Here is My Function, that i use to call sendmail:
$erfolg_email = true;
    foreach($empfaenger as $value)
    {

        $response = $this->sendMail($smtp, $value, $content, $files);
        if($response != true)
        {

            return $response;
            $erfolg_email = false;

        }

    }

And here is my PHPMailer Function
function sendMail($smtp, $empfaenger, $content, $attachements)
{

    $mail = new PHPMailer(true);

    try{

        $mail->IsSMTP();
        $mail->Host = $smtp['SMTP'];
        $mail->SMTPAuth = true;     // turn on SMTP authentication
        $mail->Port = $smtp['Port'];
        $mail->SMTPSecure = 'tls';
        if($smtp['Domain'] != '')
        {

            $username = $smtp['Username']."@".$smtp['Domain'];

        }else
        {

            $username = $smtp['Username'];

        }
        $mail->Username = $username;  // SMTP username
        $mail->Password = $smtp['Password']; // SMTP password
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );
        $mail->From = $smtp['Email_Address'];
        $mail->AddAddress($empfaenger);
        $mail->WordWrap = 50;
        $mail->isHTML(true);

        foreach($attachements as $value)
        {

            $mail->AddAttachment($value);

        }
        $mail->Subject = "Mahnung";
        $mail->Body = $content;
        $mail->AltBody = "Sie haben offene Posten";

        if($mail->Send() == true)
        {

            echo $mail->ErrorInfo;
            return $mail->ErrorInfo;

        }else
        {

            return $mail->ErrorInfo;

        }

    } catch (phpmailerException $e) {

        return $e->errorMessage(); //Pretty error messages from PHPMailer

    } catch (Exception $e) {

        return $e->getMessage(); //Boring error messages from anything else!

    }
}

$smtp contains an array with all the SMTP INformation, Email address, Signature, Smtp Server, Port, Username, Password and SSL Usage...
I am pretty sure, I am using the wrong username and password, as no Email is getting through - but i still get "true" as a result of the send mail function... its not even echoing the error. I did even try to give an Error Message, when sending is successfull... But nothing
Any help is apreciated!
Cheers

A: Your function sendMail doesn't return a boolean. Since it's an array / object the result is always true in this case. Try printing $response before your if statement and you will see the error.

A: In your php mailer function file itself you can add this coding at the last:
$send = $mail->Send(); //Send the mails
    if($send){
        echo '
Mail sent successfully
';
    }
    else{
        echo '
Mail error:
'.$mail->ErrorInfo;
    }
}


text:
Q: How to implement custom constraint using C++? I am trying to reimplement littledog.ipynb using C++. I find it is hard to translate the function velocity_dynamics_constraint and have 3 questions

*

*What is the function of ad_velocity_dynamics_context? Can we ignore it?

*How to reimplement velocity_dynamics_constraint using C++? Do I have to create a new class like class VelocityDynamicsConstraint : public drake::solvers::Constraint? Is three any easier way to implement it?

*Why we need to consider isinstance(vars[0], AutoDiffXd) condition?

# Some code from https://github.com/RussTedrake/underactuated/blob/master/examples/littledog.ipynb
ad_velocity_dynamics_context = [
    ad_plant.CreateDefaultContext() for i in range(N)
]

def velocity_dynamics_constraint(vars, context_index):
    h, q, v, qn = np.split(vars, [1, 1+nq, 1+nq+nv])
    if isinstance(vars[0], AutoDiffXd):
        if not autoDiffArrayEqual(
                q,
                ad_plant.GetPositions(
                    ad_velocity_dynamics_context[context_index])):
            ad_plant.SetPositions(
                ad_velocity_dynamics_context[context_index], q)
        v_from_qdot = ad_plant.MapQDotToVelocity(
            ad_velocity_dynamics_context[context_index], (qn - q) / h)
    else:
        if not np.array_equal(q, plant.GetPositions(
                context[context_index])):
            plant.SetPositions(context[context_index], q)
        v_from_qdot = plant.MapQDotToVelocity(context[context_index],
                                              (qn - q) / h)
    return v - v_from_qdot
for n in range(N-1):
    prog.AddConstraint(partial(velocity_dynamics_constraint,
                                context_index=n),
                        lb=[0] * nv,
                        ub=[0] * nv,
                        vars=np.concatenate(
                            ([h[n]], q[:, n], v[:, n], q[:, n + 1]))

A:
What is the function of ad_velocity_dynamics_context? Can we ignore it?

The context caches the intermediate computation result for a given q, v, u. It is very common that several constraints are imposed on the same set of q, v, u (for example, consider at the final time, we typically have a kinematic constraint on the final state, say the robot foot has to land on the ground and its center of mass is at a certain location. At the same time we we have the velocity dynamics constraint on the final state). Hence these different constraints can share some intermediate computation result, such as the rigid transform between each adjacent links. Hence we cache the result in ad_velocity_dynamics_context, and this ad_velocity_dynamics_context can be used later when we impose other constraints.

How to reimplement velocity_dynamics_constraint using C++? Do I have to create a new class like class VelocityDynamicsConstraint : public drake::solvers::Constraint? Is there any easier way to implement it?

That is right, you will need to create a new class VelocityDynamicsConstraint. The main challenge in implementing this class is to write the three overloaded DoEval function for three scalar types (double, AutoDiffXd, symbolic::Expression). You can refer to PositionConstraint as a reference. And for the moment you can ignore the case to call DoEval(const Eigen::Ref<const AutoDiffXd>&, AutoDiffXd*) with a MultibodyPlant<double> case, and only implement the this DoEval function with MultibodyPlant<AutoDiffXd>.

Why we need to consider isinstance(vars[0], AutoDiffXd) condition?

Because when the scalar type is AutoDiffXd, we want to compare not only the value of q against the one stored in context, but also its gradient. If they are different, then we need to call SetPositions to recompute the cache. When the scalar type is double, we then only need to compare the value.


text:
Q: Switch to last active session in tmux I want to know is it possible to switch to last session I visited in tmux.
For e.g., suppose I was in pane 1 of session A and I switched to pane 1 in session B (using PREFIX s and selecting the pane 1 in B). Now I want to switch back to pane 1 of session A.
Is there any keybinding for that?

A: Switch between sessions:
C-b (          previous session
C-b )          next session
C-b L          'last' (previously used) session
C-b s          choose a session from a list


text:
Q: Need to loop switch statement until 1 or 2 is entered I need to loop the switch statement until 1 or 2 is entered as an input. Any help would be nice or sample code. I tried to use a while loop and it kept crashing. I tried a do while as well and it turned into an infinite loop so I must be doing something wrong.
int main (void)
{
    int choice; // choice to run program from start menu or quit

    while (1)
    {
        // Menu for entering resistor and capacitor values
        printf("Welcome to the 555 Timer Frequency and Duty Cycle Calculator\n");
        printf("Please enter two resistor values in between ");
        printf("1 kOhms and 100 kOhms and a capacitor value\n\n");

        //Start of menu
        printf("Menu\n\n");
        printf("1. Continue\n");
        printf("2. Exit\n");

        scanf("%d", &choice); // User inputs value

        switch (choice)
        {
        case 1:
            resistor(); // Program resistor is run if 1 is input
            break;
        case 2:
            printf("Goodbye."); // Program ends if 2 is input
            break; // break is used to exit while loop
        default:
            printf("Sorry I do not understand\n\n");
            fflush(stdin);  /* clears input buffer to allow user to input a new value if anything other
                               than 1 or 2 is input into scanf  */
        }

        break;
    }

    return 0;
}

A: The problem is that you have a "break" right at the end of your "while", so it's only executed once.
It has been a long time since I did program in C, but if I remember correctly you should avoid using "fflush()" since it has an undefined behavior. Instead, you can change your "scanf()" to be something like:
scanf(" %d", &choice); // User inputs value

That way, you have the same supposed effect of the "fflush()" at the same time of having a cleaner code.

A: You can use this code
for(;;) {
    // Menu for entering resistor and capacitor values

    // Start of menu

    // User inputs value

    if(choice == 1) { ... break; }
    else if(choice == 2) { ... return 0; } // If you use the break,the for loop will be stopped or You can use return 0; to return the whole function
    else { ... break; }
}

or, also you can use this code
for(;;) {
    switch(choice ) {
        case 1: ... break;
        case 2: ... return 0; // If you use the break, only switch statement is stopped. You can use return 0; to return the whole function

        default: ... break;
    }
}

Edit :
#include <stdio.h>

int main (void)
 {
int choice; // choice to run program from start menu or quit

// Menu for entering resistor and capacitor values
    printf("Welcome to the 555 Timer Frequency and Duty Cycle Calculator\n");
    printf("Please enter two resistor values in between ");
    printf("1 kOhms and 100 kOhms and a capacitor value\n\n");

while (1)
{

    //Start of menu
    printf("Menu\n");
    printf("1. Continue\n");
    printf("2. Exit\n");

    scanf("%d", &choice); // User inputs value

    switch (choice)
        {
            case 1: // Program resistor is run if 1 is input
                break;
            case 2: printf("Goodbye."); // Program ends if 2 is input
                 return 0; // return 0; is used to exit while loop

            default: printf("Sorry I do not understand\nStart Again !\n");
                // fflush(stdin);  /* clears input buffer to allow user to input a new value if anything other than 1 or 2 is input into scanf     */

                break;

        }

        printf("\n");

}

return 0;
}


text:
Q: Redundancy in Expression Dear fellow stackexchangers, I would like to have your comment on the following, exercepted from a recent White House press conference… with Obama speaking:
"But there have been Republican Presidents with whom I disagreed with, but I didn't have a doubt that they could function as President."
Shouldn't it be 'with whom I disagreed' rather than the above? Did Obama commit a grammatical redundancy in the above phrase?
Thank you.


text:
Q: ffmpeg always gives me input/output error for the first time running the command I'm using ffmpeg to push raspberrypi video feeds (CSI camera) to a nginx-RTMP server then the nginx push it to youtube.
My problem is, every time when I run the ffmpeg command, it always gives me input/out error. Then it is working fine when I run the exact same ffmpeg command for the 2nd time.
How do I resolve this problem?
I want to start the ffmpeg command in a script file and put the script in crontab so that it can start the live streaming automatically. But this error makes it impossible to do that.
my ffmpeg command is as below(change the real domain name to mydomain.com):
ffmpeg -thread_queue_size 512 -f v4l2  -f lavfi -i anullsrc=channel_layout=stereo:sample_rate=44100  -input_format yuyv422 -video_size 1280x720 -framerate 30 -i /dev/video0 -vf eq=gamma=1.5:saturation=1.3 -c:v h264_omx -b:v 20480K -vsync 1 -g 16  -f flv rtmp://mydomain.com:1935/live/

the error log:
Input #1, video4linux2,v4l2, from '/dev/video0':
  Duration: N/A, start: 474200.421802, bitrate: 442368 kb/s
    Stream #1:0: Video: rawvideo (YUY2 / 0x32595559), yuyv422, 1280x720, 442368 kb/s, 30 fps, 30 tbr, 1000k tbn, 1000k tbc
rtmp://rtmp.simonliu.space:1935/live/: Input/output error


text:
Q: Definite integral with difficult term in the denominator. I want to integrate $$\int_0^{2\pi} \frac{1}{\sqrt{r^2+R^2-2rR \cos(\phi)+(z-b)^2}}-\frac{1}{\sqrt{r^2+R^2-2rR \cos(\phi)+(z+b)^2}} d \phi.$$
You may assume that the denominator is not zero, as $z \neq b$. Furthermore, I think that even a series representation of the solution wuld be fine, so actually there is no restriction on the kind of solution I want to have as long as I get rid of this integral there.

A: You can turn it to a complete elliptic integral of the first kind with $\phi=2\theta$. http://en.wikipedia.org/wiki/Elliptic_integral#Complete_elliptic_integral_of_the_first_kind


text:
Q: Debug a Spring Boot application started in custom task in Intellij I use Spring Boot and want to execute Spotless to reformat code before bootRun everytime, so I write the following tasks in my build.gradle.kts:
task("startServer") {
    setGroup("Sample category")
    dependsOn(":security:spotlessApply", ":database:spotlessApply").finalizedBy(":convo:bootRun")
}

When I execute this task in debug mode, Intellij doesn't stop at the breakpoint, but if I execute the built-in bootRun task, it works.
How can I let Intellij debug the Spring Boot application started in my startServer tasks?

A: I find a way to achieve this, instead of writing a custom task, I add dependsOn directly in bootRun task in the application's (here is my convo module) build.gradle.kts:
tasks.withType<org.springframework.boot.gradle.tasks.run.BootRun>() {
    dependsOn(":database:spotlessApply").dependsOn(":security:spotlessApply")
}


text:
Q: Where is your mobile phone? When a person is taking an examination which prohibits anyone to take a mobile phone or any other recording devices, examiners often ask the question,

where is your mobile phone?

To answer this question in this context, which answer of the two below sounds natural? Or how should it be answered if neither is good enough?

I've left it home.
  I left it at home.

A: Although it's true most native speakers would reply "I left it at home" in this exact context, that doesn't imply "I have left it at home" (or contracted I've) is somehow incorrect or otherwise inappropriate.
The Present Perfect is normally used when you want to make a connection between the past action and the present moment. But in OP's example there's no need for the more complex tense; the connection between past/present is semantically implicit anyway, so you may as well use the simpler tense.
There aren't actually many contexts where the choice between present perfect/simple past makes much difference. One that comes to mind is...

1: He earned my trust [in the past, so I lent him some money, which unfortunately he never repaid]
   2: He has earned my trust [so I am now going to lend him some money, which I'm sure he will repay]

...in those examples, the bracketed supplementary text only really works with the tenses as given.

A: The simplest reply would be to just say

At home.

without anything. Of the two, the correct one would be

I left it at home.

I've left is better suited in cases when the object is stationary(as in user3169's case it is airport). And it suggests that the task is still not complete.
P.S.: Saying At home may sound offensive to professors. You may also reply with: "I did not bring it."


text:
Q: Inserting row based on condition I have a postgres table that is used to hold users files.  Two users can have a file with the same name, but a user isn't allowed to have two files with the same name.  Currently, if a user tries to upload a file with a name they already used, the database will spit out the error below as it should.

IntegrityError: duplicate key value violates unique constraint "file_user_id_title_key"

What I would like to do is first query the database with the file name and user ID to see if the file name is being used by the user.  If the name is already being used, return an error, otherwise write the row.
cur.execute('INSERT INTO files(user_id, title, share)'
            'VALUES (%s, %s, %s) RETURNING id;',
            (user.id, file.title, file.share))

A: The problem is that you cannot really do that without opening a race condition:
There is nothing to keep somebody else from inserting a conflicting row between the time you query the table and when you try to insert the row, so the error could still happen (unless you go to extreme measures like locking the table before you do that, which would affect concurrency badly).
Moreover, your proposed technique incurs extra load on the database by adding a superfluous second query.
You are right that you should not confront the user with a database error message, but the correct way to handle this is as follows:

*

*You INSERT the new row like you showed.

*You check if you get an error.

*If the SQLSTATE of the error is the SQL standard value 23505 (unique_violation), you know that there is already such a file for the user and show the appropriate error to the user.

So you can consider the INSERT statement as an atomic operation check if there is already a matching entry, and if not, add the row.


text:
Q: Detect every touch on the screen I want to detect in my app the touch of the user on the screen and reset some timer in this case. I found out that I can use onTouchEvent but it works only when I press free space without any button,.... I don't want to register touchEventListener on every View in my project. Is there some other way how to do it?

A: Indeed, first you must override this method in your activity:
public boolean onTouchEvent(MotionEvent event);

Then, you have to disable action for your clickable elements.

A: You should implement that OnTouchListener for the parent view and make child views non-clickable using setClickable(false)...
If that doesn't work you probably need to follow the method suggested in this answer

A: all you have to do is to override onInterceptTouchEvent (MotionEvent ev) method in your top level container view or you can override Activity.onUserInteraction but it also includes key and trackball actions


text:
Q: How to restore current directories after reopening? I use zsh (the default shell for macOS) and I have number of tabs opened, with different name.
The problem is that on restart it reopens tabs, but loses current directories.
Is there a way to make the shell to rostore directories after restart?


text:
Q: how to make a C# struct to be compatible with both x86 and x64 without using macro? considering the following code, is there any way to get rid of #if #else #endif macro? make the struct compatible with x86 and x64 system!
    public struct SP_INTERFACE_DEVICE_DATA
{
    #if bit32
    public int cbSize;
    #else
    public Int64 cbSize;
    #endif
    public GUID InterfaceClassGuid;
    public int Flags;
    public int Reserved;
}

I tried to make two struct but it fails because the complexity of the current code is overwhelming.
this struct is used by some api that import from dll by using DllImporting

A: You would normally use IntPtr instead, 4 bytes in 32-bit mode, 8 bytes in 64-bit mode.
But that would be incorrect, you can tell from the winapi declaration that the field is declared as DWORD.  It is 4 bytes in 64-bit mode as well.


text:
Q: How to get just the error message? I have this code
$('div#create_result').text(XMLHttpRequest.responseText);

where the content of XMLHttpRequest is
responseText: Content-Type: application/json; charset=utf-8
{"error" : "User sdf doesn't exist"}
status: 200
statusText: parsererror

The result I see is
Content-Type: application/json; charset=utf-8 {"error" : "User sdf doesn't exist"}

where I would have liked
User sdf doesn't exist

How do I get just that?

A: Don't use a regular expression for this. jQuery's built-in Ajax engine brings along everything that is needed to parse the JSON properly.
The most primitive example looks like this:
$.getJSON('your/url/here', function(data)
  { $('#create_result').text(data.error);}
);

Documentation

A: you can use a regular expresion to extract value; something like:
var pattern = new RegExp(": \"(.+)\"}");
var str = 'Content-Type: application/json; charset=utf-8 {"error" : "User sdf doesn\'t exist"}';
var match = pattern.exec(str);
alert(match[1]);


text:
Q: Vue js v-for v-bind not unique I'm trying to create a form where I have a select list (fetched from API) and user can add items into a seperate array from this list. New array is also rendered via v-for and uses v-model to edit some additional data.
For example I have a list of goods/services defined beforehand which will be rendered into select option block. Now user can select one of these products and add them to a invoice. After adding (pushed to a new array), user must be able to make some additional changes.
<select class="form-control" v-model="selectedServiceId">
    <option v-for="service in services" :value="service._id">{{service.name}}</option>
</select>

<button type="button" class="btn btn-primary" v-on:click="addService">Add</button>

add service method:
addService() {
    for (var i = 0; i < this.services.length; i++) {
      if (this.services[i]._id == this.selectedServiceId) {
        this.services_goods.push(this.services[i])
        break;
      }
    }
  }

And now I want to render the list I've pushed into:

            {{item.name}}
            Price €
              <input id="itemPrice" v-model="item.price">

            Quantity
              <input type="number" min="1" id="itemQty" v-model="item.quantity">

              <button type="button" v-on:click="removeService(item._id)">X</button>

everything is fine up until I add the same item twice and try to modify the price for one of them - it changes price for both.

A: The reason it changes the price for both is that they are the same object. When you insert an object into an array, the value in the array is a reference to the object. You have two references to the same object.
Each object you insert into the array should be newly created, with contents copied from the selected item.

new Vue({
  el: '#app',
  data: {
    selectedServiceId: null,
    services: [{
        _id: 1,
        price: 1,
        quantity: 1,
        name: 'First'
      },
      {
        _id: 2,
        price: 2,
        quantity: 2,
        name: 'Second'
      }
    ],
    services_goods: []
  },
  methods: {
    addService() {
      const foundGood = this.services.find((s) => s._id == this.selectedServiceId);

      // Object.assign copies an object's contents
      this.services_goods.push(Object.assign({}, foundGood));
    }
  }
});

  <select class="form-control" v-model="selectedServiceId">
    <option v-for="service in services" :value="service._id">{{service.name}}</option>
</select>

  <button type="button" class="btn btn-primary" v-on:click="addService">Add</button>

      {{item.name}}
      Price €
              <input id="itemPrice" v-model="item.price">

      Quantity
              <input type="number" min="1" id="itemQty" v-model="item.quantity">

        <button type="button" v-on:click="removeService(item._id)">X</button>


text:
Q: How to do a select that display 2 results based on 2 different where - TOAD I have these 2 queries, they both bring info from same table but different WHERE condition, How can I execute this in just one query that gives me the result as a table of 2 column one column with value of query one and second column with value of query 2.
QUERY 1
SELECT COUNT(*) AS FirstColumn

FROM MyTable

WHERE ThisValue !=1150 and Date = today-1;

QUERY 2
SELECT COUNT(*) AS SecondColumn

FROM MyTable

WHERE ThisValue = 1130 AND
((Station_Date = today-1 AND Station_Time > 120000)
or (Station_Date = today AND Station_Time <= 120000));

A: You can do conditional sums:
SELECT
    SUM(CASE
        WHEN ThisValue !=1150 and Date = today-1
        THEN 1
        ELSE 0
    END) AS FirstColumn,
    SUM(CASE
        WHEN ThisValue = 1130 AND (
           (Station_Date = today-1 AND Station_Time > 120000)
           OR (Station_Date = today AND Station_Time <= 120000)
        )
        THEN 1
        ELSE 0
    END) AS SecondColumn
FROM MyTable

A: I would suggest using the same conditions in the WHERE clause with OR operator to avoid scanning full table data as following:
SELECT
    SUM(CASE
        WHEN THISVALUE != 1150
             AND DATE = TODAY - 1 THEN 1
        ELSE 0
    END) AS FIRSTCOLUMN,
    SUM(CASE
        WHEN THISVALUE = 1130
             AND((STATION_DATE = TODAY - 1
                  AND STATION_TIME > 120000)
                 OR(STATION_DATE = TODAY
                    AND STATION_TIME <= 120000)) THEN 1
        ELSE 0
    END) AS SECONDCOLUMN
FROM
    MYTABLE
WHERE
    ( THISVALUE != 1150
      AND DATE = TODAY - 1 ) -- FIRST CONDITION
    OR ( THISVALUE = 1130 -- SECOND CONDITION TILL END
         AND ( ( STATION_DATE = TODAY - 1
                 AND STATION_TIME > 120000 )
               OR ( STATION_DATE = TODAY
                    AND STATION_TIME <= 120000 ) ) )

Cheers!!


text:
Q: A computable model of the natural numbers must be nonstandard? If I model the natural numbers with some object $0$ and an injective computable function $s$ such that $ \forall n ( s(n) \ne 0 )$. Then due to Rogers' fixed-point theorem there must be a natural number $\Omega$ for which $ s(\Omega) = \Omega $.
Am I overlooking something obvious here?

A: The theorem only gives you a number $\Omega$ such that $\varphi_\Omega$ is the same partial recursive function as $\varphi_{s(\Omega)}$ (where $\varphi_n$ is the partial recursive function computed by, say, the $n^{\text{th}}$ Turing machine). It doesn't say that $\Omega=s(\Omega).$


text:
Q: Passing USB file descriptor to Android NDK program I am trying to port some software written in C to the Android platform.  This software has a component that reads and writes from and to a connected USB device.  What I am trying to do is open up a connection to the device in Java, then pass the file descriptor for the USB device(s) to the JNI code.
Below is the (relevant) output of lsof for my app which shows I have two descriptors for the USB device:

com.tim    8861     u0_a66   35       ???                ???       ???        ??? /dev/bus/usb/001/002
com.tim    8861     u0_a66   36       ???                ???       ???        ??? socket:[51170]
com.tim    8861     u0_a66   37       ???                ???       ???        ??? socket:[51173]
com.tim    8861     u0_a66   38       ???                ???       ???        ??? /dev/bus/usb/001/003

I've passed both descriptors (above as 35 and 38) to my native method, but when I try and write to either of the file descriptors, write() returns -1, and I get an EINVAL error.
Here is the body of my native method:
char buff[1024] = {0};
jsize len = (*env)->GetArrayLength(env, fds);
jint *arr = (*env)->GetIntArrayElements(env, fds, 0);
int i;

char data[4] = {
    0x09,
    0x90,
    0x50,
    0x50,
};

for (i = 0; i < len; i++) {
    int wrote = write(arr[i], data, 4);

    int flags = fcntl(arr[i], F_GETFL);
    char *err = strerror(errno);
    sprintf(buff, "%sFD: %d  \n"
    "wrote: %d  \n"
    "(err: %d %s)  \n"
    "flags: %d  \n"
    "NBIO %d  \n"
    "readonly %d  \n"
    "writeonly %d  \n"
    "both %d  \n"
    "append %d  \n"
    "large file %d  \n\n", buff, arr[i], wrote, errno, err, flags, flags & O_NONBLOCK,
        flags & O_RDONLY, flags & O_WRONLY, flags & O_RDWR, flags & O_APPEND,
        flags & O_LARGEFILE);
}
return (*env)->NewStringUTF(env, buff);

The string that is returned when invoking that method is:

FD: 35
wrote: -1
(err: 22 Invalid argument)
flags: 32770
NBIO 0
readonly 0
writeonly 0
both 2
append 0
large file 32768

FD: 38
wrote: -1
(err: 22 Invalid argument)
flags: 32770
NBIO 0
readonly 0
writeonly 0
both 2
append 0
large file 32768

Writing to the USB device does work through Java, so it appears to just be an issue when trying to do it via native code.
Does anyone have any experience doing something like this?

A: It seems that using write() on a USB file descriptor doesn't exactly work, since there are multiple endpoints on the USB device where the data could be written.
I was able use the ioctl() function to perform a bulk transfer to a particular endpoint on the device:
#include <linux/usbdevice_fs.h>
#include <sys/ioctl.h>

// ...

char data[4] = {0x09, 0x90, 0x50, 0x50};

struct usbdevfs_bulktransfer bt;
bt.ep = usb_endpoint;  /* endpoint (received from Java) */
bt.len = 4;            /* length of data */
bt.timeout = 100;      /* timeout in ms */
bt.data = data;        /* the data */

int rtn = ioctl(fd, USBDEVFS_BULK, &bt);


text:
Q: SWRevealViewController sidebar is not presenting in iOS I am using SWRevealViewController in my project first time.
I follow This tutorial to do this.
What i did:
I added SWRevealViewController.h and SWRevealViewController.m in my project.
i import file in FirstViewController.h is like following:
#import <UIKit/UIKit.h>
#import "SWRevealViewController.h"
#import "SideBarTableViewController.h"//this is UITableViewController which i want to display when i click on menu button.

Add property for Menu button.
@property (weak, nonatomic) IBOutlet UIBarButtonItem *sidebarButton;

In viewDidLoad method
- (void)viewDidLoad{
    [super viewDidLoad];

    SWRevealViewController *revealViewController = self.revealViewController;
    if ( revealViewController )
    {
        [self.sidebarButton setTarget: self.revealViewController];
        [self.sidebarButton setAction: @selector( revealToggle: )];
        [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
    }
}

But when i click on Menu button it shows nothing, whats the issue i occure??


text:
Q: amazon mws submit feed I am attempting a go at updating quantities using the SubmitFeed action.  Does anyone have experience with this?  The error I am receiving is: 'Either Action or Operation query parameter must be present', but I do have 'Action=SubmitFeed' in the query string.
I have written four other functions (RequestReport, GetReportRequestList, GetReport, & GetFeedSubmissionList) that work perfectly.  I imagine I am missing some cURL configuration options in order to post a file.
cURL options:
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER => array(
    'Content-Type: application/x-www-form-urlencoded',
    'Content-MD5: '. $md5,
    'Transfer-Encoding: chunked',
)),
curl_setopt($ch, CURLINFO_HEADER_OUT => true);
curl_setopt($ch, CURLOPT_UPLOAD => true);
curl_setopt($ch, CURLOPT_PROTOCOLS => CURLPROTO_HTTPS);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_PORT , 443);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, implode('&', $url_parts));

Can anyone assist?  Thank you.

A: In order to do a SubmitFeed call, you will have to use Content-Type: text/xml and use your XML feed as CURLOPT_POSTFIELDS. Your other option fields will have to go into the URL, as if this was a GET:
$ch = curl_init($url_with_fields);                   <-- change 1
curl_setopt($ch, CURLOPT_HTTPHEADER => array(
    'Content-Type: text/xml',                        <-- change 2
    'Content-MD5: '. $md5,
    'Transfer-Encoding: chunked',
)),
curl_setopt($ch, CURLINFO_HEADER_OUT => true);
curl_setopt($ch, CURLOPT_UPLOAD => true);
curl_setopt($ch, CURLOPT_PROTOCOLS => CURLPROTO_HTTPS);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_PORT , 443);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);      <-- change 3

Note that this type of call also works for RequestReport, GetReportRequestList, GetReport, & GetFeedSubmissionList: just leave $xmldata empty in those cases.


text:
Q: installing PyUserInput on OS X I was trying to install PyUserInput on os x El Capitan, but I couldn't manage to do so.
In the git repository instructions it is written that Quartz and AppKit are needed, but I can't figure out how to install them.
I would appreciate your help, Thanks!

A: Welcome to Stack Overflow.
Whenever you have to install dependencies, you should look into the package manager for the programming language (or operating system). In your case, the package manager for Python is pip.
You can use the package managers through your shell (command prompt, terminal, etc.)
Quartz.
You can find the documentation here
pip install -U pyobjc

AppKit.
You can find the documentation here
pip install appkit

Then, you can install PyUserInput.
The repo for PyUserInput is here.


text:
Q: How to get n number of entries from a namevaluecollection in batches Using C#
So I have a namevaluecollection that can contain a variable number of entries generally 40-50.
What I want to do is take 3 entries at a time and process them, in order. For e.g. if entire collection = 9, then like take 1-3, then 4-6, then 7-9.
The problem is i am unable to get them recursively, also what happens if I have say 13 entries, then it would be like 3*4 + 1.
I tried to use .TAKE but don't know how to do this recursively.
Any pointers appreciated.
int TotalTestImage = TestImages.Count();
int y = 0;

int Interator = TotalTestImage / 3;

if((TotalTestImage % 3) != 0)
{
    Interator += 1;
}

int i = 0;

for(int k = 0; k < Interator; k++)
{
    sb.AppendLine("
");

    TestImages.Take(3).Skip(y * 3).ToList().ForEach( o => {
        switch (o.Key)
        {
            case "CaseID":
                CaseID = Convert.ToInt16(o.Value);
                break;
            default:
                i += 1;
                Controls = GetDropDown(o.Value);
                ActualValues.Add(o.Value);
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendFormat("
Question {0}
", i);
                sb.AppendLine("
");
                sb.AppendLine("<button type = \"button\" class=\"btn btn-box-tool\" data-widget=\"collapse\">");
                sb.AppendLine("");
                sb.AppendLine("</button>");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendFormat("", o.Key);
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine(Controls[1]);
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine(Controls[0]);
                sb.AppendLine("
");
                sb.AppendLine("

");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine("
");
                break;
        }
    });
    sb.AppendLine("
");
    y += 1;
}

A: When you are using Take() for the second item, you should skip the first items.
In your example,
var set1 = collection.Take(3);  // will get first 3 items
var set2 = collection.Skip(3).Take(3);  // will get first 4-6 items
.
.
.

A: You can do this sequentially using .Take and .Skip in combination
var batchSize = 3;
var sequence = TestImages; //Uncertain what type is in TestImages
while(sequence.Any()) {
    sb.AppendLine("
");

    var batch = sequence.Take(batchSize);

    //process the batch
    processBatch(sb, batch);

    sb.AppendLine("
");

    sequence = sequence.Skip(batchSize);
}

The processBatch function would basically match what you were doing in the ForEach
void processBatch(StringBuilder sb, IEnumerabl<{TypeHere}> batch) {
    foreach(var o in batch) {
        switch (o.Key) {
            case "CaseID":
                CaseID = Convert.ToInt16(o.Value);
                break;
            default:
                i += 1;
                Controls = GetDropDown(o.Value);
                ActualValues.Add(o.Value);
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendFormat("
Question {0}
", i);
                sb.AppendLine("
");
                sb.AppendLine("<button type = \"button\" class=\"btn btn-box-tool\" data-widget=\"collapse\">");
                sb.AppendLine("");
                sb.AppendLine("</button>");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendFormat("", o.Key);
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine(Controls[1]);
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine(Controls[0]);
                sb.AppendLine("
");
                sb.AppendLine("

");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine("
");
                sb.AppendLine("
");
                break;
        }
    }
}


text:
Q: How can I zoom on a marker from a specific search bar created on Javascript? I'm trying to zoom on my markers from a search bar that is created with Javascript. This search bar has an autocomplete form and this function works well. But, when I select one of my glacier ( I'm working with swiss glaciers) from the select bar, there is no interaction and I don't really understand how I could create this interaction.
I don't have lots of experience in Javascript, HTML... So if you can be as clear as possible, it could be cool! I am sure that all the information of the glaciers are stored on a sql database.
Here is a part of my code that could be important:
HTML part:

Coordonnées: déplacez la souris sur la carte

 Choix du glacier:

    <form autocomplete="off" id= "glacier_form" action="zoom_barre">

        <input id="myInput" type="text" name="myGlacier" placeholder="Glaciers">

      <input id = "button_submit" type="submit">
    </form>

Javascript part:
function show_glaciers(){

  var url = '/glaciers_info.json';

  $.getJSON(url, function(data){
    var dict={};
    for (var i=0; i <data.length; i++){
      var glacier = data[i];
      dict[glacier.nom]=ajouter_marqueur_glacier(glacier);
    }
        GlacierDictionary =dict; // store Globale
    autocomplete(document.getElementById("myInput"), Object.keys(dict));
    });

}

show_glaciers();
function zoom_barre(glacier){
$('#myInput').on('change', function(e){
  var id_glacier = $('#myInput').val();
  if (id_glacier == "") return;
  var glacier = glacier[id_glacier]
  mymap.panTo(([glacier.y, glacier.x]), {animate: true});
   mymap.flyTo(([glacier.y, glacier.x]),14);
});
}
zoom_barre()
}

Thanks for your answer


text:
Q: Regex to match only strings ending with a specific word and not containing other words I tried to make a regex to match a string ending with the word 'Remixes' but only when it is not preceded by certain words and characters. I came up with the following regex with different results but both doesn't match it perfectly:
^(\w+)((?!\&|\+|And|The|Of|Various|House|Unreleased|Selected).)\s(Remixes)$

This excludes all the keywords in the string but not when it contains multiple words like: Think Twice Remixes or when it has one preceding word like: Various Remixes
^(.*)((?!\&|\+|And|The|Of|Various|House|Unreleased|Selected).)\s(Remixes)$

This excludes the following testexample: Fill Me Up + Remixes but not other examples with the excluded keywords, like Sides & Remixes
How can i make the first string match string with multiple preceding words and not match it if the exclude word is the only and first preceding word?

A: Honestly, I wouldn't. regex is a powerful tool, and you can do a lot of things with it, but your code becomes much simpler and clearer when you don't try to "single-regex" every problem.
For your example, I would be quite tempted to use perl's grep function, which lets you specify compound conditions:
 my @filtered = grep { m/Remixes$/
                     and not
                        m/(And
                             |The
                             |Of
                             |Various
                             |House
                             |Unreleased
                             |Selected
                         )\s*.?\s+Remixes/xi } @list_of_things

E.g.:
#!/usr/bin/env perl
use strict;
use warnings;

#set up a list of words to exclude when prefixing "Remix"
#qw is perl's "quote words" and lets you specify whitespace delimited values.
my @exclude_remix_prefix = qw ( And
    The
    Of
    Various
    House
    Unreleased
    Selected );

#turn that into a sub regex (qr 'compiles' a regex).
my $exclude = join( "|", @exclude_remix_prefix );
$exclude = qr/($exclude)\s+Remixes/i;

#read from the <DATA> filehandle,
#but you could use <> to read from STDIN/filenames like 'sed/grep' do.
my @filtered = grep { m/Remixes$/i and not m/$exclude/i; } <DATA>;

print @filtered;

__DATA__
Fill Me Up + Remixes
Sides & Remixes
Something Selected remixes

Output:
Fill Me Up + Remixes
Sides & Remixes

(Give me some samples of what should/shouldn't be matched, and I will expand)
We're probably straying a bit from your original use case, but if you want to create a transform pattern:
#!/usr/bin/env perl
use strict;
use warnings;

use Data::Dumper;

my @exclude_remix_prefix = qw ( And
    The
    Of
    Various
    House
    Unreleased
    Selected );

my $exclude = join( "|", @exclude_remix_prefix );
$exclude = qr/($exclude)\s+Remixes/i;

my %transform = map { m/$exclude/ ? () :  m/(.*)/ =>  m/(.*)\s+Remixes/ ; } <DATA>;
print Dumper \%transform;

__DATA__
Euterpeh Remixes
The Beauty And The Beast Remixes
Think Twice Remixes
Stop And Reset Remixes

This generates specifically a hash containing:
$VAR1 = {
          'The Beauty And The Beast Remixes' => 'The Beauty And The Beast',
          'Think Twice Remixes' => 'Think Twice',
          'Euterpeh Remixes' => 'Euterpeh',
          'Stop And Reset Remixes' => 'Stop And Reset'
        };

Which you could perhaps use to generate a sequence of rename operations?
Or if you just want to 'in place' some operation, then a for loop:
for ( <DATA> ) {
    chomp;
    next if m/$exclude/;
    print "rename ", m/(.*)\s+Remixes/, " ", m/(.*)/,"\n";
}

(OK, I know 'rename' isn't quite what you want to do, but ...)


text:
Q: wagtail: How to dynamically limit the number of Parent Key objects in the admin panel (page model)? Here is my model:
class Store(Page):
    .....
    panels=[InlinePanel(pr)]
class pr(orderable):
    ....
    store = ParentalKey(Store,...)

I want each user to have a different limit on the number of PRs.and raise ValidationError if exceeds the limit
I try to use WagtailAdminPageForm and override clean()
to detect the number of PRs, but I have a problem.

delete button not really delete item, it's just "display:none".
so, I can't use attribute of self.data "store_pr-TOTAL_FORMS" to detect the number of PRs and raise ValidationError.
When the user exceeds the limit, this form cannot be saved, even if the PR is deleted on the form, because the length of the PR sent to the server will only increase and will not decrease


text:
Q: what do I have to add to have the same paragraph to print 3 times? this is what I have done so far i needed help on adding a solution in (). I know i need to add a for loop but i am not sure where?
function getrandomnumber(min,max,notin)
{
    return min+Math.floor((max-min+1)*Math.random())
}

function roundnumber(num)
{
    return Math.round(num/10)/100
}

{
    var a=getrandomnumber(50000,10000,"")
    var b=getrandomnumber(10,100,"")
    var c=getrandomnumber(50000,10000,"")
    var d=getrandomnumber(10,100,"")

    var total=(d-b)/(a-c)

    var str= "Luis's family decides to rent a hall for her "
    var s1= "retirement party. Pin Hall charges $"+a+" for "
    var s2= "the hall and $"+b+" per meal. Bloom place "
    var s3= "charges $"+c+" for the hall and $"+d+" per "
    var s4= "meal. Find the number of guests for which the charges are the same at both halls. "

    document.write(str+s1+s2+s3+s4);
}

document.write("

solution()");

A: I can't understand what you are trying, You want to do as this example?
function getrandomnumber(min,max,notin){
   return min+Math.floor((max-min+1)*Math.random())
}

function roundnumber(num){
    return Math.round(num/10)/100
}

function solution(){
    var a=getrandomnumber(50000,10000,"")
    var b=getrandomnumber(10,100,"")
    var c=getrandomnumber(50000,10000,"")
    var d=getrandomnumber(10,100,"")

    var total=(d-b)/(a-c)

    var str= "Luis's family decides to rent a hall for her "
    var s1= "retirement party. Pin Hall charges $"+a+" for "
    var s2= "the hall and $"+b+" per meal. Bloom place "
    var s3= "charges $"+c+" for the hall and $"+d+" per "
    var s4= "meal. Find the number of guests for which the charges are the same at both halls. "

    return (str+s1+s2+s3+s4);
}

document.write(solution())`

https://jsfiddle.net/cq3uyLtv/


text:
Q: Starting Mapfragment / Polyline NullpointException I try to draw a polyline in my map. My mapfragment is placed on a fragment. I want to start the polylinedraw from my activity and get a NullpointException at:
GoogleMap map = mapFragment.getMap();

My Activity:
public void buttonMaps_Click(View view) {
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map1);
    GoogleMap map = mapFragment.getMap();
    Polyline line = map1.addPolyline(
            new PolylineOptions().add(mP0, mP1, mP2, mP3, mP4, mP5, mP6, mP7, mP8).width(5).color(Color.BLUE));
}

My fragment xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"    >
        <fragment
        android:id="@+id/map1"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

Big part of activity:
package com.Dennis.pagers_adapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import Classes.Chronometer;
import Classes.Function;
import Classes.IntentIDs;
import Classes.MyLocation;
import Classes.Time;
import Fragment.FifthFragment;
import Fragment.FourthFragment;
import android.content.Context;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

public class ThirdActivity extends FragmentActivity
        implements OnTabChangeListener, OnPageChangeListener, LocationListener {

    Time mTime;
    Function mFinishLine, mNewLine;
    MyLocation mFinishLoc1, mFinishLoc2, mLocation;
    LocationManager mLocMan;
    List<MyLocation> mLocList = new ArrayList<MyLocation>();
    int i = 0, mRoundCounter = 0, mIntersects, mCount;
    boolean mOnDistance1, mOnDistance2, mBigEnough;
    String mInst1, mInst2, mInst3, mInst4;
    long mInsta1, mInsta2, mInsta3, mInsta4;

    double mSaveTime, mStartTime, mMillis;
    long seconds = 0, millis = 0;
    Timer timer;

    MyLocation[] mFinishLoc;

    MyPageAdapter pageAdapter;
    private ViewPager mViewPager;
    private TabHost mTabHost;
    boolean mClicked = true;
    Chronometer mChronometer;
    private GoogleMap map1;

    double mP0x = 11.13053373992443;
    double mP0y = 49.46026297311668;

    double mP1x = 11.130577996373177;
    double mP1y = 49.46029696881047;

    double mP2x = 11.130626276135445;
    double mP2y = 49.460328349429936;

    double mP3x = 11.130714789032936;
    double mP3y = 49.46035624329705;

    double mP4x = 11.131033971905708;
    double mP4y = 49.46023072076999;

    double mP5x = 11.131257936358452;
    double mP5y = 49.4600973527327;

    double mP6x = 11.13104335963726;
    double mP6y = 49.45994393545658;

    double mP7x = 11.130516305565834;
    double mP7y = 49.460228977399304;

    double mP8x = 11.130727;
    double mP8y = 49.460385;

    LatLng mP0 = new LatLng(mP0y, mP0x);
    LatLng mP1 = new LatLng(mP1y, mP1x);
    LatLng mP2 = new LatLng(mP2y, mP2x);
    LatLng mP3 = new LatLng(mP3y, mP3x);
    LatLng mP4 = new LatLng(mP4y, mP4x);
    LatLng mP5 = new LatLng(mP5y, mP5x);
    LatLng mP6 = new LatLng(mP6y, mP6x);
    LatLng mP7 = new LatLng(mP7y, mP7x);
    LatLng mP8 = new LatLng(mP8y, mP8x);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_third);

        Bundle b = getIntent().getExtras();

        double mValue = b.getDouble(IntentIDs.INTENT_BUNDLE_LONGITUDE);
        double mValue1 = b.getDouble(IntentIDs.INTENT_BUNDLE_LATITUDE);
        double mRiseV = b.getDouble("RiseV");

        mViewPager = (ViewPager) findViewById(R.id.viewpager);

        // Tab Initialization
        initialiseTabHost();

        // Fragments and ViewPager Initialization
        List<Fragment> fragments = getFragments();
        pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
        mViewPager.setAdapter(pageAdapter);
        mViewPager.setOnPageChangeListener(ThirdActivity.this);

        // 2
        mTime = new Time();
        MyLocation mStartLocation = new MyLocation(mValue, mValue1, mTime);
        mFinishLine = new Function(mRiseV, mStartLocation);
        mFinishLoc = MyLocation.finishLine(mStartLocation, mFinishLine);
        mFinishLoc1 = mFinishLoc[0];
        mFinishLoc2 = mFinishLoc[1];

    }

    public void buttonChrono_Click(View view) {

        mChronometer = (Chronometer) findViewById(R.id.chronometer);
        mChronometer.start();
        mClicked = true;

    }

    public void buttonChrono_Click2(View view) {
        mChronometer = (Chronometer) findViewById(R.id.chronometer);
        mChronometer.stop();

    }

    public void buttonChrono_Click3(View view) {
        mChronometer = (Chronometer) findViewById(R.id.chronometer);
        mChronometer.setStarted(mClicked);

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub

        super.onResume();

        mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0f, this);

    }

    public void buttonMaps_Click(View view) {
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map1);
        GoogleMap map = mapFragment.getMap();
        // map1 = ((SupportMapFragment)
        // getSupportFragmentManager().findFragmentById(R.id.map1)).getMap();
        Polyline line = map1.addPolyline(
                new PolylineOptions().add(mP0, mP1, mP2, mP3, mP4, mP5, mP6, mP7, mP8).width(5).color(Color.BLUE));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.third, menu);
        return true;
    }


text:
Q: When i send too many request it gives failed and whole website will stop working I am creating a signup page in which user can choose only available username i.e which is not present in the database. so I use ajax for that.. but when I enter too many requests at a time then it gives failed and my website stop working .. after some time all will be fine but for 5-10 min it stop working.
WEBSITE GIVES ERROR:-
This page isn't working events.collegespike.com didn't send any data.
ERR_EMPTY_RESPONSE
Code to fetch data from database:
<?php

if (isset($_POST['user_name']) && $_POST['user_name'] != '') {
    $response = array();
    $username = mysqli_real_escape_string($db, $_POST['user_name']);
    $sql = "select username from login_master where username='" . $username . "'";
    $res = mysqli_query($db, $sql);
    $count = mysqli_num_rows($res);
    if ($count > 0) {
        $response['status'] = false;
        $response['msg'] = 'Username already exists.';
    } else if (strlen($username) < 6 || strlen($username) > 15) {
        $response['status'] = false;
        $response['msg'] = 'Username must be 6 to 15 characters';
    } else if (!preg_match("/^[a-zA-Z1-9]+$/", $username)) {
        $response['status'] = false;
        $response['msg'] = 'Use alphabet and numeric only.';
    } else {
        $response['status'] = true;
        $response['msg'] = 'Username is available.';
    }

    echo json_encode($response);
}
?>

Ajax code:-
//including jquery 2.0.3

//jquery code to fetch data

HTML code:-
//code to take input and show output
//taking input
<input class="check-form"  name="user_name" id="username" type="text"  placeholder="User Name (please enter unique username)">

//showing output

A: I think the issue is coming because of hosting server setting. if you fire too many post request than server will block you for 60 to 120 seconds because of the settings.
Try using GET request instead of POST request I think it will solve an issue.
$(document).ready(function() {
    $('#username').keyup(function() {
        var usercheck = $(this).val();
        $('#usercheck').html('');
        $.get("signup/check1.php", {
            user_name: usercheck
        }, function(data) {
            if (data.status == true) {
                $('#usercheck')
                   .parent('div')
                   .removeClass('has-error')
                   .addClass('has-success');

            } else {
                $('#usercheck')
                   .parent('div')
                   .removeClass('has-success')
                   .addClass('has-error');
            }
            $('#usercheck').html(data.msg);
        }, 'json');
    });
});

A: I believe your problem is from firing too many requests to the server at the same time.
I notice you are using .keyup() and then firing an AJAX request. This means if I was to type the username Jonathan it would fire 8 requests all within a second. This will create a bottleneck.
If you open your console, you will notice a single character (a single request) will work fine, type a 2nd character after you have got a response from the first, and it will work again. However typing fast and waiting for all of them to respond will not work. You will see in your console they will be loading and loading until it eventually times out / whatever.
I propose you reduce the requests you're firing off, and only fire a request if the keys have stopped being pressed for x amount of milliseconds.
Solution:
Delay the keyup execution. Here's a pure javascript solution I've used multiple times that work within my apps. I've simplified it and modified it to hopefully work for your case.
You will notice delayKeyupExecution() is called, and we pass myInput (in your case this is username), userNameAjaxCheck as the callback (this is the function that will contain your ajax request), and 500, this is the amount of ms to delay it by.
// Your username input
var myInput = document.getElementById("username");

function userNameAjaxCheck(params) {
  // Your ajax code to check the username
};

// Delay a function from triggering
function delayKeyupExecution(input, callback, delay) {
  var timer = null;
  var params = null; // Anything you want to pass to the callback function (userNameAjaxCheck)

  input.onkeypress = function() { // Equivalent to your .keyup
    if (timer) window.clearTimeout(timer);
    timer = window.setTimeout( function() {
      timer = null;
      callback(params); // Pass the params you need
    }, delay );
  };

  input = null;
};

// Execute
delayKeyupExecution(myInput, userNameAjaxCheck, 500);


text:
Q: How to create a singleton object in Flask micro framework I am creating a class for Producer which pushes messages to RabbitMQ. It makes use of pika module.
I would like to create a handler so that I have control over the number of connections that interact with Rabbit MQ.
Is there a way we can add this to app_context and later refer to that or is there way that we use init_app to define this handler.
Any code snippet would be of really good help.

A: In Python, using singleton pattern is not needed in most cases, because Python module is essentially singleton. But you can use it anyway.
class Singleton(object):
    _instance = None

    def __init__(self):
        raise Error('call instance()')

    @classmethod
    def instance(cls):
        if cls._instance is None:
            cls._instance = cls.__new__(cls)
            # more init operation here
        return cls._instance

To use Flask (or any other web framework) app as singleton, simply try like this.
class AppContext(object):
    _app = None

    def __init__(self):
        raise Error('call instance()')

    @classmethod
    def app(cls):
        if cls._app is None:
            cls._app = Flask(__name__)
            # more init opration here
        return cls._app

app = AppContext.app() # can be called as many times as you want

Or inherite Flask class and make itself as a singleton.