text:
Q: the installation package could not be open batch file I've been working on a batch file all day, that I can't get to work open through GPO (another day, another question).  So I decided to do it manually with every computer.  I have two exe's and one MSI.  The exe's work perfectly fine.  They get installed, and it all works out.   The MSI, however, doesn't.  It gives me the error: the installation package could not be opened.  Verify that the package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer package.
Now when I go to the network share and use it from there, it works perfectly fine.  So there must be an issue with my code.
Here's the code:
@echo off
IF NOT EXIST "C:\Program Files (x86)\Citrix\ICA Client\" (
 pushd "\\KOPI-DC01\ACCURO Cloudwerx\ACCURO\1\"
 .\CitrixReceiver-4.4.1000.exe /silent
)
IF NOT EXIST "C:\Program Files (x86)\triCerat\Simplify Printing\ScrewDrivers Client v4\" (
 pushd "\\KOPI-DC01\ACCURO Cloudwerx\ACCURO\2\"
 msiexec.exe /i ".\Screwdriver.msi"
)
IF NOT EXIST "C:\Program Files\Cloudwerx\CloudwerxPlugin\" (
 pushd "\\KOPI-DC01\ACCURO Cloudwerx\ACCURO\3\"
 .\cloudwerx-setup.exe /silent
)
pause

Any help would be greatly appreciated, thanks.

A: I am guessing that your problem is the distinction in powershell between the current location (set by  the pushd command) and the working directory (unaffected by the pushd command). You can see the working directory of the powershell process using the [Environment]::CurrentDirectory property:
# C:\> [Environment]::CurrentDirectory = "c:\"
# C:\> [Environment]::CurrentDirectory
c:\
# C:\> pushd C:\Temp
# C:\Temp> [Environment]::CurrentDirectory
c:\
# C:\Temp> Get-Location

Path
----
C:\Temp

WHat is probably happening is that msiexec.exe is using the working directory (i.e. [Environment]::CurrentDirectory) and not the current powershell location at invocation. I would just specify the full path to msiexec:
msiexec.exe /i "\\KOPI-DC01\ACCURO Cloudwerx\ACCURO\2\\Screwdriver.msi"

A: MSI installation packages build with an older WIX utility would throw the error whenever installation was attempted from a batch script that was accessed on a shared drive using UNC path instead of a mapped drive letter. On the other hand whenever the batch file was executed with a mapped drive letter the installation would work normally.
I'm not blaming WIX here because I'm not certain whether they are responsible. I'm just describing symptoms here. It might just be the result of invoking plain vanilla Windows batch script that in turn executes msiexec with a bunch of command line parameters.


text:
Q: What is the difference between these Jquery examples? I've seen various ways to attach event handlers using JQueryy and although each seem to work, I'm just not sure if they are at all different or if either are deprecated.
$(document).on("click", ".someSelector", function (event) {
  // do work...
});

$(function () {
  $(".someSelector").click(function (event) {
    // do work...
  });
});

