text:
Q: how to tell if a mysql insert is successful I'm learning MySQL transactions. I've searched for answers to this, but they all seem to use PHP to make what I want to do work. Here's the example of what I'm trying to do:

*

*Begin the transaction

*Update Table1

*Insert into Table2

*If Insert is successful,
a. then insert into Table3 and commit.
b. else rollback the transaction.

I don't understand how to determine programmatically whether the insert at step 3 was successful. Sure, I can query the table and see, but I thought there was some way to use the return value, but it seems that only works when I'm using PHP to do the transaction.
This is the code block for what I'm trying - it doesn't work:
begin;
start transaction;
-- attempt to reduce inventory
update store_inventory set item_qty = item_qty - 2 where id = 1;
update store_inventory set item_qty = item_qty -1 where id = 5;

-- insert the order record and check whether it succeded
insert into store_orders (purchaser_name, purchase_date)
values ('test user', now());
    -- if successful, do final insert and commit
if Row_Count() > 0 Then
insert into store_inventory (order_id, inventory_id, item_qty)
values (1, 1, 2),
        (1, 2, 1);
commit;
else    -- otherwise rollback
rollback;
end if;

end;

A: The answer is a mix of Itay Moav-Malimovka and Gordon's answer.
Everything between start transaction and commit is one atomic action. Just write it like this:
start transaction;
-- attempt to reduce inventory
update store_inventory set item_qty = item_qty - 2 where id = 1;
update store_inventory set item_qty = item_qty -1 where id = 5;

-- insert the order record
insert into store_orders (purchaser_name, purchase_date)
values ('test user', now());
insert into store_inventory (order_id, inventory_id, item_qty)
values (1, 1, 2),
        (1, 2, 1);
commit;

Or let me explain it on an easier example what's going on.
create table foo(id int primary key);
insert into foo values (1);

Now, if you have code like this:
start transaction;
insert into foo values(2);
insert into foo values(1);
insert into foo values(3);
commit;

An error is raised when the value 1 gets inserted because it violates the primary key, an entry with 1 already exists and the code that follows will never be executed. If you do a select * from foo; now, you will see, that there's a value of 2 in your table. But that's probably just you who sees the 2 in there, that depends on the isolation level (you might want to read about those). This is because the transaction is still pending. Now it's up to you, if you don't care and continue with inserting value 3 and commit or you rollback. BUT this is done on application level. Simply check for an error, if one was raised rollback, if not, everything's fine. There's no need to check inside the transaction, because if anything goes wrong / the insert fails, the code for checking if anything failed will never be reached.

A: You're probably going to need stored procedures, but I may be wrong on that being a requirement. You'll need to setup transactions yourself and do some testing.
DELIMITER $$
CREATE PROCEDURE `sample`(name VARCHAR(100))
BEGIN
    START TRANSACTION; -- Begin a transaction
    INSERT INTO `users` (`name`) VALUES name;
    IF ROW_COUNT() > 0 THEN -- ROW_COUNT() returns the number of rows updated/inserted/deleted
        COMMIT; -- Finalize the transaction
    ELSE
        ROLLBACK; -- Revert all changes made before the transaction began
    END IF
END$$
DELIMITER ;

Something like this may work (this is untested, purely pieced together from research) and you will have to use InnoDB as the storage engine because MyISAM does not support transactions.

A: IF all queries are inside the same transaction, then it is considered one atomic action. Either ALL succeed or ALL fail.
No need to both check AND use transactions.

A: if you are using java and JPA you can use the annotation
@TransactionManagement(TransactionManagementType.CONTAINER) in the bean you are using to do inserts. this will ensure that if a transaction fails the container will undo all changes. you can google EJB 3.0 to read more about transaction management


text:
Q: HAL virtual device: how to "proxy" microphone I`m trying to create "virtual microphone", that should work "in front" of default input device/microphone. So when user select "virtual microphone" as input (in Audacity, for example) and starts to record sound - Audacity will receive samples from virtual device driver, that was taken by driver from real/default microphone. So "virtual microphone" is a kind of proxy device for real (default/built-in/etc) one. This is needed for later processing of microphone input on-the-fly.
So far i created virtual HAL device (based on NullAudio.c driver example from Apple), i can generate procedural sound for Audacity, but i still can not figure out the way to read data from real microphone (using its deviceID) from inside driver.
Is it ok to use normal recording as in usual app (via AudioUnits/AURemoteIO/AUHAL), etc? Or something like IOServices should be used?
Documentation states that

An AudioServerPlugIn operates in a limited environment. First and
  foremost, an AudioServerPlugIn  may not make any calls to the client
  HAL API in the CoreAudio.framework. This will result in  undefined
  (but generally bad) behavior.

but it is not clear what API is "client" API and what is not, in regard of reading microphone data.
What kind of API can/should be used from virtual device driver for accessing real microphone data in realtime?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there an expression to downcast and simultaneously access a property in F#? In C#, in order to access a property/method I might downcast to a type and then access the property:
Fruit f = new Banana();
((Banana)f).Peel();

What is the equivalent in F#? I tried the following but the intellisense after typing the period does not give any members of the Banana type so I'm guessing this isn't valid.
let f = new Banana()
(f :?> Banana).Peel()

I know I can do it by introducing an intermediate let statement but was wondering if there was a one liner.
UPDATE
Ok I was trying to give a general example but I guess something got lost in my translation.  I'm working with Excel interop.  In any case here is the more specific code.
(worksheet.Cells.[rowNumber, dateColumn] :?> Excel.Range).<member here>
But it looks like it was just a temporary glitch in intellisense because today (after rebooting my computer) it seems to work fine.  Yesterday it was just showing me basic object members of  Equals, GetHashCode, GetType, and ToString.  Now today this same expression is giving me all the members of the Excel.Range class. So I it looks like everything works as expected.

A: Your initial guess is correct, this code works:
type Fruit() =
    member me.Test() = printfn "Test"

type Banana() =
    inherit Fruit()
    member me.Peel() = printfn "Peeling !"

let f = new Banana() :> Fruit
(f :?> Banana).Peel()

You are not showing how did you define those types, probably you have something wrong there.
Also keep in mind that in F# you have to be explicit to upcast. In your example your f object is already a Banana, nothing in your code upcast it to a Fruit.


text:
Q: emu8086 doesn't work (NI DataSocket 19.0) when I open emu8086 after installing it, this message about NI DataSocket 19.0 appears and emu8086 refuses to open. Anyone knows why this appears?

A: So the thing is that emu8086 tries to find a file called DataSocket.msi. What you need to do is to go to your file Explorer, type in the Search bar DataSocket.msi and then, when the computer finds the file for you, click right on the file. Choose properties and then copy the location of the file and go back to message shown to you in emu8086. Paste the location address of DataSocket.msi in "Use source", then press Ok. This should solve the problem.
enter image description here


text:
Q: laravel pusher - send event on production not working this is the first time Im using pusher (pusher.com),all fine on local but on production sending notification not working, if I sent from local it works and send notification to production but send from live it is not working!!!
broadcasting:
       'pusher' => [
        'driver' => 'pusher',
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'app_id' => env('PUSHER_APP_ID'),
        'options' => [
        'cluster'=> env('CLUSTER'),
        'encrypted' => true,

        ],
    ],

sending function:
 public function OrderEvent()
{

$order_number='150';

    event(new OrderSubmitted($order_number));
   return "We just sent!";
}

error in production:
 production.INFO: Broadcasting [App\Events\OrderSubmitted] on channels [order-submitted] with payload:
 {
 "order_number": "15-EA",
 "socket": null
 }

A: It was because my broadcast_driver was set to log in the .env file.
Change the broadcast driver in your .env from log to pusher
BROADCAST_DRIVER=pusher
And then, run this command on your production server.
php artisan config:clear

A: This usually happends if you haven't verified your email at pusher.
If you arleady have done that, make sure you got this in your config file. (broadcasitng.php)
      'options' => [
            'cluster' => 'ap2',
            'encrypted' => true
        ],

If none of above works, it's most likely your hostname that's misconfigured.
Remember to exclude http/https from the host. It's not https://example.com, it's example.com
'pusher' => [
    'driver' => 'pusher',
    'key' => env('PUSHER_APP_KEY'),
    'secret' => env('PUSHER_APP_SECRET'),
    'app_id' => env('PUSHER_APP_ID'),
    'options' => [
        'cluster' => env('PUSHER_APP_CLUSTER'),
        'encrypted' => true,
        'host' => env('PUSHER_HOST'),
        'port' => 6001,
        'scheme' => env('PUSHER_SCHEME')
    ],
],

and the .env file with:
PUSHER_HOST=example.com


text:
Q: Using textstream object to replace tab with spaces and delete characters I have over a thousand .s2p files (a delimited text file used by electrical testing equipment) that were edited by a VBA macro, which opened each raw file in Excel as a tab-and-space delimited text file, and replaced a few of the columns with data columns from another file, then saved them in original format (.s2p) and closed them. This is the call I used to open the each file:
    Call Application.Workbooks.OpenText(Filename:=(path & filename & ".s2p"), Origin:="437", DataType:=xlDelimited, ConsecutiveDelimiter:=True, Tab:=True, Space:=True, TextQualifier:=xlTextQualifierNone)

Now, when I open the .s2p files in Notepad to view them, the original single space separating the columns is now a full tab, and some double quote (") characters were added to some of the file header lines (despite setting TextQualifier parameter to xlTextQualifierNone...)
Because of this I want to write another macro that can open all of these .s2p files again, loop through the lines, and replace any double quotes with blanks, and any tabs with single spaces. I was planning to use .OpenAsTextStream on each file, but it seems like the TextStream object doesn't support overwriting lines, but can only write new lines...
Is there a better way to achieve what I am trying to do than just reading lines from the original file, and writing them to a newly created file? It is imperative that I save the final file as ".s2p" and not ".txt".

A: You don't need the text streams, just the basic input output actions available in VBA.
Option Explicit

Sub test()
    FixFile "c:\temp\mytestfile.s2p"
End Sub

Sub FixFile(filename As String)
    Dim fnum As Integer
    Dim fileText As String
    Dim finalText As String

    fnum = FreeFile
    On Error Resume Next
    Open filename For Input As #fnum
    If Err.Number <> 0 Then
        Debug.Print "Critical error attempting to open " & filename & _
                    ". Error #" & Err.Number & ": " & Err.Description
        Exit Sub
    End If

    finalText = ""
    Do Until EOF(fnum)
        Line Input #fnum, fileText
        fileText = Replace(fileText, """", " ", , , vbTextCompare)
        fileText = Replace(fileText, vbTab, " ", , , vbTextCompare)
        finalText = finalText & fileText & vbCrLf
    Loop
    Close fnum

    fnum = FreeFile
    Open filename For Output As #fnum
    Print #fnum, finalText
    Close fnum

End Sub

Edited to show line by line read with a final write.


text:
Q: Книги по системной аналитике и проектированию ПО Посоветуйте хорошие книги по системной аналитике и проектированию ПО. Не хочется сухой теории - хочется, чтобы с примерами и понятным языком для нового человека в данной области. Желательно на русском языке или с переводом.
Хорошей ли для данной области будет книга Стива Макконнелла "Совершенный код"?


text:
Q: Stream / play Movies (Lot's of GB) in flutter offline? I want to make an offline app which will be installed on android smart tv, there the idea is to stream movies offline (the movies will require lots of storage).
Can anyone provide an approach or a solution to this?
I could store the movies on assets but it will be really big, one solution I was thinking was with external HDD, is there a way maybe to get / read the video from external HDD and stream it offline inside the installed app on tv?
Any other approaches will be acceptable.
Thank you!


text:
Q: Why observable is always false in AuthGuard? @Injectable()

export class AuthGuard implements CanActivate {

    constructor(private authService: AuthService,private router: Router){}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
        const isAuth = this.authService.checkAuth()
        if (!isAuth){
            this.router.navigate(['/login'])
        }
        return isAuth;
    }
}

I dont understand where i`m wrong but isAuth is always false if i console.log it.
Edit
  checkAuth(){
return this.loggedIn.asObservable();

}
loginUser(email: string, password:string){
    const user: User = {email: email, password: password}
    this.http.post<{token: string}>('http://localhost:3000/api/auth/login', user).subscribe( result => {
    const token = result.token;
    this.token = token
    this.loggedIn.next(true)
    this.router.navigateByUrl('/admin')
    })
  }

