text:
Q: React-Router not rendering array content I'm following an article from Medium about using React Router to create a SPA; but is not up to date, so some things has changed.
I'm stuck in rendering an array of products; but for some reason it is not recognizing any content.
Code:
import React, { Fragment } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import './App.css';
import Navbar from './components/Navbar';
import Home from './components/Home';
import Widgets from './components/Widgets';
import Wudgets from './components/Wudgets';

const widgetprods=[
  {name: 'Master Widget', price:'$125.00'},
  {name: 'Sub Widget', price:'$115.00'},
  {name: 'Long Widget', price:'$150.00'},
  {name: 'Short Widget', price:'$135.00'}
]

const wudgetprods=[
  {name: 'Master Wudget', price:'$75.00'},
  {name: 'Sub Wudget', price:'$85.00'},
  {name: 'Long Wudget', price:'$135.00'},
  {name: 'Short Wudget', price:'$110.00'}
]

const App=()=>{
  return (
    <Router>

        <Navbar />

              <Routes>
                <Route exact path='/' element={<Home/>}
                />
                <Route exact path='/widgets'
                       render={(props) =>
                         <Fragment>
                            <Widgets prods={widgetprods}/>
                         </Fragment>
                       }
                />
                <Route exact path='/wudgets'
                       render={(props)=>
                         <Fragment>
                            <Wudgets prods={wudgetprods}/>
                         </Fragment>
                       }
                />
              </Routes>

      </Router>
  )};

export default App;

---> I see this:

---> I spect to see this:

---> One of the erros I get:

Thanks a lot!!
Luc


text:
Q: Spring-boot eureka.datacenter property not found when used in application.yml I am creating spring-boot Eureka server and client micro-services to deploy on aws. I have read on tutorials that I have to define eureka.datacenter: cloud in my application.yml of eureka server so that it knows it is on aws. But when I try to use it in my application.yml file I get unknown property 'eureka.datacenter'.
Dependencies I have included for eureka server.
 <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-eureka-server</artifactId>
            </dependency>

            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-config</artifactId>
            </dependency>

            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-eureka</artifactId>
            </dependency>

        </dependencies>

I am using Spring boot 1.5.8.RELEASE and spring cloud Edgware.SR1.
Is eureka.datacenter property included in different version of spring cloud?
application.yml
spring:
  application:
    name: eureka-svc

---
spring:
  profiles: localhost
server:
  port: 8761
eureka:
  instance:
    hostname: localhost
  client:
    fetchRegistry: false
    register-with-eureka: false
    serviceUrl:
      defaultZone: http://localhost:8761/eureka
---
spring:
  profiles: aws
server:
  port: 8761
eureka:
  instance:
    non-secure-port: ${server.port}
    environment: production
  client:
    region: region
    register-with-eureka: true
    fetchRegistry: true
    use-dns-for-fetching-service-urls: true
    eureka-server-d-n-s-name: dns-name
    eureka-server-port: 8761
    eureka-server-u-r-l-context: eureka
  server:
    a-w-s-access-id: access-id
    a-w-s-secret-key: aws-key
    binding-strategy: route53
    list-auto-scaling-groups-role-name: role-name

A: Don't you have to pass the eureka.datacenter as a commandline property?
Configuring Eureka

If you are running in the cloud environment, you will need to pass in the java commandline property -Deureka.datacenter=cloud so that the Eureka Client/Server knows to initialize the information specific to AWS cloud.

A: I'm following the instructions from
https://cloud.spring.io/spring-cloud-netflix/multi/multi__service_discovery_eureka_clients.html#_using_eureka_on_aws
@EnableEurekaServer
@SpringBootApplication
public class DiscoveryServiceApplication {

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

    @Bean
    @Profile("aws")
    public EurekaInstanceConfigBean eurekaInstanceConfig(InetUtils inetUtils) {
        EurekaInstanceConfigBean b = new EurekaInstanceConfigBean(inetUtils);
        AmazonInfo info = AmazonInfo.Builder.newBuilder().autoBuild("eureka");
        b.setDataCenterInfo(info);
        return b;
    }

}

A: Might not make a difference but could you try:
eureka.datacenter: cloud
instead of:
eureka.datacenter=cloud

redpajama_set_name: RedPajamaStackExchange


text:
Q: Please help me with my comment sections sql query OK guys, I am in need of a little help here! Using PHP and mysql, I made a comment section that users can add comments to. First off, the page is based off of the ItemID and displays the correct item. When they add a comment, I take their username and the ItemID and put it in the comment table as comment.username and messageailmentID. So the page displays correctly, and the comment section works great, except that I cannot seem to get the SQL query right. I have tried many variations, with no luck. I want the comment that anyone posts under the pages ItemID to show only those comments under that ItemID (specifically messageailmentID).
MY query ranges, but here is the one I have at the moment:
SELECT `comment`.messageID, `comment`.message, `comment`.username, `comment`.messageailmentID, Items.ItemID
FROM `comment`, Items
WHERE varItemID = `comment`.messageailmentID

(Using dreamweaver, the varItemID is basically $_GET['Items.ItemID'])
EDIT: As an example, The user clicks an item which takes them to the itemdetails.php?ItemID=8. When they leave a comment, it will add Items.ItemID into comment.messageailmentID.
The important part of the table columns are this:
Items: ItemID
comment: CommentID, message, comment.username, messageailmentID(which is the pages ItemID)
The varItemID isn't a column, but does $_GET['ItemID'], which may not even be needed in this query because it is done on another query.

A: Your query is fetching all rows.
You should use:

*

*A JOIN clause to specify the relationship between the tables.

*A WHERE clause to specify which particular items you want to fetch.

Try this:
SELECT
    comment.messageID,
    comment.message,
    comment.username,
    comment.messageailmentID,
    Items.ItemID
FROM Items
LEFT JOIN comment
ON Items.ItemID = comment.messageailmentID
WHERE Items.ItemID = 42

Using a left join means that it will still return one row even if there are no comments. Use INNER JOIN if you don't want this.

A: Try the following
SELECT comment.messageID, comment.message, comment.username, comment.messageailmentID, Items.ItemID

FROM comment, Items

WHERE Items.ItemID = comment.messageailmentID and Items.ItemID = ". $_GET['Items.ItemID']

A: Thank you guys for helping me figure out my own stupidity! The query I use that works is this:
SELECT `comment`.messageID, `comment`.message, `comment`.username
     , `comment`.ItemID, Items.ItemID
  FROM Items
 INNER JOIN `comment`
    ON Items.ItemID = `comment`.ItemID
 WHERE Items.ItemID = varItemID

varItemID is a $_GET['ItemID'] also.


text:
Q: Regex for getting multiple words separated by boolean operators I have a string like: $string='(orange fruit OR APPLE) AND (Kiwi OR banana pie)'
I need regex to extract the words separated by the boolean operators OR and AND and ignore the brackets.
So the result should be an array: orange fruit, APPLE, Kiwi, banana pie
I'm not sure where to begin as I'm not very good with regex. Is there a simple way of doing this?

A: In your current case do the following:
$string =' ( orange fruit OR APPLE )  AND (Kiwi OR  banana pie)';
// Remove all extra characters and spaces from string
$result = trim(preg_replace('#[\s\(\)]+#', ' ', $string));
// Split result by possible delimeters
$result = preg_split('# (or|and) #i', $result);
// Output
print_r($result);

Output:
Array (
  [0] => orange fruit
  [1] => APPLE
  [2] => Kiwi
  [3] => banana pie
)


text:
Q: How to send email using SendGrid I have been trying to set up email for a web page using SendGrid's PHP API, and I'm having no luck. I have tried their code from the Azure website as well as various examples I found while trying to Google it, and every time it returns nothing as a response, and the email isn't set. Here is the code I'm talking about:
<?php
 $url = 'https://api.sendgrid.com/';
 $user = 'USERNAME';
 $pass = 'PASSWORD';

 $params = array(
      'api_user' => $user,
      'api_key' => $pass,
      'to' => 'email@gmail.com',
      'subject' => 'testing from curl',
      'html' => 'testing body',
      'text' => 'testing body',
      'from' => 'anna@contoso.com',
   );

 $request = $url.'api/mail.send.json';

 // Generate curl request
 $session = curl_init($request);

 // Tell curl to use HTTP POST
 curl_setopt ($session, CURLOPT_POST, true);

 // Tell curl that this is the body of the POST
 curl_setopt ($session, CURLOPT_POSTFIELDS, $params);

 // Tell curl not to return headers, but do return the response
 curl_setopt($session, CURLOPT_HEADER, false);
 curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

 // obtain response
 $response = curl_exec($session);
 curl_close($session);

 // print everything out
 print_r($response);
 ?>

It is also worth noting that I've tried using sendgrid-php accompanied with the code supplied with it, and that causes the page to simply not load. I'm really stumped right now, and any help is greatly appreciated.

A: By default, Azure doesn't generate a SSL peer certificate for Azure Web Apps. If you add the code in your test code $error = curl_error($session);, you will get the error SSL certificate problem: self signed certificate in certificate chain.
You can simply add the code curl_setopt($session, CURLOPT_SSL_VERIFYPEER, 0); to bypass the verification.
Otherwise, you can follow Verify Peer Certificate from PHP cURL for Azure Apps to add a certificate on Azure Web Apps.

A: It's possible your version of cURL doesn't support SSL out of the box.
You can test this by putting the following at the top of your code:
if (!curl_version()['features'] & CURL_VERSION_SSL) {
    echo "SSL is not supported with this cURL installation.";
}

If it's not supported out of the box you have to configure it manually like this:
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($session, CURLOPT_SSL_VERIFYHOST, 2);
// path to CA certificate
curl_setopt($session, CURLOPT_CAINFO, '/etc/openssl/cert.pem');


text:
Q: Preventing a System.Windows.Forms.Timer from accumulating Intervals? I'm coding a Family Feud game in C# and after each answer is submitted the 30-second timer is supposed to reset. The problem is I'm accumulating 1-second Intervals so that the counter is counting down faster and faster. I can't figure out how to prevent the Intervals from accumulating. I want it to stay a fixed 1 seconds no matter how many times the button is pressed.
Code:
public System.Windows.Forms.Timer _timer = new System.Windows.Forms.Timer();
public int time = 30;
private void Check_Click(object sender, RoutedEventArgs e)
{
time = 30;
_timer.Tick += timer_Tick;
_timer.Start();
uxLabel1.Content = time.ToString();
//additional code
}
private void timer_Tick(object sender, EventArgs e)
{
_timer.Interval = 1000;
time--;
if (time == 0)
{
_timer.Stop();
strike();
}
uxLabel1.Content = time.ToString();
}