A: The first example works whether or not there's an element on the page with class "someSelector".  If one is added eventually, it'll work.
The second only applies the event handler to existing elements. If an element is added later, "click" events won't be handled.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reactjs getting multiple items when clicking only on single items How I can get only single sub-category ? right now I am clicking on single category but getting result for all related sub category. See the screenshot. Electronic have two subcategory mobile and gadget but when clicking only on mobile I am also getting gadget.
here is code:
const PostSingleAd = ({ data, itemOpenedId, setItemOpenedId,setText }) => {
  const [showsubcat, setShowSubCat] = useState(false);

  let subcategory = () => {
    setShowSubCat((prev) => !prev);
    setItemOpenedId(data.id);
    setText(data.main_category)
  };
   let subclick = (e)=>(

       console.log(e.currentTarget.textContent)
  )
  useEffect(() => {
    if (itemOpenedId !== data.id) {
      setShowSubCat(false);
    }
  }, [itemOpenedId]);

 return (
    <>

        {data.main_category}

      {showsubcat && (

           {data.sub_cat_bp.map((data)=>(<>
          {" "}
          {data.sub_category}
          </>)

      )}
    </>
  );
};

const PostAds = () => {
  const [itemOpenedId, setItemOpenedId] = useState();
  const[text,setText] = useState();
  console.log(text)
  return data.map((data) => (
    <PostSingleAd
      data={data}
      itemOpenedId={itemOpenedId}
      setItemOpenedId={setItemOpenedId}
      setText={setText}

    />
  ));
};

When I will click on mobile I should get text only for mobile not mobile and gadget both. here is my api data look like:
[
  {
    "main_category": "Electronic",
    "sub_cat_bp": [
      {
        "sub_category": "Mobile",
        "id": 1
      },
      {
        "sub_category": "Gadget",
        "id": 2
      }
    ]
  },
  {
    "main_category": "Car",
    "sub_cat_bp": [
      {
        "sub_category": "Car glass",
        "id": 3
      },
      {
        "sub_category": "Dorr brll",
        "id": 4
      }
    ]
  }
]

A: Your li element should be inside map callback
  return (
    <>

        {data.main_category}

      {showsubcat &&
        data.sub_cat_bp.map((data) => (

 // <-- moved inside map
            {" "}
            {data.sub_category}

        ))}
    </>
  );

A: your
 should be inside map and you also need to assign a unique key to


text:
Q: Spring Boot - Modules I have 5 spring boot projects which can be deployed independently. I'm using gradle for dependency management. I have few java packages (src/main/java/...) in common that has been duplicated across all the services.
I would like to remove this redundancy by having the common java packages in a project and refer it from all 5 projects. How can I do that with help of spring modules. I'm new to Spring framework, and trying to do this.
Please help. Thanks in Advance

A: Create another project and build a jar package of the files you would like to include.
And you can reference to that package by adding next to your module gradle (Not the app gradle file):
repositories {
   flatDir {
       dirs 'libs'
   }
}
dependencies {
   compile name: 'common-1.0.0'
}


text:
Q: Difference between having @staticmethod and not having it In Python 3.x what can I do with bar() that I cannot do with foo()?
class A:
    def foo():
        print("some code")

    @staticmethod
    def bar():
        print("some code")

Note: I initially forgot to specify self as an argument to foo(), but I'm leaving the mistake there, since the answers andress that.

A: bar() can be called from an uninstantiated class object. foo() needs to be fed self as an argument, and as such can only be called from an object already declared as an instance of class A

A: a staticmethod is a method that does not require an object as its first parameter. This means it is a method useful to the class itself and all instantiations of it, rather than just instances of it (object initialized as A().
What this means in practical terms, is that Python does not implicitly send the object itself as a parameter. Your first method will break once you call it:
>>> a.foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() takes 0 positional arguments but 1 was given

This is because Python supplies object methods with the object itself as a first parameter. Hence the ubiquitous self argument:
def foo(self): #Proper signature

On the other hand,
A.bar()

will work just fine, and so will
a.bar()

The object is not supplied as a first argument. Use staticmethods for methods that are supposed to be helpful to the class and its instances, but do not require knowledge of either. Usually I use these as utility functions.
Note there is a third version, a classmethod, which is similar to a regular method in that it accepts a first parameter by default - the class of the caller. In this case the minimal signature is
@classmethod
def operateOnClass(cls):

Use this to make changes that affect all instances, such as changing class variables.


text:
Q: David Williams' Exercise 4.5 $\mathbb{P}(\text{limsup}(\frac{X_n}{\sqrt{2\log{n}}})\leq1)=1$ I am attempting Exercise 4.5 from David Williams' Probability with Martingales, which is about Borel-Cantelli lemma. The question states the follows.
If $G$ is a random variable with the normal N(0,1) distribution, then, for $x>0,$ we know that:
$$\mathbb{P}(G>x)=\frac{1}{\sqrt{2\pi}}\int^{\infty}_{x}e^{-\frac{1}{2}y^2}\,dy\leq\frac{1}{x\sqrt{2\pi}}e^{-\frac{1}{2}x^2}.$$
Then, let $X_1,X_2,\dots$ be a sequence of independent N(0,1) random variables, and define $L:=$limsup$(\frac{X_n}{\sqrt{2\log{n}}}),$  prove that $\mathbb{P}(L\leq1)=1.$
To approach this question and use Borel-Cantelli lemma, I have made some attempts:

$$\mathbb{P}(L\leq1)=\mathbb{P}(\text{limsup}(\frac{X_n}{\sqrt{2\log{n}}})\leq1)\stackrel{*}{=}\mathbb{P}(\frac{X_n}{\sqrt{2\log{n}}}\leq1 \text{ eventually})\\
=\mathbb{P}(X_n\leq\sqrt{2\log{n}} \text{ eventually})=1-\mathbb{P}(X_n>\sqrt{2\log{n}} \text{  infinitly often}).$$
Then, we can use the information given by the question:
$$\mathbb{P}(X_n>\sqrt{2\log{n}})\leq \frac{1}{\sqrt{2\log{n}}\sqrt{2\pi}}e^{-\frac{1}{2}\cdot 2\log{n}}=\frac{1}{2n\sqrt{\pi\log{n}}}.$$

But the problem at this step is that $\sum^{\infty}_{n=1}\frac{1}{2n\sqrt{\pi\log{n}}}=\infty,$ and then it seems the Borel-Cantelli lemma can't be applied!
Is there any method to use the Borel-Cantelli lemma to solve this problem? Also, I'm thinking the step of my attempt marked with *:  $\mathbb{P}(\text{limsup}(\frac{X_n}{\sqrt{2\log{n}}})\leq1)\stackrel{*}{=}\mathbb{P}(\frac{X_n}{\sqrt{2\log{n}}}\leq1 \text{ eventually}),$ is it technically correct?
Many thanks in advance for any hints and solutions!


text:
Q: How to convert scriptlets into jstl tags I tried turning these scriptlets into jstl tags with no success, is it not doable with these lines of codes, and if it can how so? thanks
<%
        //String file = application.getRealPath("C:/science/");

        File f = new File("C:/uploads");
        String [] fileNames = f.list();
        File [] fileObjects= f.listFiles();
    %>

    <%
        for (int i = 0; i < fileObjects.length; i++) {
            if(!fileObjects[i].isDirectory()){

    %>

        <A HREF="DownloadServlet?value=<%= fileNames[i] %>"><%= fileNames[i] %> Download
      <%= fileNames[i] %>

      (<%= Long.toString(fileObjects[i].length()) %> bytes long)

    <%
            }
        }
    %>

A: All that code you have in the scriptles you have to do it in the java code and pass it to the jsp. I don't know if you are using any framework to do this but this is easy in frameworks like Spring MVC.
In your case you should create in java a bean with the properties you need such as isDirectory, length, name of the file, etc. Then you create a list of these beans and pass it to the jsp. Finally, you just iterate these list of beans in the jsp with a forEach loop of JSTL (http://docs.oracle.com/javaee/5/jstl/1.1/docs/tlddocs/c/forEach.html). You can google about it and you'll find lots of examples about how to do this.
Doing this you don't need to use scriptlets.


text:
Q: How to use angular material table in angular dart I am working on angular dart project and I need to implement angular material table in my application.
I am following this guide https://material.angular.io/components/table/examples. But the example given in the document is for typeScript. I want to implement that same table in my angular dart. Is there a way to do that?

A: package:angular_components does not provide data table yet
But you can use skawa package that contains a data-table
https://pub.dev/packages/skawa_material_components


text:
Q: Set checkbox value from database in C# asp.net I have 8 checkboxes.
On the page load event I want to write the code such that
if the value in the database is "Submitted" the checkbox will appear checked.
If the value is "Not Submitted" it will appear unchecked.

A: you can have something like this
if(!Page.IsPostBack)
{
     var isChecked = dbvalue.ToLower() == "submitted" ? true : false;
     for (var i = 0; i < 8;i++ )
     {
         CheckBox chk = (CheckBox)Form.FindControl("chk" + i);
         if(chk != null) chk.checked = isChecked;
     }
}

A: You can check the values like this
if(!Page.IsPostBack)
{
    if(dbvalue=="Submitted")
    {
      chk1.checked=true;
      chk2.checked=true;
      chk3.checked=true;
      chk4.checked=true;
      chk5.checked=true;
      chk6.checked=true;
      chk7.checked=true;
      chk8.checked=true;
    }
    else if(dbvalue=="Not Submitted")
    {
        chk1.checked=false;
      chk2.checked=false;
      chk3.checked=false;
      chk4.checked=false;
      chk5.checked=false;
      chk6.checked=false;
      chk7.checked=false;
      chk8.checked=false;
    }

}

A: If don't want to do anything in the code-behind, a faster and easy method would be to create a new column of data type bit on the select query  and then just bind the checkbox to that. 0 = false and 1 = true. Example would be:
SELECT
CAST((CASE WHEN SubmitColumn = 'Submitted' THEN
    1
ELSE
    0
END) AS BIT) AS chkValue

FROM Table_1


text:
Q: Can the iPhone App respond to file transferred via Apple watch if it is inactive? I am developing an apple watch application which records an audio file, saves it and then transfers the file URL to the iPhone app via WCSession (Watch Connectivity framework). My code looks like this
In InterfaceController.m
NSURL *directory = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.name.watchtest"];
__block NSString *recordingName = @"myTestFile.mp4";
__block NSURL * outputURL = [directory URLByAppendingPathComponent:recordingName];

if ([WCSession isSupported]) {
   if ([self.watchSession isReachable]) {
         [self.watchSession transferFile:outputURL metadata:nil];
   }
}

In ViewController.m (WCSession delegate)
-(void)session:(WCSession *)session didReceiveFile:(WCSessionFile *)file
{
    NSError *error;
    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                            NSUserDomainMask, YES);
    NSString *docsDir = [dirPaths objectAtIndex:0];
    NSFileManager *filemgr = [NSFileManager defaultManager];
    NSString *filePath = [docsDir stringByAppendingString:@"/myTestFile.mp4"];

    [filemgr moveItemAtPath:file.fileURL.path toPath:filePath error:&error];

    if ([filemgr fileExistsAtPath:file.fileURL.path]) {
        urlOfAudioFile = [[NSURL alloc] initFileURLWithPath:filePath];
        [self uploadToServer:urlOfAudioFile];
    }
}

This works absolutely fine if both the WatchApp & the iPhone App are Active.
How can I make it work when the iPhone is in the background/ inactive/ in the locked state?

A: The documentation on transferFile(_:metadata:) clearly states:

Use this method to send a file that is local to the current device.
  Files are transferred to the counterpart asynchronously on a
  background thread. The system attempts to send files as quickly as
  possible but may throttle delivery speeds to accommodate performance
  and power concerns. Use the outstandingFileTransfers method to get a
  list of files that are queued for delivery but have not yet been
  delivered to the counterpart.
...
This method can only be called while the session is active—that is,
  the activationState property is set to activated. Calling this method
  for an inactive or deactivated session is a programmer error.

So as per your code:
if ([WCSession isSupported]) {
   if ([self.watchSession isReachable]) {
         [self.watchSession transferFile:outputURL metadata:nil];
   }
}

If the isSupported & isReachable checks fail, then basically WCSession is inactive and your code will not reach the transferFile(_:metadata:) part.
This is the correct behavior and you would have to handle this case manually.
But... when you have a valid session and transferFile(_:metadata:) does get called then whether the iPhone is locked, or the app is in background, or even if the app is not running, it will receive the file via a background thread.
So to answer your question, if the iPhone app is "inactive"; as in isReachable is false then the file transfer will not happen.

Ref:

*

*https://developer.apple.com/documentation/watchconnectivity/wcsession/1615667-transferfile


text:
Q: Show that $\frac{2\pi}{n}$ is trisectable under certain conditions I want to show that for $n\in\mathbb{N}$ and $3\nmid n$ the angle $\alpha = \frac{2\pi}{n}$ is trisectable.
What I use is the following theorem:
An angle $\alpha$ can be trisected using compass and ruler if and only if the polynomial $4X^3-3X-\cos\alpha$ is reducible over $\mathbb{Q}(\cos\alpha)$.
My attempt:
The angle $2\pi$ is trisectable, for the polynomial $4X^3-3X-1$ has root $-1/2$ in $\mathbb{Q}$, so I know that $2\pi/3$ is constructible from compass and ruler. Now if the angle $2\pi/n$ would be constructible, too, then I could reach the conclusion by using that $gcd(3,n)=1$ somehow, although I have no idea how right now.

A: Yu are right. Given $gcd ~(3, n) = 1$ there are $a, b$ integers such that $3\cdot a + b \cdot n = 1$. So
 $\frac{1}{3\cdot n} = \frac{a}{3} + \frac{b}{n}$. That is $\frac{1}{3n}$ can be written as an integer linear combination of $\frac{1}{3}$ and $\frac{1}{n}$. Done.


text:
Q: Issues with a mysqli_num_rows statement I'm having difficulties figuring out why my $numrows variable is getting an error. I get this error..
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given
for this this line...
$numrows = mysqli_num_rows($stmt);

Which is making my else statement of "This topic does not exist display".
What is wrong with my $numrows variable?
$con = mysqli_connect("localhost", "root", "", "");
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
$cid = $_GET['cid'];
$tid = $_GET['tid'];
//$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );

//Prepared SELECT stmt
$stmt = $con->prepare("SELECT * FROM forum_topics WHERE `category_id`=? AND id=? LIMIT 1");
if ( !$stmt || $con->error ) {
    die('Select topics prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt->bind_param('ii', $cid, $tid)) {
    die('Select topics bind_param() failed: ' . htmlspecialchars($stmt->error));
}
if(!$stmt->execute()) {
    die('Select topics execute() failed: ' . htmlspecialchars($stmt->error));
}
$numrows = mysqli_num_rows($stmt);
if($numrows == 1){
    echo "
";
    if ( $_SESSION['user'] ) {
        echo "
<input type='submit' value='Add Reply' onClick=\"window.location =
    'forum_post_reply.php?cid=".$cid."$tid=".$tid."'\">
";
    } else {
        echo "

Please log in to add your reply

";
    }
    while($row = mysqli_fetch_assoc($stmt)){
        //Prepared SELECT stmt to get forum topics
        $stmt2 = $con->prepare("SELECT * FROM forum_posts WHERE `category_id`=? AND topic_id=?");
        if ( !$stmt2 || $con->error ) {
            die('Select topics prepare() failed: ' . htmlspecialchars($con->error));
        }
        if(!$stmt2->bind_param('ii', $cid, $tid)) {
            die('Select topics bind_param() failed: ' . htmlspecialchars($stmt2->error));
        }
        if(!$stmt2->execute()) {
            die('Select topics execute() failed: ' . htmlspecialchars($stmt2->error));
        }
        while($row2 = mysqli_fetch_assoc($stmt2)){
            echo "

".$row['topic_title']."

            by ".$row2['post_creator']." - " .$row2['post_date']. "
" . $row2['post_content'] ."

            User Info Here!

";
        }
    }
} else {
    echo "
This topic does not exist.
";
}

A: You are mixing object oriented & procedural style. Should be -
$numrows = $stmt->num_rows;

DOCS

A: use
$numrows = $stmt->num_rows;

Read this as well


text:
Q: R:How can use ggplot2 order month x axis My data like this,but draw plot x axis is
12_01 12_10 12_11 12_12 12_2
I want to like
12_01 12_02 12_03...... 12_12
How can do it?
thanks!
df=data.frame(year=12,
              month=1:12,
              g=c(10,20,14,15,11:18))

df2 <- df %>%
    arrange(month) %>%
    unite(year_month,year,month) %>%
    group_by(year_month)

ggplot(df2 , aes(x = year_month, y =g,group = 1))+
  geom_line() +
  geom_point(shape = 22, size = 2, fill = "white")

A: You could manage this by converting year_month into a factor; or alternatively using {lubridate}...
library(dplyr)
library(tidyr)
library(ggplot2)
library(stringr)

df=data.frame(year=12,
              month=1:12,
              g=c(10,20,14,15,11:18))

df2 <- df %>%
  arrange(month) %>%
  unite(year_month,year,month) %>%
  mutate(year_month = factor(year_month, levels = paste0("12_", 1:12))) %>%
  group_by(year_month)

ggplot(df2 , aes(x = year_month, y =g,group = 1))+
  geom_line() +
  geom_point(shape = 22, size = 2, fill = "white")

Alternatively with lubridate if you want to preserve the variable as a date object:
df2 <- df %>%
  arrange(month) %>%
  unite(year_month,year,month) %>%
  mutate(year_month = ym(year_month)) %>%
  group_by(year_month)

ggplot(df2 , aes(x = year_month, y =g,group = 1))+
  geom_line() +
  geom_point(shape = 22, size = 2, fill = "white")+
  scale_x_date(date_labels = "%y_%m",
               date_breaks = "1 month")

Created on 2022-03-18 by the reprex package (v2.0.1)

A: Why not make them into actual dates?
df %>%
  arrange(month) %>%
  mutate(date = as.Date(paste(paste0(20, year), month, 1, sep = '-'))) %>%
  ggplot(aes(x = date, y =g,group = 1))+
  geom_line() +
  geom_point(shape = 22, size = 2, fill = "white")

A: My recommdation is to create a date variable in you dataframe and use that in the x axis, that way is more flexible de axis label configuration, via scale_x_date().
Look at two options:
library(dplyr)
library(ggplot2)
library(lubridate)

df <- data.frame(year = 12, month = 1:12, g = c(10, 20, 14, 15 , 11:18))

df2 <- df %>%
  mutate(
    date = make_date(year + 2000, month, "01")
  )

ggplot(df2, aes(x = date, y = g)) +
  geom_line() +
  geom_point(shape = 22, size = 2, fill = "white") +
  scale_x_date(labels = ~format(., '%m_%y'))

ggplot(df2, aes(x = date, y = g)) +
  geom_line() +
  geom_point(shape = 22, size = 2, fill = "white") +
  scale_x_date(labels = ~format(., '%b %y'))

Created on 2022-03-18 by the reprex package (v2.0.1)


text:
Q: Issue while loading Google maps api V3 in Firefox over https I am loading google maps api v3 script over https using the url
https://maps.googleapis.com/maps/api/js?sensor=false
.The maps get loaded and work properly in IE and chrome. But on firefox the maps don't work and I can see the error TypeError: google.maps.event is undefined
.I checked if the google object is loaded using undefined check and its not getting loaded on Firefox, IE and chrome load it properly.
The same behavior can be checked via the url
https://google-developers.appspot.com/maps/documentation/javascript/examples/full/map-simple
. The error occurs only over https and not http. The same issue has been noticed over multiple networks and multiple machines.
Firefox version being used:- 33.1.
My script import is in the head and my jquery bindings in the document.ready, so not much chance of the scripts executing before the import.
Same behavior is getting exhibited even in Firefox safe mode.
Can somebody help me out with a solution for this?

A: maybe the problem would be the ssl, you could try erasing the "s" from http
http://maps.googleapis.com/maps/api/js?sensor=false


text:
Q: How to properly read large html in chunks with .iter_content? So, I'm a very amateur python programmer but hope all I'll explain makes sense.
I want to scrape a type of Financial document called "10-K". I'm just interested in a little part of the whole document. An example of the URL I try to scrape is: https://www.sec.gov/Archives/edgar/data/320193/0000320193-20-000096.txt

Now, if I download this document as a .txt, It "only" weights 12mb. So for my ignorance doesn't make much sense this takes 1-2 min to .read() (even I got a decent PC).
The original code I was using:
from urllib.request import urlopen
url = 'https://www.sec.gov/Archives/edgar/data/320193/0000320193-20-000096.txt'

response = urlopen(url)
document = response.read()

After this I was basically dividing the whole document into portions <DOCUMENT>data</DOCUMENT>, and using a for loop for searching if inside every document data it was present some keywords like CONSOLIDATED BALANCE SHEETS that told me there was a the table I wanted to scrape. All this in a regular manner (can share code if needed), because I've tried bs4 and other parsers and was a PITA for my low-level. The correct document with the table parsing was done using df.read_html()
So now my approach is this:
import requests
KeyWord = b'CONSOLIDATED BALANCE SHEETS'
interesting_chunk = b''

document = requests.get(url)

for chunk in document.iter_content(10000):
     if KeyWord in chunk:
          interesting_chunk = chunk
     else:
          continue

And after this, I search for the start and the end of the <DOCUMENT>
doc_start_pos = interesting_chunk.find(b'<DOCUMENT>')
doc_end_pos  = interesting_chunk[doc_start_pos:].find(b'</DOCUMENT>')

final_document = interesting_chunk[doc_start_pos:doc_end_pos]

Problems here:

*

*KeyWord could be split between two chunks so I wouldn't find it.

*Same for <DOCUMENT> start and end or even these doesn't appear at all inside the chunk.

So I've thought in using another string to save the previous chunk in the loop, so if I find KeyWord, I'm still able to sum previous and current chunk and find the DOCUMENT start, and with the end, I could continue iteration until next </DOCUMENT>
But with the problem of a split KeyWord, Idk how to handle it. It's random, it's a large file, and is unlikely, but if I use small chunks it's not that difficult. How I avoid a KeyWord split between two chunks?
Also IDK what should be the optimal size of the chunks...

A: The time it takes to read a document over the internet is really not related to the speed of your computer, at least in most cases. The most important determinant is the speed of your internet connection. Another important determinant is the speed with which the remote server responds to your request, which will depend in part on how many other requests the remote server is currently trying to handle.
It's also possible that the slow-down is not due to either of the above causes, but rather to measures taken by the remote server to limit scraping or to avoid congestion. It's very common for servers to deliberately reduce responsiveness to clients which make frequent requests, or even to deny the requests entirely. Or to reduce the speed of data transmission to everyone, which is another way of controlling server load. In that case, there's not much you're going to be able to do to speed up reading the requests.
From my machine, it takes a bit under 30 seconds to download the 12MB document. Since I'm in Perú it's possible that the speed of the internet connection is a factor, but I suspect that it's not the only issue. However, the data transmission does start reasonably quickly.
If the problem were related to the speed of data transfer between your machine and the server, you could speed things up by using a streaming parser (a phrase you can search for). A streaming parser reads its input in small chunks and assembles them on the fly into tokens, which is basically what you are trying to do. But the streaming parser will deal transparently with the most difficult part, which is to avoid tokens being split between two chunks. However, the nature of the SEC document, which taken as a whole is not very pure HTML, might make it difficult to use standard tools.
Since the part of the document you want to analyse is well past the middle, at least in the example you presented, you won't be able to reduce the download time by much. But that might still be worthwhile.
The basic approach you describe is workable, but you'll need to change it a bit in order to cope with the search strings being split between chunks, as you noted. The basic idea is to append successive chunks until you find the string, rather than just looking at them one at a time.
I'd suggest first identifying the entire document and then deciding whether it's the document you want. That reduces the search issue to a single string, the document terminator (\n</DOCUMENT>\n; the newlines are added to reduce the possibility of false matches).
Here's a very crude implementation, which I suggest you take as an example rather than just copying it into your program. The function docs yields successive complete documents from a url; the caller can use that to select the one they want. (In the sample code, the first matching document is used, although there are actually two matches in the complete file. If you want all matches, then you will have to read the entire input, in which case you won't have any speed-up at all, although you might still have some savings from not having to parse everything.)
from urllib.request import urlopen
def docs(url):
    with urlopen(url) as f:
        buff = b''
        fence = b'\n</DOCUMENT>\n'
        while True:
            chunk = f.read(65536)
            if not chunk: break
                start = max(0, len(buff) - len(fence))
                buff += chunk
                end = buff.find(fence, start)
                if end != -1:
                    end += len(fence)
                    yield buff[find(buff, b'<DOCUMENT>'):end]
        buff = buff[end:]

url = 'https://www.sec.gov/Archives/edgar/data/320193/0000320193-20-000096.txt'
keyword = b'CONSOLIDATED BALANCE SHEETS'

for document in docs(url):
    if keyword in document:
        # Process document
        break


text:
Q: Need to re-add GoogleMobileAds on each build? Whenever I build my game for iOS, I need to remove GoogleMobileAds.framework and add it again with Add Files To ..., otherwise XCode complains that "module 'GoogleMobileAds' not found."
Does anyone have any idea how to get it to 'stick'? (I'm pretty new with XCode)

A: You can add the framework automatically to the Xcode project after Unity generates it using the [PostBuildProcess] attribute in an Editor script. Place the script in Assets/Editor.
Here's an example for adding frameworks. Here's a plugin that seems to do the heavy lifting for you using a JSON file to specify the modifications.
[PostProcessBuild] // <- this is where the magic happens
public static void OnPostProcessBuild(BuildTarget target, string path) {
    // Do post-build processing here
}


text:
Q: Generating JLabels on demand I would like to be able to generate a map, of sorts, which places small JLabels at coordinate locations on a panel. The problem is that I need them to be randomly generated, so I don't know in advance how many I will have. Is there a way to do that?
I hope this isn't breaking any Java coding taboos - I'm self-taught.
*Edit:
I know I was vague - my program is huge and cumbersome and I have developed my own conventions (which I'm sure would raise the hackles of real java coders :-P) I should have specified that I have a class Location, and I can easily generate random locations. The trouble I have is in creating a new jLabel for each of those locations. Here's what I have:
//Method called after a new Location has been created, to add it to the map
public void addLocation(Location newLocation)
{
    int xx = newLocation.getXloc();
    int yy = newLocation.getYloc();

    for (int i=0;i<1;i++)
    {
        JLabel tempLabel = new JLabel(); //tempLabel instantiated elsewhere (is that a problem?)
        tempLabel.setBackground(Color.BLACK);
        tempLabel.setBounds(xx,yy,3,3);
        Map.add(tempLabel); //Map is a JPanel with null layout manager
        tempLabel.setVisible(true);
    }
}

The problem is that it doesn't seem to do anything. No black dots appear on the map. Maybe now it's as simple as incorrect implementation of adding a label to a panel?

A: Here is some code that might help you in some way, your question was a little vague on the details but i think this is what you are looking for.
public void generate(JPanel panel)
{
    int panelWidth = 500;
    int panelHeight = 500;
    JLabel label;

    Random random = new Random(Calendar.getInstance().getTimeInMillies());
    int numberOfLabels = random.nextInt(100);
    for(int x=0;x<numberOfLabels;x++)
    {
        int locX = random.nextInt(panelWidth);
        int locY = random.nextInt(panelHeight);

        label = new JLabel("Hello World!!");
        label.setLocation(locX,locY);
        label.setVisible(true);
        panel.add(label);
    }
}

If this is not the answer you are looking for or you need more help, let me know ill be glad to help. Hope this helped!!
Update: This is the way you would do it with a MouseListener:
public void generate(JPanel panel)
{
    int panelWidth = 500;
    int panelHeight = 500;
    JLabel label;

    Random random = new Random(Calendar.getInstance().getTimeInMillies());
    int numberOfLabels = random.nextInt(100);
    for(int x=0;x<numberOfLabels;x++)
    {
        int locX = random.nextInt(panelWidth);
        int locY = random.nextInt(panelHeight);

        label = new JLabel("Hello World!!");
        label.setName("World Label");
        // If some of your labels have the same Text then you should set a different
        //     name to each one so that you can tell the difference between them
        //     when you handle the mouse events.
        label.addMouseListener(new PlayerListener());
        // PlayerListener would be the class that implements MouseListener
        label.setLocation(locX,locY);
        label.setVisible(true);
        panel.add(label);
    }
}

This would be your MouseListener:
public void mousePressed(MouseEvent e)
{
    JLabel label = (JLabel)e.getSource();
    if(label.getName().equalsIgnoreCase("World Label"))
    {
        System.out.println("Hello World!!");
    }
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseClicked(MouseEvent e){}

This MouseListener should only be added to JLabels because of the type cast. Hopefully this helped!

A:
but do you happen to know if it's possible to add a mouselistener to each of these jlabels as they're created?

Sure its possible. You don't even need to create a new listener every time. You can create one listener that is used by all labels. Then inside the listener code you use:
JLabel label = (JLabel)event.getSource();

and you have access to the label that generated the MouseEvent.


text:
Q: How do I craft an IIF, ELSEIF that Compares Values and Accounts For Nulls I am trying to compare Field1 to Field2 values and include cases where Null's exist in either field (or in some cases) both as well.
Field1 | Field2 | Expected      | Condition
-----------------------------------------------------------------
A      | A      | Pass          | Perfect Match
A      | B      | Fail          | Value ofI Field1 does not match Field2
A      | Null   | Investigate   | Field1 has a value but Field2 does not
Null   | Null   | No Version    | Field1 is null and Field2 is null
Null   | A      | Error         | Field1 is null Field2 has a value

This is the iif, else I conjured up but keep throwing an error
=iif((Field1 = Field2, "Pass", "Fail") ELSEIF (Field1 NOT NULL, and Field2 IS NULL, "Manual", "Error"))

from there things get crazy in the nesting.
I am starting to think it's best to go to using CASE in SQL as it is cleaner, but I'm not sure of approach.

A: I'd use case.
Case when field1 is null and field2 is not null then 'Error'
     when field1 is null and field2 is null then 'No Version'
     when field1 is not null and field2 is null then 'Investigate'
     when field1=field2 then 'Pass'
     when field1<> field2 'Fail'
     else 'Unhandled Case' end as Expected

Much easier to see the business rules and maintain in the long run.
or build a function that you call that determines the value for ease of re-use. If you expect to use these business rules over and over.

A: case stops at the first success, so if you order your tests you can simplify the logic.
case when Field1 is null and Field2 is null then 'No Version'
when Field1 is null then 'Error'
when Field2 is null then 'Investigate'
when Field1 <> Field2 then 'Fail'
else 'Pass'
end


text:
Q: Comparing the time measured results produced by rdtsc clock and c++11 std::chrono::high_resolution_clock I am trying to compare the times measured by c++11 std::chrono::high_resolution_clock and the rdtsc_clock clock at below. From the high_resolution_clock, I am getting result like 11000, 3000, 1000, 0. From the rdtsc_clock, I am getting 134, 15, 91 etc. Why their result look so differently? From my gut feeling, I believe the rdtsc_clock is presenting the ~accurate results, am I right?
    template<std::intmax_t clock_freq>
    struct rdtsc_clock {
        typedef unsigned long long rep;
        typedef std::ratio<1, clock_freq> period;
        typedef std::chrono::duration<rep, period> duration;
        typedef std::chrono::time_point<rdtsc_clock> time_point;
        static const bool is_steady = true;

        static time_point now() noexcept
        {

            unsigned lo, hi;
            asm volatile("rdtsc" : "=a" (lo), "=d" (hi));

            return time_point(duration(static_cast<rep>(hi) << 32 | lo));
        }
    };

The timing code:
typedef std::chrono::high_resolution_clock Clock;
//typedef rdtsc_clock<3300000000> Clock;
typedef std::chrono::nanoseconds nanoseconds;
typedef std::chrono::duration<double, typename Clock::period> Cycle;
for(int n=0; n < 10; n++){
   auto t1 = Clock::now();
   //codes
   auto t2 = Clock::now();
   printf(%.0f ns \n", duration_cast<nanoseconds>(Cycle(t2 - t1)).count());
}

A: Issues with RDTSC usage
If you read some online docs on RDTSC, you'll see that it doesn't ensure instructions from after the RDTSC instruction aren't executed in the pipeline before the RDTSC instruction itself runs (nor that earlier instructions don't run afterwards).  The normal advice is to use a CPUID instruction immediately before and/or after the RDTSC to trigger such "sequence points".  Obviously this impacts program performance, and is more desirable for some kinds of measurements than others (where average throughput figures are of more interest than individual samples).  You can expect that the Standard library implementation's being much more careful about this, which may be one reason its measurements are far higher.
Cross-Core Issues (not relevant per your comment)
Each CPU core maintains its own TSC register... if you just start taking samples on a thread that's not bound to a core, or on multiple threads not bound to the same core, you may see "weird" jumps in values.  Some companies (e.g. Microsoft) insist that the Hardware Abstraction Laye (HAL) is responsible for trying to get the registers as close to in-sync as possible, but many (even brand new high end) PCs simply fail to do this.
You can get around this by binding to a core, or by doing some calibration step that measures the cross-core deltas (with some calibration error margin), then adjust later samples based on the core from which they're sampled (which itself is painful to determine on most CPUs - you'll need to spin taking samples between CPUID instructions or something similar).

A: I think you are not comparing the same thing, on my mac this example work, rdtsc and std::chrono give the same number of cycle, if it can help:
#include <iostream>
#include <vector>
#include <numeric>
#include <chrono>

static __inline__ unsigned long long rdtsc(void){
    unsigned hi, lo;
    __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
    return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32   );
}

static int sink = 0;

int main(){
    typedef std::ratio<1, 2400000000> period; // My mac @ 2.4 GHz
    unsigned long long int a,b;
    for (auto size = 1ull; size < 1000000000ull; size *= 100) {
        // record start time
        auto start = std::chrono::high_resolution_clock::now();
        a = rdtsc();
        // do some work
        std::vector<int> v(size, 42);
        sink = std::accumulate(v.begin(), v.end(), 0u); // make sure it's a side effect
        // record end time
        b = rdtsc();
        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double, period> diff = end-start;
        std::cout << "Time to fill and iterate a vector of "
                  << size << " ints : " << diff.count() << " [cycle]"
                  << ", old style: "<< b-a << " [cycle] \n";
   }
}

Time to fill and iterate a vector of 1 ints : 13965.6 [cycle], old style: 13731 [cycle]
Time to fill and iterate a vector of 100 ints : 1065.6 [cycle], old style: 969 [cycle]
Time to fill and iterate a vector of 10000 ints : 68076 [cycle], old style: 67899 [cycle]
Time to fill and iterate a vector of 1000000 ints : 5.4853e+06 [cycle], old style: 5483487 [cycle]
Time to fill and iterate a vector of 100000000 ints : 6.57399e+08 [cycle], old style: 657395277 [cycle]

A: I'm finding pretty big differences from Timocafe's example code on my own Mac laptop
clang++ 9.1.0  -O3
Time to fill and iterate a vector of 1 ints : 27650.4 [cycle], old style: 35464 [cycle]
Time to fill and iterate a vector of 100 ints : 763.2 [cycle], old style: 939 [cycle]
Time to fill and iterate a vector of 10000 ints : 90712.8 [cycle], old style: 117181 [cycle]
Time to fill and iterate a vector of 1000000 ints : 4.79993e+06 [cycle], old style: 6199891 [cycle]
Time to fill and iterate a vector of 100000000 ints : 4.80331e+08 [cycle], old style: 620426953 [cycle]
g++ 5.5 -O3
Time to fill and iterate a vector of 1 ints : 2400 [cycle], old style: 1324 [cycle]
Time to fill and iterate a vector of 100 ints : 0 [cycle], old style: 944 [cycle]
Time to fill and iterate a vector of 10000 ints : 96000 [cycle], old style: 125444 [cycle]
Time to fill and iterate a vector of 1000000 ints : 5.4648e+06 [cycle], old style: 7059362 [cycle]
Time to fill and iterate a vector of 100000000 ints : 5.05517e+08 [cycle], old style: 652940006 [cycle]
Things like 0 time is bothersome.  That indicates the compiler re-ordered things around the high_precision_clock.  At least with our assembly code rdtsc timers we can use volatile to get some behavior we desire.  If I put the rdtsc calls inside the high_precision_clock calls then I can get a monotonic clock, which would tell me that it is the volatile in our assembly that is preserving ordering.   Also, the time_point seems to be in different units and accuracy across the two compilers.  ugh.


text:
Q: The usage of present tense and participles in a past tense context
It was probably around 3,000 yeras ago that people first began making things to help them measure the passage of time. Having observed that shadows move around trees as the sun moves across the sky, someone drew a circle and put a stick in the centre. As the sun passed overhead, he marked even divisions on the circle as the shadow of the stick crossed it.

The given sentences are taken from Grade 11 English Text. What I want to know is the usage of participle and present tense in the second sentence. Why is it written in present tense though others are past tenses?

A: A participle is a non-finite form: it has no tense. The clause it heads is understood to have the same tense as the finite clause to which it is subordinated.
The two moves are cast in the present tense because the author has decided to treat the movement of shadows and sun as a 'generic' truth, something true at all times, not just at the time those particular observations were made. You can observe the same thing today, and anybody who's around 3,000 years from now will be able to observe the same thing then.
The sentence would be equally grammatical if the moves were cast in the past tense.


text: Q: Some of the Hot Network Questions aren't completely shown in the iOS app Another (minor) bug in the iOS app; unlike my two previous bug reports I'm not entirely sure these are related to the launch of iOS 13. The app has the complete list of Hot Network Questions (accessible via the Feed, tap More Hot Network Questions). For some questions, the title isn't fully displayed and they lack the tags and the number of answers as well:


text:
Q: Conditional cell disablement in Excel I'm using Excel 2007. I want the following behaviour:

*

*If cell A2 is empty or contains value "Create" then cell B2 is inactive and the user cannot enter a value.

*If cell A2 contains the value "Modify" or "Retire" then cell B2 is active and the user can enter a value.

These behaviours need to be limited to their specific rows, so cell B3 needs to be unaffected by the value in cell A2. These behaviours need to be functional in rows 2 to 501.
I guess that this will require some VBA

A: 2 ways you can persue here I think, either you protect the worksheet and lock those specific cells based on the conditions you stated, or you write a routine for the worksheet_change event.
The first is rather devious I think, so I would opt for the latter.
Something like this perhaps?
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 2 Then
    If Target.Value = vbNullString Then Exit Sub 'to prevent endless loops
    If Cells(Target.Row, 1) = "Create" Or Cells(Target.Row, 1) = vbNullString Then
        Target.Value = vbNullString
    End If
End If

End Sub

All this in the worksheet.
Some explanation:
This sub gets called by Excel whenever the worksheet is changed (hence the name). So if you type a value into any cell, the sub gets called when you leave the cell (hit enter or click another cell, etc).
The Target argument in the sub is the range that has just changed.
So if you type 33 in cell B1, Target will be Range("B1"). So Target.Column is the column of the cell that has just changed (in this case, 2), Target.Row is the row (1) and Target.Value hold the value you just entered (33). So Cells(Target.Row, 1) is (in this case) cell A1.
This sub will work for all the rows in the sheet, but I'm sure you can adapt it to check which row it is in.

EDIT: added some explanation

A: The simplest solution (yet not fail proof) would be to create a data validation for the cell by going to data, data-validation, and custom. In the formula input, you could put in
=A2<>"Create"

if you dont want B2 to be editable if A2 contains "Create". Then you can highlight A2 and B2 and drag it down to row 501. thats the quickest solution that I've stumbled across. Hope this helps


text:
Q: conda install conda finds conflicts on fresh install How do I run conda install conda without conflicts?
Everything I do with Anaconda now finds conflicts and fails. To try and fix this problem I did the following:

*

*Uninstall current Anaconda,

*Restart the computer,

*Fresh install of Anaconda3-2020.11-Windows-x86_64,

*conda install conda.

I already have conflicts! The list of conflicts is probably 40 pages worth of text.
Did I do a bad job of uninstalling the previous Anaconda Installation or is this now the expected behavior? Is there some way to get around this issue? I'd like to abandon Anaconda all together but a package I use can't be installed without it (rdkit).
Thank you for any insight you can provide.

A: Retry the uninstall. Make sure to remove related hidden files (see what anaconda-clean deletes). You may also want to run conda init --reverse before uninstalling.
Sounds like you don't need Anaconda at all, but really just Conda. In that case, install Miniforge, or some variant.
Finally, avoid compromising your base installation by not using it for work. Create new environments for your projects (or just to install rdkit).


text:
Q: Is there a way to get the derived class to have the base class edit the protected varibales So I am experiencing a problem within this class assignment, we are set to code a "Tic Tac Toe" styled game. I thought it would be a good approach to have 2 versions such as original with 3 across and then 4 across. So here is the base class with the problem functions
Here is the minimal that leaves nothing cut out
main.cpp
#include "tic_tac_toe.h"
#include "tic_tac_toe_3.h"
#include "tic_tac_toe_4.h"
int main()
{
  std::vector <std::reference_wrapper<Tic_tac_toe>> games;

  string playerOption{ "" };

  bool isRunning{ true }, error{ true };
  int position{ 0 }, playerInt{ 0 };
  char option{ ' ' };

  //main loop
  while (isRunning)
  {

     cout << "Tic Tac Toe game 3 or 4: ";
     cin >> playerInt;

     if (playerInt == 3)
     {
         cout << "Executing tic tac toe 3";
         Tic_tac_toe_3 game3;
         games.push_back(game3);
     }
     else if (playerInt == 4)
     {
         cout << "Executing tic tac toe 4";
         tic_tac_toe_4 game4;
         games.push_back(game4);
     }

     //allows for constant looping to get user to input X or O. So program wont blow up
     while (error)
     {
         cout << "Player 1, X or O: ";
         cin >> playerOption;
         try
         {
             games[games.size() - 1].get().start_game(playerOption); //the .get gets the stored reference
             error = false;
             cout << "\n"; //to add a break in the text
         }
         catch (Error e)
         {
             cout << e.get_message();
         }
     }

     try
     {
         cin >> games[games.size() - 1].get(); //FAIL POINT IMO
         cout << games[games.size() - 1].get();
     }

     catch(Error e)
     {
         cout << e.get_message();
     }
 }
return 0;
}

tic_tac_toe.h
#include vector

using std::string;

class Tic_tac_toe
{
  public:
    Tic_tac_toe(int size) : pegs(size* size, " ") { } //multiply 3 or 4 by itself for 9 or 16

    void start_game(std::string first_player);
    void mark_board(int position);

    friend std::ostream& operator<<(std::ostream& out, const Tic_tac_toe& t);
    friend std::istream& operator>>(std::istream& in, Tic_tac_toe& b);

    string get_player() const { return player; }
    string get_winner() const { return winner; }

protected:

    std::vector<string> pegs; //initializes a vector of x elements with each being a space.

private: //most logic goes within the private functions

    void set_next_player();

    string player;
}

tic_tac_toe.cpp
{
void Tic_tac_toe::start_game(std::string first_player)
{
    if (first_player == "X" || first_player == "O")
    {
        player = first_player;
        clearBoard();
    }
    else { throw Error("Player must be X or O\n"); }
}

void Tic_tac_toe::mark_board(int position)
{
    if (position < 1 || position > 9)
    {
        throw Error("Position must be 1 to 9.\n");
    }
    else if (player == "")
    {
        throw Error("Must start game first.\n");
    }
    else
    {
        pegs[(position - 1)] = player; //minus one for the index
        set_next_player();
    }
}

std::ostream& operator<<(std::ostream& out, const Tic_tac_toe& b)
{
    std::cout << "\n"; //formatting purposes
    for (std::size_t i = 0; i < 9; i += 3) // += 3 for new row
    {
        out << b.pegs[i] + " | " + b.pegs[i + 1] + " | " + b.pegs[i + 2] + "\n";
    }
    return out;
}

std::istream& operator>>(std::istream& in, Tic_tac_toe& b)
{
    std::cout << "Pegs size" << b.pegs.size();
    int pos{ 0 };
    std::cout << "Player " << b.get_player() << " enter a position: ";
    in >> pos;
    b.mark_board(pos);

    return in;
}
}

tic_tac_toe_4 //4 and 3 are exactly same atm
class Tic_tac_toe_4 : public Tic_tac_toe
{

public:

tic_tac_toe_4() : Tic_tac_toe(4) { std::cout << "Passing to constructor"; }

}

A: Your program has undefined behavior, because you are pushing references to local variables such as
Tic_tac_toe_3 game3;

into games. When these variables leave their scope, the references in games become invalid and trying to use them later will have undefined behavior.
If you want a container that owns the Tic_tac_toe objects, then use
std::vector<std::unique_ptr<Tic_tac_toe>>

as type instead and create the objects with std::make_unique. Then the objects will live until the vector elements owning them are destroyed.


text:
Q: Use minio for storing attachments of an android application Im trying to use minio as I want to use minio for self-host instead amazon S3 in my android application, so my yml file configuration look like this :
s3:
accessKey: 1PAVK1425juiUAH
accessSecret: inhoKJSHDUIIrichskiY7Fpc9
attachmentsBucket: bucket
endpoint: http://127.0.0.1:9000
region: us-east-1
pathStyleAccess: true
signerAlgorithm: AWSS3V4SignerType
but it doesn't work, when I try to send an attachment the signal application give my this error "signal has stoped" .
any one have an idea?

A: The way to calculate storage capacity is based on number of objects to be uploaded and cater for a future window so that you don't run out of disk space.
Start with calculating what will be the average file size and total number of objects to be uploaded. This would give you an effective disk capacity that you need.
Minio is fully self contained comes in single binary,  you can run locally or in the cloud like (DigitalOcean, packet.net) etc.


text:
Q: Can't see the specific off-topic reason in the Reopen queue When I am doing the Reopen Review queue, I like to see why the question was closed. If the question is closed due to it being "off-topic" however, I can't see the specific off-topic reason:

It just says off-topic and expanding the div doesn't reveal any more information about it, so I'm forced to go to the "Question (revised)" tab:

And view the banner on the question for the specific reason:

Can we show the specific off-topic reason in that first div?

A: I can't decide if I buy this or not. On one hand, the site has an interest in making sure things are fixed, and showing details of the initial close reason could help efficiency. On the other, that's not the whole goal/story.
If a post has multiple problems, we want them all to be fixed, not just the one that shows up as the official closure reason. If you go to a hospital complaining of a broken leg, you definitely want to get that set, but you don't necessarily want the doctor to miss a gash on your arm because they were focused exclusively on your leg.
Getting back from the analogy to our actual situation, it might be better to present posts without comment, and let reviewers evaluate them "fresh". After all, what ultimately matters is that a post is of sufficient quality to exist on the site, not the amount of progress it made from its previous state.
We already do a similar thing with the popular community standard of asking editors—especially edit suggestors—to fix all the problems with a post, rather than (for example) indenting a code block but ignoring blatant typos.
In addition to pure post quality, the way we're training/affecting users is worth thinking about. For an author who edits a closed post and then is told it can't be reopened without a whole different set of fixes, there's some chance of learning how to write a post more in line with site standards, but a huge chance of learning to dislike both the indirect process and some perceived cabal of arrogant power users.
After all this, I was going to propose allowing multiple close reasons per post, but it turns out there's an existing, moderately popular proposal to do just that, for largely these reasons. But as noted there, it could introduce other issues.


text:
Q: Get the length of jsonResults.Data in C# I want to check if jsonResults.Data (that contains list of objects) length is greater than jsonResults.MaxJsonLength (I set it to int.MaxValue) to avoid the following error: "Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.".
so I think I need to convert the list to a string, in order to get the number of the characters.
Do you have any idea how?
(I can not use Json.Net because it requires NuGet client version '2.12' +, but my version of NuGet is '2.8.60610.756' and I do not want to update it.)
Thanks.

A: You can try serialize your json and catch the possible exception :
using System.Web.Script.Serialization;

public static bool IsJsonLengthValid(object myObj) {
    try {
         var jsonValue = new JavaScriptSerializer().Serialize(myObj);
    } catch(InvalidOperationException e) {
         return false;
    }
    return true;
}

Also if MaxJsonLength is not big enough, you can increase its size by using :
<configuration>
   <system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="50000000"/>
           </webServices>
       </scripting>
   </system.web.extensions>
</configuration>


text:
Q: how to save a Date Time on DB with sqlflite? I have a problem on how to save a DateTime on a data base with sqflite , so even if I change a page the date won't desapear, Could any one help me please ? Thank you .
enter image description here

A: If you just need to save one date, sqflite is overkill, take a look at shared_preferences.
onPressed:  ()async{
final selectedDate= await selectTimePicker(context);
 SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.seString('date', '$selectedDate');
}


text:
Q: Python 3.7.3 Inadvertently Installed on Mac OS 10.15.1 - Included in Xcode Developer Tools 11.2 Now? I decided yesterday to do a clean install of Mac OS (as in, erase my entire disk and reinstall the OS).
I am on a Macbook Air 2018. I did a clean install of Mac OS 10.15.1.
I did this clean install due my previous Python environment being very messy.
It was my hope that I could get everything reigned in and installed properly.
I've started reinstalling my old applications, and took care to make sure nothing was installed in a weird location.
However, when I started setting up VS Code, I noticed that my options for Python interpreters showed 4 options. They are as follows:

*

*Python 2.7.16 64-bit, located in /usr/bin/python

*Python 2.7.16 64-bit, located in /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python

*Python 3.7.3 64-bit, located in /user/bin/python

*Python 3.7.3 64-bit, located in /Library/Developer/CommandLineTools/usr/bin/python3
In terminal, if I enter where python python3
it returns
/usr/bin/python /usr/bin/python3.
How in the world did python3 get there?
My only idea is that it now is included in the Xcode Developer Tools 11.2 package, as I did install that. I cannot find any documentation of this inclusion.
Any ideas how this got here? More importantly, how do I remove it? I want to use Homebrew for all of my installation needs. Also, why does VS Code show 4 options?
Thanks!

A: The command line tool to run the python 2.7 environment is at /usr/bin/python, but the framework and dependencies for it are in /System. This includes the Python.app bundle, which is just a wrapper for scripts that need to run using the Mac's UI environment.
Although these files are separate executables, it's likely that they point to the same environment.
Every MacOS has these.
Catalina does indeed also include /usr/bin/python3 by default. The first time you run it, the OS will want to download Xcode or the Command line tools to install the 'complete' python3. So these pair are also the same environment.
I don't think you can easily remove these, due to the security restrictions on system files in Catalina.
Interestingly, Big Sur still comes with python2 !


text:
Q: Tango Unity Object Recognition I'm actually making a tango application using unity, but i have an hard time with this technology, especially with how to use the cloud point.
I want to be able to compare an object in the room with a library of model when i press it on the screen. For this i want to use the cloud point system. And i think that the best way to do this is to recognise the floor under the object that interest me and get all the point above it.
My problem is here, i don't know how ask unity to get that point cloud, and compare it with the model in my library.How do i know in the TangoPointCloudData which point get which index? Is it possible to get a floor if there is an object on it?
I know it's a lot of question, and it's not the more precise thing i could give you, but i hope you will find a way to answer me.
Thanks.


text:
Q: solving a 2D eigenvalue problem for a partial differential equation I'm fairly new to Mathematica and I'm looking for a way to solve a partial differential equation subject to periodic boundary conditions. The form of the equation looks like this:
$\frac{\partial^2}{\partial x^2}F(x,y) + \frac{\partial^2}{\partial y^2}F(x,y) + \frac{\partial}{\partial x}F(x,y) + \frac{\partial}{\partial y}F(x,y) + \frac{\partial^2}{\partial x \partial y}F(x,y) + G(x,y)F(x,y) = K F(x,y)$
where in that equation, the function $G(x,y)$ is non-separable, therefore making it impossible to recast the problem into two separate ODEs. I want to be able to solve this numerically by assuming that
$F(x,y) = \sum_{n}k_n f_{n}(x,y)$
So how do I go about doing this in mathematica? I assume I cant do this with NDSolve right?


text:
Q: How to make log4j not log anything? I tried this
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
    INFO="false" debug="false">

    <appender name="foo" class="org.apache.log4j.varia.NullAppender" />
    <root>
        <level value="FATAL" />
        <appender-ref ref="foo" />
    </root>

</log4j:configuration>

but I still get a lot of logs, for example
20:09:20.721 [main] DEBUG o.s.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]

20:09:33.202 [main] DEBUG o.a.cxf.phase.PhaseInterceptorChain - Invoking handleMessage on interceptor org.apache.cxf.jaxws.interceptors.WrapperClassInInterceptor@75ba3523

A: CXF uses java.util.logging, not Log4J. You will have to configure that too, or use a bridge to send j.u.l output through log4j if you want all the configuration in one place.


text:
Q: Passing a parameter to RelayCommand I'm experimenting with the ICommand and RelayCommand constructs. Looking around, I've put together the following code:
public class RelayCommand : ICommand
{
    private Action<object> _executeMethod;
    private Func<object, bool> _canExecuteMethod;

    public RelayCommand(Action<object> ExecuteMethod, Func<object, bool> CanExecuteMethod)
    {
        _executeMethod = ExecuteMethod;
        _canExecuteMethod = CanExecuteMethod;
    }

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        if (_canExecuteMethod != null)
        {
            return _canExecuteMethod(parameter);
        }
        else
        {
            return false;
        }
    }

    public void Execute(object parameter)
    {
        if (_executeMethod != null)
        {
            _executeMethod(parameter);
        }
    }
}

and I use all this from my main code as follows:
private bool CanExecuteMyCommand (object parameter) { /* do something here */ }

private void ExecuteMyCommand(object parameter) { /* do something here */ }

private ICommand _execMyCmd;
public ICommand ExecMyCmd
{
    get { return _execMyCmd; }
    set { _execMyCmd = value; }
}

ExecMyCmd = new RelayCommand(ExecuteMyCommand, CanExecuteMyCommand);

This works fine, but one thing I've not been able to find is how to pass a parameter to ExecuteMyCommand. I've tried something like:
ExecMyCmd = new RelayCommand(ExecuteMyCommand ("foo"), CanExecuteMyCommand);

but Visual Studio shows an error. Can anybody shed some light on this?
Thanks
Gianni

A: Command parameters are typically passed by the control which binds to the command. Here is an example:
<Button x:Name="btn"
        Content="Click"
        Command="{Binding ExecMyCmd}"
        CommandParameter="{Binding ElementName=btn, Path=Content}"/>

This will pass the content of the button, which is "Click", as parameter. Note that this is an example, so you could pass what ever you want here.


text:
Q: Minimum functions Suppose that $X$ is uniformly distributed on the interval $[0,10]$ and $Y$ is uniformly distributed on the interval $[0.10]$ and that they are independent.
Find the distribution function and the density function for $\min(X,Y).$
The book gives the formula for the min density function as $f_v(x)=n f_X(x)(1-F_X(x))^{n-1}$, however I have no idea what to plug in for $n.$
So far I have $f_v(x)=n \frac{1}{100}(1-\frac{x}{100})^{n-1}$ but this doesn't even help me get close to the answer in the back of the book which is $\frac{10-t}{50}.$
Can someone please help me apply this formula? Thanks in advance.

A: One more thing: you need to say this is the density function for $0 < x < 10$, and that the density function is 0 otherwise.
Another method, in case it helps you: Let $V = \min(X, Y).$ Then
for $x \in (0, 1),$ we have
$$P(V > x) = P(X > x)P(Y > x) = [(10 - x)/10]^2.$$
so $F_V(x) = 1 - [(10 - x)/10]^2$ and $f_V(x) = F_V^\prime(x),$
which gives the answer in the back of the book.
Also, here is a brief simulation of 100,000 such minimums. At left, is a histogram of the results with an overlay of the density
function from the book. At right, is a plot (heavy black) of the empirical cumulative
distribution function (ECDF) with an overlay of the CDF (in green) found
above.
 m = 10^5
 x = runif(m, 0, 10);  y = runif(m, 0, 10)
 u = pmin(x, y)


text:
Q: Verify current user authenticity from Cloud Code I have a Parse Cloud Code function that returns some user private data given a user id. How can I verify that the given user id is indeed the id of the currently logged in user?

A: I ended up creating this function and calling it from my other Cloud Code functions.
// Verifies that the given user is an authentic user
// Parameters: user
// Return: Promise
function verifyUserAuthenticity(user)
{
  var promise = new Parse.Promise();

  var userSessionToken = user.getSessionToken();

  var query = new Parse.Query(Parse.Session);
  query.equalTo("user", user);
  query.equalTo("sessionToken", userSessionToken);
  query.find({ useMasterKey: true }).then(
      function(results)
      {
        if(results.length > 0)
        {
          promise.resolve("User is authentic.");
        }
        else
        {
          promise.reject("User is not authentic.");
        }
      },
      function(error)
      {
        promise.reject("Error verifying user's authenticity: " + error);
      }
    );

  return promise;
}


text:
Q: Read Excel file with PHPExcel in php Hi i am using PHPExcel to import contact in mysql from Excel files.
Up until today everything was fine ,when one client wanted to upload excel file.
I am using this code to read the excel file :
$filetype = PHPExcel_IOFactory::identify(IEM_STORAGE_PATH . "/import/{$newfilename}");
$objReader = PHPExcel_IOFactory::createReader($filetype);
            $objPHPExcel = $objReader->load(IEM_STORAGE_PATH . "/import/{$newfilename}");

            foreach ($objPHPExcel->getWorksheetIterator() as $worksheet)
            {
                $importinfo['highestRow'] = $worksheet->getHighestRow(); // e.g. 10
                $highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
                $importinfo['highestColumnIndex'] = PHPExcel_Cell::columnIndexFromString($highestColumn);
            }

You can find the excel file here : https://phpexcel.codeplex.com/workitem/20675 .
I have spend more than 5 hours trying to solve this problem but nothing has worked so far.


text:
Q: matplotlib - Drawing directly on the canvas Due to performance issues for dynamical updates, I need to draw directly a lot of rectangle on the canvas as very low level, that is to say without using matplotlib.patches and as we have to do with classical GUI.
More precisely, I would like to only draw one rectangle and not only all the figure.
Is it possible ?
Here is my testing code using the link given by  Joe Kington.
#!/usr/bin/env python3

from random import randint, choice
import time

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.colors as colors
import matplotlib

back_color = "black"
colors     = ['red', 'green', 'cyan', 'yellow']

width  = 16
height = 16

ax     = plt.subplot(111)
canvas = ax.figure.canvas

ax.set_xlim([0, width])
ax.set_ylim([0, height])

def update():
    global ax, canvas, colors, width, height

    x = randint(0, width - 1)
    y = randint(0, height - 1)

    rect = mpatches.Rectangle(
        (x, y), 1, 1,
        facecolor = choice(colors),
        edgecolor = back_color
    )

    start = time.time()
    ax.draw_artist(rect)
    canvas.blit(ax.bbox)
    print("draw >>>", time.time() - start)

timer = canvas.new_timer(interval = 1)
timer.add_callback(update)
timer.start()

plt.show()

Under Mac O$, I obtain the following message.
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/matplotlib/backend_bases.py", line 1203, in _on_timer
    ret = func(*args, **kwargs)
  File "/Users/xxx/test.py", line 86, in update
    ax.draw_artist(rect)
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/matplotlib/axes.py", line 2100, in draw_artist
    a.draw(self._cachedRenderer)
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/matplotlib/artist.py", line 56, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/matplotlib/patches.py", line 393, in draw
    gc = renderer.new_gc()
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/matplotlib/backends/backend_macosx.py", line 97, in new_gc
    self.gc.save()
RuntimeError: CGContextRef is NULL

For Maverick users
I have a good news for the Mac users who want to play with the following codes, and also with animations. I've reinstalled Maverick OS on my Mac without any softwares, this is called a clean installation, and then I've installed Anaconda, and XQuark (see this).
To make animations work, you just have to use the following two lines before any other matplotlib imports.
import matplotlib
matplotlib.use('TkAgg')

I think this will work for any Mac OS supported by Anaconda. The use of XQuark is only needed for Maverick.

A: You have two problems with your current code.

*

*You're trying to blit without having drawn the canvas first.  The error you're getting is backend-specific, but basically, it's saying that the canvas's renderer hasn't been initialized yet.

*You're not adding the rectangle artist to the axes. Therefore, it's not being drawn with you call ax.draw_artist(rect).

Here's a working example:
from random import randint, choice
import time
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

back_color = "black"
colors     = ['red', 'green', 'cyan', 'yellow']
width, height = 16, 16

fig, ax = plt.subplots()
ax.set(xlim=[0, width], ylim=[0, height]) # Or use "ax.axis([x0,x1,y0,y1])"

# Be sure to draw the canvas once before we start blitting. Otherwise
# a) the renderer doesn't exist yet, and b) there's noting to blit onto
fig.canvas.draw()

def update():
    x = randint(0, width - 1)
    y = randint(0, height - 1)

    rect = mpatches.Rectangle(
        (x, y), 1, 1,
        facecolor = choice(colors),
        edgecolor = back_color
    )
    ax.add_artist(rect)

    start = time.time()
    ax.draw_artist(rect)
    fig.canvas.blit(ax.bbox)
    print("draw >>>", time.time() - start)

timer = fig.canvas.new_timer(interval=1)
timer.add_callback(update)
timer.start()

plt.show()

At this point, though, it would make a lot more sense not to add a new artist each time.  Instead, add the initial rectangle and update it each time.  For example:
from random import randint, choice
import time
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

back_color = "black"
colors     = ['red', 'green', 'cyan', 'yellow']

width, height = 16, 16

fig, ax = plt.subplots()
ax.set(xlim=[0, width], ylim=[0, height]) # Or use "ax.axis([x0,x1,y0,y1])"

rect = mpatches.Rectangle(
    (0, 0), 1, 1,
    facecolor = choice(colors),
    edgecolor = back_color
)
ax.add_artist(rect)

# Be sure to draw the canvas once before we start blitting. Otherwise
# a) the renderer doesn't exist yet, and b) there's noting to blit onto
fig.canvas.draw()

def update():
    x = randint(0, width - 1)
    y = randint(0, height - 1)
    rect.set(xy=[x,y], facecolor=choice(colors))

    start = time.time()
    ax.draw_artist(rect)
    fig.canvas.blit(ax.bbox)
    print("draw >>>", time.time() - start)

timer = fig.canvas.new_timer(interval=1)
timer.add_callback(update)
timer.start()

plt.show()


text:
Q: How to display a directory full of junit test result files As part of testing in the cloud, I plan to copy my test results (I happen to be using gradle) as xml out of a short lived container to an s3 bucket.
I am wondering what is the best approach for making use of the bucket full of test results and if anyone has ideas for how to get the most of these results with the least custom code, etc.
In the past I have handled this with XSLT to make the XML into HTML but that approach feels like more work than I'd like to have to do.
Has anyone solved this issue for their own purposes that can share your approach?
As I side note... I could also copy out to my s3 bucket the HTML reports from gradle if someone has an idea about how to use the HTML instead.
Ideally, I would be able to see a sorted list of results and click on the most recent to see the test run details.

A: Disclaimer: I'm not a Devops guy, I'll present a "developer's" point of view here
The answer IMO depends on what exactly would like to do with all these reports.
In a nutshell, you can have text/xml reports from the test execution (I can't say for gradle but in maven surefire plugin creates these reports, I believe gradle does the same).
You can also generate a good looking site with the reports information, there are tools for this as well, for example Allure Reports. Bottom line, some stuff to be shown can be generated in the build directory.
Copying the reports is as simple as copying a file, but the question is what would like to do with them when they're in S3?
In my understanding, its a Job for CI tools (like Jenkins) to run the tests during the build, or maybe a suit of automation tests against a deployed environment (in the cloud).
These CI Tools run gradle to build the project, and run tests, then they show test results per build memorizing last N builds. It can also be integrated with tools like aforementioned allure and show the HTML report per build as long as the build is stored in CI tool.
So I'm not sure I understand why would you like to "run tests in the cloud" (from which I assume you're running tests suite when the artifact is being deployed).
As for possible ideas of what can be done with all these results:

*

*You can create a site that will show the results across builds (again, this is
 already solved by CI tool like Jenkins)

*You can store the results of running the tests in some database and provide some
 clever statistics (I personally don't see much benefit if usually the build is
 green and you're not in the process of "recuperation" of project from flaky tests or
 something)


text:
Q: How to secure pre marshmallow application crashings I am making an application that contains a part of activities that can be executed on pre marshmallow devices and some part of activities on marshmallow and above.
So what I want to do is don't let the application crash on pre marshmallow device that runs the activity that is supported on marshmallow device and just show a toast that your device does not support this module to access.
Here I am stuck on finger print module that crashes the applications on pre marshmallow device.
 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {

//do something
}
else
showToastMessage();

Error
FATAL EXCEPTION: main
                java.lang.VerifyError: com/example/android/fingerprintdialog/MainActivity
                at java.lang.Class.newInstanceImpl(Native Method)
                at java.lang.Class.newInstance(Class.java:1130)
                at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2210)
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
                at android.app.ActivityThread.access$700(ActivityThread.java:159)
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
                at android.os.Handler.dispatchMessage(Handler.java:99)
                at android.os.Looper.loop(Looper.java:176)
                at android.app.ActivityThread.main(ActivityThread.java:5419)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:525)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
                at dalvik.system.NativeStart.main(Native Method)