This is working fine but, it not seems a good practice.. and i was tryn to write better code lines.
    @Injectable()
export class AuthGuard implements CanActivate {
auth: Subscription;
isAuth: boolean;
    constructor(private authService: AuthService,private router: Router){}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
        this.auth = this.authService.checkAuth().subscribe(result=>{
            this.isAuth = result
        })
        if (!this.isAuth){
            this.router.navigate(['/login'])
        }
        return this.isAuth;
    }
}

A: @Kardon63 You're right but I think the method to call is getValue() instead of value.
Therefore you have to change your checkAuth method and write :
checkAuth(){
  return this.loggedIn.getValue();
}

Check this post : https://stackoverflow.com/a/37089997/6444705


text:
Q: QTreeWidget insert between two items using drag and drop I have a QTreeWidget which I have setup like so...
ModelTreeWidget::ModelTreeWidget(QWidget *parent):QTreeWidget(parent), mpModelStruct(nullptr), mpModeldragging(nullptr), mpBufferModel(nullptr), mpModelCurrent(nullptr)
{

    setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::EditKeyPressed);
    setColumnCount(1);
    setSelectionMode(QAbstractItemView::SingleSelection);

    setDragEnabled(true);
    viewport()->setAcceptDrops(true);
    setDropIndicatorShown(true);
    setDragDropMode(QAbstractItemView::DragDrop);
    setDefaultDropAction(Qt::MoveAction);

}

I've also overwritten my drop event, but it's fairly innocuous:
void ModelTreeWidget::dropEvent(QDropEvent* event)
{
    QTreeWidget::dropEvent(event);
}

Supported action is MoveAction:
Qt::DropActions ModelTreeWidget::supportedDropActions() const
{
    return Qt::MoveAction;
}