A: Don't put _timer.Tick += timer_Tick; in the button click code, put it once in the constructor of your form and have that be the only event registration.
public partial class YourForm : Form
{
    public YourForm()
    {
        InitializeComponets();
        _timer = new System.Windows.Forms.Timer();
        _timer.Tick += timer_Tick;
        _timer.Interval = 1000;
     }

    private System.Windows.Forms.Timer _timer;
    private int time = 30;
    private void Check_Click(object sender, RoutedEventArgs e)
    {
    time = 30;
    _timer.Start();
    uxLabel1.Content = time.ToString();
    //additional code
    }
    private void timer_Tick(object sender, EventArgs e)
    {
    time--;
    if (time == 0)
    {
    _timer.Stop();
    strike();
    }
    uxLabel1.Content = time.ToString();
    }
}


text:
Q: why array.push doesnt work? i have this code
function imagenesIn(errU,errores)
    {
        if(errU) throw errU;
        var directorios=new Array();
        var origenDir='';
        var destinoDir='';
        if(errores=='')
        {
            if(campos.img instanceof Array)
            {
                for(file in campos.img)
                {
                    origenDir='';
                    destinoDir='';
                    origenDir=campos.img[file].path;
                    destinoDir='/uploads/publish/alquiler/'+req.session.passport.user+campos.img[file].name;
                    fs.rename(origenDir,process.cwd()+'/public'+destinoDir,function(err)
                    {
                        if (err) throw err;
                        directorios.push(destinoDir);
                        console.dir(directorios)
                    })
                }
            }
        }else{
            res.send(errores)
        }
        return directorios;
    },

i want to get in directorios an array of the destiny of all files content in req.files.img
that are in campos.img
but when i print in console this happend
"img": [
  "/uploads/publish/alquiler/andres@hotmail.comTulips.jpg",
  "/uploads/publish/alquiler/andres@hotmail.comTulips.jpg"
],

im trying to get this result
"img": [
  "/uploads/publish/alquiler/andres@hotmail.comTulips.jpg", //first img
  "/uploads/publish/alquiler/andres@hotmail.flowers.jpg"//second img
],

why .push() method put only the first image directory and not the second???
i miss something???
tnx

A: Your problem is that in
               fs.rename(origenDir,process.cwd()+'/public'+destinoDir,function(err)
                {
                    if (err) throw err;
                    directorios.push(destinoDir);
                    console.dir(directorios)
                })

your push() won't have actually run by the time you do
    return directorios;

You need to make sure that the call to fs.rename(...) that finishes last (which is not, I repeat not, necessarily going to be the same call that starts last) handles the case where all the calls have finished. Using asynchronous calls, you cannot just fall through after firing up a bunch of them and do a return; you will have to put the code that you want to run after all the work is done in a callback that addresses what I called "handles" earlier.
Control-flow libraries like async.js could simplify your code, but you'll need to get your head around the notion that once your function goes async everything that follows it has to be async as well.