A: In my application I have a download button that requires runtime permission.
This is how I managed to do it:
public static int MY_PERMISSIONS_REQUEST_DOWNLOAD_IMAGE = 1;

btnDownLoad.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
                        urlFromDownload();
                        }
    });

public void urlFromDownload() {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(getActivity(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {

                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_DOWNLOAD_IMAGE);
                } else {

                    DowloadFileFromUrl downloadwall = new DowloadFileFromUrl();
                    if (downloadwall.getStatus() == AsyncTask.Status.RUNNING) {
                        // My AsyncTask has not started yet
                        Toast.makeText(getActivity(), "Please wait until download is complete", Toast.LENGTH_SHORT).show();
                    } else {
                        downloadwall.execute(imageUrl);
                    }

                }
            } else {

                DowloadFileFromUrl downloadwall = new DowloadFileFromUrl();
                if (downloadwall.getStatus() == AsyncTask.Status.RUNNING) {
                    // My AsyncTask has not started yet
                    Toast.makeText(getActivity(), "Please wait until download is complete", Toast.LENGTH_SHORT).show();
                } else {
                    downloadwall.execute(imageUrl);
                }

            }

        }

I hope you understand my code. What I've done is wrote my download code twice. First for marshmallow and second for lower versions.

A: Put that within the below condition
if (Build.VERSION.SDK_INT >= 23) {
    // Your code for
    } else {
    // Code for previous versions
    }