Each item has the flags:
Qt::ItemFlags ModelTreeWidget::getTreeItemFlags() const
{
    return (Qt::ItemIsDragEnabled | Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
}

Now when I populate my tree widget with items, I can drag one item over another, and it becomes added as a child to the item I dragged onto. However when I try to drag an item between two other items, I don't get an indicator (which I think should be a line) between the two rows. I just get the not allowed indicator.
My question is, how do I enable insertion of an item between two other items using drag and drop for QTreeWidget?
Edit:
I setup my tree root using the following code:
        QTreeWidgetItem* rootId = new QTreeWidgetItem((QTreeWidget*)0, QStringList(currentModel->name));
        QVariant v = qVariantFromValue((void *) currentModel);
        rootId->setData(0, Qt::UserRole, v);
        rootId->setFlags(Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
        insertTopLevelItem(0, rootId);

While each child of my root is setup as the following:
            QTreeWidgetItem *item = new QTreeWidgetItem(parent, QStringList(tempModel->name));
            QVariant v = qVariantFromValue((void *) tempModel);
            item->setData(0, Qt::UserRole, v);
            item->setFlags(getTreeItemFlags());
            parent->addChild(item);

A: It seems that there are two problems here. One is that my supportedDropActions() only supported MoveAction, which seems to interfere with the drag n drop insert function, which add and delete data around. The symptoms of this were that each time I inserted data between two entries in a basic test QTreeWidget class, it would also erase the element before the object I was dragging. By adding Qt::CopyAction so that my supportedDropActions() looks like
Qt::DropActions ModelTreeWidget::supportedDropActions() const
{
    return (Qt::MoveAction | Qt::CopyAction);
}

Fixed the prob of drag and drop insertions between entries deleting an entry each time it moved.
However, this didn't fix my actual problem asked in this post.
What fixed my actual problem was not manually setting my tree root's flags.
        QTreeWidgetItem* rootId = new QTreeWidgetItem((QTreeWidget*)0, QStringList(currentModel->name));
        QVariant v = qVariantFromValue((void *) currentModel);
        rootId->setData(0, Qt::UserRole, v);
//Commented this out        rootId->setFlags(Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
        insertTopLevelItem(0, rootId);

Doing so solved my problem. I'm still not completely sure why that would interfere with the insertion operation but it did.


text:
Q: Can principal component analysis be applied to datasets containing a mix of continuous and categorical variables? I have a dataset that has both continuous and categorical data. I am analyzing by using PCA and am wondering if it is fine to include the categorical variables as a part of the analysis. My understanding is that PCA can only be applied to continuous variables. Is that correct? If it cannot be used for categorical data, what alternatives exist for their analysis?

A: Continuing on what @Martin F commented, recently I came across with the nonlinear PCAs. I was looking into Nonlinear PCAs as a possible alternative when a continuous variable approaches distribution of an ordinal variable as the data gets sparser (it happens in genetics a lot of times when the minor allele frequency of the variable gets lower and lower and you are left with very low number of counts in which you cant really justify a distribution of a continuous variable and you have to loosen the distributional assumptions by making it either an ordinal variable or a categorical variable.) Non linear PCA can handle both of these conditions but after discussing with statistical maestros in genetics faculty, the consensus call was that the Nonlinear PCAs are not used much often and the behavior of those PCAs is not yet tested extensively (maybe they were referring only to genetics, so please take it with grain of salt). Indeed it is a fascinating option.
I hope I have added 2 cents (fortunately relevant) to discussion.

A: PCAmixdata #Rstats package:

Implements principal component analysis, orthogonal rotation and multiple factor analysis for a mixture of quantitative and qualitative variables.

Example from vignette shows results for both continuous and categorical output

A: A Google search "pca for discrete variables" gives this nice overview by S. Kolenikov (@StasK) and G. Angeles. To add to chl answer, the PC analysis is really analysis of eigenvectors of covariance matrix. So the problem is how to calculate the "correct" covariance matrix. One of the approaches is to use
polychoric correlation.

A: There is a recently developed approach to such problems: Generalized Low Rank Models.
One of papers that use this technique is even called PCA on a Data Frame.

PCA can be posed like this:
For $n$ x $m$ matrix $M$
find $n$ x $k$  matrix $\hat{X}$ and $k$ x $m$ matrix $\hat{Y}$ (this encodes rank $k$ e constraint implicitly) such that
$\hat{X}, \hat{Y}$ = $\underset{X, Y}{argmin} \| M - XY \|_F^2$.
The 'generalized' from GLRM stands for changing $\| \cdot \|_F^2$ to something else and adding a regularization term.

A: I would suggest having a look at Linting & Kooij, 2012 "Non linear principal component analysis with CATPCA: a tutorial", Journal of Personality Assessment; 94(1).

Abstract
This article is set up as a tutorial for nonlinear principal components analysis (NLPCA), systematically guiding the reader through the process of analyzing actual data on personality assessment by the Rorschach Inkblot Test. NLPCA is a more flexible alternative to linear PCA that can handle the analysis of possibly nonlinearly related variables with different types of measurement level. The method is particularly suited to analyze nominal (qualitative) and ordinal (e.g., Likert-type) data, possibly combined with numeric data. The program CATPCA from the Categories module in SPSS is used in the analyses, but the method description can easily be generalized to other software packages.

A: Although a PCA applied on binary data would yield results comparable to those obtained from a Multiple Correspondence Analysis (factor scores and eigenvalues are linearly related), there are more appropriate techniques to deal with mixed data types, namely Multiple Factor Analysis for mixed data available in the FactoMineR R package (FAMD()). If your variables can be considered as structured subsets of descriptive attributes, then Multiple Factor Analysis (MFA()) is also an option.
The challenge with categorical variables is to find a suitable way to represent distances between variable categories and individuals in the factorial space. To overcome this problem, you can look for a non-linear transformation of each variable--whether it be nominal, ordinal, polynomial, or numerical--with optimal scaling. This is well explained in Gifi Methods for Optimal Scaling in R: The Package homals, and an implementation is available in the corresponding R package homals.


text:
Q: Why does Farm Simulator crash with GPU "3D-Engine" operating at full capacity? My Question sounds odd at first, but I then tried running a DIFFERENT game (Asphalt 9) on a DIFFERENT PC (Intel NUC) and the "3D" graph at the GPU section in TaskManager spikes at 100% as well, but the game does not crash.
My suspicion is, that if the "3D" section is at 100% usage, you still can't predict wheter a game is going to crash or not. Does it depend on "the GHz of the shader cores" or something like that?
GPU Model of "bad PC": GTX750 (or GT750, does that exist at all?)
Integrated CPU of "good PC": i5-8259U (I thought this was worse, because it's integrated, but seems to be a newer model...)


text:
Q: Compare items in an existing list based on property in HQL Let say I have two class:

public class A{
 public virtual int Id;
 ...
 ...

}
public class B{
   public virtual int Id;

   public virtual A a;
 ...

}

I have a list of A. List existingObjectAList;
and also I want to search object B's which contains existingObjectAList.
How can I do this In C# with HQL.

A: var bs = session.CreateQuery("from B where A in (:list)"
                .SetParameterList("list", existingObjectAList)
                .List<B>();


text:
Q: doc URL cannot be read: Unable to read entire header; 6 bytes read; expected 32 bytes I am trying to read a Word document from a web URL using POI version 3.6. Non-working code:
String url = "http://prevention.cancer.gov/sites/default/files/uploads/clinical_trial/Master-DMP-Template.doc";
InputStream inputStream = new URL(urlString).openStream();
HWPFDocument doc = new HWPFDocument(inputStream);
WordExtractor extractor = new WordExtractor(doc);
String text = extractor.getText();

Above code results in java.io.IOException: Unable to read entire header; 6 bytes read; expected 32 bytes
Attempt 2: the interesting part is that downloading the file (just pasting the URL in the browser address bar), and then executing similar code for reading the doc locally does work:
InputStream inputStream = new FileInputStream("C:\\Users\\me\\Downloads\\Master-DMP-Template (2).doc");
HWPFDocument doc = new HWPFDocument(inputStream);
WordExtractor extractor = new WordExtractor(doc);
System.out.println(extractor.getText());

Attempt 3: and now the strangest part. I thought that the file needs to be downloaded first. So I downloaded it first using Java, and then executed the previous code for reading the doc locally. Fails like the first case!
final String url = "http://prevention.cancer.gov/sites/default/files/uploads/clinical_trial/Master-DMP-Template.doc";
String localPath  = FileUtils.downloadFile("C:\\Users\\me\\Downloads", url);
InputStream inputStream = new FileInputStream(localPath);
HWPFDocument doc = new HWPFDocument(inputStream);
WordExtractor extractor = new WordExtractor(doc);
System.out.println(extractor.getText());

public static String downloadFile(String targetDir, String sourceUrl) throws IOException {
    sourceUrl = StringUtils.removeEnd(sourceUrl, "/");
    String fileName = sourceUrl.substring(sourceUrl.lastIndexOf("/") + 1);
    String targetPath = targetDir + FileUtils.SEPARATOR + fileName;
    InputStream in = new URL(sourceUrl).openStream();
    Files.copy(in, Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
    System.out.println("Downloaded " + sourceUrl + " to " + targetPath);
    return targetPath;
}

Any idea what is going on here?
An update: I created a separate project for trying with POI 4.1.0. Same code (of first attempt) results in org.apache.poi.EmptyFileException: The supplied file was empty (zero bytes long)
I tried pasting the URL in the browser after hitting F12 and observing the Network tab. The message that appears there is:
Resource interpreted as Document but transferred with MIME type application/msword: "https://prevention.cancer.gov/sites/default/files/uploads/clinical_trial/Master-DMP-Template.doc".
I am still stuck...
An update: as https://stackoverflow.com/users/3915431/axel-richter pointed out, there is a 301 redirecto to https://prevention.cancer.gov/sites/default/files/uploads/clinical_trial/Master-DMP-Template.doc . However, now I am running into strange problems that are not related to Word. Followig code fails:
public static void main(String[] args) {
    try {
        if (args.length > 0 && args[0].equals("disableCertValidation")) {
            SSLUtil.disableCertificateValidation(); // redirect is https
        }
        final String stringURL = "https://prevention.cancer.gov/sites/default/files/uploads/clinical_trial/Master-DMP-Template.doc";
        URL url = new URL(stringURL);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        int responseCode = con.getResponseCode();
        System.out.println("Response code: " + responseCode); //301 Moved Permanently
        InputStream in = con.getInputStream();
        HWPFDocument doc = new HWPFDocument(in);
        WordExtractor extractor = new WordExtractor(doc);
        String text = extractor.getText();
        System.out.println(text);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

When running main without an argument, the line
int responseCode = con.getResponseCode();

fails with following exception:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
When running the code with the disableCertificateValidation argument, the response code is 404 and I am getting following exception:
java.io.FileNotFoundException: https://prevention.cancer.gov/sites/default/files/uploads/clinical_trial/Master-DMP-Template.doc
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
        at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1890)
        at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1885)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1884)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1457)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
        at com.keywords.control.util.TestHTMLParser.main(TestHTMLParser.java:472)
Caused by: java.io.FileNotFoundException: https://prevention.cancer.gov/sites/default/files/uploads/clinical_trial/Master-DMP-Template.doc
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1836)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
        at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
        at com.keywords.control.util.TestHTMLParser.main(TestHTMLParser.java:470)
Any ideas?

A: The initial HTTP request to your URL leads to a redirect 301 Moved Permanently. So we need handling this and reading the new location.
Complete example:
import java.io.InputStream;
import java.net.URL;
import java.net.HttpURLConnection;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class OpenHWPFFromURL {

 public static void main(String[] args) throws Exception {

  String stringURL = "http://prevention.cancer.gov/sites/default/files/uploads/clinical_trial/Master-DMP-Template.doc";

  URL url = new URL(stringURL);
  HttpURLConnection con = (HttpURLConnection)url.openConnection();

  int responseCode = con.getResponseCode();
  System.out.println(responseCode); //301 Moved Permanently

  if (responseCode != HttpURLConnection.HTTP_OK) {
   if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP
       || responseCode == HttpURLConnection.HTTP_MOVED_PERM
       || responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
    url = new URL(con.getHeaderField("Location")); //get new location
    con = (HttpURLConnection)url.openConnection();
   }
  }

  InputStream in = con.getInputStream();
  HWPFDocument doc = new HWPFDocument(in);
  WordExtractor extractor = new WordExtractor(doc);
  String text = extractor.getText();

  System.out.println(text);

 }
}

Note: Simply setting HttpURLConnection.setFollowRedirects to true (what is the default as well) will not help if the redirect also changes the protocol (from HTTP to HTTPS for example). Exactly this is the case here too. So we need getting the new location manually as shown in my code.

A: This code new URL(urlString).openStream() return InputStream look here instead FileInputStream like this:
InputStream inputStream = new FileInputStream("C:\\Users\\me\\Downloads\\Master...")
Maybe problem in this difference?


text:
Q: How to wait for 2 actions and join their results in redux-saga in my application I'd like to define a saga that will handle either LEFT_CHANGED or RIGHT_CHANGED actions and continue with new action SOURCES_CHANGED with payload consisting of payloads of the aforementioned actions.
export function* watchLeftRightChanged() {
  const left = null;
  const right = null;
  while (true) {
    const result = yield take(['LEFT_CHANGED', 'RIGHT_CHANGED'])
    switch (result.type) {
      case 'LEFT_CHANGED':
        yield put({ type: 'SOURCES_CHANGED', result, right })
        continue;
      case 'RIGHT_CHANGED':
        yield put({ type: 'SOURCES_CHANGED', left, result })
        continue
    }
  }
}

The problem is that left and right variables are null when SOURCES_CHANGED action is emitted and their value is not maintained (I believe dut to the nature of the iterator).
Can anybody help? Thanks


text:
Q: Can webdriverio tests be executed on Unix How can we execute webdriverio Tests on Unix platform. Would the below command work ?
npx wdio run ./wdio.conf.js

A: WebdriverIO is basically a package that resides in NPM here. That means you need to follow system requirements for this package, which means installing a certain version of Node.js. And that could run on multiple OS.


text:
Q: Reading Hibernate configurations dynamically I need to fetch hibernate connection url, username and password configurations from another service AMS (just like amazon KMS).
I have written another method to fetch those values from AMS. BUT how to set/use these values hibernate to connect my database.
eg. hibernate.cfg.xml
<property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>

Util.java
getAMSValue(propertyName){
...
}

how can I achieve this?

A: Why don't you specify complete configuration in a java file instead of XML?
See this documentation

A org.hibernate.cfg.Configuration also allows you to specify
  configuration properties.
... ...
This is not the only way to pass configuration properties to
  Hibernate. Some alternative options include:

*

*Pass an instance of java.util.Properties to Configuration.setProperties().

*Place a file named hibernate.properties in a root directory of the classpath.

*Set System properties using java -Dproperty=value.

*Include  elements in hibernate.cfg.xml (this is discussed later).

In your case, you can configure somewhat like this in your java file
Configuration configuration = new Configuration().configure();

...
...
configuration.setProperty("hibernate.connection.url", getAMSValue("url"));
configuration.setProperty("hibernate.connection.username", getAMSValue("username"));
configuration.setProperty("hibernate.connection.password", getAMSValue("password"));


text:
Q: How Can I print Python output at runtime in PHP I want to display the output of the python script at runtime on the web browser through php. Can someone help upon this..??
I'm calling a simple python script through php here is the code:
run.py:
  import os
    import subprocess
    import sys
    import time
    print "
 Hi from Python"
    sys.stdout.flush()
    for i in range(0,5):
        time.sleep(1)
        print "
 Hi from Python"
        sys.stdout.flush()

this is the php script:
<?php
$handle = popen("python run.py ", 'r');
while(!feof($handle)) {
$buffer = fgets($handle);
echo "$buffer
\n";
ob_flush();
}
pclose($handle);
?>

Can someone help upon this..??

A: use exec instead
$res = NULL;

exec("python full/path/to/script.py 2>&1" ,$res); //2>&1 @comments.KEK

if(isset($res)){
    foreach($res as $rowRes){
        echo $rowRes;
    }
}


text:
Q: Why lambda expression threw this error? When a started my jetty server, it throws this error:

[INFO] Scanning for projects... [WARNING]  [WARNING] Some problems
  were encountered while building the effective model for
  br.com.governa.ponto:governa-ponto-web:war:1.0-SNAPSHOT [WARNING]
  'dependencies.dependency.(groupId:artifactId:type:classifier)' must be
  unique: br.com.governa.admin:governa-admin-persistencia:jar ->
  duplicate declaration of version (?) @ line 32, column 15 [WARNING]
  'dependencies.dependency.(groupId:artifactId:type:classifier)' must be
  unique: org.springframework:spring-web:jar -> duplicate declaration of
  version (?) @ line 147, column 15 [WARNING]  [WARNING] It is highly
  recommended to fix these problems because they threaten the stability
  of your build. [WARNING]  [WARNING] For this reason, future Maven
  versions might no longer support building such malformed projects.
  [WARNING]  [INFO]  [INFO] Using the builder
  org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder
  with a thread count of 1 [INFO]
  [INFO]
  ------------------------------------------------------------------------ [INFO] Building governa-ponto-web Maven Webapp 1.0-SNAPSHOT [INFO]
  ------------------------------------------------------------------------ [INFO]  [INFO] >>> jetty-maven-plugin:9.0.5.v20130815:start
  (default-cli) @ governa-ponto-web >>> [INFO]  [INFO] <<<
  jetty-maven-plugin:9.0.5.v20130815:start (default-cli) @
  governa-ponto-web <<< [INFO]  [INFO] ---
  jetty-maven-plugin:9.0.5.v20130815:start (default-cli) @
  governa-ponto-web --- [INFO] Configuring Jetty for project:
  governa-ponto-web Maven Webapp [INFO] webAppSourceDirectory not set.
  Defaulting to
  /home/vinicius/projetos/GerenciadorPonto/Fontes/trunk/governa-ponto-all/governa-ponto-web/src/main/webapp
  [INFO] Reload Mechanic: automatic [INFO] Classes =
  /home/vinicius/projetos/GerenciadorPonto/Fontes/trunk/governa-ponto-all/governa-ponto-web/target/classes
  [INFO] Configuring Jetty from xml configuration file =
  /home/vinicius/projetos/GerenciadorPonto/Fontes/trunk/governa-ponto-all/governa-ponto-web/src/test/resources/jetty.xml
  [INFO] Configuring Jetty from xml configuration file =
  /home/vinicius/projetos/GerenciadorPonto/Fontes/trunk/governa-ponto-all/governa-ponto-web/src/test/resources/jetty-ssl.xml
  [INFO] Configuring Jetty from xml configuration file =
  /home/vinicius/projetos/GerenciadorPonto/Fontes/trunk/governa-ponto-all/governa-ponto-web/src/test/resources/jetty-https.xml
  [INFO] Context path = /governa-ponto-web [INFO] Tmp directory =
  /home/vinicius/projetos/GerenciadorPonto/Fontes/trunk/governa-ponto-all/governa-ponto-web/target/tmp
  [INFO] Web defaults = org/eclipse/jetty/webapp/webdefault.xml [INFO]
  Web overrides =  none [INFO] web.xml file =
  file:/home/vinicius/projetos/GerenciadorPonto/Fontes/trunk/governa-ponto-all/governa-ponto-web/src/main/webapp/WEB-INF/web.xml
  [INFO] Webapp directory =
  /home/vinicius/projetos/GerenciadorPonto/Fontes/trunk/governa-ponto-all/governa-ponto-web/src/main/webapp
  [INFO] jetty-9.0.5.v20130815 log4j:WARN No appenders could be found
  for logger (com.mchange.v2.log.MLog). log4j:WARN Please initialize the
  log4j system properly. log4j:WARN See
  http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
  [INFO] No Transaction manager found - if your webapp requires one,
  please configure one. [WARNING] EXCEPTION
  java.lang.ArrayIndexOutOfBoundsException: 22502   at
  org.objectweb.asm.ClassReader.(Unknown Source)  at
  org.objectweb.asm.ClassReader.(Unknown Source)  at
  org.objectweb.asm.ClassReader.(Unknown Source)  at
  org.eclipse.jetty.annotations.AnnotationParser.scanClass(AnnotationParser.java:986)
    at
  org.eclipse.jetty.annotations.AnnotationParser.parseDir(AnnotationParser.java:781)
    at
  org.eclipse.jetty.annotations.AnnotationParser.parseDir(AnnotationParser.java:769)
    at
  org.eclipse.jetty.annotations.AnnotationParser.parseDir(AnnotationParser.java:769)
    at
  org.eclipse.jetty.annotations.AnnotationParser.parseDir(AnnotationParser.java:769)
    at
  org.eclipse.jetty.annotations.AnnotationParser.parseDir(AnnotationParser.java:769)
    at
  org.eclipse.jetty.annotations.AnnotationParser.parseDir(AnnotationParser.java:769)
    at
  org.eclipse.jetty.annotations.AnnotationParser.parseDir(AnnotationParser.java:769)
    at
  org.eclipse.jetty.maven.plugin.MavenAnnotationConfiguration.doParse(MavenAnnotationConfiguration.java:91)
    at
  org.eclipse.jetty.maven.plugin.MavenAnnotationConfiguration.parseWebInfClasses(MavenAnnotationConfiguration.java:70)
    at
  org.eclipse.jetty.annotations.AnnotationConfiguration.configure(AnnotationConfiguration.java:122)
    at
  org.eclipse.jetty.webapp.WebAppContext.configure(WebAppContext.java:464)
    at
  org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1317)
    at
  org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:731)
    at
  org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:490)
    at
  org.eclipse.jetty.maven.plugin.JettyWebAppContext.doStart(JettyWebAppContext.java:280)
    at
  org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:69)
    at
  org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:108)
    at
  org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:90)
    at
  org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:58)
    at
  org.eclipse.jetty.server.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:156)
    at
  org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:69)
    at
  org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:108)
    at
  org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:90)
    at
  org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:58)
    at
  org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:69)
    at
  org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:108)
    at org.eclipse.jetty.server.Server.start(Server.java:342)   at
  org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:90)
    at
  org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:58)
    at org.eclipse.jetty.server.Server.doStart(Server.java:290)     at
  org.eclipse.jetty.maven.plugin.JettyServer.doStart(JettyServer.java:68)
    at
  org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:69)
    at
  org.eclipse.jetty.maven.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:563)
    at
  org.eclipse.jetty.maven.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:359)
    at
  org.eclipse.jetty.maven.plugin.JettyRunMojo.execute(JettyRunMojo.java:167)
    at
  org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:133)
    at
  org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    at
  org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at
  org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at
  org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:108)
    at
  org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:76)
    at
  org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at
  org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:116)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:361)   at
  org.apache.maven.DefaultMaven.execute(DefaultMaven.java:155)  at
  org.apache.maven.cli.MavenCli.execute(MavenCli.java:584)  at
  org.apache.maven.cli.MavenCli.doMain(MavenCli.java:213)   at
  org.apache.maven.cli.MavenCli.main(MavenCli.java:157)     at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)   at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)     at
  org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at
  org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at
  org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at
  org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
  [INFO] No Spring WebApplicationInitializer types detected on classpath
  [INFO] Initializing Spring root WebApplicationContext May 08, 2015
  12:12:03 PM com.sun.faces.config.ConfigureListener contextInitialized
  INFO: Initializing Mojarra 2.2.10 ( 20150205-0906
  https://svn.java.net/svn/mojarra~svn/tags/2.2.10@14334) for context
  '/governa-ponto-web' May 08, 2015 12:12:06 PM
  com.sun.faces.spi.InjectionProviderFactory createInstance INFO:
  JSF1048: PostConstruct/PreDestroy annotations present.  ManagedBeans
  methods marked with these annotations will have said annotations
  processed. May 08, 2015 12:12:06 PM
  com.sun.faces.config.JavaClassScanningAnnotationScanner$ConstantPoolInfo
  containsAnnotation SEVERE: Unknow type constant pool 18 at position 47
  May 08, 2015 12:12:06 PM
  com.sun.faces.config.JavaClassScanningAnnotationScanner$ConstantPoolInfo
  containsAnnotation SEVERE: Unknow type constant pool 0 at position 48
  May 08, 2015 12:12:06 PM
  com.sun.faces.config.JavaClassScanningAnnotationScanner$ConstantPoolInfo
  containsAnnotation SEVERE: Unknow type constant pool 0 at position 49
  May 08, 2015 12:12:06 PM
  com.sun.faces.config.JavaClassScanningAnnotationScanner$ConstantPoolInfo
  containsAnnotation SEVERE: Unknow type constant pool 0 at position 50
  May 08, 2015 12:12:06 PM
  com.sun.faces.config.JavaClassScanningAnnotationScanner$ConstantPoolInfo
  containsAnnotation SEVERE: Unknow type constant pool -17 at position
  51 May 08, 2015 12:12:06 PM
  com.sun.faces.config.JavaClassScanningAnnotationScanner$ConstantPoolInfo
  containsAnnotation SEVERE: Unknow type constant pool 15 at position
  239 May 08, 2015 12:12:06 PM
  com.sun.faces.config.JavaClassScanningAnnotationScanner$ConstantPoolInfo
  containsAnnotation SEVERE: Unknow type constant pool 76 at position
  242 May 08, 2015 12:12:06 PM
  com.sun.faces.config.JavaClassScanningAnnotationScanner$ConstantPoolInfo
  containsAnnotation SEVERE: Unknow type constant pool 16 at position
  243 May 08, 2015 12:12:08 PM
  com.sun.faces.config.ConfigureListener$WebConfigResourceMonitor$Monitor
   INFO: Monitoring
  file:/home/vinicius/projetos/GerenciadorPonto/Fontes/trunk/governa-ponto-all/governa-ponto-web/src/main/webapp/WEB-INF/faces-config.xml
  for modifications May 08, 2015 12:12:08 PM
  org.primefaces.webapp.PostConstructApplicationEventListener
  processEvent INFO: Running on PrimeFaces 5.1 May 08, 2015 12:12:08 PM
  org.primefaces.extensions.application.PostConstructApplicationEventListener
  processEvent INFO: Running on PrimeFaces Extensions 3.0.0 [INFO] Set
  web app root system property: 'webapp.root' =
  [/home/vinicius/projetos/GerenciadorPonto/Fontes/trunk/governa-ponto-all/governa-ponto-web/src/main/webapp]
  [INFO] Initializing Spring FrameworkServlet 'rest' [INFO] Started
  o.e.j.m.p.JettyWebAppContext@1ee27d73{/governa-ponto-web,[file:/home/vinicius/projetos/GerenciadorPonto/Fontes/trunk/governa-ponto-all/governa-ponto-web/src/main/webapp/,
  jar:file:/home/vinic
  ius/.m2/repository/com/sun/faces/jsf-impl/2.2.10/jsf-impl-2.2.10.jar!/META-INF/resources/,
  jar:file:/home/vinicius/.m2/repository/org/primefaces/primefaces/5.1/primefaces-5.1.jar!/META-INF/resources/,
  jar:f
  ile:/home/vinicius/.m2/repository/org/primefaces/extensions/primefaces-extensions/3.0.0/primefaces-extensions-3.0.0.jar!/META-INF/resources/,
  jar:file:/home/vinicius/.m2/repository/org/primefaces/themes/all
  -themes/1.0.10/all-themes-1.0.10.jar!/META-INF/resources/],AVAILABLE}{/governa-ponto-web.war}
  [WARNING] !RequestLog [INFO] Started
  ServerConnector@3da7772b{SSL-http/1.1}{0.0.0.0:8443} [INFO] Started
  Jetty Server

My lambda code:
List<HorarioDetalhe> horarioDetalheLista = new ArrayList<HorarioDetalhe>();
horarioDetalheLista.addAll(Arrays.asList(
                        new HorarioDetalhe(DiaDaSemanaEnum.SEG),
                        new HorarioDetalhe(DiaDaSemanaEnum.TER),
                        new HorarioDetalhe(DiaDaSemanaEnum.QUA),
                        new HorarioDetalhe(DiaDaSemanaEnum.QUI),
                        new HorarioDetalhe(DiaDaSemanaEnum.SEX),
                        new HorarioDetalhe(DiaDaSemanaEnum.SAB),
                        new HorarioDetalhe(DiaDaSemanaEnum.DOM)));
horarioDetalheList = horarioDetalheLista.stream()
    .sorted(Comparator.comparing(HorarioDetalhe::getDiaSemana ))
    .collect(Collectors.toList());

A: The version of my Jetty was old, i have changed to 9.2.0.v20140526 and it works


text:
Q: display 3 images per row I want to display 3 images per row. but the code show first row with 2(two) images then it shows 3 images next row. where is the problem of the code?

               {foreach from=$execommittee item=v name=cat}

                 {if $smarty.foreach.cat.iteration % 3 == 0 && $smarty.foreach.cat.iteration > 0}

               {/if}

{$v.ename}

               {/foreach}

A:

               {foreach from=$execommittee item=v name=cat}

                 {if $smarty.foreach.cat.iteration % 3 == 0 && $smarty.foreach.cat.iteration > 0}

               {/if}

{$v.ename}

               {/foreach}

your tr tags should be inside your loop. I'm not sure about that if statement, i think its not needed.


text:
Q: How do you get a position:absolute; element above a position:relative; one You can see the issue in this fiddle.
I've got an absolutely positioned element with a z-index of 2 and a relatively positioned element with a z-index of 1.  The relatively positioned element contains the absolutely positioned one.  I thought that the z-index:2 element would show above the z-index:1 items, but it does not.  Is there a way to fix this so that the z-index:2 items are above all z-index:1 items?

div {
  background: green;
  position: relative;
  width: 100%;
  z-index: 1;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
}

  Row 1
  I thought this would show above 'Row 2'

  Row 2

A: When you add a z-index to a child that is in a positioned parent element that also has a z-index, the parent z-index starts a new stacking order, and the child z-index is relative to the parent's z-index. So in this case, z-index: 2 is only compared to other elements inside of the parent with z-index: 1. To get around this, you could just apply the z-index to the span, or don't give the last div a z-index
You can read more about it here https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

body {
  font-family: arial;
}

* {
  padding: 10px;
}

div {
  background: green;
  position: relative;
  width: 100%;

}

div:first-child {
  z-index: 1;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
  display: inline-block;
}

  Row 1

  I thought this would show above 'Row 2'

  Row 2

A: The problem was because the div with absolute position was not relative to the second row. I added a wrapper around the two divs and added position: relative; to it.

.wrapper div {
  background: green;
  width: 100%;
  z-index: 1;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
}

.wrapper {
  position: relative;
}

    Row 1
    I thought this would show above 'Row 2'

    Row 2

A: Just remove z-index:1.

div {
  background: green;
  position: relative;
  width: 100%;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
}

  Row 1
  I thought this would show above 'Row 2'

  Row 2


text:
Q: Stomp.py how to return message from listener I've already read this topic: Stomp.py return message from listener
But i still don't get how this works, and why there's no way to retrieve a message from the stomp object, or the listener directly?
If i can send a message via the send method, and If i can receive a message with an on_message listener method, why can't I return that message to my original function, so I could return it to the frontend?
So if i have:
class MyListener(object):
    def on_error(self, headers, message):
        print '>>> ' + message
    def on_message(self, headers, message):
        print '>>> ' + message

how could I return a message from the on_message method?
or could I do it somehow after the conn.subscribe(...) ??

A: Ok, I found a way myself. All you have to do, is a slight change of the listener class:
class MyListener(object):
    msg_list = []

    def __init__(self):
        self.msg_list = []

    def on_error(self, headers, message):
        self.msg_list.append('(ERROR) ' + message)

    def on_message(self, headers, message):
        self.msg_list.append(message)

And in the code, where u use stomp.py:
conn = stomp.Connection()
lst = MyListener()
conn.set_listener('', lst)
conn.start()
conn.connect()
conn.subscribe(destination='/queue/test', id=1, ack='auto')
time.sleep(2)
messages = lst.msg_list
conn.disconnect()
return render(request, 'template.html', {'messages': messages})


text:
Q: The resolution option is greyed out when duplicating display with monitor and projector I have a Windows 7 PC which has an built-in Intel graphics card and one NVIDIA Quadro 410 graphics card.
A monitor and a projector are connected to the PC.
When I duplicate the monitor display with the projector, the resolution option is greyed out.
If I change the resolution just for the monitor, then it is working.
If I change the resolution just for the projector, then it is greyed out.
How do I get the resolution option enabled when duplicating my display across the monitor and the projector?


text:
Q: Is there a word for every cinematographic techniques used by cameramen? Is there a word for every cinematographic techniques used by cameramen? I can only think of specific terms like "scene transitions" and "shots", but I am wondering if there's a word that include all of them and more. I need to know what such a word might be so I can do more research on the subject.

A: You're so close: cinematography.
Unrelated: "every" is a little misleading in your title. It seems to ask if each technique has a corresponding name, rather than to seek a word covering all techniques.


text:
Q: Painting JLabel cuts off HTML Text I'm trying to paint a JLabel to a BufferedImage using html as text but it always prints the text in the middle (vertically), and cuts off the text on the right.
Here is my code:
public static void test() throws IOException
{
    int width = 100;

    JLabel label = new JLabel();
    label.setText("
asdf asdfasdf asdfsdf asdfasdf asdfasdf asdfasdfasdfasdf asdfasdfasdfa sdfasd fasdf asdfasdf asdfasdf asdfasdfasdfa sdfasdf
");
    Dimension size = getPreferredSize(label.getText(), true, width);

    label.setSize(size);

    BufferedImage image =
            new BufferedImage(
                    label.getWidth(),
                    label.getHeight(),
                    BufferedImage.TYPE_INT_RGB);

    Graphics g = image.getGraphics();
    g.setColor(Color.LIGHT_GRAY);
    g.fillRect(0, 0, 500, 900);
    label.paint(g);

    ImageIO.write(image, "png", new File("testImage.png"));
}

private static final JLabel resizer = new JLabel();

public static java.awt.Dimension getPreferredSize(
        String html,
        boolean width,
        int prefSize)
{

    resizer.setText(html);

    View view =
            (View) resizer
                    .getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey);

    view.setSize(width ? prefSize : 0, width ? 0 : prefSize);

    float w = view.getPreferredSpan(View.X_AXIS);
    float h = view.getPreferredSpan(View.Y_AXIS);

    return new java.awt.Dimension((int) Math.ceil(w), (int) Math.ceil(h));
}

And here is the resulting image:

A: I think the html word wrapping is handled by something in the swing thread loop, if you are doing this form that loop as a actionlistener then it can't recalculate the html


text:
Q: Projective space has no non-trivial first order deformations A first order deformation is a deformation over the dual numbers $k[t]/(t^2)$. I have read that there are no non-trivial first order deformations of complex projective space $\mathbb{P}^n$ (i.e. no first order deformations other than $\mathbb{P}^n\times \operatorname{Spec} k[t]/(t^2)\rightarrow \operatorname{Spec} k[t]/(t^2)$).
I am aware of the result for affine smooth schemes (for example here) using the infinitesimal lifting property, but am not sure how to approach this for $\mathbb{P}^n$, perhaps we use the cohomology of line bundles on $\mathbb{P}^n$?
Question: Why are there no non-trivial first order deformations on $\mathbb{P}^n$?


text:
Q: How can I lock contentOffset y position of a FlatList when new items are added I have a flatList with items in it. After I have scrolled down a bit, an item is added to the top. This causes the list to move down by one cell. How can I avoid this?

A: The trick is to scroll to the Y location (unanimated) when an item is added to the list
function itemAdded() {
    //...
    const listYOffset = this.state.listYOffset;
    const cellHeight = this.topmostItemHeight;
    const newYOffset = listYOffset + cellHeight;
    this.listRef.scrollToOffset({ offset: newYOffset, animated: false });
    this.setState({ listYOffset: newYOffset });
}

Then in flatlist, set this this.topmostItemHeight to the height of the item added.
Note my code was used for adding one item at a time, but the fundamentals are the same


text:
Q: Disable Codeigniter logging and allow native PHP logging I am running Codeigniter 2.1.4 and as far as I can tell CodeIgniter is intercepting PHP error messages and storing them in /application/logs
I would like to disable CodeIgniter logging and simply allow the native PHP error log to get used.
Has anyone done this before?

A: take a look at the top of the main codeigniter index.php file
theres different ways of defining the environment but you can just define it on that index page. what you want is 'production'
    // comment this line out
    //define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');

   // put in this line
    define('ENVIRONMENT', 'production');

you will see in the code that codeigniter also accommodates your php version.
OR you can just go under that section of code and paste this in
ini_set('display_errors', 0);

a faster sloppier way of switching between showing errors or not.
==== edit
this post was in reply to this comment you made:

This is great information but unfortunately CI seems to still be
  intercepting "Notice" level messages and is outputting them to the
  browser.

so the above instructions controls if error messages are sent to the browser. otherwise in terms of codeigniter 'logging' your errors - you can turn off codeigniter logging in application/config and do whatever type of logging you want.

A: on /application/config.php
check if $config['log_threshold'] = 0;
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| If you have enabled error logging, you can set an error threshold to
| determine what gets logged. Threshold options are:
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
|   0 = Disables logging, Error logging TURNED OFF
|   1 = Error Messages (including PHP errors)
|   2 = Debug Messages
|   3 = Informational Messages
|   4 = All Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;


text:
Q: Why should I have an account with Stack Overflow anymore? SO is always throwing this error when I post a question (meaning that I've been found to have poor questions):

Oops! Your question couldn't be submitted because:

*

*Sorry, we are no longer accepting questions from this account.

So is it worth it to have my account anymore?  And how do I remove my account from Stack Overflow?

A: The answer to your first question is up to you. What are you doing now with your SO account? Do you want to continue doing it? If so, keep your SO account (and contact support if you don't know why you can't ask questions). Otherwise, you may consider closing it.
Your second question is answered by Can I delete my account?.

A: The block on asking questions is reversible, if you can show that you've changed your ways by posting good quality answers.
As you're already aware, the block on asking questions stems from consistently asking questions of a poor quality.  This is automated based on the votes on your questions.  Looking at your account, you only have one question with a negative score (it's possible some were deleted). It's also possible your many questions with low views and no answers were also taken into account.
This is an example of one of your questions, the one that has a score of -1:

Facebook like link sharing module in drupal or Screen Scrapping with images?
Hi,
im looking for a module or class file if user provide an url and its show output of title,desc, with images as same like facebook link share works
anyone have idea plz share,
Thanxs, Gobi

Firstly, this question is so poorly written that it's bound to attract downvotes.  Users specializing in this field might be able to work out the gist of what you're asking for, but many users will just see this question as junk.  Frankly, I'm surprised you only received one downvote for this question.
Secondly, it looks like you're specifically asking for code, not for help writing the code.  Stack Overflow is a programming Q&A website.  It's for programmers to ask programming related questions and receive programming related answers.  Asking for someone to give you a plugin to do what you're asking isn't asking for programming help, because you're not doing any programming.  Asking for code is almost always met with downvotes and close votes.
It's clear at this point that English isn't your first language (if it is, then may God have mercy on your soul!).  Although I can sympathize that it might be difficult to write questions clearly in a language you don't write/speak in very well, it's not an excuse.  In fact, it's even more of a reason to add more detail and examples to your question.  If we can see that you've put effort into your post, someone will almost certainly edit your question to make more sense.
Things you can do to improve your questions:

*

*Add as much detail as you can without repeating yourself or rambling.

*Avoid shortening words like "please" to "plz".

*Try and avoid using phrases like "please share", this is synonymous with asking for someone to do your work for you.

*Show the code that you've written so far.  If you don't have the slightest clue as to what you're trying to do, you might be better off reading some tutorials first.

*Post images that illustrate what you're trying to achieve.

Having the ban lifted will most probably require you to have a positive involvement on the "A" part of the site, writing answers to questions.  If you think you can help others, you should make an effort to do so.  Writing some quality answers will show that you have seen the error of your ways and you can ask here for the ban to be lifted.
Of course, if you don't want to put this effort in then Stack Overflow might not be the right place for you.  You can leave your account as it is or you can ask for it to be deleted.

A: Quick answer: it shows that the SO moderation system works, works well.


text:
Q: How to create a Thread which will have a field which can be read from another class I would like to create a Thread in C# which will be counting frequency of sound at the microphone input of the computer. I am not asking about the FFT algorithm but just how to start a thread so I can modify A.hz field while Thread.hz is changing.
There will be only 1 Thread.
public class A()
{
    Thread t;
    int hz;  <-- i would like to change this when

    A()
    {
        starts Thread
        onchange t.hz modifies and dispays this.hz
    }
}

class Thread
{
    int hz; <-- this changes

    void computeFrequency() <-- because of that method
    {
        changesHZField...
    }
}

A: As promised, here's a solution using Rx:
using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;

namespace rxtest
{
    class FrequencyMeter
    {
        Random rand = new Random();
        public int Hz
        {
            get
            {
                return 60+rand.Next(3);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var obs = Observable.Generate<FrequencyMeter, int>(
                new FrequencyMeter(), //state
                x => !Console.KeyAvailable, // while no key is pressed
                x => x, // no change in the state
                x => x.Hz, // how to get the value
                x => TimeSpan.FromMilliseconds(250), //how often
                Scheduler.Default)
                .DistinctUntilChanged() //show only when changed
                ;

            using (IDisposable handle = obs.Subscribe(x => Console.WriteLine(x)))
            {
                var ticks = Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe(x=>Console.WriteLine("tick")); //an example only
                Console.WriteLine("Interrupt with a keypress");
                Console.ReadKey();
            }
        }
    }
}

Delivering values asynchronously:
Interrupt with a keypress
60
61
tick
62
60
tick
61
60
tick
62
61
tick
62
60
tick

A: You won't have to do anything special - multiple threads will be able to access your hz field.  You'll need to consider synchronization issues (http://msdn.microsoft.com/en-us/library/ms173179.aspx)
When you have multiple threads reading/writing the same variable there are all sorts of problems.  The easiest thing is probably to follow the link and copy their locking approach.

A: public class A()
{
    Thread t;
    int hz;

    A()
    {
        //starts Thread
    }

    internal void Signal(int hz){
        //modifies and dispays this.hz
    }

}

Now the Thread class can call the method Signal each time his property is set.
To reference the A class instance, you can either pass it to the Thread class constructor and store a reference as private variable, or declare A itself as static; this depends on your overall architecture.
class MyThread : Thread
{
    int _hz;
    A _instance;

    public void MyThread(A inst){
        _instance = inst;
    }

    void computeFrequency()
    {
        //changesHZField...
        _instance.Signal(_hz);
    }
}

Finally, you might need to enable cross thread operations, depending on what you're doing in A class and MyThread class


text:
Q: Draw dynamic circle in gatsby react issue I am using Strapi as a backend, and in my frontend I am using Gatsby.
I am using the values from the backend to draw a circle inside a card. The number of cards are generated from the backend value.
For now I am hard coding the three first cards in css with n:th child values with the following css code:
.svgAssesment circle {
  width: 100%;
  height: 100%;
  fill: none;
  stroke-width: 10;
  stroke: rgba(255, 255, 255, 0.05);
  transform: translate(5px, 5px);
  stroke-linecap: round;
}
.svgAssesment circle:nth-child(2) {
  stroke: #fff;
  stroke-dasharray: 440px;
}
.card:nth-child(1) .svgAssesment circle:nth-child(2) {
  stroke-dashoffset: calc(440px - (440px * 9) / 10);
}
.card:nth-child(2) .svgAssesment circle:nth-child(2) {
  stroke-dashoffset: calc(440px - (440px * 9) / 10);
}
.card:nth-child(3) .svgAssesment circle:nth-child(2) {
  stroke-dashoffset: calc(440px - (440px * 8) / 10);
}

Instead of hard coding these values, is there a way to draw them dynamically so that each circle's stroke-dashoffset is based upon the prop {item.rate} I have in my frontend.
So in the example above the hard coded values are 9,9 and 8 should be replaced with the values of {item.rate} for each of the cards generated and not just the three I have in my nth:child code.
This is my frontend code:
import React from "react"
import Title from "./Title"
import { graphql, useStaticQuery } from "gatsby"

    const query = graphql`
      {
        allStrapiAssessment {
          nodes {
            title
            rating {
              id
              topic
              rate
            }
          }
        }
      }
    `

    const SelfAssesment = () => {
      const data = useStaticQuery(query)
      //console.log(data)

      const {
        allStrapiAssessment: { nodes: assesments },
      } = data
      //console.log(assesments)
      const [value] = React.useState(0)
      const { title, rating } = assesments[value]
      console.log(title, rating)

      return (

          <Title title={title} />

              {rating.map(item => {
                return (

                          <svg className="svgAssesment">
                            <circle cx="70" cy="70" r="70"></circle>
                            <circle cx="70" cy="70" r="70"></circle>
                          </svg>

                              {item.rate}
                              /10

                      {item.topic}

                )
              })}

      )
    }

    export default SelfAssesment

A: You will need to use styled-components in order to use React props in the styling.
Alternatively, you can just use inline styles for stroke-dashoffset CSS rule and delegate the rest of the styling into your CSS stylesheet. Something like:
import React from "react"
import Title from "./Title"
import { graphql, useStaticQuery } from "gatsby"

const query = graphql`
  {
    allStrapiAssessment {
      nodes {
        title
        rating {
          id
          topic
          rate
        }
      }
    }
  }
`

const SelfAssesment = () => {
  const data = useStaticQuery(query)
  //console.log(data)

  const {
    allStrapiAssessment: { nodes: assesments },
  } = data
  //console.log(assesments)
  const [value] = React.useState(0)
  const { title, rating } = assesments[value]
  console.log(title, rating)

  return (

      <Title title={title} />

          {rating.map(item => {
            return (

                      <svg className="svgAssesment">
                        <circle cx="70" cy="70" r="70"/>
                        <circle cx="70" cy="70" r="70" style={{
                          strokeDashoffset: `calc(440px - (440px * ${item.rate}) / 10)`
                        }}/>
                      </svg>

                          {item.rate}
                          /10

                  {item.topic}

            )
          })}

  )
}

export default SelfAssesment

Note the:
 <circle cx="70" cy="70" r="70" style={{
    strokeDashoffset: `calc(440px - (440px * ${item.rate}) / 10)`
  }}/>

In the snippet above you are just calculating the stroke-dashoffset rule with inline styles applying the dynamic item.rate value in the second circle.


text:
Q: Special Upper Bound Kolmogorov Distribution and Integral Hey everyone I'm currently working on some properties of the Kolmogorov distribution, which we have defined as
$F\left(x\right):=\mathbb{P}\left(\sup_{t \in\left[0,1\right]}|B^{0,1}_t|\le x\right)=\begin{cases}1+2∑_{j=1}^∞ \left(-1\right)^j\exp \left(-2j^2x^2\right),x>0\\0,x\le 0\end{cases}$
Now the task is to show that:
(a) $F(x)\le \exp(-2x^2)$ for $x \in (0,1/2)$
(b) $\forall\epsilon\in(0,1/2)$ $\exists N \in \mathbb{N}:$ $\forall n\ge N$ $\int_{0}^{1/2}(1-(F(\sqrt{x\log(n})))^n)dx \ge1/2-\epsilon$
To $(a)$
clearly we have an alternating real null sequence so by Leibnitz criteria for alterning series we now it converges. If we take partial sums we have the following relation:
$∑_{j=1}^{2k+1}\left(-1\right)^j\exp \left(-2j^2x^2\right)\le ∑_{j=1}^{∞}\left(-1\right)^j\exp \left(-2j^2x^2\right)\le∑_{j=1}^{2k+2}\left(-1\right)^j\exp \left(-2j^2x^2\right)$
and for $k=0$ we find
$F(x)\ge 1-2\exp(-2x^2)$ for $x>0$ and $F(x)\le1-2\exp(-2x^2)+2\exp(-8x^2)$
The second expression on the right hand side is clearly bounded by $\exp(-2x^2)$ if $x\in (0,1/2)$ but we only have strict inequality then because equality only arises in the limit $x\to0$. So my question if there is any other way to show that $F(x)\le \exp(-2x^2)$ for $x \in (0,1/2)$ ?
Thank you in advance for any hints.


text:
Q: Alternative to multiple AND operator is there a cleaner(better) alternative to using multiple AND operator in T-sql.
for example
use Portal
go
SELECT
U.Id,
U.FirstName,
U.LastName,
U.Email,
U.Gender,
U.Country

FROM AspNetUsers U
WHERE (U.M01 >= 80 and U.M02 >= 80 and u.M03 >= 80 AND U.M04 >= 80)

A: No, if result depends on columns that you have in WHERE. If there will be good index it will be fast too (good index for this query is
create index [some name] on AspNetUsers (M01, M02, M03, M04) include (Id, FirstName, LastName, Email, Gender, Country)

But this query looks strange and probably it is problem with design/normalization

A: If AND is what you need then AND is the proper operator.
AND is efficient as it can give up as soon as it gets a single false.
The query optimizer is (typically) smart enough to look for the easy false first.
OR is not as efficient so some times you will refactor to get rid of the OR but I have never had a reason to refactor an AND.
If the value changes then maybe go with this for convenience but it should not effect execution
declare @count int = 80;
SELECT
U.Id,
U.FirstName,
U.LastName,
U.Email,
U.Gender,
U.Country
FROM AspNetUsers U
WHERE U.M01 >= @count
  and U.M02 >= @count
  and u.M03 >= @count
  AND U.M04 >= @count;

A: There are few options to simplify this particular selection syntax but it is hard to say if they make sense without knowing your entire context and your definition of better/cleaner...
Let's assume that cleaner/better means "selection without conjunction operators" for you.
Some of possible options:

*

*Create a view that will prefilter your AspNetUsers table. Then your query syntax could be simplified to:
SELECT
Id,
FirstName,
LastName,
Email,
Gender,
Country
FROM AspNetUsersPerfiltered

*Move filtering logic to dedicated function that will check the condition. Then your query syntax could be simplified to:
SELECT
Id,
FirstName,
LastName,
Email,
Gender,
Country
FROM AspNetUsers
WHERE myFunction(M01, M02, M03, M04) = 1

*Create additional column(flag) that will be set during row insert/update or by some background process. Then your query syntax could be simplified to:
SELECT
Id,
FirstName,
LastName,
Email,
Gender,
Country
FROM AspNetUsers
WHERE FlagColumn = 1
HTH


text:
Q: Is MongoDB Connections getting too high? I currently have my MongoDB running in Production Environment. It has 1 Primary, 1 secondary and an Arbiter. Configuration of the ubuntu machines are pretty decent, it's got 56GB of RAM and about 100GB of HardDisk space. It's been around a week's time since MongoDb has been running continuously. I did some reading about the uLimit and it is set as
httpd soft nofile 10240
httpd hard nofile 10240
* soft nofile 65000
* hard nofile 65000

Our server-side is Java and we have implemented connection pooling. Today when I did a  db.serverStatus(), under connections I got the following
"connections" : {
            "current" : 19314,
            "available" : 32686,
            "totalCreated" : NumberLong(53770)
    },

Is this something which I should be concerned with, because I could not find any limit or number which tells me I've reached a danger limit before mongoDB crashes. Can anyone let me know if there is anything I should be doing?

A: RAM, mainly. Every connection gets a stack allocated, at the size of 1MB. The more connections you have, the more RAM is needed for them and the less RAM is available for keeping indices or the working set of data in RAM.
So with your 19314 connections, roughly 19GB of RAM is used for connections. That's roughly a third of your available RAM – which is too much, from my point of view. What is acceptable has very much to do with your use cases, performance needs and whatnot. Finding out an acceptable RAM utilization is out of scope of an answer and can take many hours of analysis and optimization.


text:
Q: Advice for database implementation We need to configure a database for our NGO. We have to save information about the children and several pictures and documents for each of them.
A friend is currently saving the data of over 70 kids in folders and subfolders of her device and it's becoming a mess. She asked me if I could digitalize it and I am not sure how I want to implement it.
We need the database and some kind of frontend where my friend can easily add, change or display information in the database without any IT knowledge. It would also be beneficial if we could connect our website to that database to display some pictures of the kids.
I've read about Wordpress and their database, is that a good solution? Or should I create our own MySQL database and a simple webpage where my friends has access to it?
I'm kinda new to databases but I really want to implement something that is better than our current storage situation. We are currently using a simple PHP, HTML, CSS, JavaScript website: www.kencef.de. A friend and I are the only developers and aren't that experienced yet. Should we switch to Wordpress?

A:
... save information about the children and several pictures and documents ...
... A friend is currently saving the data of over 70 kids in folders and subfolders on her device ...
... We need the database ... frontend ... easily add, change or display informations ... without any IT-knowledge ...

I don't say this very often, but in this case, I don't think you can - or should - avoid it.
Hire somebody that knows what they're doing, especially in the fields of Data Security, Web Application Security, and who knows their way around the General Data Protection Regulations (GDPR) - at the very least.
The rules and regulations around Data Protection and Security and, more importantly still in your application, Safeguarding, etc., are Legion and you DO NOT want to get on the wrong side of them.
Question: What's does your Privacy Notice say?
If your answer is "What's a Privacy Notice", then you should not be touching this problem with a barge-pole!

A: Wordpress is likely going to give you everything you need out of the box, especially if you guys don't have a lot of development experience. But if you want to take on the challenge of learning how to implement something yourself then you can try to create your own system. The design of the database side is relatively simple but it will definitely take a lot longer for you to implement your own system from scratch.


text:
Q: jQuery - select a container which has only more than certain amount of children I have some divs which all are siblings. Inside each div there are multiple images as direct children. I want to select divs which only has more than 5 images inside it, and append a div into it using jQuery.
My approach for this is as follows.

jQuery snippet I wrote is
$( document ).ready(function() {
    //var countimg = $(".main").find('img').length;
    var count2 = $(".main").children('img').length > 20;
    //console.log(countimg);
    //console.log(count2);
    if(count2 === true){
        //var i = 0;

        $.each($('.main img'), function (index, value) {
            //i++;
            console.log('um inside'+i);
            //if(i > 10){
                $(this).css('display','block');
            //}else{
            //    $(this).css('display','block');
            // }

            return ( index !== "three" );
        });

        $.each($('.main img'), function (index, value) {
                $(this).css('display','none');
        }
        $(this).parent().append("See More");
        }
});

A: A simpler way is to query by combining .has(), :nth-child() and > selector
for e.g. , select .main with at least 5 direct img children
$('.main').has('>img:nth-child(5)');

for appending
$('.main').has('>img:nth-child(5)').append("See More");

demo: https://jsfiddle.net/jacobgoh101/tj48zgLf/2/

A: Your explanation in the question and the snippet you have written doesn't seem to match. However the following should do the needful.
$("div.main").each(function(){
    var imgCount = $(this).find("img").length;
  if(imgCount > 5){
    //Do what you wanna do
    console.log(imgCount);
  }
});

Check this fiddle out.

A: Below solution helps even if you are not aware what your child elements going to be.
Here you have  but even in the case where container has different child elements, this below solution would work.

let certainAmount = 5;
const $container = $('.main');

$container.each(function(){
  let $this = $(this);

  console.log($this.find('> *').length);

  if(($this.find('> *').length) > (certainAmount - 1) ) {
    //Selected and do something.
    $this.addClass('selected');
  }
});
.main {
  padding: 5px;
  border:1px solid #a29e9e;
  background: #e8e8e8;
}
.main.selected {
  background: green;
 }

Update: Append into Selected Container

let certainAmount = 5;
const $container = $('.main');

$container.each(function(){
  let $this = $(this);

  console.log($this.find('> *').length);

  if(($this.find('> *').length) > (certainAmount - 1) ) {
    //Selected and do something.
    $this.addClass('selected').append("<button>Show More</button>");
  }
});
.main {
  padding: 5px;
  border:1px solid #a29e9e;
  background: #e8e8e8;
}
.main.selected {
  background: green;
 }
 img {
  height: 5px;
  width: 5px;
 }

A: You can use the below code
$('.main:has(img:nth-of-type(5))').append('See More');

:nth-of-type() selector, this would work only if the img elements are the direct children of the .main element


text:
Q: Printing formatted floats in nested tuple of mixed type I have a list of tuples where the entries in the tuples are mixed type (int, float, tuple) and want to print each element of the list on one line.
Example list:
 [('520',
     (0.26699505214910974, 9.530913611077067e-22, 1431,
     (0.21819421133984918, 0.31446394340528838), 11981481)),
 ('1219',
     (0.2775519783082116, 2.0226340976042765e-25, 1431,
     (0.22902629625165472, 0.32470159534237308), 14905481))]

I would like to print each tuple as a single line with the floats formatted to print to the ten-thousandth place:
 [('520', (0.2669, 9.5309e-22, 1431, (0.2181, 0.3144), 11981481)),
 ('1219', (0.2775, 2.0226e-25, 1431, (0.2290, 0.3247), 14905481))]

I was using pprint to get everything on one line
pprint(myList, depth=3, compact=True)
> ('1219', (0.2775519783082116, 2.0226340976042765e-25, 1431, (...), 14905481))]

but I wasn't sure how to properly format the floats in a pythonic manner. (There has to be a nicer way of doing it than looping through the list, looping through each tuple, checking if-float/if-int/if-tuple and converting all floats via "%6.4f" % x).

A: This is not exactly what you need, but very close, and the code is pretty compact.
def truncateFloat(data):
    return tuple( ["{0:.4}".format(x) if isinstance(x,float) else (x if not isinstance(x,tuple) else truncateFloat(x)) for x in data])
pprint(truncateFloat(the_list))

For your example the result is
(('520', ('0.267', '9.531e-22', 1431, ('0.2182', '0.3145'), 11981481)),
 ('1219', ('0.2776', '2.023e-25', 1431, ('0.229', '0.3247'), 14905481)))

You can play with options of .format() to get what you want.


text:
Q: Recently deleted line from a text file as a string left as blank and I cannot remove the blanks from the string I am reading in from a text file and putting it into a string and then removing a specific line from this string by using a counter to count the number of new lines and then writing to a new string. It works to remove the specific line I want but it leaves blanks in its place when I write it back to the text file. Im trying to remove these blanks but struggling to find a solution.
Ive tried searching through the string manually to remove the spaces by using a for loop and searching for ' ' but it returned unidentified symbols I was unsure about.
void removeBook(int line){
  char *bookrecord = "records/bookrecord.csv";
  FILE *file = fopen(bookrecord,"r");
  int currentline = 1;
  int count = 0,newcount = 0,length;
  char *string;
  char *newstring;

  fseek(file,0,SEEK_END);
  length = ftell(file);
  fseek(file,0,SEEK_SET);
  string = malloc(length+1);
  fread(string,sizeof(char),length,file);
  fclose(file);
  string[length] = '\0';

  length = strlen(string);
  newstring = malloc(length+1);

  while(string[count] != '\0')
  {
    if(currentline == line)
    {
      while(string[count] != '\n')
      {
        count++;
      }
    }
    if(string[count] == '\n')
    {
      currentline++;
    }
    printf("%c",string[count]);
    newstring[newcount] = string[count];
    count++;
    newcount++;
  }
}

void main(){
  removeBook(2);
}

Input from Text File/Output String


text:
Q: When running "docker-compose up" I get the following message "services must be a mapping" docker-compose.yml contains:
version: "3.9"
services:
build: .
web:
ports:
  - "8000:8000"
command: python manage.py runserver 0.0.0.0:8000
volumes:
  - .:/code

A: It looks like everything after service: should be indented. Also, the service name should be before the build: . instruction. And it is best practice to use an array for the command when spaces are involved.
Try
version: "3.9"
services:
  web:
    build: .
    ports:
      - "8000:8000"
    command: ["python", "manage.py", "runserver", "0.0.0.0:8000"]
    volumes:
      - .:/code


text:
Q: Basic Series Question Let $(a_n)$ be a sequence such that $\liminf |a_n| = 0$. Then there exists a subsequence $(a_{n_k})$ such that $\sum_{k=1}^\infty a_{n_k}$ converges.
any thoughts?

A: Here's an outline, leaving a lot of the detail for you.
You want to find a subsequence $\langle a_{n_k}:k\in\Bbb Z^+\rangle$ of $\langle a_n:n\in\Bbb Z^+\rangle$ that approaches $0$ so quickly that $\sum_{k\ge 1}a_{n_k}$ converges. Start by using the fact that $\liminf_na_n=0$ to infer that $\langle a_n:n\in\Bbb Z^+\rangle$ has a subsequence $\langle a_{n_k}:k\in\Bbb Z^+\rangle$ converging to $0$. This implies that for each $n\in\Bbb Z^+$ there is a $k\in\Bbb Z^+$ such that $|a_{n_k}|<\frac1{2^n}$. Use this to construct an increasing sequence $\langle k(i):i\in\Bbb Z^+\rangle$ such that $$|a_{n_{k(i)}}|<\frac1{2^i}$$ for each $i\in\Bbb Z^+$; $\langle a_{n_{k(i)}}:i\in\Bbb Z^+\rangle$ is a subsequence of $\langle a_n:n\in\Bbb Z^+\rangle$.
Finally, explain why $\displaystyle\sum_{i\ge 1}a_{n_{k(i)}}$ converges. (Indeed, you should be able to explain why it converges to some number in the interval $[-1,1]$.)


text:
Q: Not able to run protractor tests in Safari I have Angular7 project and few E2E tests, in Chrome everything fine (All tests 'OK'). But i need to run my tests in Safari, and Protractor crashes with error.
First i had protractor.conf.js with :
multiCapabilities: [{ 'browserName': 'safari' }],
directConnect: true,

But i get:
Error: browserName safari is not supported with directConnect.
Then i change it to:
directConnect: false.
But now protractor crashes with error:
E/launcher - Error: Error: Server terminated early with status 1
    at earlyTermination.catch.e (...node_modules/selenium-webdriver/remote/index.js:252:52)
    at process._tickCallback (internal/process/next_tick.js:68:7)
[10:52:05] E/launcher - Process exited with error code 100
An unexpected error occurred: undefined

A: There was no answer for this issue in any forum, but I finally found a solution. the error happens because of Direct connect. It doesn't support Safari. The solution is to give the seleniumServerJar path
seleniumServerJar:'/usr/local/lib/node_modules/protractor/node_modules/webdriver-manager/selenium/selenium-server-standalone-3.141.59.jar',
it looks like below in the config file:


text:
Q: Convergence of the method :Newton-Raphson.(GATE) This question was asked in GATE exam and It's answer is 1. I could not understand this question.
Suppose that the Newton-Raphson method is applied to the equation $2x^2+1-e^{x^2}=0$  with an initial approximation $x_0$ sufficiently close to zero. Then, for the root $x= 0$, the order of
convergence of the method is equal to _________(Fill in the blanks)

A: In the case of a simple zero Newton's method converges quadratically. But not so if we have a zero of higher order. Assume that we want to find the zero of the function $f(x):=x^2$ using this method. We then obtain the recursion
$$x_{n+1}=x_n-{f(x_n)\over f'(x_n)}=x_n-{x_n^2\over 2x_n}={x_n\over2}\qquad(n\geq0)\ .$$
This shows that at each step the distance to the zero of $f$ is halved, in other words: We only have linear convergence.
In the example at hand the situation is similar: We are told to find the zero of
$$g(x):=1+2x^2-e^{x^2}=1+2x^2-\left(1+x^2+{x^4\over2}+?x^6\right)=x^2-{x^4\over2}+?x^6\ .$$
Newton tells us to look at the auxiliary function
$$\psi(x):=x-{g(x)\over g'(x)}=x-{x^2-x^4/2+?x^6\over 2x-2x^3+?x^5}={x^2-3x^4/2+?x^6\over 2x(1-x^2+?x^4)}\ .$$
It follows that
$$\psi(x)={x\over2}\left(1-{x^2\over2}+?x^4\right)\ ,$$
so that at each step the distance to the zero is essentially halved when $x_n\to0$.
(In the above each question mark represents a certain power series $a_0+a_1x+a_2 x^2+\ldots$ convergent in a neighborhood of $0$.)


text:
Q: Infinitely many points in plane s.t. no point is a convex combination of other points Let $A$ be an infinite set of points in the plane, with no three points of $A$ collinear. I want to prove that $A$ contains an infinite set $B$ such that no point of $B$ is a convex combination of other points of $B$.

*

*Is it equivalent/stronger/weaker to ask for a set $B$ in which any $4$ points form a convex quadrilateral?

*Can I prove this using Ramsey theory?

*I know that using Ramsey theory one can prove that for any $n$, sufficiently many points in the plane contain a convex $n$-gon. Does this help to prove the infinite case?

A: HINT:
Use the infinite Ramsey theorem. Consider the infinite set $A$. Color the subsets with $4$ elements of $A$ in two colors: red if the points form a convex quadrilateral, blue otherwise. There exists an infinite subset $B$ of $A$ with all subsets with $4$ elements of the same color. This color cannot be blue. Indeed, it is known that among any $5$ points in the plane, every $3$ non-colinear, $4$ of them will be the vertices of a convex quadrilateral (cf a result of Erdos) .  Therefore, every $4$ points of $B$ form a convex quadrilateral, so no point is in the convex hull of the other $3$. Now, use Caratheodory theorem to show that no point of $B$ is in the convex hull of another finite subset of $B$.


text:
Q: Upgrading slf4j-api-1.5.8.jar file in Grails (1.3.x) to a newer one, what to consider? I'm planning to replace log4j with logback. In order to get Groovy configuration (http://logback.qos.ch/manual/groovy.html) to function, I need at least logback-0.9.22.
The problem is that Grails 1.3.x ships with slf4j-api-1.5.8 which is only enough to use logback-0.9.17 which, in turn, does not support Groovy configuration.
What does actually happen (does something break / causes unexpected situations) if I upgrade slf4j-api in Grails?

A: See slf4j release history at http://slf4j.org/news.html.
The 1.6.0 version lists only one incompatibility:

The log method in LocationAwareLogger interface now admits an
  additional parameter of type Object[] representing additional
  arguments of the log request. Due to this modification, slf4j-api
  version 1.6.x will not work with bindings shipping with SLF4J 1.5.x --
  bindings shipping with 1.6.x must be used.

I guess this is the exact single reason that slf4j-api-1.5.8 and logback-0.9.22 don't match.
So after upgrading both slf4j-api and logback everything should just work.


text:
Q: Next.js export failing due to import? I am getting the following error when exporting my nextjs app:
SyntaxError: Unexpected token {
    at new Script (vm.js:80:7)
    at createScript (vm.js:274:10)
    at Object.runInThisContext (vm.js:326:10)
    at Module._compile (internal/modules/cjs/loader.js:664:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)

This is my next.config.js:
import {getBlogPosts} from "./src/api";
import {mapPosts} from "./src/mappers/BlogMapper";
module.exports = {
    async exportPathMap() {
        const response = await getBlogPosts();
        const posts = mapPosts(response);
        const pages = posts.reduce(
            (pages, post) =>
                Object.assign({}, pages, {
                    [`/blog/${post.uid}`]: {page: '/blog/[uid]'},
                }),
            {}
        );
        // combine the map of post pages with the home
        return Object.assign({}, pages, {
            '/': {page: '/'},
        })
    },
};

src/api file:
import Prismic from "prismic-javascript";
import {Client} from "./prismic-configuration";
export const getBlogPosts = (req) => {
    return Client(req).query(
        Prismic.Predicates.at("document.type", "post"),
        {orderings: "[my.post.date desc]"}
    );
};
export const getBlogPost = (req, uid) => {
    return Client(req).getByUID("post", uid, null);
};

I found this in the docs but I am not sure who to resolve it:

Avoid using new JavaScript features not available in your target
  Node.js version. next.config.js will not be parsed by Webpack, Babel
  or TypeScript.

A: Your code for next.config.js: is written using ES6 syntax.
You should convert it to CommonJS
Try like this:
const getBlogPosts = require('./src/api').getBlogPosts
const mapPosts = require('./src/mappers/BlogMapper').mapPosts

module.exports = {
    exportPathMap: async function () {
        const response = await getBlogPosts();
        const posts = mapPosts(response);
        const pages = posts.reduce(
            (pages, post) =>
                Object.assign({}, pages, {
                    [`/blog/${post.uid}`]: {page: '/blog/[uid]'},
                }),
            {}
        );
        // combine the map of post pages with the home
        return Object.assign({}, pages, {
            '/': {page: '/'},
        })
    },
};


text:
Q: How can I pass weights in a variable to rpart? For some reason, the rpart from the rpart package can't see a variable defined in the context from which it is called. You can see in the reprex below that wts is defined just before the call to rpart, but when I call rpart, I get the error "object 'wts' not found".
If I omit the weights argument, there is no problem.
library(rpart)

data(mpg, package = "ggplot2")

scale <- function(x) {
    x/sum(x)
}

fit_rpart <- function(formula, data, iters = 10) {
    data <- as.data.frame(data)
    models <- list()

    for (i in 1:iters) {
        wts <- scale(runif(nrow(data)))
        print(head(wts))
        models[[i]] <- rpart(formula = formula,
                             data = data, weights = wts,
                             method = "class")
    }
    return(models)
}

results <- fit_rpart(cyl == 4  ~ drv + cty + fl + class, mpg)
#> [1] 0.0072092177 0.0059019498 0.0007893446 0.0038617957 0.0067420603
#> [6] 0.0076892493
#> Error in eval(extras, data, env): object 'wts' not found

Created on 2022-09-28 by the reprex package (v2.0.1)

A: It seems the answer is similar to that provided here. (Similar, but not the same, as this issue relates to rpart, not lm. Not sure how to generalize the question to cover both.)
If I put these two lines at the top of fit_rpart, the code runs fine.
formula <- as.formula(formula)
environment(formula) <- environment()

A: It seems to be a name scoping problem as you said. You can also use <<- to pass an affectation to the parent environment.
(Also, data and formula are already existing objects in R so to be clear one could prefer to rename them).
library(rpart)

data(mpg, package = "ggplot2")

scale <- function(x) {
  x/sum(x)
}

fit_rpart <- function(f, d, iters = 10) {

  d <- as.data.frame(d)
  models <- list()

  for (i in 1:10) {
    wts <<- scale(runif(nrow(d)))
    print(head(wts))
    models[[i]] <- rpart(formula = f,
                         data = d,
                         weights = wts,
                         method = "class")
  }
  return(models)
}

results <- fit_rpart(cyl == 4  ~ drv + cty + fl + class, mpg)

# [1] 0.0007921094 0.0039999229 0.0026862458 0.0018832820 0.0006866826 0.0076998391
# [1] 0.005962060 0.006942240 0.001572535 0.009360314 0.005485438 0.008135806
# [1] 0.007224990 0.004209857 0.007706282 0.007071345 0.003784652 0.006335056
# [1] 0.004098536 0.003289626 0.006710783 0.007364727 0.003099702 0.007693150
# [1] 0.005154814 0.001212012 0.001169259 0.005829825 0.004401704 0.004269959
# [1] 0.001262500 0.003705485 0.007466314 0.005450551 0.001292365 0.007920012
# [1] 0.0007083308 0.0033698483 0.0073883706 0.0013445097 0.0068669108 0.0048488413
# [1] 0.005139870 0.002053938 0.002125759 0.006488419 0.007129400 0.006937384
# [1] 0.006957664 0.006296365 0.000640707 0.008121049 0.008014404 0.007706194