A: ebohlman pretty much called it. Right now your for loop is setting up the anonymous functions that the rename function will call once it finishes.
As soon as these are setup, imagenesIn will return directories. It may contain some or none of the directories, depending on whether or not rename finished before your return.
The power of node is that it is asynchronous. You could use fs.renameSync yes, and it would follow what you expect. Node is not like an apache php server. The php server gets a request, and reserves a small slice of memory for the request. That's why other requests can still be processed, because they all get their own memory. Node doesn't do this. It runs on a single thread and if you do anything that is blocking (like synchronous IO), other requests have to wait until it's finished before they can be processed.
Ideally, your imagenesIn should also be asynchronous as well, taking a function as the final parameter. The standard for the function usually follows function(error, data). Error should be null if there was none. fs.rename follows this pattern.
Also the function that calls imagenesIn should ideally handle the server response. This allows the function to be used in other types of cases. What if you don't want to send that specific response on error? What if you don't want to send a response at all? Right now this is a good recipe for accidentally sending headers twice (and getting an error).
If it were me, this is how I would write your function (I didn't test but should give you some direction).
function imagenesIn(callback) {

    var directorios=new Array();
    var origenDir='';
    var destinoDir='';
    if(campos.img instanceof Array) {

        function recursion(index){

            //the case that ends the recursion and returns directories
            if (index >= campos.img.length) {
                callback(null, directorios);
                return;
            }

            origenDir=campos.img[index].path;
            destinoDir='/uploads/publish/alquiler/'+req.session.passport.user+campos.img[index].name;

            fs.rename(origenDir, process.cwd() + '/public' + destinoDir, function(err) {

                //the case that ends recursion and sends an error
                if (err) {
                    callback(err);
                    return;
                }
                directorios.push(destinoDir);
                console.dir(directorios);
                recursion(index++);
            })
        }

        recursion(0);
    }
    else {
        callback('Campos.img was not an array.');
    }
}

and your code that calls it might look something like this
imagenesIn(function(err, directories) {
    if (err) {
        res.send(err);
    }
    else {
        //do cool stuff with directories.
    }
});

Also, I wanted to make sure you understood the unique difference between for( ; ; ) and for(key in object). "For in" iterates through the keys of an object. This works on an array because it is essentially an object with numeric keys. I could do this however
var array = ['data', 'data'];
array.nonNumericKey = 'otherdata';

If you did for (var i = 0; i < array.length; i++), you would only iterate through the array data. If you used for (key in array), you would also iterate through the nonNumericKey. This is why personally, I only use "for in" on objects that are not arrays.


text:
Q: Convert rtf formate to plain text I received RTF format text from API (WPF,C#). I want to convert it to plain text and display in Textview. I tried all the possible ways but didn't the success.

rtf text :
  0x7B5C727466315C616E73695C616E7369637067313235325C64656666305C6465666C616E67313033337B5C666F6E7474626C7B5C66305C666E696C5C666368617273657430204D6963726F736F66742053616E732053657269663B7D7D5C766965776B696E64345C7563315C706172645C66305C667331382068656C6C6F5C70617220207D

in API side we are able to convert it to below code. but I want to convert it to android side
ASCIIEncoding ascii = new ASCIIEncoding();
    Archonix.Controls.RichTextBox rtbnote;
                                byte[] note;
                                rtbnote = new Controls.RichTextBox();
                                note = (dr["AlertNote"]) as byte[];
                                rtbnote.Rtf = ascii.GetString(note);
                                string tempRtfText = rtbnote.Rtf;
                                string tempRegularText = rtbnote.Text;
                                objAlertList.AlertNote = tempRegularText;

A: That is not RTF. That is a hex-encoding of bytes.
The bytes are text (and RTF is text), so you must decode the hex string first:
public static void main(String[] args) {
    String hex = "0x7B5C727466315C616E73695C616E7369637067313235325C6465" +
                 "6666305C6465666C616E67313033337B5C666F6E7474626C7B5C66" +
                 "305C666E696C5C666368617273657430204D6963726F736F667420" +
                 "53616E732053657269663B7D7D5C766965776B696E64345C756331" +
                 "5C706172645C66305C667331382068656C6C6F5C70617220207D";
    byte[] bytes = hexStringToByteArray(hex.substring(2));
    String text = new String(bytes, StandardCharsets.US_ASCII);
    System.out.println(text);
}
public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

Note: hexStringToByteArray taken from Convert a string representation of a hex dump to a byte array using Java?
Output
{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}\viewkind4\uc1\pard\f0\fs18 hello\par  }

Now that is RTF.
As for parsing the RTF and extracting text, see Java RTF Parser or do a web search.


text:
Q: Behaviour space in Netlogo crashes when using extension R I am making a simulation with NetLogo and extension R. I have made a supply chain model, where I have distributors and consumers. Consumers provide orders to distributors and distributors forecast future demand and places orders to suppliers in advance to fulfill market demand. The forecast is implemented with extension R (https://ccl.northwestern.edu/netlogo/docs/r.html) by calling elmNN package. The model works fine when simply using "go".
However, when I want to conduct experiments by using behavior space, I keep getting errors. If I set only a few ticks with behavior space, the model works fine. But when I want to launch a few hundred ticks behavior space keeps crashing. For example, "Extension exception: Error in R-extension: error in eval, operator is invalid for atomic vector", "Extension exception: Error in R-extension: error in eval: cannot have attributes on CHARSXP". Sometimes the behavior simply crashes without any error.
I assume that the errors are related to computability issues between NetLogo, R, R extension and java. I am using NetLogo 5.3.1, 64-bit; R-3.3.3 64-bit; rJava 0.9-8.
Model example: https://www.youtube.com/watch?v=zjQpPBgj0A8
A similar question was posted previously, but it has no answer: NetLogo BehaviorSpace crashing when using R extension

A: The problem was with programming style, which is not suitable for behavior space. Behavior space supports parallel programming due to which some variables were rewritten by new information in the process. When I set Simultaneous runs in parallel to 1 in the behavior space everything was fine.


text:
Q: Nuclear binding energy and natural radioactive decay I have just started to learn about nuclear binding energy. While I believe I understand the concept well, there is one thing I do not still fully grasp.
I understand that the nuclear binding energy reflects the energy required to remove nucleons from the nucleus. Also, I get the fact that with larger atoms beyond iron, the repulsive force becomes greater, and so the atom becomes more unstable and, therefore, potentially radioactive.
It therefore makes sense to me that in, for instance, a fission reactor, firing a neutron at a uranium atom could intiate a nuclear reaction as it doesn't take that much effort to make uranium reach an excited state. However, where exactly does the energy come from which initiates natural radioactive decay? Say for instance when uranium somewhere in nature emits an alpha particle. Surely, some binding energy must be overcome in order for the particle to become emitted, right? So where does this energy come from when we do not have neutrons to fire at it?
If someone can explain this to me, then I would greatly appreciate it!


text:
Q: System.OutOfMemory being thrown. How to find the culprit? I am using Visual C# Express 2008 and I have an application that starts up on a form, but uses a thread with a delegated display function to take care of essentially all the processing. That way my form doesn't lock up while tasks are being processed.
Semi-recently, after going through a repeated process a number of times (the program processes incoming data, so when data comes in, the process repeats) my app will crash with a System.OutOfMemory error.
The stack trace in the error message is useless because it only directs me to the the line where I call the delegated form control function.
I've heard people say they use ProcMon from SysInternals to see why errors like this happen. But I, for the life of me, can't figure it out. The amount of memory I am using doesn't change as the program runs, if it goes up, it comes back down. Plus, even if it was going up, how do I figure out which part of my program is the problem?
How can I go about investigating this problem?
EDIT:
So, after delving further into this issue, I looked through anything that I was ever re-declaring. There were a few instances where I had hugematrix = new uint[gigantic], so I got rid of about 3 of those.
Instead of getting rid of the error, it is now far more obscured and confusing.
My application takes the incoming data, and renders it using OpenGL. Now, instead of throwing "System.OutOfMemory" it simply does not render anything with OpenGL.
The only difference in my code is that I do not make new matrices for holding the data I plot. That way, I hope, my array stays in the same place in memory and doesn't do anything suicidal to my LOH.
Unfortunately, this twists the beast far beyond my meager means. With zero errors popping up, and all my data structures apparently still properly filled, how can I find my problem? Does OpenGL use memory in an obscure way so as to not throw exceptions when it fails? Is memory still a problem? How do I find out? All the memory profilers in the world seem to tell me very little.
EDIT:
With the boatloads of support from this community (with extra kudos to Amissico) the error has finally been rooted out. Apparently I was adding items to an OpenGL list, and never taking them off the list.
The app that finally clued me in was .Net Memory Profiler. At the time of crash it showed 1.5GB of data in the <unknown> category. Through process of elimination (everything else in the list that was named), the last thing to be checked off the list was the OpenGL rendering pipleline. The rest is history.

A: Based on the description in your comments, I would suspect that you are either not disposing of your images correctly or that you have severe Large Object Heap fragmentation and, when trying to allocate for a new image, don't have enough contiguous space available.  See this question for more info - Large Object Heap Fragmentation

A: You need to use a memory profiler, such as the ants memory profiler to find out what causes this error.
Are you re-registering an event handler on every loop and not un-registering it?

A: CLR Profiler for the .NET Framework 2.0 at https://github.com/MicrosoftArchive/clrprofiler
The most common cause of memory fragmentation is excessive string creation.

A: Following considerations:

*

*Make sure that threads you spawn are destroyed (aborted or function return). Too much threads can fail application, although in Task Manager used memory is not too high

*Memory leaks. Yes, yes, you can cause them in .net pretty well without setting reference to nulls. This can be solved by using memory profilers like dotTrace or ANTS Memory Profiler

A: I had an OutOfMemoryException-problem as well:
Microsoft Visual C# 2008 Reducing number of loaded dlls
The reason was fragmentation of 2GB GB virtual address space and poster nobugz suggested Sysinternal's Vmmap utility which has been very helpful for diagnostics. You can use it to check if your free memory areas become more fragmented over time. (First sort by size then by type -> refresh repeat sorting and you can see if contiguous free memory blocks become smaller)


text:
Q: launchctl plist has a stderr that talks about how getcwd operation not permitted so how do I fix it? TLDR for those who googled and found this
In Catalina, launchd can't read files or run scripts located inside your ~/Documents folder. Just avoid putting your scripts there and rewrite your scripts not to read files in ~/Documents. Creating a new file or symlink will work, though. See the answer below for details.

Original question
I came via this answer to help me create a script that will update a symlink every day.
And there was an article it links to teaching me how to use plist and launchctl
SO this is my plist com.journal.today.plist which is installed in ~/Library/LaunchAgents
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>

    <key>Label</key>
    <string>com.journal.today.plist</string>

    <key>RunAtLoad</key>
    <true/>

    <key>StandardErrorPath</key>
    <string>/Users/kim/journals/stderr.log</string>

    <key>StandardOutPath</key>
    <string>/Users/kim/journals/stdout.log</string>

    <key>EnvironmentVariables</key>
    <dict>
      <key>PATH</key>
      <string><![CDATA[/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin]]></string>
    </dict>

    <key>WorkingDirectory</key>
    <string>/Users/kim/journals</string>

    <key>ProgramArguments</key>
    <array>
      <string>./makeTodaySym.sh</string>
    </array>

  </dict>
</plist>

When i check the stderr I saw the below
shell-init: error retrieving current directory: getcwd: cannot access parent
  1 bash: ./makeTodaySym.sh: Operation not permitted

stdout.log was empty
How do I solve this?

My original script
#!/usr/bin/env bash

date=`date +"%Y-%m-%d %A"`
folder="." # replace with full path to desired folder
file="$folder/$date.md"

if [ ! -f "$file" ]; then
    touch "$file"
    echo "Created file: $file"
fi

ln -sf "$file" "$folder/today.md"
echo "Created link to file: $file"

After trying out jksoegaard answer, the last part of my plist looks like this:
<key>ProgramArguments</key>
<array>
  <string>/Users/kim/journals/makeTodaySym.sh</string>
</array>

Latest change after taking jaume comment
<key>ProgramArguments</key>
<array>
  <string>/bin/bash</string>
  <string>/Users/kim/journals/makeTodaySym.sh</string>
</array>

Latest change
in the bash script
folder="$1" # replace with full path to desired folder

in the plist
<key>ProgramArguments</key>
<array>
  <string>/bin/bash</string>
  <string>/Users/kim/journals/makeTodaySym.sh /Users/kim/journals</string>
</array>

I have also tried
<key>ProgramArguments</key>
<array>
  <string>/bin/bash</string>
  <string>/Users/kim/journals/makeTodaySym.sh</string>
  <string>/Users/kim/journals</string>
</array>

And now I get this
shell-init: error retrieving current directory: getcwd: cannot access parent directories: Operation not permitted
/bin/bash: /Users/kim/journals/makeTodaySym.sh: Operation not permitted

thanks to @jaume with great patience, he/she/they have helped me get to the point where I realized that the only thing that worked was to move away from the Documents folder in Catalina.
I did find this link https://discussions.apple.com/thread/250719819?answerId=251683647022#251683647022 suggesting to create a fake bash clone, but I didn't try.
Also a big thank you to @nohillside
One useful thing I learn is to load and unload plist without restarting laptop
first unload
launchctl unload ~/Library/LaunchAgents/com.test.today.plist

then load
launchctl load -w ~/Library/LaunchAgents/com.test.today.plist

A: Analysis
After a long chat session, it turns out that the root of the problem was that bash can't fully access the Documents folder. The OP had shortened the actual path for makeTodaySym.sh: instead of being located in /Users/kim/journals, the script resides in a subfolder of ~/Documents.
The Documents folder is sandboxed, as explained in this Apple document:

In macOS, data in critical areas is itself sandboxed — which ensures that users remain in control of access to files in Desktop, Documents, Downloads and other areas from all apps, whether the apps attempting access are themselves sandboxed or not.

and bash can't read its contents from within the .plist file.
Two solutions
Place the script outside of ~/Documents
Interestingly enough, although bash can't read the contents of the Documents folder, it can write to it.
So one solution is to move makeTodaySym.sh outside of ~/Documents. For instance, if placed in /Users/kim/bin/makeTodaySym.sh, this should work:
<key>ProgramArguments</key>
<array>
  <string>/bin/bash</string>
  <string>-c</string>
  <string>/Users/kim/bin/makeTodaySym.sh /Users/kim/Documents/Apps/CompanyLevelApps/OILD/16-journals</string>

(Tested on macOS 10.15.5 Catalina.)
Grant full disk access to bash
Another solution is give bash full disk access. Just add /bin/bash to System Preferences>Security & Privacy>Privacy>Full Disk Access.
Note that even with full disk access, permissions would prevent bash from reading arbitrary files in the file system, but you have one fewer level of protection.
(Tested on macOS 10.15.5 Catalina.)
Two suggestions
I'd suggest that you do the following two changes to your configuration:
Remove reference to working directory
I've noticed that setting a working directory in the .plist file:
<key>WorkingDirectory</key>
    <string>/Users/kim/Documents/Apps/CompanyLevelApps/OILD/16-journals</string>

causes this error:

job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Operation not permitted

Your script doesn't need the WorkingDirectory key to successfully create the symlink, so you may want to remove it to get rid of the error.
Create symlink with relative path
Your script creates the symlink:
ln -sf "$file" "$folder/today.md"

with an absolute path:

today.md@ -> /Users/kim/Documents/Apps/CompanyLevelApps/OILD/16-journals/2020-06-10 Wednesday.md

To may want to use:
ln -sf "$(basename "$file")" "$folder/today.md"

instead to create a relative symlink that is easier to read:

today.md@ -> 2020-06-10 Wednesday.md

Full path in plist file
It's important to note that providing the full path for makeTodaySym.sh (as explained in jksoegaard's answer) was a necessary change for the .plist to work properly, as relative paths are not supported.

A: You need to change this:
<string>./makeTodaySym.sh</string>

so that you refer the whole path to the file. That could for example be like this:
<string>/Users/kim/journals/makeTodaySym.sh</string>


text:
Q: Time Series Estimation is Negative value in R I have a problem when I am running time series model,the forecast results (C.I. 95%) are negative values. It does not make any sense. I am not sure which part I made a mistake.
week total_amount_by_week
52     10000
52     12000
52     12300
52     9800
52     23400
51
51...
.
.
.
00      10000
00      12930

The dataset looks like this:
because the plot.ts looks backward ,so I made a reverse of the datasets.
order_ts1 <- ts(order_sum$Total_Amount_by_week,start = c(00),end =c(52))
order_ts1[] <-rev(order_ts1)
plot.ts(order_ts1,col ='blue')

And then I calculated difference, ACF,and PACF.
order_tsdiff3 <-diff(order_ts1,differences=3)
plot.ts(order_tsdiff3) # d=3

# calcualate ACF
acf(order_tsdiff3,lag.max=53)
acf(order_tsdiff3,lag.max=53,plot=FALSE)

# calculate PACF
pacf(order_tsdiff3,lag.max=53)
pacf(order_tsdiff3,lag.max=53,plot=FALSE)

fit_ma <- arima(order_ts1, order = c(1, 3, 1))
fit_ma

order_arimaforecast1 <- forecast.Arima(fit_ma,h=3,level=c(99.5))
order_arimaforecast1

So the plot looks like this:

So I get some estimation value,but I guess it's wrong.Why it happens negative values?
Call:
arima(x = order_sumts1, order = c(1, 3, 1))

Coefficients:
          ar1      ma1
      -0.6673  -1.0000
s.e.   0.1135   0.0539

sigma^2 estimated as 84368661:  log likelihood = -529.98,  aic = 1065.96

  Point Forecast   Lo 99.5  Hi 99.5
53      -1420.589 -27459.41 24618.23
54      -7983.391 -51772.69 35805.91
55     -21921.514 -93114.57 49271.54

All estimate amount should be positive value.

A: Try using transformations to help with making sure you always get positive values
## some sample data
a<-ts(c, frequency = 5)
## use ar() model with BoxCox() transform on the data & setting lambda = 0 (equivalent to taking the log)
fit <- ar(BoxCox(a,lambda=0))
## compute forecast and set lambda to 0 so that a back-transform is done (since we transformed the original data set we now want to back transform it to the original scale)
forecast(fit,h=3, lambda=0)

   Point Forecast     Lo 80    Hi 80     Lo 95    Hi 95
3.0       2.015135 1.1019547 3.685060 0.8005621 5.072398
3.2       1.385040 0.6984705 2.746480 0.4861378 3.946073
3.4       1.692792 0.8355244 3.429637 0.5749517 4.983975

If you go through these steps without the transform ie just forecast "a", you will get negative values also, however the transform in the above case helps with that.
a<-ts(c, frequency = 5)
## lambda = 1 means no transformation
fit <- ar(BoxCox(a,lambda=1))
forecast(fit,h=3, lambda=1)

    Point Forecast     Lo 80    Hi 80      Lo 95    Hi 95
3.0            1.8 0.4764192 3.123581 -0.2242421 3.824242
3.2            1.8 0.4764192 3.123581 -0.2242421 3.824242
3.4            1.8 0.4764192 3.123581 -0.2242421 3.824242

You can adapt this code for your particular case:
arima(x = BoxCox(order_sumts1, lambda=0), order = c(1, 3, 1))

Hope that it helps!


text:
Q: Find limit $\lim_{z\to 0}\frac{\bar z}{z}$
Evaluate $\lim_{z\to 0}\frac{\bar z}{z}$ where $z=x+iy$

My try:
$$\lim_{z\to 0}\frac{\bar z}{z}=\lim_{z\to 0}\frac{x-iy}{x+iy}$$
$$=\lim_{z\to 0}\frac{(x-iy)(x-iy)}{(x+iy)(x-iy)}$$
$$=\lim_{z\to 0}\frac{x^2-y^2-2ixy}{x^2+y^2}$$
$$=\lim_{z\to 0}\frac{x^2-y^2}{x^2+y^2}-\frac{2ixy}{x^2+y^2}$$
I can't solve it from here. My teacher says that the limit doesn't exist but I don't know how & why. Please help me solve this question

A: You don't need simplify
$$\lim_{z\to 0}\frac{\bar z}{z}=\lim_{z\to 0}\frac{x-iy}{x+iy}$$
consider for $x=0$ and $y=0$. Then you have different values.

A: Hint: Try to approach the origin along the real axis, and then along the imaginary axis (i.e. take first $z = t,\; t\in \mathbb{R}$ and let $t \to 0$, and then take $z = it, \; t\in\mathbb{R}$ and let $t \to 0)$.  Do you get the same limit?

A: Yes, starting form your step, the limit
$$\lim_{z\to 0}\frac{\bar z}{z}=\lim_{(x,y)\to (0,0)}\frac{x^2-y^2}{x^2+y^2}-\frac{2ixy}{x^2+y^2}$$
doesn't exist indeed

*

*for $y=0$ $$\implies \frac{x^2-y^2}{x^2+y^2}-\frac{2ixy}{x^2+y^2}=\frac{x^2}{x^2}-\frac{0}{x^2}=1\implies \lim_{z\to 0}\frac{\bar z}{z}=1$$

*for $x=y$ $$\implies \frac{x^2-y^2}{x^2+y^2}-\frac{2ixy}{x^2+y^2}=0-\frac{2ix^2}{2x^2}=-i\implies \lim_{z\to 0}\frac{\bar z}{z}=-i$$
As noticed by Nosrati, we don't need to simplify the original expression to obtain the same result.

A: Just a correction to a comment. Limit does exists, but limit along real component is different than limit along imaginary component. Hence function is not continuous. Right? I wonder if epsilon-delta form of limit might help prove no limit exists.

A: Polar coordinates;
$z=re^{i\phi}$, $r\not =0.$
$\overline{z}=re^{-i\phi}$.
$\dfrac{\overline{z}}{z}= e^{i(-2\phi)}.$
Approaching $0$ , i.e.
$r \rightarrow 0$, along any $\phi =$const,
yields a different point $P(e^{i(-2\phi)})$ on the unit circle in the complex plane.


text:
Q: Setting permissions in Keycloak I want to create role-based access control system using Keycloak's authorizaion system.
I'm using OAuth 2.0 in microservice architecture and faced the following problem: I have records with unique IDs (they are rooted to other entities) and what I want to achieve is that only certain users or a group of users can see (modify) entries with these IDs.
And I would like to be able to explicitly bind users (or groups) to these IDs (and it is possible to receive them in JWT for example).
How could this problem be solved using Keycloak and what best practices to do this?
Perhaps I misunderstood something and this problem can be solved in another way?
Thanks in advance!

A: There are 2 ways to handle this:
1. Using Client roles:
i) ie. create some set of pre-defined roles (viewer, admin, editor, etc).
ii) Now whenever your IDs are generated, then generate one client in keycloak and assign any of above roles.
iii) in JWT, it will be visible in path :
    "resource_access" --> <CLIENT_IDs> --> "roles": [your defined roles]