A: Just check whether installed app is using marshmallow or above Android OS.
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M)
{
 // FingerPrint is supported by Android
  // Show the FingerPrint touch screen.
}
else
{
//FingerPrint is not supported by Android
//Don't show the FingerPrint touch screen.
}


text:
Q: Configuring sqlnet.ora and tnsnames.ora on the client side I have an application server talking to an Oracle database, using the Oracle instant client. We are troubleshooting a specific bug, and it was asked if I could add the following flags to to my sqlnet.ora file:
DIAG_ADR_ENABLED=OFF
DIAG_SIGHANDLER_ENABLED=FALSE
DIAG_DDE_ENABLED=FALSE

Prior to this request, we did not need a sqlnet.ora file on the client side, with instant client, we could reference the classpath of ojdbc6.jar and the ld_library_path of the directory of the jar, and use a URL like this:
jdbc:oracle:oci:@server:port:sid

Looking at the Oracle Docs, it appeared that I could reference a sqlnet.ora file and/or a tnsnames.ora file on the client side if I added environment variables for ORACLE_HOME and TNS_ADMIN.
I created the sqlnet.ora file with the parameters above, and added some trace parameters so that I could verify that the file was being read:
TRACE_LEVEL_CLIENT=10
TRACE_DIRECTORY_CLIENT=/tmp