Then, in service layer can autorised using granted Authority or by roles-group.
2. Using Realm roles:
i) in JWT: this will be fetched from path:  "realm_access"-> "roles":[your defined roles].

If you have only 2 roles (eg: admin and viewer), then 2nd option would be preferred.
Let me know if this helps. :)


text:
Q: Use Excel formula in c# (^) symbol I was trying to convert this excel code to c#
IF(D5=F5,ROUND(((SQRT(F5) +0.0833) ^2),0)

and the output for the excel file i'm getting is 19423
but when i use the same code for c#
D5 = 19400.25
F5 = 19400.25
string s = Math.Round(Convert.ToDecimal(Convert.ToInt32((Math.Sqrt(F5) + 0.0833)) ^ 2)).ToString();

I'm getting the output as 137.
I don't know where I'm going wrong I tried each and everything and got stuck to this thing.Can anyone please help me ?
Thanks is advance.

A: The ^ symbol doesn't resemble the power function, as in Excel. You can't just translate this one-on-one. The C# ^ symbol does a bitwise exclusive-OR.
The actual C# code you should use to translate this function:
result = Math.Pow(Math.Sqrt(F5) + 0.0833, 2);

A: Let's decompose your c# code:
D5 = 19400.25
F5 = 19400.25
string s = Math.Round(Convert.ToDecimal(Convert.ToInt32((Math.Sqrt(F5) + 0.0833)) ^ 2)).ToString();
//                   î                 î               îî__ are closed here ___îî    îî
//                   |                 |______________ is closed here _______________||
//                   |_________________________ is closed here _______________________|

So basically, you are converting to int the following:
Math.Sqrt(F5) + 0.0833 // 139.36[...]

This results in a rounding, therefore 139.
You are then applying ^2 (bitwise exclusive-OR) as stated by Patrick Hofman, which results in 137.
You then convert this to decimal, and round it, which actually doesn't do much...

In Excel, you square Sqrt(F5) + 0.0833, this is written like this in c#:
Math.Pow(Math.Sqrt(F5)+0.0833,2)

Then you round it. Therefore, just wrap this in a Math.Round:
Math.Round(Math.Pow(Math.Sqrt(F5)+0.0833,2))

But you only do this if D5 equals F5:
D5 == F5 ? Math.Round(Math.Pow(Math.Sqrt(F5)+0.0833,2)) : 0

A: D5 = 19400.25
F5 = 19400.25

double R =  (D5 == F5) ? Math.Pow(Math.Sqrt(F5) + +0.0833, 2) : 0;

String s = Math.Round(R, 0).ToString();

But be warned that the condition, D5 == F5 is already very suspect. Equality for floating point types is easily fooled by rounding.

A: Probelm 1 : it's different between Math.Pow and ^
origin code logic :
var D5 = 19400.25m;
var F5 = 19400.25m;

//Right
var right1 = (decimal) Math.Sqrt((double)F5) + 0.0833m; //139.368080216648
var right2 = Convert.ToInt32(right1); // 139
var right3 = Math.Pow(right2,2) ; //19321
string rightStr = Math.Round(Convert.ToDecimal(right3)).ToString(); //"19321"

//Wrong
var wrong1 = (decimal)Math.Sqrt((double)F5) + 0.0833m; //139.368080216648
var wrong2 = Convert.ToInt32(wrong1); // 139
var wrong3 = wrong2 ^ 2; //137
string wrongStr = Math.Round(Convert.ToDecimal(wrong3)).ToString(); //""137""

Probelm 2 : it can be shorter
like @Patrick Hofman's answer
result = Math.Pow(Math.Sqrt(F5) + 0.0833, 2);
his answer is great!


text:
Q: hardware back button on Android is stopping the app I making mp3 player with ionic. I use "cordova.plugins.backgroundMode.enable()" for play music in background if close the app.
But when press hardware back button on Android is "stopping and closing" the app instead of just "closing and go back".

A: You have to use something called Android Services.
From the docs:
"A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use."
Here's the excellent official guide to using services to get you started: http://developer.android.com/guide/components/services.html
Here's a good tutorial on building an audio player: http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/
Here's a video tutorial for building a streaming music player: http://www.youtube.com/watch?v=LKL-efbiIAM


text:
Q: Mapping a texture from "1D" to "2D" with OpenGL matrix transformations (With this question I'm trying to investigate an idea I had for solving this other one)
If I have a standard 2D array of dimensions width and height in memory, I can turn that into a 1D array of length width * height and then index it via index = x + y * width. This mapping is extremely helpful when allocating and freeing memory for the array as the memory manager does not need to worry about packing the structures in 2D but only needs to worry about the overall length of every allocated array if expressed in 1D.
I am trying to see if I can use this same approach for image-memory management for OpenGL textures. The idea (as described in the above linked question) is to combine a whole bunch of needed textures into a single bigger one by bin-packing them (i.e. drawing them next to each other) into the big texture. This helps minimize costly texture-binding operations during rendering.
Let's say my big texture is 8×8 pixels (i.e. 64 pixels total):
8x8 texture:                5x5 image:            4x5 image:

   | 0 1 2 3 4 5 6 7           | 0 1 2 3 4           | 0 1 2 3
---+-----------------       ---+-----------       ---+---------
 0 | . . . . . . . .         0 | A B C D E         0 | a b c d
 1 | . . . . . . . .         1 | F G H I J         1 | e f g h
 2 | . . . . . . . .         2 | K L M N O         2 | i j k l
 3 | . . . . . . . .         3 | P Q R S T         3 | m n o p
 4 | . . . . . . . .         4 | U V W X Y         4 | q r s t
 5 | . . . . . . . .
 6 | . . . . . . . .
 7 | . . . . . . . .

And I would like to store a 5×5 image and a 4×5 image in it (i.e. 25 + 20 = 45 pixels total). Technically, I have plenty of pixels available, but I can't place these images next to each other into the big texture as that would require a minimum dimension of 9 in one direction and 5 in the other.
If I could simply treat my 8×8 texture as 64 continues pixels of memory and map the two images into 1D blocks of memory inside that, I could arrange the images as follows inside the texture:
    8x8 texture:
   | 0 1 2 3 4 5 6 7
---+-----------------
 0 | A B C D E F G H
 1 | I J K L M N O P
 2 | Q R S T U V W X
 3 | Y a b c d e f g
 4 | h i j k l m n o
 5 | p q r s t . . .
 6 | . . . . . . . .
 7 | . . . . . . . .

If I draw all my images at a scale of 1:1, i.e. no fractional pixel coordinates anywhere and no need for any linear filtering or other pixel blending, is it possible to come up with a transformation matrix that I can use to draw the 4×5 image using this texture?
With vertex and fragment shaders, this looks like it might be fairly easy (unless I'm forgetting something; I haven't tried this):

*

*The vertex shader maps the four corners of the image to draw to the texture expressed as a 64×1 image:

*

*a: (0, 0) → (0 + 0*4 + 25, 0) = (25, 0)     where 25 is the offset of the 4×5 image

*d: (3, 0) → (3 + 0*4 + 25, 0) = (28, 0)

*q: (0, 4) → (0 + 4*4 + 25, 0) = (41, 0)

*t: (3, 4) → (3 + 4*4 + 25, 0) = (44, 0)

The interpolation of other coordinates inside the texture should (?) then also map to the right offset along this line for integer coordinates

*The fragment shader converts this 64×1-coordinate into the final 8×8 coordinate by simply taking the quotient and remainder of a division by 8, e.g.:

*

*a: (0, 25) → (25 % 8, 25 / 8) = (1, 3)

*d: (0, 28) → (28 % 8, 28 / 8) = (4, 3)

*k: (0, 35) → (35 % 8, 35 / 8) = (3, 4)

*q: (0, 41) → (41 % 8, 41 / 8) = (1, 5)

*t: (0, 44) → (44 % 8, 44 / 8) = (4, 5)

Unfortunately custom shaders require OpenGL ES v2.0 or better, which is not available on all devices.
Is it somehow possible to achieve this mapping just via the matrix transformations offered by OpenGL ES 1.1?

A: I haven't tried this yet, but I wanted to throw it out there as an idea already:
UPDATE: I tried it now and it works beautifully with one minor change (see comment)!
Let's say my big texture has width size and the image I want to draw has width width and starts at offset offset inside the big texture, where offset is the 1-D representation of the offset, i.e. x + y * size.
Then, the following 4x4 matrix will almost achieve this mapping:
     _                                           _
    |      1        width        offset      0    |
    |                                             |
    |   1/size   width/size   offset/size    0    |
M = |                                             |
    |      0          0            0         0    |
    |                                             |
    |_     0          0            0         1   _|

So, in the example above, to draw the 4×5 image, the matrix would be
 _                    _
|   1    4    25    0  |
|  1/8  1/2  25/8   0  |
|   0    0     0    0  |
|_  0    0     0    1 _|

The image coordinates will then need to be specified with a 4-vector containing
( x, y, 1, 1 )

So, for example the coordinates of k (i.e. (2,2)) will map to:
M*( 2, 2, 1, 1 ) => ( 35, 4.375, 0, 1 )

which will be interpreted as texture coordinate (35, 4.375).
If we now turn on nearest neighbor as the interpolation rule and enable texture wrapping in the x-direction, this should correspond to:
( 3, 4 )

(I was using integer coordinates here, whereas in the final implementation, the final coordinates would need to be floats in the range from 0 to 1. This might be achievable very easily by replacing the 1 in the bottom right corner of the matrix with size, since that will end up in the fourth position of the output vector and thus divide the other three. This, as @chbaker0 pointed out, would only work, though, if the texture coordinates are subject to the usual perspective division. If they are not, the entire matrix M needs to be divided by size instead to achieve the desired result.)
Does this sound reasonable at all or can someone see a problem with this before I go ahead and try to implement this? (Might take me a few days, since I have to do a couple other things first to get to a testable app...)


text:
Q: Is both merger are same in Pandas asof & Polars join Is both are same pandas merge_asof & ploars join.
Is both are given same out put or not.

A: Am try to execute several time to execute to check both merger are same or not but i got result is :
Both Are not same.


text:
Q: Configuring Content-Security-Policy header for grails 2.5 application I was going through different solutions available for preventing clickjacking in a grails application. One of the solutions was using X-Frame. So, I found a grails plugin, X-Frame-Options Plugin, by mrhaki.
It is serving my purpose of adding a response header

X-Frame:DENY

to every response. Great!
I read there was a modern solution - Content-Security-Policy header. I'm unable to configure this for my Grails application. Could someone help?

A: The X-Frame-Options plugin is simple and inserts a servlet filter to add a header to requests. For your situation I'd recommend creating your own servlet filter to add the Content-Security-Policy headers.
You can see an example here of how to add a header:
https://github.com/mrhaki/grails-x-frame-options-plugin/blob/df230a9f01cd2e1c6ac4be6d9eac41fbcae48293/src/main/groovy/com/mrhaki/grails/plugin/xframeoptions/web/XFrameOptionsFilter.groovy#L69
Another option would be to use your web server infront of your app (apache httpd or nginx) to add the headers.


text:
Q: MIPS Simulator. What is wrong ? The program keeps looping and freezes up simulator MIPS program to loop 10 times and print the loop counter using Procedure call
main:
# initialize values to 2 registers
addi $a1,$zero,10     # $s1= $zero+10
addi $a2,$zero,0      # $s2= $zero+0
jal AddMeth           # call procedure
# Print out the loop counter
li $v0,1          # print integer
add $a0,$v1,$zero     # $a0 = $s2+$zero , load return value into argument
syscall

AddMeth:
Loop:   beq $a1,$a2,Exit  # goto Exit if $s1=$s2
    addi $a2,$a2,1    # $s2 = $s2+1
    j Loop        # goto Loop

Exit:
add $v1,$zero,$s2
jr $ra

A: The (emulated) CPU has no idea that you meant for the program to terminate after the print integer syscall. You need to tell it that that's what you want explictly, otherwise it will just keep on executing the next instruction (so it will end up in an infinite loop where it executes AddMeth and then the print integer syscall over and over).
The exit syscall in SPIM/MARS is number 10, i.e:
li $v0, 10
syscall

You also seem to have mixed up $a2 and $s2 in a couple of places.


text:
Q: Determining the bounds for a triple integral? I need help with a triple integration problem. I don't need help actually integrating this thing, I just need help with setting the actual integral(s) up. Specifically, I dont know how to determine what the bounds are.
We basically have a 3D donut. The problem says we can model the donut as a torus centered at the origin (0,0,0) with outer radius R=4 and inner radius r=2. The points (x,y,z) inside the torus are described by the following condition:
Equation Link
Here, c is the radius from the origin to the center of the torus tube (so I think it's 3), and a is the radius of the donut tube (so I think it should be 1), the cross section of the donut tube is a circle.
I need to calculate the volume of the donute after 2 cuts. The first cut happens parallel to the x axis at y = -3, and then parallel to the y axis at x = 1.
So far, I set up the following integral (in polar coordinates) that I think represents the volume of the whole donut:
Integral Eq
But I dont know how to subtract the cuts? I'm assuming I need two more integrals that have to be subtracted from the whole volume, but I cant set it up. Can anyone help? Is the volume I have correct so far?

A: You have a problem of order: The limits on the $z$ integral depend on $r$, and therefore it has to be done where $r$ is defined. In other words, the integral is $$\int_0^{2\pi}\int_2^4\int_{-\sqrt{a^2-(r-c)^2}}^{\sqrt{a^2-(r-c)^2}} rdzdrd\theta$$
And you are correct that $c = 3$ and $a = 1$
But as noted in the comments, this approach does not work well with the cuts. The problem is, the cuts are flat, which leads to complicated limits of integration for $r$ and/or $\theta$, which will undo the advantages of going to cylindrical representation ("polar" coordinates are in the plane - the 3D analogs are either "cylindrical", as you are using here, or "spherical").
Let's look at the cuts. The first is by the plane $y = -3$ (which is automatically parallel to the x-axis and to the z-axis). This plane is tangent to the "center ring" of the torus. The other plane is $x = 1$, which passes through the hole. Note that these two planes meet inside the torus. To set the up as an integral in $x, y, z$, you need to consider that for given values of $x$, there are in general two separate ranges of values for $y$ that need integrated over, and vice versa. The way to handle this is to break the torus up into quadrants and work each quadrant separately. Within each quadrant, there is only one range for $x$ or $y$ to be integrated. We can also do the same for $z$, limiting attention to $z \le 0$ and $z \ge 0$ separately. But in this case, the geometry is symmetric, so we will pick up the same volume on either side. Thus we can calculate only $z \ge 0$, then double it to get the whole volume.
The equation of the torus surface is $$z^2 +(\sqrt{x^2 + y^2} - 3)^2 = 1$$ So we can set up the integration over the entire first quadrant as
$$2\int_0^4\int_0^{\sqrt{16 - x^2}}\int_0^{\sqrt{1-(\sqrt{x^2+y^2}-3)^2}} dzdydx$$
After cutting, for each quadrant we have:

*

*Quadrant 1: $0 \le x \le 1, 0 \le y$

$$2\int_0^1\int_0^{\sqrt{16 - x^2}}\int_0^{\sqrt{1-(\sqrt{x^2+y^2}-3)^2}} dzdydx$$

*

*Quadrant 2: $x \le 0, 0 \le y$

$$2\int_{-4}^0\int_0^{\sqrt{16 - x^2}}\int_0^{\sqrt{1-(\sqrt{x^2+y^2}-3)^2}} dzdydx$$

*

*Quadrant 3: $x \le 0, -3 \le y \le 0$

$$2\int_{-4}^0\int_{-3}^{\sqrt{4 - x^2}}\int_0^{\sqrt{1-(\sqrt{x^2+y^2}-3)^2}} dzdydx$$

*

*Quadrant 4: $0 \le x \le 1, -3 \le y \le 0$

$$2\int_0^1\int_{-3}^{\sqrt{4 - x^2}}\int_0^{\sqrt{1-(\sqrt{x^2+y^2}-3)^2}} dzdydx$$
The $z$ integration is easy, but for the $y$ and $x$ integrations, you will need some trigonmetric substitutions.


text:
Q: SimpleDateFormat parse for time i need to parse a String value and get it as date object. Am using the following snippet
  java.util.Date temp = new SimpleDateFormat("HH:mm:ss").parse("14:58:00");

My output is : Thu Jan 01 14:58:00 IST 1970
But what i need is only 14:58:00 as Date object is there any way to achieve this? If not what is the other way around? Please help.
EDIT
I need this way because,
I have a Jspinner(in a Jpanel) for selecting time in HH:mm:ss format . The scenario is I will open the JPanel to select the time and click on save button so the values selected will be saved in a variable(x).Now if i open the Jpanel again the previously selected values should be shown which will be read from the variable(x).
For this am using following code,
    SpinnerModel Startmodel = new SpinnerDateModel();
    StarttimeSpinner = new JSpinner(Startmodel);
    Date date = new SimpleDateFormat("HH:mm:ss").parse("14:58:00");
    StarttimeSpinner.setValue(date);

On parse line am facing the problem. where i need only time(14:58:00) as date object.
NOTE:
I have tried the below code( it will work but wont allow us to change value again)
    StarttimeSpinner = new JSpinner();
    Date time = new SimpleDateFormat("HHmmss", Locale.ENGLISH).parse("000000");
    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
    String dateString = formatter.format(time);
    StarttimeSpinner.setModel(new SpinnerListModel(new String[]{dateString}));

A: You want to use new SimpleDateFormat("HH:mm:ss").formatDate(date) (you can use same instance of formatter) for output probably...


text:
Q: What does  before the return type of a method mean? The following method returns a List composed of T type elements:
public <T> List<T> getList() {
    return new ArrayList<T>();
}

In the signature we have <T> List<T>. The List<T> makes sense, because that is the type of the return value.  What is the need for the preceding <T> though?
The code doesn't compile without both <T> and List<T>. Leaving out the <T> gives

Cannot resolve symbol T

I have read the official Oracle tutorial on generic methods. It explains that this is part of the syntax:

The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type.

But it does not really explain why it is needed in the first place or what exact effect it has on the method.

A: The first <T> signifies that the second T is a placeholder for a generic parameter and not the actual name of class which you are going to store in that list.
Without that first <T> compiler will treat T as a class name (like Object, String, etc) try to find a class named T in the same package where the class with that method exists or in the import section of the class with that method. And if compiler is unable to find class named T it will show compilation error.


text:
Q: SSIS package not executing Script Task when called from C# web form I have a C# web form built in Visual Studio that calls a SSIS package. The first step in the SSIS package is a Script Tasks that unzips a file. It then deletes data in some tables in SQL Server and then inserts data back into those tables from the contents of the .zip file. When the package is run in VS, it completes successfully without any issues. When I call the package from the C# form, it will not run the Script Task but doesn't throw any errors.
Here is my code that calls the SSIS package:
using System;
using Microsoft.SqlServer.Dts.Runtime; // SSIS Package Execution

namespace LoadZip
{
    public class ExecuteSSIS
    {
        public void exePackage(string tbFilePath, string server)
        {
            String pkgLocation = @"C:\SSIS.dtsx";
            Package ssisPackage;
            Application app;
            DTSExecResult result;
            Variables vars;

            app = new Application();
            ssisPackage = app.LoadPackage(pkgLocation,null);

            vars = ssisPackage.Variables;
            vars["sqlServerName"].Value = server; Console.WriteLine("var server = " + server);
            vars["filenameWithPath"].Value = tbFilePath; Console.WriteLine("var tbFilePath = " + tbFilePath);

            result = ssisPackage.Execute();

            if (result == DTSExecResult.Success)
                Console.WriteLine("SSIS Package Successfully Executed");
            else if (result == DTSExecResult.Failure)
            {
                Console.WriteLine("********** SSIS PACKAGE FAILED **********");
                foreach (DtsError local_DtsError in ssisPackage.Errors)
                {
                    Console.WriteLine(local_DtsError.Description);
                }
                Console.WriteLine("********** END FAILED REPORT **********");
            }
        }
    }
}

Here is what the SSIS package looks like:

As I mentioned, when I run the package from my C# form, I get returned "SSIS Package Successfully Executed" but it really does not run it. Instead it seems to "fail" at the Script Task and not execute the rest of the package.
If I disable the Script Task (UnZip File) and re-run the SSIS package from my C# form, the package executes successfully. So I know my form is hitting the package and passing along the variables, but it just doesn't seem to like the script task although when executed outside the form, it works just fine.


text:
Q: Ordering Color by Hex Value I'm not sure how to classify this question, nor explain it effectively, but I'll do my best.
I have a series of random Hex code values gathered from my app.
I want to present these colors in a gradient, that will (in theory) show the prominence of one group of colors.
As in, if in my random array of colors there are more blue shades, then putting it into this gradient will reflect that.
But first, I need to "order" the colors in the gradient to be next to like colors.
I'm using C# -- but moreso just after the theory on how to map/order/group Hex color values together.

A: Thanks for the comments, I used the Hue method as commented, which results in the below -- which is works great, as you can see shows that there were more Blue colors in my List of colors (which is set dynamically) so thanks again.
BUT there is still a bug in it -- it's repeating instead of taking up the entire height for some reason :( (should only be 1 Linear from blues to reds)
(I'll open another question for this).

My code was as follows (ColorFromString was a method I wrote for this question):
private Color[] OrderColorByHue(List<string> colors)
{
  foreach(string c in colors)
  {
    Color color = ColorFromString(c); // This was defined in another question of mine :)
    float hue = color.GetHue();

    hueColors.Add(new KeyValuePair<Color, float>(color, hue));
  }

  hueColors.Sort((color1, color2) => color2.Value.CompareTo(color1.Value));
  Color[] value = hueColors.Select(color => color.Key).ToArray();

  return value;
}

Hope this helps someone else :)

A:     // GET: Admin/Colors
    public ActionResult Index()
    {
        var colors = db.Colors.OrderBy(a => a.HexCode);
        return View(colors);
    }

I used it in my MVC.Net project.
I think you may modify it for yourself.
HexCodes must begin with '#' (important for ordering)


text:
Q: Amplify alsa capture beyond 100%? I'm using ALSA. The volume of my mic is so low that even 100% of capture volume is not enough in a skype conversation. Is there any way to amplify the capture volume beyond 100%?
I cannot use pulseaudio. Because my computer is very old, using pulseaudio with skype will consume most of the CPU resources so that the quality of video chat become unacceptable.
Thank you very much!

A: use softvol module, It is explained here:
http://blog.tpa.me.uk/2013/10/23/alsa-pre-amp-volume-boost-the-simple-explanation/
# Set your DEFAULT device to the softvol plug-in
# NOT to a hardware card device
#
# The "!" means completely override the previous default
# Not just changing/adding to it.
pcm.!default {
  type plug
  slave.pcm "softvol"
}

# Configure softvol
pcm.softvol {
  type softvol

  # Send softvol's output to dmix
  slave {
    pcm "dmix"
    # If you wanted to you could send the output to a card directly
    # But in most cases it's better to send it to dmix and let
    # dmix handle where to send it. You can add a whole extra section
    # to configure dmix and where it sends output, but I'm
    # not covering that here.

    ## Use Card 0 Device 0 instead of dmix
    # pcm "hw:0,0"
    ## Use Card 2 Device 0 instead of dmix
    # pcm "hw:2,0"
  }

  # Add a control slider in your mixer interfaces
  # i.e. KMix and alsamixer
  control {
    name "Pre-Amp"
    card <CardNumberYouWantControlToShowOn>
    # i.e. card 0 or card 2
  }

  # Minimum dB when slider is at 0%
  min_dB -5.0

  # Maximum DB when slider is at 100%
  max_dB 40.0

  # How many levels the slider should go through
  # i.e. how granular do you want your control to be
  resolution 12
}


text:
Q: shadowbox stops working after jquery function call I have a shadowbox script. When I load the page everything works fine, but when I call this jquery load function and then try to trigger the shadowbox by clicking on the image, the large image opens in new window instead.
Here's the code:
<link href="CSS/main.css" rel="stylesheet" type="text/css" />

Any idea why this is happening?

A: EDIT
So, we finally get the bottom of this. 15 hours after first commenting on this issue, and at least 50 iterations later, we finally have identified what the problem is and how to fix it.
It actually struck me suddenly when I was creating local aaa.html and bbb.html on my server. That was when it hit me that the element nodes for the content that was being replaced was being removed altogether from the DOM when $.load() runs the callback function. So, once the #menu-home content elements were replaced, they were removed from the DOM and no longer had Shadowbox applied to them.
Once I figured this out, it was just a matter of a single web search and I found:
Nabble-Shadowbox - Reinit Shadowbox
Specifically, the response from mjijackson. What he describes is how to "restart" (reinitialize) Shadowbox using:
Shadowbox.clearCache();
Shadowbox.setup();

So once the #menu-home content was reloaded, what needs to happen is the Shadowbox cache needs to be cleared (essentially, shutting it down on the page), then the Shadowbox.setup() is run, which will detect the elements all over again. You don't run the Shadowbox.init() method again either.
I noticed that you had tried to copy/paste the Shadowbox.setup() in after the $.load(), at least sequentially in the code. However, this wasn't going to work, due to the cache clearing that needs to happen first, and primarily because the .clearCache() and .setup() functions need to be run after the $.load() completes (finishes and runs any callbacks). Those two functions need to be run in the $.load() callback handler; otherwise, you're running it's immediately, but the $.load() is asynchronous and will complete at some later time.
I'm going to go over some other changes I made, just so you understand what, why and wherefore.
Note, I'm not sure if you're familiar with <base>, but the following is at the top of the HEAD element:
<base href="http://62.162.170.125/"/>

This just let's me use the resource files on your computer. You'll not want to use this on your actual site more than likely. If you copy/paste, make sure and remove this line.

Home

Services

Tour

Login

Here, you'll notice I have a relative url in the HREF attribute, and a link to some pages on my server. The reason for the links to my server is that I couldn't access your aaa.html and bbb.html files through AJAX due to cross-site scripting limitations. The links to my website should be removed as well.
Now, the reason I'm using the rel attribute here is that I want allow for the links by way of the href attribute to continue to work in case the JS doesn't function correctly or there's some other error. If you have separate files, one for full HTML document and another for just the fragments, this is what you'll want to do. If you can serve both the full document AND the content-only from the linked file, then you probably don't need the rel attribute, but you'll need to manage the request so the server knows how to respond (full document or just the content part).
var boxInitialize = function(){
    try {
        if (!Shadowbox.initialized) {
            Shadowbox.init();
            Shadowbox.initialized = true;
        } else {
            Shadowbox.clearCache();
            Shadowbox.setup();
        }
    } catch(e) {
        try {
            Shadowbox.init();
        } catch(e) {};
    }
};

All I've done here is create a central location for the initialization/setup requests. Fairly straightforward. Note, I added the Shadowbox.initialized property so I could keep track of if the Shadowbox.init() had run, which can only be run once. However, keeping it all in one spot is a good idea if possible.
I also created a variable function which can be called either as a regular function:
boxInitialize();

Or as a function reference:
window.onload = boxInitialize; // Note, no () at the end, which execute the function

You'll probably notice I removed the $() and replaced them with jQuery() instead. This can turn into a real nightmare if you end up with an environment with multiple frameworks and libraries competing for $(), so it's best to avoid it. This actually just bit me real good the other day.
Since we have a closure scope within the .ready() callback, we can take advantage of that to save several "private" variables for ow use at different times in the scripts execution.
var $ = jQuery,
    $content = jQuery("#content"), // This is "caching" the jQuery selected result
    view = '',
    detectcachedview = '',
    $fragment,
    s = Object.prototype.toString,
    init;

Note the , at the end of all but the last line. See how I "imported" the $ by making it equal to the jQuery variable, which means you could actually use it in that#.
var loadCallback = function(response, status, xhr){
    if (init != '' && s.call(init) == '[object Function]') {
        boxInitialize();
    }

    if (xhr.success()
          && view != ''
            && typeof view == 'string'
              && view.length > 1) {
        $fragment = $content.clone(true, true);
        cacheContent(view, $fragment);
    }
};

This runs when the $.load() completes the process of the AJAX request. Note, the content returned in the request has already been placed on the DOM by the time this runs. Note as well that we're storing the actual cached content in the $content.data(), which should never be removed from the page; only the content underneath it.
var cacheContent = function(key, $data){
    if (typeof key == 'string'
          && key.length > 1
            && $data instanceof jQuery) {
        $content.data(key, $data.html());
        $content.data(detectcachedview, true);
    }
};

cacheContent() is one a method you may not want; essentially, if it was already loaded on a previous request, then it will be cached and then directly retrieved instead of initiating another $.load() to get the content from the server. You may not want to do this; if so, just comment out the second if block in the menuLoadContent() function.
var setContent = function(html){
    $content.empty().html(html);

    if (init != '' && s.call(init) == '[object Function]') {
        boxInitialize();
    }
};

What this does is first empty the $content element of it's contents/elements, then add the specified string-based markup that we saved earlier by getting the $content.html(). This is what we'll re-add when possible; you can see once the different links have been clicked and loaded, reclicking to get that to redisplay is really quick. Also, if it's the same request as currently loaded, it also will skip running the code altogether.
(We use $content like because it is a reference to a variable containing a jQuery element. I am doing this because it's in a closure-scope, which means it doesn't show up in the global scope, but will be available for things like event handlers.
Look for the inline comments in the code.
var menuLoadContent = function(){
    // This is where I cancel the request; we're going to show the same thing
    // again, so why not just cancel?
    if (view == this.id || !this.rel) {
        return false;
    }

    // I use this in setContent() and loadCallback() functions to detect if
    // the Shadowbox needs to be cleared and re-setup. This and code below
    // resolve the issue you were having with the compass functionality.
    init = this.id == 'menu-home' ? boxInitialize : '';
    view = this.id;
    detectcachedview = "__" + view;

    // This is what blocks the superfluous $.load() calls for content that's
    // already been cached.
    if ($content.data(detectcachedview) === true) {
        setContent($content.data(view));
        return false;
    }

    // Now I have this in two different spots; there's also one up in
    // loadCallback(). Why? Because I want to cache the content that
    // loaded on the initial page view, so if you try to go back to
    // it, you'll just pickup what was sent with the full document.
    // Also note I'm cloning $content, and then get it's .html()
    // in cacheContent().
    $fragment = $content.clone(true, true);
    cacheContent(view, $fragment);

    // See how I use the loadCallback as a function reference, and omit
    // the () so it's not called immediately?
    $content.load(this.rel, loadCallback);

    // These return false's in this function block the link from navigating
    // to it's href URL.
    return false;
};

Now, I select the relevant menu items differently. You don't need a separate $.click() declaration for each element; instead, I select the #menu a[rel], which will get each a element in the menu that has a rel="not empty rel attribute". Again, note how I use menuLoadContent here as a function reference.
jQuery("#menu a[rel]").click(menuLoadContent);

Then, at the very bottom, I run the boxInitialize(); to setup Shadowbox.
Let me know if you have any questions.

I think I might be getting to the bottom of this. I think the flaw is the way you're handling the $.load() of the new content when clicking a menu item, coupled with an uncaught exception I saw having to do with an iframe:

Uncaught exception: Unknown player iframe

This Nabble-Shadowbox forum thread deals with this error. I'm actually not getting that anymore, however I think it came up with I clicked on the tour menu item.
Now, what you're doing to load the content for the menu items really doesn't make any sense. You're requesting an entire HTML document, and then selecting just an element with a class="content". The only benefit I can see for doing this is that the page never reloads, but you need to take another approach to how to get and display the data that doesn't involve downloading the entire page through AJAX and then trying to get jQuery to parse out just the part you want.
I believe handling the content loading this way is the root cause of your problem, hence the $.load() toggling of menu views breaks your page in unexpected ways.
Question: Why don't you just link to the actual page and skip all the $.load() fanciness? Speed-wise, it won't make that much of an impact, if any at all. It just doesn't make sense to use AJAX like this, when you could just link them to the same content without issue.
There are two alternatives that would allow you to prevent roundtrip page reloads:

*

*Setup your AJAX calls to only request the .content portion of the markup if you have the ?contentonly=true flag in the URL, not the entire HTML document. This is how it's traditionally done, and is usually relative simple to do if you have a scripting environment.
$(".content").load('index.html?contentonly=true');

Then your server responds only with the content view requested.

*Serve all of the content views within the same HTML document, then show as appropriate:
var $content = $('.content');
$content.find('.content-view').hide();
$content.find('#services-content').show();

It doesn't look like you have a whole lot of content to provide, so the initial page load probably won't have that much of an impact with this particular approach.  You might have to look into how to preload images, but that's a very well known technique with many quality scripts and tutorials out there.
Either one of these techniques could use the #! (hashbang) technique to load content, although I believe there are some issues with this for search engines. However, here is a link to a simple technique I put together some time ago:
http://jfcoder.com/test/hash.html
Also, this is just a tip, but don't refer to your "content" element with a class, ie, .content. There should only be one content-displaying element in the markup, right? There's not more than one? Use an id="content"; that's what ID attributes are for, to reference a single element. classes are meant to group elements by some characteristic they share, so above when I .hide() the inline content views (see #2), I look for all of the class="content-view" elements, which are all similar (they contain content view markup). But the $content variable should refer to $('#content');. This is descriptive of what the elements are.

A: This worked for us, we made a site that used vertical tabs and called in the pages with our shadowbox images using jQuery.load
Just give all of your anchor tags the class="sbox" and paste this script in the header.

Note: we had to put the .sbox class on all our rel="shadowbox" anchors as well as the on the anchor for the tab that called the .load
Thanks to this guy-> http://www.webmuse.co.uk/blog/shadowbox-ajax-and-other-generated-content-with-jquery-and-javascript/

A: Well, based on Shem's answer, this is my solution.
Every click on specific class, setup and open shadowbox with elements from same class:
jQuery('.sb-gallery a').live('click',function(e){
    Shadowbox.setup(jQuery('.sb-gallery a'));
    Shadowbox.open(this);
    //Stops loading link
    e.preventDefault();
});

Thanks to all


text:
Q: Extracting part of string according to tags I have a big string and would like to extract parts of the string. You can see an example below. I would extract the text corresponding to the text tags. So we have three text tags, namely "text": "{{{VAR_2}}}", "text": "Tell me. How old are you?", "text": "{{{VAR_0}}}".
This should result in the following list of strings: ["What is your age?", "Tell me. How old are you?", "How old are you?"]. The number of text tags varies. If no text tag is present, it should result in None.
How can this be solved in an elegant way?
<VAR_0>
How old are you?
</VAR_0>
<VAR_2>
What is your age?
</VAR_2>

(set:$ageask to 'true')
(set:$storybeat_01 to 1)
(set:$inputAge to -1)

<audio stopall>

<audio src="sound.wav" autoplay loop volume="100%">

<onSuccess($user_age==0,$inputAge:=age)>[[age selector]]
<onSuccess(5>age OR 100<age,$inputAge:=age)>[[impossible age]]
<onSuccess(90<age,$inputAge:=age)>[[very old]]

<interaction type="AgeNumberQuestionInteraction">
{
    "BaseClassConfig QuestionInteractionInterface": {
        "QuestionInteractionInterfaceConfig": {
            "maxQuestionRepetitionCount": 1
        },
        "QuestionSpeakingInteraction": {
            "SpeakingInteractionConfig": {
                "speech": [
                    {
                        "emotion": "HAPPY",
                        "text": "{{{VAR_2}}}"
                    },
                    {
                        "emotion": "HAPPY",
                        "text": "Tell me. How old are you?"
                    },
                    {
                        "emotion": "HAPPY",
                        "text": "{{{VAR_0}}}"
                    }
                ]
            }
        }
    }
}
</interaction>

A: You can use a regular expressions pattern to search for the "text".
html_doc is your HTML above:
for text in re.findall('"text": ".*?"', html_doc):
    print(text)

Prints:
"text": "{{{VAR_2}}}"
"text": "Tell me. How old are you?"
"text": "{{{VAR_0}}}"

Or: using beautifulsoup:
soup = BeautifulSoup(html_doc, 'html.parser')
tag = soup.find("interaction")

for text in re.findall('"text": ".*?"', tag.text):
    print(text)

EDIT: to get the VAR text:
for text in re.findall(r"{{{(.*?)}}}", html_doc):
    print(text)

A: Here is a BeautifulSoup / JSON solution, which should be more resistant to changes in the HTML layouts.  Regular expressions are a terrible choice when working with HTML pages.
import bs4
import json

page = bs4.BeautifulSoup( open('x.html').read(), 'html.parser' )

data = json.loads(  page.find('interaction').text )

results = []
lst = data["BaseClassConfig QuestionInteractionInterface"]["QuestionSpeakingInteraction"]["SpeakingInteractionConfig"]["speech"]
for item in lst:
    if item['text'].startswith('{{{'):
        results.append( page.find(item['text'].strip('{}').lower()).text.strip() )
    else:
        results.append( item['text'] )
print(results)

Output:
['What is your age?', 'Tell me. How old are you?', 'How old are you?']


text:
Q: How to remove current theme customizations How can I delete my current theme and all its customizations so that I can use a new theme from scratch? In other words, how can I use a new theme without it loading the old theme's customizations?

A: What do you mean by "customization"? Modifying the theme's PHP, or modifying some settings the theme creates? Most themes do not clean up after themselves when they are deactivated or deleted. So for many themes, there is no easy way to flush their data. This is actually a good thing, if you want to switch back and forth between themes, but it forces you to pay attention to what you install on your system. If there is no content, you could start with a new database, that would certainly reset any theme options.

A: Do you have an unedited copy of the theme directory?
If you do, and just want to just start from 'scratch' you can just remove the theme that you are using from the wp-content>>themes directory and replace it with a new one.
If you don't have an unadulterated copy to reload into the directory you would have to try and feel out what has been altered... which would be a mess I imagine.

A: Found two solutions that worked and allowed me to reset the wordpress theme and restore it to default status: (1) using mysql to update options table; and (2) simply uploading a fresh copy of the theme's functions.php file


text:
Q: when two fabricjs rects beside each other Why do i have a horizontal gray line in the middle of two rects ? Even when i set hasBorder to false!
  fabric.Rect.prototype.backgroundColor = '#000'
  fabric.Rect.prototype.opacity = 0.7
  fabric.Rect.prototype.selectable = false
  fabric.Rect.prototype.hasBorder = false

  var canvas = new fabric.Canvas('c')

  var rect1 = new fabric.Rect({
    left: 0,
    top: 0,
    width: 500,
    height: 100
  })

  var rect2 = new fabric.Rect({
    left: 0,
    top: 100,
    width: 500,
    height: 100
  })

  canvas.add(rect1, rect2)

see fiddle here
Any answer will be appreciated, thanks!

A: It is hasBorders (instead of hasBorder)
Fiddle - http://jsfiddle.net/m7djt7ty/

A: I finally find the answer to the gray line appearing is because the rect's height is decimals, maybe my math calc should be more precise! Or to use another way to calc with decimals.
Thanks again!


text:
Q: Не получается создать фрагмент в фрагменте нужна помощь с добавлением таблицы, как фрагмент на лэйаут другого фрагмента. Когда я запускаю приложение, происходит вылет, при переходе на фрагмент с другим фрагментом.
Лэйаут с таблицей:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:background="#eeeeee"
        android:stretchColumns="*"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TableRow android:background="#cccccc"
            android:padding="5dp"
            android:layout_marginTop="25dp">
            <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="Дата"
                android:gravity="center_horizontal"
                android:textAppearance="?android:attr/textAppearanceLarge"
                />
            <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="Кол-во"
                android:gravity="center_horizontal"
                android:textAppearance="?android:attr/textAppearanceLarge"
                />
            <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="Сумма"
                android:gravity="center_horizontal"
                android:textAppearance="?android:attr/textAppearanceLarge"
                />
        </TableRow>
        <TableRow android:padding="5dp">
            <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="2012-11-22"
                android:gravity="center_horizontal"
                android:textAppearance="?android:attr/textAppearanceMedium"
                />
            <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="397"
                android:gravity="center_horizontal"
                android:textAppearance="?android:attr/textAppearanceMedium"
                />
            <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="19039.21"
                android:gravity="center_horizontal"
                android:textAppearance="?android:attr/textAppearanceMedium"
                />
        </TableRow>
        <TableRow android:padding="5dp">
            <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="2012-11-23"
                android:gravity="center_horizontal"
                android:textAppearance="?android:attr/textAppearanceMedium"
                />
            <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="348"
                android:gravity="center_horizontal"
                android:textAppearance="?android:attr/textAppearanceMedium"
                />
            <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="16759.28"
                android:gravity="center_horizontal"
                android:textAppearance="?android:attr/textAppearanceMedium"
                />
        </TableRow>
        <TableRow android:padding="5dp">
            <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="2012-11-24"
                android:gravity="center_horizontal"
                android:textAppearance="?android:attr/textAppearanceMedium"
                />
            <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="305"
                android:gravity="center_horizontal"
                android:textAppearance="?android:attr/textAppearanceMedium"
                />
            <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="14527.19"
                android:gravity="center_horizontal"
                android:textAppearance="?android:attr/textAppearanceMedium"
                />
        </TableRow>
    </TableLayout>

Код фрагмента с таблицей:
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class table extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment7, null);
    }
}

Код фрагмента в котором надо создать фрагмент с таблицей:
public class fragment5 extends Fragment {

    table table;
    FragmentTransaction fTrans;
    CheckBox chbStack;

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

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

        return inflater.inflate(R.layout.fragment5, null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        table = new table();

        fTrans.add(R.id.frgmCont2, table);
    }

    public void onClick(View v) {
        fTrans = getFragmentManager().beginTransaction();

        fTrans.commit();
    }

}

FATAL EXCEPTION: main
  Process: com.example.jone1.navigation_drawer, PID: 22035
  java.lang.NullPointerException: Attempt to invoke virtual method
  'android.app.FragmentTransaction
  android.app.FragmentTransaction.add(int, android.app.Fragment)' on a
  null object reference                                     at
  com.example.jone1.graciaonline.fragment5.onViewCreated(fragment5.java:53)
  at
  android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1010)
                                                                                at
  android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)
                                                                                at android.app.BackStackRecord.run(BackStackRecord.java:816)
                                                                                at
  android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1580)
                                                                                at android.app.FragmentManagerImpl$1.run(FragmentManager.java:483)
                                                                                at android.os.Handler.handleCallback(Handler.java:754)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:163)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6221)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)