I also created a tnsnames.ora file:
APPDB =
    (DESCRIPTION =
        (ADDRESS LIST =
                (ADDRESS = (PROTOCOL = TCP)(HOST = *host*)(Port = *port*)))
        (CONNECT_DATA =
                (SERVER = DEDICATED)
                (SERVICE_NAME = *service*)))

Finally, I added environment variables, and restarted the application. I tried with the original simpler URL, and it was clear that the settings weren't picking up, as I would expect with the trace flags that a file would be created if it were being read. Next I tried to create the URL using the TNS name, which per the docs sounded like it would look in TNS_ADMIN for additional files to connect with.
jdbc:oracle:oci:@(DESCRIPTION=(ADDRESS LIST=(ADDRESS = (PROTOCOL = TCP)(HOST = *host*)(Port = *port*)))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = *service*)))

So far, I haven't seen any trace files come up, and I have a feeling I'm doing a part of this wrong, or missing a step, or using the wrong URL. I tried a few variants of connection strings that would reference "APPDB" as in my tnsnames.ora file, but either it doesn't work at all, or it connects, but does not seem to be picking up the settings from sqlnet.ora.
Any ideas on what I could be missing, or if in fact applying these settings is only possible on the DB side?

A: The difference of oracle instant client and the oracle client installed by Oracle Universal Installer is in how they are installed. The Oracle universal installer maintains a registry which the instant client does not have or use. But the software components are the same independent of the method you use to install. If you use the jdbc oci driver then you use java to access the libraries of the Oracle OCI client which is the well known client that use all the clients that can use a tnsname.ora. These are sqlplus, ODBC program, C-Programs that use the Oracle Precompiler, ... Access with the OCI client can be configured with tnsnames.ora and sqlnet.ora and the well known environment variables (like ORACLE_HOME, ORACLE_SID, TNS_ADMIN,...). In java there is a new way to access the Oracle database by using the jdbc thin client. This is a client completely implemented in java that does not use the oracle OCI libraries but has implemented the necessary oracle net protocols in java to communicate with an Oracle database. This client cannot be influenced by tnsnames.ora, sqlnet.ora or the environment variables. It does not even need these files. It only needs an appropriate jar file that implements the thin client.
If you use the oci client for a program then  in the environment that starts this program the Oracle relevaant variables must be set. So if a program is started by a shell script this shell script should set and export the relevant variables. The directory stored in the  variable TNS_ADMIN is searchd for the tnsnames.ora and sqlnet.ora. If this variable is not set then other directories are searched for these files (or similar files). This depends on the operating system and of the value of ORACLE_HOME, if set. If no appropriate file is found default values are used.
DIAG_ADR_ENABLED=OFF determines if ADR-logging (available since 11.1)  is used or the traditional logging is used. If ADR-logging is not disabled the TRACE_DIRECTORY_CLIENT parameter will be ignored and the sqlnet trace files will be found somewhere in the diag-directories used by ADR-logging.

A: I figured it out. Instead of having the environment variables set for the user, they had to be asserted when starting the JVM for the application, just like you have to set the LD_LIBRARY_PATH and CLASSPATH for the JDBC Driver. If everything is set when starting up the JVM, and you have a sqlnet.ora file in the directory you've set TNS_ADMIN, the file will be read.


text:
Q: Why does the linear regression of "x on y" intersect with the linear regression of "y on x" at (x̄, ȳ)? Problem:
The following table below shows the marks scored by seven students on two different mathematics tests.
$$\begin{array}{c|c|c|}
\text{Test 1 (x)} & 15 & 23 & 25 & 30 & 34 & 34 & 40 \\ \hline
\text{Test 2 (y)} & 20 & 26 & 27 & 32 & 35 & 37 & 35 \\ \hline
\end{array}$$
Let $L_{1}$ be the regression line of x on y. The equation of the line $L_{1}$ can be written in the form $x = ay + b$.
(a)  Find the value of $a$ and the value of $b$.
Let $L_{2}$ be the regression line of $y$ on $x$. The lines $L_{1}$ and $L_{2}$ pass through the same point with coordinates $(p,q)$.
(b) Find the value of $p$ and the value of $q$.
My solution:
I inputted both sets of data into the calculator (TI-84) and got a line of best fit for both.
$x$ on $y$:
$y=1.2908291457286x-10.379396984925$
$y$ on $x$:
$y=0.69993188010899x+10.187670299727$
These two lines intersect at $(34.81,34.55)$
The actual solution:
The lines should meet at $(x̄, ȳ) = (28.7,30.3)$
Can anyone point me in the correct direction? I just don't see how these two lines could intersect at the mean x,y values when those values are obviously flipped in the two lines.
Edit: This problem is from the IB Math AA HL curriculum, exam code SPEC/5/MATAA/SP2/ENG/TZ0/XX/M . This is a practice test provided by IB.