A: у вас нарушен алгоритм. При создании View вы добавляете в "стек" фрагмент
fTrans.add(R.id.frgmCont2, table);, а потом, при клике на кнопку переинициализируете фрагмент менеджер: fTrans = getFragmentManager().beginTransaction(); Делайте все в одном месте, локально. не храните менеджер в глобальной переменной и будет вам щастье

A: Можно добавить в layout фрагмента (в который нужно вставить другой фрагмент) объект FrameLayout, и потом с помощью FragmentTransaction переместить фрагмент с таблицей в FrameLayout в другом фрагменте. Должно получится что-то вроде этого:
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.idFrameLayout, new YoursFragmentName());
ft.setTransition(FragmentTrasaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();

(В моём коде могут быть небольшие помарки, но в целом, я думаю, что он должен помочь)


text:
Q: What would be predicted class of KNN for an even value of K and in case of a tie? In KNN (K nearest neighbour) classifiers, if an even value of K is chosen, then what would be the prediction in majority voting rule or in Euclidean distance rule. For example if there are 3 classes say

*

*Iris-setosa

*Iris-versicolor

*Iris-virginica

And now say we have value of n_neighbors = 6. There is a fair amount of chance to get a tie result for Majority Voting Rule? In most visualisation this region is represented in white saying no decision could be achieved. But What would be the actual prediction for tie. This problem is hard to emulate and fairly conceptual hence may not be emulated so easily.
Also does an odd value of n_neighbors solves/reduces this issue? Do you think instead of using simple majority voting, euclidean/Manhattan distance would better handle this. However sklearn docs does not mention this at all.

A: After some digging, I have some good answers. First let me tell you that as mentioned by some users like @anasvaf, you should only use odd number for binary classification. This is absolutely untrue. Firstly, when we use majority voting for binary classification, on some tie, it is entirely dependent on the actual library to choose the action. For example, in scikit-learn, it takes the mode of the variable. This means if in the training dataset, number of datapoints for class 1 is more, then 1 would be used on the tie. But there is a better solution.
What we can use weighted-KNN instead of normal KNN. In the weighed KNN, if there is a tie, we can see total distance for 1 labeled datapoints from k points and 0 labelled points. If total distance for 1 is more, then class would be 0 and vice-versa.
There are other good techniques too to handle tie in KNN but to be very honest, KNN is not a good learning algorithm specially due to its space of time complexity on large datasets.

A: Since you are using majority voting, a selection of odd values for the nearest neighbors solves the issue when for instance two classes labels achieve the same score.


text:
Q: how to use "snapshot.hasData" with Dynamic Future builder I had a String type future method but I had to do some modifications to the code and I changed my future method to dynamic future and everysince the future builder never validate if snapshot has data

  late final Future myFuture;

 @override
  void initState() {
    myFuture =  getUserInfo();

    super.initState();
  }

Future  getUserInfo() async{
    SharedPreferences preferences = await SharedPreferences.getInstance();
    bool check = preferences.containsKey('$userID,imageURL');
    if(check == true){
      userName = preferences.getString('$userID,name')?? "No name found";
      userWeight = preferences.getString('$userID,weight') ?? "no wight found";
      userHeight = preferences.getString('$userID,height') ?? "no Height found";
      userGender = preferences.getString('$userID,genderType') ?? "no gender Type found";
      birthDateInString = preferences.getString('$userID,dateOfBirth') ?? "no date  found";
      imageURL = preferences.getString('$userID,imageURL') ?? "no image  found";
    }else{
      await downloadValues();
    }

  }

..........

 Widget userValues(){
    return
      FutureBuilder(
        future: myFuture,
        builder: (BuildContext context, AsyncSnapshot snapshot){
          if(snapshot.connectionState == ConnectionState.waiting){
          return const CircularProgressIndicator();
          }
          else if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              return Center(
                child: Text(
                  '${snapshot.error} occurred',
                  style: const TextStyle(fontSize: 18),
                ),
              );
            }
            else if (snapshot.hasData){
              return Column(
                children: [
                  Container(

                  ),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
                    child: ListTile(
                      title: Text("$userName",
                        textAlign: TextAlign.center,
                        style: GoogleFonts.mouseMemoirs(
                            fontSize: 30,
                            color: Colors.black
                        ),
                      ),
                    ),
                  ),

                ],
              );
            }
          }
          return const Center(
            child: CircularProgressIndicator(),
          );
        },
      );
  }

In this case the future builder is always returning CircularProgressIndicator. However, if I change the condition from else if (snapshot.hasData) to just else {   }, then the code will run properly but I dont think thats how it should be done.
Any suggestions?

A: @pskink is right. You should return a value (if you're using the returned value) or return nothing (like: return;) and set another value somewhere else and use this, which you are doing right now if I understood correctly.
Edit: my mistake. snapshot.hasData checks if anything returned from the future. You should return a value from the Future in this case. Sorry about that.
Future  getUserInfo() async{
    SharedPreferences preferences = await SharedPreferences.getInstance();
    bool check = preferences.containsKey('$userID,imageURL');
    if(check == true){
      userName = preferences.getString('$userID,name')?? "No name found";
      userWeight = preferences.getString('$userID,weight') ?? "no wight found";
      userHeight = preferences.getString('$userID,height') ?? "no Height found";
      userGender = preferences.getString('$userID,genderType') ?? "no gender Type found";
      birthDateInString = preferences.getString('$userID,dateOfBirth') ?? "no date  found";
      imageURL = preferences.getString('$userID,imageURL') ?? "no image  found";
    }else{
      await downloadValues();
    }

   return userName; // this should do the trick
  }