A: Any linear regression goes through $\bar x,\bar y$, hence, these two should intersect too.
Consider regressions $y=a+bx+e$ and $x=c+dy+u$, take the expectations of both sides of equations:
$$E[y]=a+bE[x]+E[e]$$
$$E[y]=a+bE[x]$$
similarly
$$E[x]=c+dE[y]$$

A: Ok, so I think I see where I messed up. In this line:
$x$ on $y$:
$y=1.2908291457286x-10.379396984925$
The position of the x and y are reversed. The equation should be written as
$x=1.2908291457286y-10.379396984925$
In order to put these two regression lines on the same graph, both equations need to be solved for the same variable (even if in the first equation, Y is the independent).
Now when I graph, I see that these two lines of regression do indeed intersect at the $(\bar x,\bar y)$ .


text:
Q: How to aggregate a metric and plot groups separately I have this dataset:
df = pd.DataFrame()
df['year'] = [2011,2011,2011,2011,2011,2011,2011,2011,2011,2011,2011,2011]
df['month'] = [1,2,3,4,5,6,1,2,3,4,5,6]
df['after'] = [0,0,0,1,1,1,0,0,0,1,1,1]
df['campaign'] = [0,0,0,0,0,0,1,1,1,1,1,1]
df['sales'] = [10000,11000,12000,10500,10000,9500,7000,8000,5000,6000,6000,7000]
df['date_m'] = pd.to_datetime(df.year.astype(str) + '-' + df.month.astype(str))

And I want to make a line plot grouped by month and campaign, so I have tried this code:
df['sales'].groupby(df['date_m','campaign']).mean().plot.line()

But I get this error message KeyError: ('date_m', 'campaign'). Please, any help will be greatly appreciated.

A: *

*Plotting is typically dependant upon the shape of the DataFrame.

*.groupby creates a long format DataFrame, which is great for seaborn

*.pivot_table creates a wide format DataFrame, which easily works with pandas.DataFrame.plot
.groupby the DataFrame

*

*df['sales'].groupby(...) is incorrect, because df['sales'] selects one column of the dataframe; none of the other columns are available

*.groupby converts the DataFrame into a long format, which is great for plotting with seaborn.lineplot.

*

*Specify the hue parameter to separate by 'campaign'.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# perform groupby and reset the index
dfg = df.groupby(['date_m','campaign'])['sales'].mean().reset_index()

# display(dfg.head())
      date_m  campaign  sales
0 2011-01-01         0  10000
1 2011-01-01         1   7000
2 2011-02-01         0  11000
3 2011-02-01         1   8000
4 2011-03-01         0  12000

# plot with seaborn
sns.lineplot(data=dfg, x='date_m', y='sales', hue='campaign')

.pivot_table the DataFrame

*

*.pivot_table shapes the DataFrame correctly for plotting with pandas.DataFrame.plot, and it has an aggregation parameter.

*

*The DataFrame is shaped into a wide format.

# pivot the dataframe into the correct shape for plotting
dfp = df.pivot_table(index='date_m', columns='campaign', values='sales', aggfunc='mean')

# display(dfp.head())
campaign        0     1
date_m
2011-01-01  10000  7000
2011-02-01  11000  8000
2011-03-01  12000  5000
2011-04-01  10500  6000
2011-05-01  10000  6000

# plot the dataframe
dfp.plot()

Plotting with matplotlib directly
fig, ax = plt.subplots(figsize=(8, 6))
for v in df.campaign.unique():
    # select the data based on the campaign
    data = df[df.campaign.eq(v)]
    # this is only necessary if there is more than one value per date
    data = data.groupby(['date_m','campaign'])['sales'].mean().reset_index()

    ax.plot('date_m', 'sales', data=data, label=f'{v}')
plt.legend(title='campaign')
plt.show()

Notes

*

*Package versions:

*

*pandas v1.2.4

*seaborn v0.11.1

*matplotlib v3.3.4


text:
Q: Given a point, a line and a circle; how can I find a point on the line having the following property? First of all: I searched with different search engines and on StackExchange, but did not find a solution to my problem. This may be because its specific description is kind of long. For the same reason, I had to choose an unspecific title to this question due to the character limit.
Now, here is my problem:
Given

*

*A point $D$

*A line $l$

*A circle $K$ (with center $C$ and radius $r$)

all in $\mathbb{R}^2$

I want to find a point $G$ such that:

*

*$G$ is incident to $l$

*Let the intersection of the line $GC$ with $K$ be $H$. It should hold that $G$ has the same distance to $D$ as to $H$, i.e. $\left\lVert\vec{GD}\right\rVert = \left\lVert\vec{GH}\right\rVert$

So far I tried to find some property that this point has that allows me to construct it, but haven't found one yet. I am also very inexperienced and have little to no knowledge in geometry, which might be why this is hard to me.
Edit (clarifications):

*

*$D$ and $C$ may be assumed to lie on the same side of $l$ (I guess this can even be assumed w.l.o.g., as we could otherwise just mirror the point $D$).

*$H$ is the intersection point that is further away from $G$ than $C$.

*$D$ can be assumed to be exterior $K$.

*$l$ can be assumed to intersect $K$ at two different points and to not pass through $C$.

*I preferably look for geometric solutions or algebraic solutions in closed form.

A: *

*Reflect $D$ in the line $l$, denote the image $D^*$.

*Draw the line $DD^*$.

*Pick an arbitrary, but convenient, point $E$ on the line $l$ and draw the circle with center $E$ and radius $ED = ED^*$. It is very helpful if this circle $K(E, ED)$ intersects the the original one $K$ at two points.

*Draw the radical axis of the two circles $K(E, ED)$ and $K$. If the two circle intersect, then the radical axis is the line that passes through both intersection points of the two circles.

*Denote by $F$ the intersection point between the radical axis and the line $DD^*$

*Construct the line through point $F$ and tangent to the circle $K$. There are two of them, so you have two solutions.

*Denote by $T$ the point of tangency between the line from point 5 and the circle $K$.

*The circumcircle of triangle $\Delta \, TDD^*$ is the circle you are looking for (there are two solutions).

A: Sketch for an algebraic solution.
Translate, rotate and scale your picture so that the circle is the unit circle, the line $\ell$ is horizontal at known height $y=h$. Then $D$ will have known coordinates $(c,d)$. The distance from $D$ to $\ell$ is $d-h$. Suppose $G=(x,h)$. Then the line from $G$ through the center of the circle has meets the circle at the two points $\theta$ for which $b/a = \tan(\theta)$. Moreover, $G = ((\tan \theta)/h, h)$.
Equate the squares of the two distances you care about:
$$
(c- ((\tan \theta) / h)^2 + (d- h)^2= (a-\cos \theta)^2 + ( b - \sin \theta)^2
$$
That's sufficient information to solve for the angle $\theta$. You may encounter algebraic problems that will reflect the fact that the ambiguities in the picture suggest cases with no solutions and multiple solutions.


text:
Q: C++ exception to the general rule against using, inside namespaces, in headers Other questions address the general question of putting using namespace statements inside namespace blocks in headers, and speak against it.
Does this equally hold for using namespace std; or using namespace std::placeholders;?


text:
Q: Is there a way to fail a Cypress test on CONREFUSED? I'm using the new Cypress component test option for my frontend tests, and I absolutely love it. I'm using it as an integration test solution, mounting the root component of my react app and using Cypress to test extensive user interactivity with it. In nearly every way, it's working perfectly, despite its beta status.
For API calls, I'm using the Cypress intercept() feature. Before each test I use intercept to define the mocked API responses I need for the test. It works great.
What I've noticed, however, is if there is an API call that doesn't impact my test, but is still fired in the background, it'll cause a CONREFUSED error. In and of itself, this doesn't really impact my tests, it just outputs the error to the log. However, the completionist in me doesn't like this.
Ideally, I'm hoping there is an option in Cypress where if any CONREFUSED errors occur in an ajax call, it'll fail the test. This may be out of scope for what Cypress offers, and I'm not really sure how to even accomplish it. However, if there is a way, I would love to integrate it into my test suite.

A: Generally throwing an error will fail the test, try doing so in an intercept.
cy.intercept(url, (req) => {
  req.continue((res) => {
    if (res.body.statusCode === 502) {
      throw new Error('Conncetion refused')
    }
  })
})

A: You could write a rule based on the event that is triggered on CONREFUSED as suggested here in the docs.
To find out what the exact event trigger keyword is you could run a verbose debug session as described here in the docs and then add the resulting event into the exception handling?


text:
Q: cuda filter with ouput of this block is the input of the next block Working on a filter following, I am having a problem of doing these pieces of codes for processing an image in GPU:
for(int h=0; h<height; h++) {
    for(int w=1; w<width; w++) {
    image[h][w] = (1-a)*image[h][w] + a*image[h][w-1];
    }
}

If I define:

dim3 threads_perblock(32, 32)

then each block I have: 32 threads can be communicated. The threads of this block can not communicate with the threads from other blocks.
Within a thread_block, I can translate that pieces of code using shared_memory however, for edge (I would say): image[0,31] and image[0,32] in different threadblocks. The image[0,31] should get value from image[0,32] to calculate its value. But they are in different threadblocks.
so that is the problem.
How would I solve this?
Thanks in advance.

A: If image is in global memory then there is no problem - you don't need to use shared memory and you can just access pixels directly from image without any problem.
However if you have already done some processing prior to this, and a block of image is already in shared memory, then you have a problem, since you need to do neighbourhood operations which are outside the range of your block. You can do one of the following - either:

*

*write shared memory back to global memory so that it is accessible to neighbouring blocks (disadvantage: performance, synchronization between blocks can be tricky)

or:

*

*process additional edge pixels per block with an overlap (1 pixel in this case) so that you have additional pixels in each block to handle the edge cases, e.g. work with a 34x34 block size but store only the 32x32 central output pixels (disadvantage: requires additional logic within kernel, branches may result in warp divergence, not all threads in block are fully used)

Unfortunately neighbourhood operations can be really tricky in CUDA and there is always a down-side whatever method you use to handle edge cases.

A: You can just use a busy spin (no joke). Just make the thread processing a[32] execute:
while(!variable);

before starting to compute and the thread processing a[31] do
variable = 1;

when it finishes. It's up to you to generalize this. I know this is considered "rogue programming" in CUDA, but it seems the only way to achieve what you want. I had a very similar problem and it worked for me. Your performance might suffer though...
Be careful however, that
dim3 threads_perblock(32, 32)

means you have 32 x 32 = 1024 threads per block.


text: Q: Is there a way to change my webcam's output buffer I was curious since opencv has a way to grab frames from your webcam, is there a way to edit the frame and insert it back into the webcam's buffer? I would want to do image editing in real time to edit out a static background. I would want to be able to create a dummy device that discord or zoom would be able to select to show the output buffer to.


text:
Q: Clear cache of index page in drupal I have tried the code below to clear the cache of the index page to show the latest content to the user.
<filesMatch "index.html">
  FileETag None
  <ifModule mod_headers.c>
     Header unset ETag
     Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
     Header set Pragma "no-cache"
     Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
  </ifModule>
</filesMatch>

But when I try this code it gives forbidden error.