text:
Q: HTML Form is submitted without to be populated on iOS devices I have simple html form on my site:
    <form action="mailer.php" method="post">

    <fieldset>

        Name *
        <input type="text" id="name" name="name" required>
        Error!

        Email *
        <input type="text" id="email" name="email" required>
        Error!

          .... // some more fields
       <input type="submit" id="submit" name="submit" value="Enter your Information">
    </form>

The problem is that on iOS devices ( phone, tablet .. ) form it can be submitted without user to populate required fields.
Why is that? Is there a way to fix it on client side?

A: This should work. But it will be for all not only for iOS
<form action="mailer.php" method="post" id="myForm">

Then this
var form = document.getElementById('myForm');
     form.noValidate = true;
     form.addEventListener('submit', function(event) {
        if (!event.target.checkValidity()) {
             event.preventDefault();
             alert('Error! You must fill all required fields.');
    }
}, false);


text:
Q: Performing statistical analysis of buffers? I am doing a buffer analysis of incinerators and looking at the output areas within those buffers, is there a way of doing a statistical analysis of several buffers to see if there is a significant pattern between the data within the buffers?

A: Because this question is buried in comments, let's assemble them in one place to see what's the issue:

(1) I have created shapefiles that identify the location of operational incinerators and areas that have refused incinerators planning permission and wish to compare the buffers of each.
(2) I also wish to ... see if there is any correlation between the distance from an incinerator and the geodemographics... .

In short, you want to relate various geodemographic (response) variables to two factors: (1) whether an incinerator was refused or accepted and (2) distance to some point location relevant to (1).
This calls for a regression model.  Normally, you don't perform regression modeling in a GIS if you can help it: although it can be done, no GIS supports all the diagnostic, cross-checking, and reporting needed for rigorous analysis, nor have any of them undergone the extensive testing needed to assure correct results.  Instead, use the GIS to output the data (as a list of tuples containing the refuse/accept indicator, the distance, and the geodemographic variables).  Pass these to a statistical program or code library and perform the regression.
(Note that actually creating buffers in the GIS is unnecessary.  Note, too, that you don't have to leave the GIS environment to do this work: Python supports regression analysis (if you're willing to do a bit of programming) and there are R interfaces to ArcGIS.)
This leaves us with a subtle issue, but perhaps it's the most important: because you include spatial-analyst as a tag, it suggests your data are in a gridded form.  "Geodemographic variables" are rarely collected in grids.  Instead, they are reported by administrative units such as blocks, tracts, or counties.  Although these units can be represented by collections of cells on a grid, it would be a mistake to treat each cell as if it had independent data.  (Doing to would make it appear you have far more data than you really have, which would greatly inflate the apparent significance of any regression coefficients.)  You get only one collection of geodemographic values per unit, period.  That, therefore, will be the basic unit of statistical analysis.  Accordingly, you need to summarize the distances within each administrative unit.  One way is to compute zonal statistics of a Euclidean distance grid.  This will give you a mean distance, extreme distances, and some measures of variation of distance within each unit.  Any of these--or even combinations of these--can be used as independent (explanatory) variables in the regression.  Thus, the data to be output by the GIS should correspond, one-to-one, to the administrative units and not to the grid cells.

A: Turns out this is not the question the poster is asking, but I will leave the information here as it might be useful to others who come across this question:

I -think- you might be looking for an analysis of spatial auto-correlation at different distance bands?

Check out this series of esri instructional videos:
http://www.youtube.com/esritv#p/u/7/cXXry6wE86M
http://www.youtube.com/esritv#p/u/9/QJtPmnFgZbs
http://www.youtube.com/esritv#p/u/8/3WtpYnlpKaU
The 2nd one might be particularly useful for you, as it discusses Moran's I, which I think might be the statistic you will be interested in.
Really though, we need a lot more detail on the exact question you are trying to answer. There are a wide range of statistical tools available that are appropriate to different problems.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Filling missing data for two columns in pandas dataframe using non missing data I have a pandas dataframe with 3 columns.
data = data[['id','foo','bar']]

for about 1% of the dataset both foo and bar are missing, but not id. I'm looking to impute with random pairs of non-null foo and bar. Assume id is never null and either foo and bar are both null or both non-null.

A: Are you looking to do something like this?
import pandas as pd
import numpy as np
index = range(10)
df = pd.DataFrame(np.random.randn(10,2), index=index, columns=['foo','bar'])
df['foo'].iloc[0:4] = np.nan

invalid = df['foo'].isnull()
nInvalid = df[invalid].shape[0]
valids = df['foo'][-invalid]
nValid = valids.shape[0]
randomInst = np.random.randint(0,nValid,nInvalid)
df['foo'].loc[invalid] = valids.iloc[randomInst].as_matrix()

Edit to apply to bar as well:
df['bar'].loc[invalid] = df['bar'][-invalid].iloc[randomInst].as_matrix()

A: Can this help you?
 import pandas as pd
 data = pd.DataFrame(data)
 invalid_data = data[(data['foo'].isnull()) & (data['bar'].isnull())]

A: Assuming that when the 'foo' value is missing, the 'bar' value is also missing (as per your question), and that the column types are floating point:
mask = df['foo'].isnull()
df.loc[mask,['foo', 'bar']] = np.random.random((np.sum(mask), 2))

If you want to use valid values from the actual dataframe itself (as they better represent the value range of your data), you could use the following instead:

df.loc[mask,['foo', 'bar']] = df[['foo', 'bar']][~mask].sample(np.sum(mask)).values

(possible with replace=True as argument to the sample method; ditto for np.random.random, of course.)


text:
Q: how to plot two sets of data onto one set of axis whilst still having a facet wrap in ggplot2 for R? Struggling with producing two sets of data from one data frame splitting it by a variable sex.
The variable sex is either Male or Female.
ggplot(student_data,
       aes(x = height,
           y = age,
           group = eye_colour, colour = sex)) +
  geom_line(lwd = 1.5) +
  facet_wrap(~ eye_colour, scales = "free_y") +
  theme(axis.text.x = element_text(size = 14, angle = 270, hjust = 0, vjust = 0.5),
        axis.text.y = element_text(size = 14),
        axis.title.x = element_text(size = 16),
        axis.title.y = element_text(size = 16, angle = 270),
        strip.text.x = element_text(size = 14),
        title = element_text(size = 20),
        legend.position = "none") +

Currently this outputs one line with both data that alternates colour between each point. However, I cant seem to get it to formulate two lines even though its able to differentiate between the variable.
Many thanks in advance,
Samuel

A: group should be sex. colour should be eye_colour. Next time provide a minimal reproducible example such as the one below.
library(ggplot2)
student_data <- data.frame(age = c(5,22,33,4,45), height = c(25,39,5,6,2),
                           eye_colour = c("red", "green", "brown", "brown", "brown"),
                           sex = c("f", "m", "m", "f", "m"))

ggplot(student_data, aes(x = height, y = age, group = sex, colour = sex)) +
geom_line()


text:
Q: Crystal Reports, 'The report you requested requires further information' is working fine in development, not working in testing server I have a problem with Crystal Reports, the reports are working fine in the development environment, but, when executing the application in the test server I get this prompt from the CrystalViewer:
Server name:  *Here's the absolute path of the report in the development server*
Database name: *Correctly filled*
User name:  *Correctly filled*
Password: *Empty*

This is the code that I'm using to pass the login information to the report:
Try
        rptDoc = New ReportDocument
        rptPath = Server.MapPath(rutaReporte)
        Dim conInfo As New ConnectionInfo
        conInfo.ServerName = Server.MapPath("~/reportes.dsn")
        conInfo.DatabaseName = "database"
        conInfo.UserID = "reportUser"
        conInfo.Password = "password"
        rptDoc.Load(rptPath)
        setInicioReportes(conInfo, rptDoc)
        CrystalReportViewer1.ReportSource = rptPath
    Catch ex As Exception
        'Show error message
    End Try

I don't understand why the CrystalReport isn't recognizing the DSN file that I have specified  in code. And in the DNS file I have saved the password, user_id, server and database, which, as I said before, is working  in development environment.
If someone knows how to solve this, it will be really helpful.
Thanks to everyone.
EDIT: Also, when I enter the password in the prompt try to Log In the page just refreshes and nothing happens, the prompt pops again.

A: In Visual Studio, in your solution explorer, you will need to click on references, then CrystalReports.Shared, and then set the properties as shown:

Set Embed Interop Types to False and the Copy Local to True.
CrystalDecisions.Shared is where your connection class definitions are stored for CrystalReports.  Without a Visual Studio environment (or this library nearby) on your server, this is likely why you are getting your error.
Re-Build your solution and put the new executable on your server and it should work!


text:
Q: wayland and remote desktop apparently Fedora 25, even if in alpha state (not for long, beta comins soon) is doing extremely well with Wayland enable by defaut. I wonder if there's any graphical/easy_to_setup solution out there for remote desktop management (under another linux machine) out there that will work with Wayland? Or is it too early? Any help appreciated, thanks

A: Updated answer:
There has been recent work to bring remote desktop capabilities to GNOME under Wayland. It looks like the old screen sharing server, Vino, will be replaced by a new GNOME Remote Desktop service. At least for GNOME under Wayland, remote desktop over VNC will be a thing in the not too distant future.
Old answer:
It's not supported yet. The official answer is "use X if you need remote desktop access." You can login under X rather than Wayland by clicking on the settings gear on the login screen. There doesn't seem to be much work on this from GNOME as of yet, with little evidence other than a single initiative page.

A: Written by Michael Larabel in Wayland on 2 April 2013 at 04:12 AM EDT:

RDP Back-End Merged For Wayland's Weston Now having undergone six code
  revisions, the Weston Remote Desktop Protocol back-end has been
  merged.
This RDP back-end to Weston waits for RDP clients to connect and then
  sends frame-updates to these clients. Each RDP client has its own seat
  -- thereby being multi-seat friendly in Weston -- and frame updates can be done with surfaces or the RemoteFX codec. FreeRDP is in
  compliant with most of Microsoft's RDP 7.1 protocol.

Most distros have RDP-client software installed out-of-the-box or in their repositories so connecting should not be a problem.


text:
Q: How can sed be used, with variables names, without adding a trailing newline in macOS? I'm trying to make an index for a tex document. To make the process faster, I made a list of words in a CSV file named "idxprep.csv" that have in it the words to look for and the string to replace (the structure (dput (in R)) of the CSV is available at the end of the post). I'm on macOS Mojave 10.14.
Here is the script that I'm using to search and replace the words in the CSV into the tex file.
# This is just a variable that will raise slowly after changing the words
i=1
j=2 # this is the same as the one above, just that it refers to j=i+1

# This is the tex file in which there is the text to change.
PART="ttest.tex"

# Making a copy of the `tex` file and append a number to it (`i`) and adds `_ind.tex`
cp ~/Desktop/$PART ~/Desktop/${PART%.tex}.${i}_ind.tex

# get all the columns and rename them to use the columns in variables
while IFS="," read -r v1 v2 srch v4 v5 v6 rp remainder
do
    old=$srch
    new=$rp

 # this is to keep weird characters
    escOld=$(sed 's/[^^]/[&]/g; s/\^/\\^/g' <<< "$old")
 # this is to keep weird characters
    escNew=$(sed 's/[&/\]/\\&/g' <<< "$new")

 # This is the command to find/replace
    sed "s/$escOld/$escNew/g" ~/Desktop/${PART%.tex}.${i}_ind.tex >  ~/Desktop/${PART%.tex}.${j}_ind.tex

  ((i=i+1)) # increment both numbers
  ((j=j+1))

# Input the file
done < ~/Desktop/idxprep.csv

I have a .tex file called "ttest.tex" that contains this:
I think that this example won't involve Darwin's finches' nests, but it might talk about their adaptive radiation.

But the final output is this:
I think that this example won't involve Darwin's finches'\index{Darwin's finches}
 nests, but it might talk about their adaptive radiation\index{adaptive radiation}
.

Is there a way to have an output that doesn't contain newlines at the places where the words were replaced? Expect output:
I think that this example won't involve Darwin's finches'\index{Darwin's finches} nests, but it might talk about their adaptive radiation\index{adaptive radiation}.

Here is the CSV
structure(list(X7 = c(7L, 9L, 9L), X1 = c(2L, 1L, 2L), Darwin.s.finches. = structure(c(3L,
1L, 2L), .Label = c("adaptive radiation", "Adaptive radiation",
"Darwin's finches "), class = "factor"), X.index. = structure(c(1L,
1L, 1L), .Label = "\\index{", class = "factor"), Darwin.s.finches = structure(c(2L,
1L, 1L), .Label = c("adaptive radiation", "Darwin's finches"), class = "factor"),
    X. = structure(c(2L, 1L, 1L), .Label = c("}", "} "), class = "factor"),
    Darwin.s.finches..index.Darwin.s.finches. = structure(c(3L,
    1L, 2L), .Label = c("adaptive radiation\\index{adaptive radiation}",
    "Adaptive radiation\\index{adaptive radiation}", "Darwin's finches \\index{Darwin's finches} "
    ), class = "factor")), class = "data.frame", row.names = c(NA,
-3L))

Here is the raw CSV:
7,1,Darwin's finches',\index{,Darwin's finches,},Darwin's finches'\index{Darwin's finches}
7,2,Darwin's finches ,\index{,Darwin's finches,} ,Darwin's finches \index{Darwin's finches}
9,1,adaptive radiation,\index{,adaptive radiation,},adaptive radiation\index{adaptive radiation}
9,2,Adaptive radiation,\index{,adaptive radiation,},Adaptive radiation\index{adaptive radiation}


text:
Q: Easy Way to Add Closing Tags on HTML Document so XSLT can be Applied I am working on a system where I need to pass some HMTL through an XSLT transformation, but the HTML has a few header tags that don't have closing tags so it is not technically "well-formed" to be able to apply XSLT. Here are the tags:
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=9">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="bootstrap.min.css">
  <link rel="stylesheet" href="smartdoc.css">

Here is the issue, the documents that I am working with are downloaded to a server so I don't have direct access to simply open the file, in say notepad, and close the tags manually. What is the best way to go about closing those tags so that I can use the XSLT on them? Note I am using a Java library to run the XSLT transformation so I could potentially use something from Java to edit the HTML before applying the XSLT, but I am not sure what to use.

A: There is a Java version of HTML Tidy called JTidy that you could use to clean-up your HTML.
The JTidy How To Page shows an example use of their API:
Tidy tidy = new Tidy(); // obtain a new Tidy instance
tidy.setXHTML(boolean xhtml); // set desired config options using tidy setters
...                           // (equivalent to command line options)

tidy.parse(inputStream, System.out); // run tidy, providing an input and
                                     // output stream

A: I use tagsoup.
By the way, take a look at this thread : What are the pros and cons of the leading Java HTML parsers? [closed]


text:
Q: How to make default android Launcher I am trying to create a launcher application and I did it fine.
but there is a problem with my launcher:
When I choose it as default launcher for a device with pressing back button of device my launcher will disappear and last default launcher will appear!
this is my manifest:
<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity android:name=".MainActivity">
        <intent-filter>

            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.HOME" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.LAUNCHER" />

        </intent-filter>
    </activity>

    <activity android:name=".AppsListActivity"/>

</application>

Thank you for your help.

A: <activity
android:name="ah.hathi.simplelauncher.HomeActivity"
android:label="Simple Launcher Home"
android:theme="@android:style/Theme.Wallpaper.NoTitleBar.Fullscreen"
android:launchMode="singleTask"
android:stateNotNeeded="true"
>
<intent-filter>
  <action android:name="android.intent.action.MAIN" />
  <category android:name="android.intent.category.HOME" />
  <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

do it like this hope this will work for you


text:
Q: resume gnuscreen with split area When I'm in a gnu screen I can split horizontally (or vertically) and start a terminal session in the new region.  If I detach from this screen with Ctrl-a,d and then resume, now I just see the second region of the split in the entire window.  I know the first region is still there somewhere because if I type exit in the second region then the first session shows up and I can type exit again to actually close end the screen session.
How can I resume a screen with a split into regions and actually get my splits all visible at once?
An easy way to reproduce this issue:
$ screen -S splitresume
$ export PS1="region 1$ "
<Ctrl-a |>, <Ctrl-a TAB>, <Ctrl-a c>
$ export PS1="region 2$ "
<Ctrl-a d>
$ screen -r splitresume

At least on my system, after screen -r splitresume I only see the prompt with region 2$.  As I said above, If I exit that terminal session, I can now see the terminal with the regsion 1$ PS1.  I'd like to be able to resume and have the regions sredrawn in some visible space as well.
EDIT: I tried with the resize command, but the response from screen is just a complaint: resize: need more than one region.

A: See GNU Screen FAQ

When I split the display and then detach, screen forgets the split.
(The implied question being, "How do I keep my split windows over a detach?")
The short is answer is that you can't. The longer answer is that you can fake it. (Note: the next screen release, probably numbered 4.1.0, will be able to remember display layouts.)
Splits are a property of your display. The process managing your screen session doesn't really know about them; only the single process that's displaying the session does. Thus, the screen session can't remember the splits because it doesn't know about them, and once you detach, the process that did know about them has exited.
The hack is to use nested screen sessions. Start one session and give it some escape sequence that you won't use much (or just disable its escape character completely). Bind your usual detach key sequence to this screen session. Now, start or attach to your main screen session. All of your work will be done in the inner session, and you can split your display. When you detach, however, it will be the outer session that detaches, so your splits in the inner session will be preserved.
Assuming you use the default escape character, C-a, your alternate screenrc should contain:
escape ""
bindkey ^ad detach


text:
Q: Function to be run when value changes java After figuring out that i cannot autobox my own type, I am still stuck needing a value that automatically adjusts itself upon assignment. Would this work, or would it simply freeze? If it won't, then help would be appreciated.
while(true){
    if(x){
        y=z
    }
}

NOTE: It might help if I explained my class better, so here goes:
It is essentialy the same as an Integer, but it needs a max and a min value. I need so that when its value is > max, it starts back at min, and vice-versa.
example:
LoopInteger i = new LoopInteger(0, 3, 0); //min, max, value
i.setValue(5); //When this is run, i need it to set the value to 1, as it is two more than the max of 3
i.setValue(-2); //The same here, except now it has to be set to 2, as it is two less than the min of 0.

basically, it's and unsigned it with configurable max at least.

A: Well you could make something like that work (sort of) provided that it is written like this:
volatile boolean x;
...
while (true) {
   if (x) {
       y = z;
       break;
   }
}

(Note that you need to either declare x as volatile or use synchronized synchronization for this thread to reliably see updates to x made by another thread.)
However, this is a bad way of implementing this.  Essentially, a thread will be executing that loop continually until x is set to true.  That is going to tie down one of your cores using a lot of your system's memory bandwidth ... and draining your machine's battery.
A better way to do this is to make x private, and write its setter to notify the other thread when the variable is updated.
Or better yet, implement whatever you are trying to do using events / event listeners, or one of java.util.concurrent classes.  (It is hard to suggest which is best, because your example is too contrived ...)

A: I don't see any termination condition for your loop, therefore it will keep looping. I think you can do one of the two as below:

*

*Using break:
 while(true){
   if(x){
      y=z;
      break;
   }
}

*Using status flag:
 boolean found = false;
 while(!found){
   if(x){
      y=z;
      found = true;
   }
}

Also I would advice to put some time interval withing the loop e.g. 100 millisecond (Thread.sleep(100)); otherwise it will continuously loop unit x condition is met.


text:
Q: How to add custom labels in a Shield UI JavaScript line chart The code which I used for plotting the Shield UI line chart is shown below. On hovering over each dots, I am able to get the labels (Right/Wrong). But I need to show the labels (Right/Wrong) printed on the chart in place of data values like 4,0,1,2,3,4 etc.

$(function() {
  $("#chart").shieldChart({
    chartAreaBorderColor: '#E8E8E8',
    theme: 'dark',
    chartAreaBorderWidth: 1,
    primaryHeader: {
      text: "Quiz Attendance"
    },
    exportOptions: {
      image: false
    },
    seriesSettings: {
      line: {
        dataPointText: {
          enabled: true,
          style: {
            fontWeight: "bold"
          }
        }
      }
    },
    tooltipSettings: {
      customHeaderText: "Your answer was:",
      customPointText: function(point, chart) {
        return shield.format(
          '{value}', {
            value: point.pointName
          }
        );
      }
    },
    axisY: {
      min: 0,
      max: 4 // four levels max
    },
    axisX: {
      categoricalValues: ['Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8', 'Q9', 'Q10', 'Q11', 'Q12', 'Q13', 'Q14', 'Q15', 'Q16']
    },
    dataSeries: [{
      seriesType: 'line',
      color: "#FFD500",
      collectionAlias: 'Your quiz attendance',
      data: [{
        y: 4,
        pointName: "Right"
      }, {
        y: 0,
        pointName: "Right"
      }, {
        y: 1,
        pointName: "Right"
      }, {
        y: 2,
        pointName: "Right"
      }, {
        y: 3,
        pointName: "Right"
      }, {
        y: 4,
        pointName: "Right"
      }, {
        y: 3,
        pointName: "Wrong"
      }, {
        y: 2,
        pointName: "Wrong"
      }, {
        y: 1,
        pointName: "Wrong"
      }, {
        y: 0,
        pointName: "Wrong"
      }, {
        y: 1,
        pointName: "Right"
      }, {
        y: 2,
        pointName: "Right"
      }, {
        y: 3,
        pointName: "Right"
      }, {
        y: 4,
        pointName: "Right"
      }, {
        y: 4,
        pointName: "Right"
      }, {
        y: 3,
        pointName: "Wrong"
      }]
    }]
  });
});
<!DOCTYPE html>

  <meta charset=utf-8 />
  <title>Altoopa Research and Concepts Private Limited</title>
  <link id="themecss" rel="stylesheet" type="text/css" href="http://www.shieldui.com/shared/components/latest/css/light-bootstrap/all.min.css" />

A: You can use a format function or modify the text directly for any given point. More on this is available in the following topic:
https://www.shieldui.com/documentation/components/javascript/shieldui.chart/api/seriesSettings/line/dataPointText/format


text:
Q: How to open Word document from memory stream In our WPF application, we must create a Word document and open it automatically.
Today we ask the user to specify the file name and location BEFORE we create the document and them open the file using the Process.Start method.
Now, I want to create the Word document in memory stream, open it and eventually, when the user decides to save the document in Microsoft Word, he will have to specify the location and name. So I will not be using the SaveFileDialog in my app.
This is similar to when you start Microsoft Word. A default document is created and when you click save, you will guided to the "save as" function.
How can I do that?

A: I don't think you can do this purely on the memory stream.  However, I would save the memory stream to a temporary file, by saving to the Temp folder or AppData\temp or something like that with a randomly-generated name, and then mark that file as read-only.  Then open word on that file (with System.Diagnostics.Process or however you are doing it), and since it is read-only, it will ask the user to save changes when they exit.

A: Just programmatically create a new Word document using the standard Microsoft.Interop.Word .Net namespace:

*

*How to: Programmatically Create New Documents
Note that you might need to install MS-Office to do this.
Note, too, that your application can display it's own "Save As" dialog (or, for that matter, could just use a hard-coded path) independent of Word.  Your program chooses the path - and your program writes the Word document object if/when it's ready.
Finally, here's an alternative, open source library, DocX:

*

*http://www.codeproject.com/Articles/660478/Csharp-Create-and-Manipulate-Word-Documents-Progra

*How to: Open a word processing document from a stream (Open XML SDK)
ADDENDUM:
Thank you for your clarification:

*

*You're using the OpenXML SDK (as an alternative to .Net Interop or DocX libraries I mentioned above). You've already created an in-memory document object.

*Now you want the user to be able to open the document object in Word (presumably to review it), before saving it (to a filename of his/her own choosing).

*You can't (easily) do that :)

*One option, suggested by sovemp above:
a. OpenXML writes to a temp file (so it can be opened in Word)
b. Make the temp file read-only (to force the user to do an explicit "Save As")
c. Use .Net Process.Start() to invoke MSWord (specifying your temp file in your command line).

*Another option might be to use a "Preview Handler":

*

*http://www.codeproject.com/Articles/25465/Using-Vista-Preview-Handlers-in-a-WPF-Application

*https://previewhandlers.codeplex.com/

*Still another option might be to serve the memory stream in a web browser, using HTTP ContentType "application/msword" (for example)

*Finally, if all you want is for the user to specify a filename (if "preview" isn't essential), you can always pop up your own "Save as" dialog and write document to disk directly from OpenXML.


text:
Q: tensorflow:2.0.0- docker container unable to access to GPU Hi to everybody and thanks in advance.

My goal is to use a GPU enabled container to execute the notebooks of Hands on Machine Learning book (2nd edition). The idea is to use the GPU enabled container, maybe adding some imports and then committing to create a new image.
I checked the prerequisites as from https://github.com/NVIDIA/nvidia-docker/wiki/Installation-(version-2.0).

O.S. Ubuntu 18.04
Processor: Intel® Core™ i7-7700HQ CPU @ 2.80GHz × 8
Graphic card: GeForce GTX 1080/PCIe/SSE2
NVIDIA-SMI 418.87.00 and the graphic card is recognized,
docker Version:           19.03.5 API version:       1.40,
nvidia-docker2 is already the newest version (2.2.2-1),
nvidia-docker (the old version) is not present,
Executing:
docker pull tensorflow/tensorflow:2.0.0-gpu-py3-jupyter

docker run -u $(id -u):$(id -g) -it --rm -v $(realpath ~/Projects/GDL/GDL_code):/tf/notebooks -p 8888:8888 tensorflow/tensorflow:2.0.0-gpu-py3-jupyter

the container starts regularly and I can use the the notebooks, but with no GPU support...
import tensorflow as tf
from tensorflow.python.client import device_lib

only the CPU is recognized...
I'm probably missing something of obvious ... I'm a newbie with docker and tensorflow...
Any help is appreciated!

A: Sorry, missing --runtime=nvidia ...
docker run --runtime=nvidia -u $(id -u):$(id -g) -it --rm -v $(realpath ~/Projects/GDL/GDL_code):/tf/notebooks -p 8888:8888 tensorflow/tensorflow:2.0.0-gpu-py3-jupyter
Thanks anyway to everybody!


text:
Q: migration errors for project using django-csvimport I am having trouble moving my Django 1.11 app to production.
There's another question that looks like a similar issue, but I am unable to make the answers suggested in the comments work as desired:
Django import errors for app csvimport
if I comment out the code in settings.py to remove the django-csvimport library stuff like so:
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
   # 'csvimport.app.CSVImportConf',
    'custom_app_name',

]

then my migrations work fine, and the app runs(sans csvimport app).  Then if I comment the csvimport APP line back in and run the migrations, they fail with the following:
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, csvimport, sessions, custom_app_name
Running migrations:
  Applying csvimport.0002_test_models...Traceback (most recent call last):
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: syntax error at or near "csvtests_country"
LINE 1: ...CONSTRAINT "csvtests_item_country_id_5f8b06b9_fk_"csvtests_c...
                                                             ^

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 93, in __exit__
    self.execute(sql)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 120, in execute
    cursor.execute(sql, params)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 80, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: syntax error at or near "csvtests_country"
LINE 1: ...CONSTRAINT "csvtests_item_country_id_5f8b06b9_fk_"csvtests_c...

Any advice would be very helpful.
Thanks!

A: So I was able to fix this issue based on the stack trace error which read:
django.db.utils.ProgrammingError: syntax error at or near
"csvtests_country"
LINE 1: ...CONSTRAINT "csvtests_item_country_id_5f8b06b9_fk_"csvtests_c...

The issue was that there was a piece of generated code which added double quotes inside of single quotes, like so:
 options={
                'managed': True,
                'db_table': '"csvtests_country"',
            },

To find the migration I went to my virtual environment's python install:
django_env/lib/python3.4/site-packages/csvimport/migrations/

and removed the double quotes based on the fact that none of the other 'db_table' : 'sometable_name' calls used double-quotes.  I guess this is a bug that I'll be reporting to the csvimport github page. I will post any updates to this question if I find more information.
Hopefully this helps someone in a similar situation.
Thanks!

UPDATE:
I did not see this in the issue list from the csvimport github page before. It appears to be a known bug:
https://github.com/edcrewe/django-csvimport/issues/77


text:
Q: Bar graphs with different range bars I have the following bar graph -

*

*Is it ok to have bars of different ranges or is it misleading? For example, the range of the first bar is 0-10M. The range of the last bar is 500M - $1B. The person who made this told me they did it this way because our data is skewed but is this ok to do or will it be misleading the end user?

*If it is misleading, is there a better way to plot this?


text:
Q: Serial upvoting reversed: I lost 0 reputation Some goofball has been serial upvoting me for the past two days, and while I've sent out hunting parties to find the miscreant and taze him bro until he quits, I did notice an extreme oddity:
When the serial upvoting was reversed, instead of losing the 90-100 rep I was expecting to lose, I lost zero.

I know that I didn't actually lose any rep, since before "Serial upvoting reversed" I had 40,119 reputation, and now I have 40,179 reputation after having had six answers upvoted afterward.

A: In the same way as the upvotes you received after hitting the rep cap on the previous day don't show up with a zero, neither does the reversal.
It's consistent with any action that doesn't really affect your reputation. It makes more sense to me to leave it blank rather than placing a zero there saying:

"You've lost/gained 0 reputation"

A: The day you got serially upvoted (yesterday - 28-06-2013), your reputation was 232; 200 from regular upvotes, 2 accepted answers and 2 reputation from accepting an answer. You hit the daily rep cap. After this happened, somebody started serially upvoting you; so, you didn't earn a single reputation point from those upvotes.
The automated script, having detected such serial voting, simply reversed all the upvotes. As you hadn't earned any reputation from the serial upvotes, you didn't lose anything when the action was reversed.
Disclaimer: I am saying all of this by looking at your profile.


text:
Q: Understanding a piece of code from the OpenGL Red Book I am completely new to OpenGL and graphics programming in general and so I quickly picked up the OpenGL Red Book. I have just started reading but I can't understand the following piece of code. This probably has something to do with me not being very familiar with the C++ enums, but how can we use NumVAOs and NumBuffers when declaring the GLuint arrays? Doesn't this make two 1 element arrays? Is there any reason that they are declared like this?
Here is the code:
#include <iostream>
using namespace std;
#include "vgl.h"
#include "LoadShaders.h"
enum VAO_IDs { Triangles, NumVAOs };
enum Buffer_IDs { ArrayBuffer, NumBuffers };
enum Attrib_IDs { vPosition = 0 };
GLuint VAOs[NumVAOs];
GLuint Buffers[NumBuffers];
const GLuint NumVertices = 6;

A: The idea behind this is that taking for example
enum VAO_IDs { Triangles, NumVAOs };
That when you need more VAOs you add the id's for them before NumVAOs which will cause NumVAOs to always have as a value the number of VAO's you are using.
Thought I do not see why you would want to structure your code this way but maybe that becomes clear later in the book.


text:
Q: Unity C# - for loop: go from one object to the next one (movement) - gets stuck on first object What I have
Scenario where a sphere moves towards a cube. There are multiple cubes. I want it to go to 1 cube that is within sight, and when it reached the cube, I want it to search for the next one. I know this should be easy but I've tried to fix this for several hours.
Code
WithinSight.cs
using UnityEngine;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;

public class WithinSight : Conditional {

    public float fieldOfViewAngle;
    public string targetTag;
    public SharedTransform target;

    private Transform[] possibleTargets;

    public override void OnAwake() {
        var targets = GameObject.FindGameObjectsWithTag (targetTag);
        possibleTargets = new Transform[targets.Length];
        for (int i = 0; i < targets.Length; ++i) {
            possibleTargets [i] = targets [i].transform;
        }
    }

    public override TaskStatus OnUpdate() {
        for (int i = 0; i < possibleTargets.Length; ++i) {
            if (withinSight(possibleTargets [i], fieldOfViewAngle)) {
                target.Value = possibleTargets [i];
                return TaskStatus.Success;
                gameObject.tag = "Untagged";
            }
        }
        return TaskStatus.Failure;
    }

    public bool withinSight(Transform targetTransform, float fieldOfViewAngle) {
        Vector3 direction = targetTransform.position - transform.position;
        return Vector3.Angle(direction, transform.forward) < fieldOfViewAngle;
    }

}

MoveTowards.cs
using UnityEngine;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;

public class MoveTowards : Action {

    public float speed = 0;
    public SharedTransform target;
    private bool pietje;

    void PrintMessage (string message) {
        Debug.Log(message);
    }

    void Start() {
        pietje = false;
    }

    public override TaskStatus OnUpdate() {

        if (Vector3.SqrMagnitude (transform.position - target.Value.position) < 0.1f && !pietje) {
            PrintMessage ("Found the cube.");
            pietje = true;
            if (pietje) {
                PrintMessage ("Searching...");
                pietje = false;
            }
            return TaskStatus.Success;
        }

        transform.position = Vector3.MoveTowards (transform.position, target.Value.position, speed * Time.deltaTime);
        transform.LookAt (target.Value.position);
        return TaskStatus.Running;

    }
}

Anyone that can help me will get a virtual cookie! (hmmm...)

A: I think the error is OnUpdate() in WithinSight class. When you do the return it never does this gameObject.tag = "Untagged";
Change the order of the lines like this.
public override TaskStatus OnUpdate() {
    for (int i = 0; i < possibleTargets.Length; ++i) {
        if (withinSight(possibleTargets [i], fieldOfViewAngle)) {
            target.Value = possibleTargets [i];
            gameObject.tag = "Untagged";
            return TaskStatus.Success;
        }
    }
    return TaskStatus.Failure;
}

I can't reproduce this scenario, but this code won´t go back to a previuos cube. In case you want that you should save a reference of the last cube the sphere moved towards and do the comparisons in OnUpdate() of WithinSight.


text:
Q: How to add "static" block at the end of screen? I have one editText field, one scroolView field in which there is linearLayout field, which has a lot of elements which are generated programatically, and then I want to add static linear layout field (advert), which would show up at the end of the screen. The problem is that my scrollView takes all of the space in screen, so linearLayout with its content doesn't show up. Also, I have to make sure that if advert is hidden (programatically), then scrollView takes all of available space on the screen. To illustrate this better, here is the xml code:
<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="3dp"
    xmlns:android="http://schemas.android.com/apk/res/android">

    // first field: editText - everythings good here
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:ems="10"
        android:id="@+id/etInput"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:hint="@string/hint" />

    // second field: scrollView. It chews up a lot of space (height wise) since linearLayout is huge.
    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/scrollView"
        android:layout_below="@+id/etInput"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <LinearLayout
            android:orientation="vertical"
            android:id="@+id/lLayout"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_below="@+id/scrollView"
            android:layout_toRightOf="@+id/scrollView" />
    </ScrollView>

    // third field (advert): linearLayout. I want this to be added at the bottom of the screen.
    <LinearLayout
        android:orientation="vertical"
        android:id="@+id/advert"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/scrollView"
        android:layout_toRightOf="@+id/scrollView">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:id="@+id/textView"
            android:layout_gravity="center_horizontal" />
    </LinearLayout>
</RelativeLayout>

A: to ScrollView add
layoutAbove="@+id/advert"

EDIT
Circular dependency because in your advert you are referencing the scrollview
All you need is advert at the bottom of screen.
<ScrollView
    android:id="@+id/scrollView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/etInput"
    android:layout_above="@+id/advert">

    <LinearLayout
        android:id="@+id/lLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" />
</ScrollView>
// third field (advert): linearLayout. I want this to be added at the bottom of the screen.

<LinearLayout
    android:id="@+id/advert"
    android:layout_alignParentBottom="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="New Text" />
</LinearLayout>

When you want to remove the advert, set visibility to invisible so the view is not removed and scrollview stays always above the advert

A: You can play with margins programatically
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
//when you want to show linearlayout
    params.bottomMargin = the height of linear layout;
//when you don't
  params.bottomMargin = 0;
scrollVIew.setlayoutparams(params);

or just use ListView and set the linearlayout as a FooterView of the list

A: You are messing up some stuff.
When you have a fixed block, you should start by placing that block and position everything else relative to that.
So that is untested but might work:
<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="3dp"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- I am at the BOTTOM! -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView"
        android:layout_alignParentBottom="true"
        android:layout_gravity="center_horizontal" />

    <!-- I am at the TOP! -->
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:ems="10"
        android:id="@+id/etInput"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:hint="@string/hint" />

    <!-- and now lets place the scrollview between textview and edittext -->
    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/scrollView"
        android:layout_below="@+id/etInput"
        android:layout_above="@+id/textView>
        <LinearLayout
            android:orientation="vertical"
            android:id="@+id/lLayout"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
    </ScrollView>
</RelativeLayout>

When you really need your LinearLayout at the bottom (if you want to add more there) just wrap the TextView with a LinearLayout put the layout_alignParentBottom into the LinearLayout and modify the layout_below id of the ScrollView to fit the one from the LinearLayout


text:
Q: how to fetch N most recent items but sort them in ascending order using NSFetchRequest I am trying to create an NSFetchRequest to fetch the most recent 80 items from my entity and sort them in ascending order.
Is it possible to achieve this in one request?  Currently I am doing two requests.  One to get the date of the most recent item offset by 80 and then using that date in the second request.
What I want to achieve is:
let request:NSFetchRequest<Item> = Item.fetchRequest()

let sort = NSSortDescriptor(key: "itemTimestamp", ascending: false)
request.sortDescriptors = [sort]

request.predicate = NSPredicate(format: "itemGroupId == %@", self.itemGroupId)

request.fetchLimit = 80

// add logic to sort the returned results in ascending: true


text:
Q: Sum Data of the Same Column in Spotfire I wanted to sum up all values of the same column.
Some example data:
Amount
2
3
4

I want to get the value of 9.
I used Sum([Amount]) but it is not working.
Any help is greatly appreciated.


text:
Q: Best wopt options for large rasters What are the best wopt and gdal options when processing large rasters with terra::?
I want to match a raster stack (2.5arcmin) with a raster that has a much higher resolution (500*500m). Workflow: disaggregate as close as possible, then resample and finally mask. This works, but the output tif is > 100gb and the process takes forever.
r <- rast("rasterstack_004166deg.tif")
r_template <- rast("rasterstack_000449deg.tif")

wopt_options <- list(gdal = c("BIGTIFF=YES",
                              "PREDICTOR = 2",
                              "NUM_THREADS = ALL_CPUS"),
                     tempdir = "/somewhere_I_have_a_lot_of_space",
                     todisk = TRUE)

r_processed <- disaggregate(r, fact = 9) %>%
  resample(., r_template) %>%
  mask(., r_template,
       filename = "outputfile.tif",
       wopt = wopt_options)

Should the wopt_options be placed inside terra::disaggregate() and terra::resample() as well? Is there any way to reduce the file size and speed up the process?
I also tried the following gdal options gdal=c("COMPRESS=DEFLATE", "TFW=YES") or gdal=c("COMPRESS=LZW", "TFW=YES"), but nothing really changed. Also tried without any gdal options.
In addition, I also did this with raster::projectRaster() function (used disaggregated r) which was much faster and the outputfile.tif was much smaller. However, I guess I should avoid using projecRaster() here:
beginCluster()
r_processed<-
  projectRaster(stack(r_disaggregated),
                raster(r_template),
                filename = "outputfile.tif")
endCluster()

The r raster looks like this:

A: Here are some comments that may be of help. The default behavior of terra is to set BIGTIFF to true when necessary, so you normally do not need to specify that. Also by default, LZW compression is used so you should see a difference if you set compression to NONE.
To set the tempdir, use
terraOptions(tempdir="/somewhere_I_have_a_lot_of_space")`
terraOptions()
#memfrac   : 0.6
#tempdir   : /somewhere_I_have_a_lot_of_space

You should not set todisk=TRUE, that is for debugging only.
Now we have
x <- disaggregate(r, fact = 9)
y <- resample(x, r_template)
z <- mask(y, r, filename="outputfile.tif", wopt=wopt_options)

I split it because that is easier to read and debug. You were masking with r_template but that should be with r. If you wanted to use the options at all three steps, you would need to use the wopt argument each time, not just the last time.
Can you show(r) so that I can make a reproducible example?
I am assuming the problem is with resample because that is implemented a bit differently but this may have improved with the development version. You can install it like this:
install.packages('terra', repos='https://rspatial.r-universe.dev')


text:
Q: Creating a grid layout that holds 100 buttons with 80 empty buttons and 20 random treasure buttons We are working on a Treasure Hunt game in class as a project. Below is the code that we have so far.
I need to randomize where the Treasure Buttons are.
My question is:
Do I need to create an array that will hold EmptyButton and TreasureButton and then call Random on it or is there a way to create a random layout within the TreasureButton class?
Here is our code so far
public class TreasureGame
{
    // has-a number of tries
    private int numberOfTriesLeft = 50;
    //has-a number of hidden treasure
    private int numberStillHidden = 20;
    // Purpose: Subtract 1 try for every attempt taken by the player
    public void reduceTriesLeft()
    {
        numberOfTriesLeft -= 1;
    }

    public void reduceNumberStillHidden()
    {
        numberStillHidden -=1;
    }

    public int getNumberStillHidden()
    {
        return numberStillHidden;
    }

    public int getNumberOfTriesLeft()
    {
        return numberOfTriesLeft;
    }
}

import java.awt.*;
import javax.swing.*;
import java.util.Random;
public class TreasureGameView extends JFrame
{
    // has-a TreasureGame
    private TreasureGame treasureGame;
    //has-a triesLeftField
    private JTextField triesLeftField;
    //has-a treasures left field
    private JTextField treasuresLeftField;
    private JTextField lastMoveField;

    public TreasureGameView(TreasureGame newTreasureGame)
    {
        treasureGame = newTreasureGame;
        setTitle("Treasure Hunt");
        setSize(800, 500);
        setLayout(new BorderLayout());

        JPanel gridPanel = new JPanel();
        gridPanel.setLayout(new GridLayout(10, 10));
        add(gridPanel, BorderLayout.CENTER);

        for(int counter=0; counter<treasureGame.getNumberStillHidden(); counter++)
        {

            gridPanel.add(new TreasureButton(treasureGame, this));

        }
        for(int counter=0; counter<(10*10)-treasureGame.getNumberStillHidden(); counter++)
        {

            gridPanel.add(new EmptyButton(treasureGame, this));
        }

        JPanel triesLeftPanel = new JPanel();

        JLabel triesLeftLabel = new JLabel("Tries left:");
        triesLeftPanel.add(triesLeftLabel);
        triesLeftField = new JTextField("" + treasureGame.getNumberOfTriesLeft());
        triesLeftPanel.add(triesLeftField);
        JLabel treasuresLeftLabel = new JLabel("Treasures left:");
        triesLeftPanel.add(treasuresLeftLabel);
        treasuresLeftField = new JTextField("" + treasureGame.getNumberStillHidden());
        triesLeftPanel.add(treasuresLeftField);

        add(triesLeftPanel, BorderLayout.WEST);

        JPanel lastMovePanel = new JPanel();
        JLabel lastMoveLabel = new JLabel("Your last move was: ");
        lastMovePanel.add(lastMoveLabel);
        lastMoveField = new JTextField("" );
        lastMovePanel.add(lastMoveField);
        add(lastMovePanel, BorderLayout.SOUTH);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    //Purpose; Update Value of triesLeftField
    public void updateUI()
    {
        triesLeftField.setText("" + treasureGame.getNumberOfTriesLeft());
        treasuresLeftField.setText("" + treasureGame.getNumberStillHidden());
    }
}

import javax.swing.*;
public class EmptyButton extends JButton
{
    //has-a TreasureGame
    private TreasureGame game;

    //has-a TreasureGameView
    private TreasureGameView gameView;
    public EmptyButton(TreasureGame game, TreasureGameView gameView)
    {
        super();
        this.game = game;
        this.gameView = gameView;
        //setText("?");
        addActionListener(new EmptyButtonListener(this, game, gameView));
    }
}

public class TreasureButton extends EmptyButton
{
   public TreasureButton(TreasureGame game, TreasureGameView gameView)
   {
       super(game, gameView);

       //setText("T");
       addActionListener(new TreasureButtonListener(this, game, gameView));
   }

}

import java.awt.event.*;
public class EmptyButtonListener implements ActionListener
{
    private EmptyButton button;
    //has-a TreasureGame
    private TreasureGame  game;
    //has-a TreasureGameView
    private TreasureGameView gameView;

    public EmptyButtonListener(EmptyButton button, TreasureGame game, TreasureGameView gameView)
    {
        this.game = game;
        this.button = button;
        this.gameView = gameView;
    }

    public void actionPerformed(ActionEvent e)
    {
        //button.setText("X");
        button.setEnabled(false);
        game.reduceTriesLeft();
        gameView.updateUI();
    }
}

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TreasureButtonListener implements ActionListener
{
    // Has-a TreasureButton
    private TreasureButton button;
    private TreasureGame game;
    private TreasureGameView gameView;

    public TreasureButtonListener(TreasureButton button, TreasureGame game, TreasureGameView gameView)
    {
        this.button = button;
        this.game = game;
        this.gameView = gameView;
    }

    public void actionPerformed(ActionEvent e)
    {
        button.setText("$");
        game.reduceNumberStillHidden();
        gameView.updateUI();
    }
}

A: You have to think in terms of MVC.
First create a model for your treasure. This could be an array of class Field. .
A field would represent weather it has a treasure and a state (eg. revealed)
Populate the array with the fields from which 20 are representing an treasure.
Shuffle the array.
Your view will then iterate over the array and represents the model in a user friendly way. For ease you can pass the field instance to your button to manipulate the field state in your actionlistener.

A: The answer is mostly opinion based. Better to maintain a List<Buttons> buttons and store both empty and TreasureButton inside it. Whenever you need to randomize it, use Collections.shuffle(buttons) to shuffle. As the action remains same you don't need to create button every time. Just shuffle it and display in grid by iteration that list.


text:
Q: Explicity enable cache in Django by function/endpoint but not site wide Our Django application is quite big, and it has reached the point where Caching in certain parts will improve a lot the performance.
However, when we enable caching it will do site wise, and so some endpoints are failing for different reasons.
Our ideal solution therefore would be to have cache by explicitly setting it by function or rest api endpoint, and all the rest disable by default.
In order to enable it we could just use the decorator:
@cache_page

The problem is that I cannot get the default cache to be disabled, I tried these different options but non of them seem to work.
CACHES = {
    'manual': {
        'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

--
CACHES = {
    'default': {},
    'manual': {
        'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

--
CACHES = {
    'default': None,
    'manual': {
        'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
        'LOCATION': '127.0.0.1:11211',
    }
}


text:
Q: C++ Strange Access Violation with OpenGL I'm pretty new to C++ so I hope I can get some help here.
I try to port my Game Engine to C++ but C++ behaves a litle bit... "Strange".
Following Situation:
if I run test1() It all works as it should.
main.cpp
#include <iostream>

#include "../headers/base.h"

#include "../headers/DemoGame.h"
#include "../headers/TestShader.h"

using namespace std;
using namespace engine;

void run(TestShader* t, GLuint VAO, GLFWwindow* w)
{
    glfwPollEvents();

    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(t->progID);
    glBindVertexArray(VAO);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glBindVertexArray(0);

    glfwSwapBuffers(w);
}

void test1()
{
    Window w = Window(800, 600, "test");
    TestShader t = TestShader();
    GLuint VAO, VBO;

    GLfloat vertices[9] = {
        -0.5f, -0.5f, 0.0f,
        0.5f, -0.5f, 0.0f,
        0.0f,  0.5f, 0.0f
    };

    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);

    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glBindVertexArray(0);

    while (!glfwWindowShouldClose(w.getWindow()))
    {
        run(&t, VAO, w.getWindow());
    }

}

void test2()
{
    DemoGame game = DemoGame();
    game.start();
}

int main()
{

    test1();

    return 0;
}

If i'm running test2() with following involved classes:
Engine.h
#pragma once

#ifndef H_ENGINE
#define H_ENGINE

#include "base.h"

namespace engine
{
    class Engine
    {
        private:
            bool running;

        public:
            void start()
            {
                init();
                process();
            }

            void stop()
            {
                this->running = false;
            }

        private:
            void process()
            {
                update();
            }

        public:
            virtual void init() = 0;
            virtual void update() = 0;
            virtual void render() = 0;
            virtual void terminate() = 0;
    };
}

#endif

DemoGame.h
#pragma once

#ifndef DEMO_DEMO_GAME
#define DEMO_DEMO_GAME

#include "base.h"

#include "Window.h"
#include "Engine.h"
#include "TestShader.h"

using namespace engine;

class DemoGame : public Engine
{

    public:
        Window* w;
        TestShader* t;

        GLuint VBO, VAO;

    public:
        DemoGame() : Engine() { }

    public:
        void init();

        void update();

        void render();

        void terminate();
};

#endif

DemoGame.cpp
#include "../headers/DemoGame.h"
#include <iostream>

using namespace std;

void DemoGame::init()
{
    cout << "ping" << endl;

    Window wi = Window(800, 600, "test");
    w = &wi;
    TestShader te = TestShader();
    t = &te;

    GLfloat vertices[9] = {
        -0.5f, -0.5f, 0.0f,
        0.5f, -0.5f, 0.0f,
        0.0f,  0.5f, 0.0f
    };

    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);

    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glBindVertexArray(0);

    while (!glfwWindowShouldClose(w->getWindow()))
    {
        render();
    }
}

void DemoGame::update()
{

}

void DemoGame::render()
{
    glfwPollEvents();

    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(t->progID);
    glBindVertexArray(VAO);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glBindVertexArray(0);

    glfwSwapBuffers(w->getWindow());
}

void DemoGame::terminate()
{

}

It works aswell. But as you may see Engine.h is supposed to control the mainloop. If I change the code a little bit:
Engine.h
#pragma once

#ifndef H_ENGINE
#define H_ENGINE

#include "base.h"

namespace engine
{
    class Engine
    {
        private:
            bool running;

        public:
            void start()
            {
                init();

                running = true;

                while (running)
                {
                    process();
                }

            }

            void stop()
            {
                this->running = false;
            }

        private:
            void process()
            {
                update();
            }

        public:
            virtual void init() = 0;
            virtual void update() = 0;
            virtual void render() = 0;
            virtual void terminate() = 0;
    };
}

#endif

DemoGame.cpp
#include "../headers/DemoGame.h"
#include <iostream>

using namespace std;

void DemoGame::init()
{
    cout << "ping" << endl;

    Window wi = Window(800, 600, "test");
    w = &wi;
    TestShader te = TestShader();
    t = &te;

    GLfloat vertices[9] = {
        -0.5f, -0.5f, 0.0f,
        0.5f, -0.5f, 0.0f,
        0.0f,  0.5f, 0.0f
    };

    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);

    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glBindVertexArray(0);

}

void DemoGame::update()
{
    render();
}

void DemoGame::render()
{
    glfwPollEvents();

    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(t->progID);
    glBindVertexArray(VAO);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glBindVertexArray(0);

    glfwSwapBuffers(w->getWindow());
}

void DemoGame::terminate()
{

}

Now all of a sudden I get an "Access Violation". The question is why?
The file "base.h" just contains
#define GLEW_STATIC
#include "GL/glew.h"
#include "GLFW/glfw3.h"

and the classes Window and TestShader shouldn't matter because they work in the first two examples. As I stated before I'm pretty new to C++ and I just don't understand why that doesn't work. Can you please help me finding out at least why that doesn't work or better help me solving the problem.
This is my second attempt to get a useful answer from StackOverflow by posting a question. Please do me a favour. Please consider read the situation before you mark this question an duplicate. The last time it wasn't an duplicate the problem was by far different.
Edit
As requested the Error message(sry I'm at work so the language is german)

Ausnahme ausgelöst bei 0x0126489D in GLFWGame.exe: 0xC0000005:
  Zugriffsverletzung beim Lesen an Position 0xCCCCCEA4.
Falls ein Handler für diese Ausnahme vorhanden ist, kann das Programm
  möglicherweise weiterhin sicher ausgeführt werden.

And I'll try to shorten the code to the most important.

A: You store addresses of stack objects that get deleted. For example,
Window wi = Window(800, 600, "test");
w = &wi;

Creates a local variable wi on the stack, which gets deleted automatically when it goes out of scope (which is the case at the end of the function). After that, w will point to an address that is already freed, which will lead to big troubles when you try to access this variables later on as you do here:
glfwSwapBuffers(w->getWindow());

If you want to create the window object on the heap, you have to use the following code in DemoGame::init():
w = new Window(800, 600, "test");

Don't forget to delete this object manually by calling delete w when you don't need it anymore. The same problem also occures for the TestShader instance.
Side note: Window wi = Window(800, 600, "test"); is still a strange syntax when creating objects on the stack. The correct way would be Window wi(800, 600, "test"); Have a look at this posts for why this makes a difference: Calling constructors in c++ without new
Edit: Your first example just works because you are calling the render function inside the init function, thus the objects do not get out of scope. Storing pointers to local object is still not good practice.

A: Your problem is here:
Window wi = Window(800, 600, "test");
w = &wi;
TestShader te = TestShader();
t = &te;

Both, the instance of Window as well as the instance of TestShader are local variables that will get cleaned up as soon as they go out of scope (end of init) and hence remembering their addresses has no meaning. You will need to create those instances dynamically (new) or set them up within your class definition.


text:
Q: How do I open a window as a modal dialog in MonoMac using C#? I am developing a Cocoa application with MonoMac (C#).
I have a class MyWindowController that inherits MonoMac.AppKit.NSWindowController, and open a new instance of this window like this:
MyWindowController mwc = new MyWindowController();
mwc.Window.MakeKeyAndOrderFront(this);

But how do I open it as a modal dialog? It is imperative that nothing else in my application is executed while the dialog is open, so I cannot use a window sheet (which only blocks the current window). And I can't find anything else that seems to do what I want on my controller. On Windows, I would have done this simply by calling:
mwc.ShowDialog();

So what I want is the MonoMac equivalent of ShowDialog(), I believe.

A: I spent almost three hours trying to figure this out before posting the question, but of course I found the solution right after asking.
It looks like I need to use the NSApplication object:
NSApplication.SharedApplication.RunModalForWindow(ewc.Window);

A: I had success with the answer above, but then had trouble dismissing the modal in the case that the 'close' button was pressed. The solution was to add the code
[Export ("windowWillClose:")]
    public void WindowWillClose(NSNotification notification)
    {
        Console.WriteLine("windowWillClose:");
        NSApplication.SharedApplication.StopModal ();
    }

to the window controller, then set the window controller to be the window's delegate by, in Interface Builder, right-click the window and drag a line from "delegate" to the "file's owner" block.


text:
Q: Как можно реализовать функцию опроса в приложении? Делаю приложение пытаюсь все сделать классно, но встрял с разработкой алгоритма(скорее всего из-за неопотности). В чем суть, есть класс в нем функция которая должна выводить из переданного массива вопросы и ответы из другого, потом ставит обработчики нажатий (у меня есть заготовка), потом ждет нажатия кнопки и переходит на следующий вопрос.
Имена кнопок и т.д (все передано в класс)
QuestionField - поле для вопроса
AnswerField1 - вариант ответа1
AnswerField1 - вариант ответа2
AnswerField1 - вариант ответа3
questions - массив вопросов
answers - массив ответов
Заранее спасибо.

A: Массивы и прочие элементы:
String[] questions = {"вопрос1", "вопрос2", "вопрос3"};

//массив правильных ответов
String[] true_answers = {"ответ1", "ответ2", "ответ3"};

//массив ответов пользователя (значения меняются при ответах)
String[] user_answers = {" ", " ", " "};

//варианты ответа
Button AnswerField1, AnswerField2, AnswerField3;

TextView QuestionField;

Реализовать переход по вопросам можно вот так:
//получаем длину массивов
int Answers_length = answers.length;
int Questions_length = questions.length;

//переменная хранит текущий вопрос и обновляется после нажатия на кнопку ответа
int this_question = -1

//действия при нажатии на кнопку ответа
this_question++;
QuestionField.setText(questions[this_question]);
//если нажата правильная кнопка - в ячейку будет записан правильный ответ
user_answers[this_question] = "Вариант ответа";

Проверка ответов:
for (int i = 0; i < Answers_length; i++) {
     if(user_answers[i].equals(true_answers[i])){
          //какой-либо метод записи верно/неверно, можно снова с массив
     }
}

Надеюсь, смог хоть чем-то помочь, или хотя бы подкинул идею :)


text:
Q: host website using IIS 8.5 and windows 8.1 I am using .Net framework 4.5 and my OS is Windows 8.1, 64-bit. My IIS is 8.5. I am trying to host my web application but I am unsuccessful. I have tried this from VS 2010 by selecting USE LOCAL IIS WEB SERVER but when I click CREATE VIRTUAL DIRECTORY, these messages came:
configuring web http //localhost/ForIIS for asp.net 4.0 failed. You must manually configure this site for asp.net 4.0 in order for the site to run correctly. ASP.Net 4.0 has not been registered on the web server. you need to manually configure your web server for asp.net 4.0 in order for your site to run correctly.
then next pop-up was:
The virtual directory was created successfully.
But when I go to IIS I can see my application under Default Web Site and when I click browse, in the browser I get this error:
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

*

*Error Code: 0x80070021

*Config Error: This configuration section cannot be used at this path.
This happens when the section is locked at a parent level. Locking is
either by default (overrideModeDefault="Deny"), or set explicitly by
a location tag with overrideMode="Deny" or the legacy
allowOverride="false".

*Config File:\?\C:\Users\Ansar\Documents\VisualStudio2010\Projects\ForIIS\ForIIS\web.config

Also in my IIS when I click Add Application Pool I get dropdown .NET CLR Versions and its items as
.NET CLR Versions v4.0.30319, .NET CLR Versions v2.0.50727, No Managed Code.
But when I see other system who is having other OS I can see their dropdown as
.NET Framework Versions and dropdown items as .NET Framework v4.0.30319 etc.
I think the problem is because of windows 8.1 or IIS 8.5 whatever but I have Googled many times but I am not able to host my website. I have also run aspnet_regiis from folder C:\Windows\Microsoft.NET\Framework\v4.0.30319. but nothing happened.
I have also tried creating virtual directory for my website directly from IIS but I get the same error in browser.


text:
Q: Swift httppost data not inserting to MySQL database I am trying to send data to php and insert it to mysql database but it doesn't seem to work. I have tried sending data to php just to encode it to json and echo it back to swift and it returns a result so it means that the php file received the data. However inserting the data is not working.
swift2 httppost
func post() {

    let myUrl = NSURL(string: "http://localhost:8080/json/json.php");
    let request = NSMutableURLRequest(URL:myUrl!);
    request.HTTPMethod = "POST"
    // Compose a query string
    let postString = "firstName=James&lastName=Bond";

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil
        {
            print("error=\(error)")
            return
        }

        // You can print out response object
        print("response = \(response)")

        // Print out response body
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")

        //Let's convert response sent from a server side script to a NSDictionary object:

        do{

            let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary

            if let parseJSON = myJSON {
                // Now we can access value of First Name by its key
                let firstNameValue = parseJSON["firstName"] as? String
                print("firstNameValue: \(firstNameValue)")
            }

        }catch let error as NSError {
            print("JSON Error: \(error.localizedDescription)")
        }

    }

    task.resume()

}

json.php
<?php
// Read request parameters
$firstName= $_REQUEST["firstName"];
$lastName = $_REQUEST["lastName"];// Store values in an array

$conn = mysqli("localhost", "root", "root", "notify");

$query = mysqli_query($conn, "INSERT INTO user values('', '$firstName',
'$lastName')");

 ?>

A: If having the server just echo the request works, then the problem rests within the server, not the client code. I would suggest adding some error handling in the PHP code:
<?php

// specify that this will return JSON

header('Content-type: application/json');

// open database

$con = mysqli_connect("localhost","user","password","notify");

// Check connection

if (mysqli_connect_errno()) {
    echo json_encode(array("success" => false, "message" => mysqli_connect_error(), "sqlerrno" => mysqli_connect_errno()));
    exit;
}

// get the parameters

$field1 = mysqli_real_escape_string($con, $_REQUEST["firstName"]);
$field2 = mysqli_real_escape_string($con, $_REQUEST["lastName"]);

// perform the insert

$sql = "INSERT INTO user (first_name, last_name) VALUES ('{$field1}', '{$field2}')";

if (!mysqli_query($con, $sql)) {
    $response = array("success" => false, "message" => mysqli_error($con), "sqlerrno" => mysqli_errno($con), "sqlstate" => mysqli_sqlstate($con));
} else {
    $response = array("success" => true);
}

echo json_encode($response);

mysqli_close($con);

?>

Notes:

*

*I wouldn't recommend logging in as root.

*Make sure you use mysqli_real_escape_string to protect yourself against SQL injection attacks (see point 1).

*I don't know if your user table has other fields in it, but if so, you might want to specify the column names in the insert statement. Even if you only have those two columns, it's a good way to "future-proof" your code.

*Note, I've changed this to generate JSON response. I do that because it makes it easier for the client code to parse and handle the response. I'll leave the NSJSONSerialization to you.


text:
Q: How do I remove printer that is no longer used? The MG2220 printer is no longer connected to my computer.
Yet lpstat is still showing it.
How can I get that removed?
$ lpstat -p
printer Canon_TS9100_series is idle.  enabled since Mon 11 Mar 2019 04:41:26 PM CDT
printer HL-2240-series is idle.  enabled since Tue 12 Mar 2019 03:28:52 PM CDT
printer MG2200-series is idle.  enabled since Wed 20 Feb 2019 10:50:51 AM CST

A: I found the answer when I opened CUPS in my browser.
Administration, Manage Printers, and Delete Printer.


text:
Q: Why the jpexs tool not working when decompile swf file? Anyone knows how to decompile .SWF file?
I have tried JPEXS and Sothink SWF Decompiler but it not working.
I put this .swf in this link.
Thanks.

A: The SWF is not opening with JPEXS because it is compressed!!.
The first thing you should do when a file (eg: swf, jpeg, mp3, mp4) does not open in any program, is to check if the format bytes are correct by using a hex editor.
Checking your file bytes:
Usually a SWF file begins with bytes 43 57 53 (eg:"CWS") or even bytes 46 57 53 (eg: "FWS").

*

*Your file begins with 78 DA 00 43 40 BC BF 43 57 53 (the last three bytes are the expected 43 57 53 of a normal SWF).

*Those first two bytes 78 DA means it has some ZLib compression (eg: like
a .zip file).
Solution:
Two options to decomress ZLib. One is by AS3 code and the other is by external (Windows) tool.
Option 1) Use AS3 to decompress.

*

*Get the library AS3ZLib and copy its as3zlib folder to same place as your Flash project .as files. (Find folder at: src/com/wirelust/as3zlib/).

*Load (or read) your SWF file's bytes into an AS3 bytearray called fileBytes.
Try this code logic:
import Zlib; //do import of API

....

public var zlibdecomp :Zlib; //create instance variable

....

public var fileBytes :ByteArray = new ByteArray;
public var swfBytes :ByteArray = new ByteArray;

//#  SWF original file bytes load
fileBytes = ... ; //your loading code here

//# Decompress loaded into new SWF bytes
zlibdecomp = new Zlib; //create new ZLIB instance in variable
swfBytes = zlibdecomp.uncompress( fileBytes ); //update with decompress version
trace("swfBytes length (DEFLATED) : " + swfBytes.length); //is 8,617,377 bytes??

The bytes in swfBytes now can be saved as a file new.swf and this will open correctly in JPEXS. Use fileReference API to save AS3 bytes to disk.
Option 2) Use an external ZLib tool.
Using OffZip (for Windows OS) you can decompress the SWF.
This is the direct OffZip file. Copy Offzip.exe into a folder like c:\offzip\.
Now open command line by running cmd.exe. Type cd\offzip\ (press enter). Alternatively just hold shift and right-click the Offzip folder then choose "open command window here".
Type offzip -a vpt.swf (press enter).

You should see output like this...
C:\offzip>offzip -a vpt.swf

Offzip 0.4
by Luigi Auriemma
e-mail: aluigi@autistici.org
web:    aluigi.org

- open input file:    vpt.swf
- zip data to check:  32 bytes
- zip windowBits:     15
- seek offset:        0x00000000  (0)

+------------+-----+----------------------------+----------------------+
| hex_offset | ... | zip -> unzip size / offset | spaces before | info |
+------------+-----+----------------------------+----------------------+
  0x00000000 .

................................................................................
................................................................................
................................................................................

................................................................................
................................................................................
.................................................................... 8496131 ->
8617377 / 0x0081a403 _ 0 8:7:26:0:1:2657f334

- 1 valid compressed streams found
- 0x0081a403 -> 0x00837da1 bytes covering the 100% of the file

Now the output file 00000000.cws can be opened in JPEXS. You can rename this to 00000000.swf.


text:
Q: How to link a Django model field to an instance of the same model I'm trying to design a Django model for articles with attributes like title, publication date, etc. One of the attributes is other article(s) that the article in question is commenting on. I'm not sure how to code this since there is no foreign key involved - I just want a reference to other instances of the Article model (i.e. one or more other articles). This is what I have so far:
class Article(models.Model):
    title = models.CharField(max_length=400)
    publication_date = date_published = models.DateField()
    comment_on = ?????????????

Any suggestions would be much appreciated. Thank you!

A: I think you should user ForeignKey
 comment_on = models.ForeignKey('self',null=True,blank=True)

To create a recursive relationship -- an object that has a many-to-one
  relationship with itself -- use  models.ForeignKey('self').

Django foreign key docs

A: you can use ManyToManyField
comment_on = models.ManyToManyField('self',null=True,blank=True)

refer to DOCUMENTATION for further symmetric use.


text:
Q: Xcode 7 linker error with RestKit and CocoaPods I just upgraded to Xcode 7 and CocoaPods 0.38.2 and, after resolving some Swift 2 issues, got the following linker error with my mixed Objective-C & Swift project targeting iOS 7:
Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_RKManagedObjectRequestOperation", referenced from:
      objc-class-ref in NetworkHelper.o
  "_OBJC_CLASS_$_RKManagedObjectResponseMapperOperation", referenced from:
      type metadata accessor for ObjectiveC.RKManagedObjectResponseMapperOperation in MappingHelper.o
  "_RKLogCoreDataError", referenced from:
      ___33-[RKEntityByAttributeCache load:]_block_invoke in libRestKit.a(RKEntityByAttributeCache.o)
      ___43-[RKManagedObjectImporter finishImporting:]_block_invoke in libRestKit.a(RKManagedObjectImporter.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

CoreData is included in my .pch file and is included before RestKit in the bridging header, and Bitcode is off. I'm using RestKit 0.24.1.
Since it appears that RestKit isn't detecting the presence of the CoreData framework and its conditional declarations are accordingly getting passed over, I've tried lots of various ways to tell my app or the RestKit pod about the presence of Core Data, but nothing seems to help.

A: I resolved this issue by following these steps:

*

*Upgrade my cocoapods (0.39.0)

*Goto build settings of my target and search for header search paths.

*Make all header search paths recursive (This is important) I also tried by my making recursive only to restkit but for some reason i don't know it does not work.

*Then disable the bitcode.

*Finally build.

For more information see this link

A: Upgrading from an older version of RestKit (0.23.3) to 0.25.0 worked for me.
I also upgraded Xcode to 7.0.1, deleted xcworkspace, and reran pod install for good measure.

A: upgrade you cocoapods and xcode7.0.1
and remove xcworkspace and pod install again.


text:
Q: Thread leak detected when using condition variable instead of join() with pthread I'm new to pthread synchronization, searched "pthread condition variable" in google and grab an example from the pdf: https://pages.cs.wisc.edu/~remzi/OSTEP/threads-cv.pdf .
The example code is as follow, whose purpose is "use condition variable and a variable done to implement pthread_join()" (as I understand):
// https://godbolt.org/z/8rPMq54K8
#include <stdio.h>
#include <pthread.h>

volatile int done  = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c  = PTHREAD_COND_INITIALIZER;
void thr_exit() {
    pthread_mutex_lock(&m);
    done = 1;
    pthread_cond_signal(&c);
    pthread_mutex_unlock(&m);
}
void *child(void *arg) {
    printf("child\n");
    thr_exit();
    return NULL;
}
void thr_join() {
    pthread_mutex_lock(&m);
    while (done == 0)
    {
        pthread_cond_wait(&c, &m);
    }
    pthread_mutex_unlock(&m);
}

int main(int argc, char *argv[])
{
    printf("parent: begin\n");
    pthread_t p;
    pthread_create(&p, NULL, child, NULL);
    thr_join();
    printf("parent: end\n");
    return 0;
}

Compiled with:
clang++ main.cpp -fsanitize=thread -g -fno-omit-frame-pointer

Running it will see "thread leak" reported:
(base) ➜  case12 git:(main) ✗ ./a.out
a.out(71120,0x10433c580) malloc: nano zone abandoned due to inability to preallocate reserved vm space.
parent: begin
child
parent: end
==================
WARNING: ThreadSanitizer: thread leak (pid=71120)
  Thread T1 (tid=1365892, finished) created by main thread at:
    #0 pthread_create <null>:74364228 (libclang_rt.tsan_osx_dynamic.dylib:arm64e+0x2bbe8)
    #1 main main_v4.cpp:31 (a.out:arm64+0x100003e38)

SUMMARY: ThreadSanitizer: thread leak main_v4.cpp:31 in main
==================
ThreadSanitizer: reported 1 warnings

Is this C++ code really a thread leak, or just a false positive report from tsan?

A:
Is this C++ code really a thread leak, or just a false positive report from tsan?

It is really a thread leak, arising from the fact that you cannot implement a substitute for pthread_join().  At least, not in any portable way or based only on the C++ (or C) and pthreads specifications.  The program starts a thread and neither detaches nor joins it before terminating.  That's a thread leak.
The program does successfully and reliably wait to terminate until the child thread provides evidence that it has called thr_exit(), but that is not a substitute for joining the child thread.

A: (This is not an answer, just the solution code that I can write, after reading John Bollinger's answer.)
Solution 1:
int main(int argc, char *argv[])
{
    printf("parent: begin\n");
    pthread_t p;
    pthread_create(&p, NULL, child, NULL);
    pthread_detach(p);  // !! new added line
    thr_join();
    printf("parent: end\n");
    return 0;
}

Solution2:
void *child(void *arg) {
    pthread_detach(pthread_self()); //!! new added line
    printf("child\n");
    thr_exit();
    return NULL;
}


text:
Q: How do I add color to labels in a pca plot? I am trying to plot pca. But there are overlap of the label names in the plot. How do I move those labels in the plot?

code used
library(factoextra)
library(FactoMineR)

# Compute PCA with ncp = 2
res.pca <- PCA(datm, ncp = 2, graph = FALSE)
# Compute hierarchical clustering on principal components
res.hcpc <- HCPC(res.pca, graph = FALSE)

plot(res.hcpc, choice = "3D.map", sub="PCA Clusters")

I want to add PPBC1a, PPBC1b, PPBC1c one color, similarly for PPBC2a,b,c and PPBC3a,b,c,d
the data used as follows:
dput(datm)
structure(c(12.79802058, 10.89742342, 13.00479536, 13.64688912,
14.17038237, 13.90494906, 13.54635544, 14.25565698, 14.86503437,
13.54133782, 11.1653212, 11.01250594, 10.9527396, 13.69093192,
14.70875995, 11.38278472, 11.12961813, 13.29853222, 13.49095453,
13.1619033, 9.966433138, 10.67426065, 10.78077335, 14.15939746,
16.02465067, 11.73237694, 10.42060106, 9.453730095, 13.37238268,
16.35668986, 10.70283822, 11.46108048, 4.667661637, 14.41355243,
16.58813424, 12.21522223, 11.22616596, 12.32599886, 11.43089556,
15.3907471, 10.7018847, 11.05914848, 10.01466231, 12.91440139,
14.85643716, 11.17261824, 11.41834054, 10.39116957, 11.21272536,
14.25124128, 12.22137936, 12.93868862, 11.56519352, 10.50344844,
11.55031894, 11.38322914, 10.47556631, 11.15981881, 11.52102261,
10.94487402, 11.64516694, 13.78851408, 11.42176044, 11.03451725,
10.88189033, 11.53493091, 10.92014018, 11.74711381, 10.98622502,
10.27737559, 10.04825453, 10.06856283, 9.473361641, 12.29532767,
14.9837309, 10.2983783, 10.11032589, 10.19707019, 11.07196875,
13.73176839, 11.28729374, 11.80497494, 13.56806793, 11.14757033,
10.42813405, 10.83331515, 9.856914347, 11.21904373, 10.80822287,
10.91284032, 10.20859053, 9.410343499, 9.948968741, 11.47888667,
11.50839216, 11.47823205, 11.96327312, 11.17161266, 11.5667065,
11.42616106, 9.493094329, 9.448753468, 9.288950806, 12.82071465,
13.8216361, 9.618496101, 9.264784876, 9.158918708, 11.81330267,
13.29542936, 11.64169084, 11.1446361, 11.78787136, 10.00885973,
10.8443866, 9.620006131, 9.795650634, 10.95021727, 10.72375077,
9.688961166, 11.56038993, 10.77185199, 11.56282223, 9.909142388,
10.13332508, 10.64896999, 10.08616698, 10.79031452, 10.36053333,
9.949119042, 9.667419497, 9.2998083, 9.270160036, 10.93375289,
11.32732089, 10.43670451, 11.06311588, 11.21425016, 12.02255073,
9.573431887, 9.214022307, 9.157054545, 8.618929314, 12.0888963,
13.44540908, 9.497197032, 9.515249128, 8.623513357, 11.39360436,
12.97238166, 10.36255544, 9.036073308, 8.975751645, 8.661048339,
12.53967869, 10.38703923, 10.74839297, 10.0727921, 11.53731204,
11.85151216, 8.963064616, 8.905819317, 8.961398581, 12.45768699,
13.26878505, 9.13890204, 9.098268177, 8.641522307, 10.92563493,
12.51834881, 9.031546274, 7.92737859, 9.332794101, 10.58509175,
11.92010082, 10.18771142, 10.40310795, 10.26934483, 11.1051311,
10.88559116, 11.69057173, 10.03446933, 11.23332211, 10.50344844,
9.417949681, 9.443619859, 10.06159633, 9.274065761, 9.893683766,
9.982434562, 8.347704963, 7.998531668, 9.203153275, 10.92113512,
14.51497636, 9.087402337, 8.715407397, 8.14626007, 10.9365942,
13.26424666, 9.022397644, 9.291377206, 7.802169848, 9.624119866,
11.63210545, 10.91918468, 9.628354314, 9.715402094, 10.27459859,
11.85488782, 9.085248988, 8.903975769, 7.842128194, 11.13963286,
10.9426894, 10.1253052, 11.18126721, 10.88911888, 10.33176186,
9.124823973, 10.23388164, 12.38883251, 9.768248709, 10.35329359,
8.232032734, 9.206833364, 9.919787227, 9.063412539, 9.523736019,
9.663506002, 10.91023525, 9.933398449, 11.09861509, 9.245256138,
9.343531381, 9.578669343, 8.67702586, 10.39435208, 9.714191234,
9.154382761, 11.37184936, 10.22273334, 10.33336875, 9.457908594,
9.052084518, 9.458890947, 8.774155458, 9.081974159, 9.475674974,
9.688961166, 10.02403938, 10.5024381, 11.03117054, 9.260761293,
9.220378095, 9.613956493, 8.918174108, 8.510438946, 9.888047223,
9.709006423, 11.71440478, 9.980458168, 10.51792787, 9.58525359,
9.447318876, 9.02032214, 9.166742167, 9.243778354, 9.239244702,
8.614926126, 10.83830018, 9.588324046, 10.60694522, 9.789244256,
8.93708957, 8.976160958, 9.269086561, 9.074048482, 9.402415129,
9.036295386, 6.701686821, 7.377218224, 8.98819414, 10.66235984,
13.42158018, 8.692687637, 8.240953611, 8.057584229, 10.22851668,
13.07653088, 10.91517999, 9.291377206, 10.93542887, 9.397483884,
9.294090175, 8.821827081, 9.110308905, 10.19220187, 9.234807728,
8.246792484, 8.731823059, 8.363957616, 7.470325568, 9.306299357,
12.12012408, 9.38086296, 9.981342621, 7.759351889, 11.43862499,
10.65328466, 9.067569876, 8.152966733, 8.668411667, 9.223264482,
11.03793682, 8.896081541, 10.5311998, 9.783354462, 9.530989752,
10.08376407, 10.32340931, 9.824703064, 10.88411494, 9.173338947,
9.733479214, 8.544415804, 8.953370094, 8.322117986, 9.291448403,
9.4176827, 10.60728078, 10.18305421, 10.1916577, 9.297306238,
8.697110912, 9.410839171, 9.338269397, 8.556743415, 9.080141698,
8.692623603, 8.811928095, 8.177667088, 7.307511459, 9.863185379,
9.556158498, 10.02745688, 9.249626944, 10.67118117, 9.422058192,
10.55015172, 10.07649154, 9.827619905, 10.2642534, 8.649299253,
9.387969121, 9.013438829, 9.066482425, 8.391946397, 8.728792309,
9.396201652, 10.60728078, 9.439882325, 10.29029261, 8.688859999,
8.583939305, 9.281281423, 9.384594534, 9.161414002, 8.747621482,
8.294169479, 8.125790217, 7.998531668, 8.361435176, 8.713889348,
11.16604497, 8.746298376, 9.238701298, 9.453730095, 9.830435279,
10.74347379, 11.34645, 9.245558055, 10.45345693, 9.025018286,
8.454643693, 9.212852871, 6.184579775, 8.526040439, 9.527367451,
8.863557236, 7.295645309, 7.193411473, 8.803364617, 8.233438374,
10.69877804, 9.62151458, 9.676087343, 9.463869602, 10.25283839,
9.53744679, 9.891447443, 9.275790795, 10.47820851, 9.226426791,
8.841917928, 8.550777269, 8.856575833, 8.745075803, 8.297187146,
8.415380547, 7.623943184, 8.311965668, 8.4897075, 8.608617442,
10.88427676, 8.863268496, 7.883308702, 10.20071067, 9.570245299,
9.9128568, 7.748462407, 8.552538573, 7.756876788, 8.531327176,
10.45085452, 9.271702802, 8.456732294, 10.23188233, 9.119190827,
10.1603572, 9.774738472, 13.41074356, 7.324670625, 10.34677543,
7.077674568, 9.55202058, 9.444764619, 8.490695346, 7.635886226,
7.195360015, 10.70474337, 8.968898113, 10.46683747, 9.40866043,
7.268486595, 8.615923306, 8.028128113, 9.09247427, 8.61031829,
8.327075009, 8.192784529, 7.84863112, 8.168216487, 7.944293433,
9.910217283, 9.495552562, 8.249715019, 9.40193343, 10.15533647,
9.396201652, 13.13663182, 6.623433691, 8.609746358, 7.586017239,
9.504319631, 7.580262953, 8.953370094, 9.674085744, 9.726878458,
6.608960227, 9.8947901, 9.382833733, 9.719025557, 8.991940494,
8.542122463, 7.567669559, 7.540070977, 8.683843888, 8.630755359,
8.677416831, 10.51148541, 9.26578359, 9.947151017, 8.083971149,
8.422061056, 8.298080674, 8.258423094, 8.125885143, 8.086003207,
8.521463999, 7.777954993, 7.605282271, 7.861693809, 10.37836558,
10.97775208, 7.665407713, 7.734648946, 6.380465146, 9.198810841,
11.82593974), .Dim = c(10L, 50L), .Dimnames = list(c("PPBC1a",
"PPBC1b", "PPBC1c", "PPBC2a", "PPBC2b", "PPBC2c", "PPBC3a", "PPBC3b",
"PPBC3c", "PPBC3d"), c("DSP", "ASPH", "ERBB2", "SCGB2A2", "CASC3",
"GLUL", "ITPRID2", "MSL1", "PXDN", "TC2N", "PSMD3", "HLA-DRB1",
"GRN", "MTUS1", "MED24", "CRACR2B", "ORMDL3", "ANK3", "CIITA",
"GSDMB", "MAGI3", "SELENOP", "ABHD2", "VWA1", "IRF1", "SYNGR2",
"TNFAIP3", "ITGB2", "GRB7", "SGK1", "ARHGEF38", "FAM118A", "C1QB",
"EFHD2", "VAV3", "C1QC", "TNFRSF14", "MPHOSPH6", "RGS16", "RHPN2",
"PGD", "SPTSSA", "SAMD12", "RGS5", "SOCS3", "C11orf80", "GABRE",
"GBP4", "HLA-DQA1", "PGAP3")))

A: I would recommend you to not use a 3D visualization. Instead, you could simply use the fviz_dend which creates a cluster dendrogram that is actually the same and even better to read of. Here is a reproducible example:
library(factoextra)
library(FactoMineR)

# Compute PCA with ncp = 2
res.pca <- PCA(datm, ncp = 2, graph = FALSE)
# Compute hierarchical clustering on principal components
res.hcpc <- HCPC(res.pca, graph = FALSE)

fviz_dend(res.hcpc)

Created on 2023-01-04 with reprex v2.0.2


text:
Q: Extracting year from datetime datatypes is giving output as float I'm a newbee in Pandas. I need your support in a problem i'm facing
I have a datatime column in a dataframe and I'm trying to extract the year from it but the output it is giving is in float?
fifa['Joined_date'].head()
0   1970-01-01
1   1970-01-01
2   1970-01-01
3   1970-01-01
4   1970-01-01
Name: Joined_date, dtype: datetime64[ns]

fifa['Joined_date'].dt.year
0        1970.0
1        1970.0
2        1970.0
3        1970.0
4        1970.0
Name: Joined, Length: 18207, dtype: float64

Output Expected is --> 1970

Can you please help?

A: There are different ways but below are 2 may help you
this will apply on entire frame
pd.options.display.float_format = '{:,.0f}'.format

this is for the column
df['your column'] = df['your column'].astype(int)

if your column has mixed type of data
 df['your column'] = df['your column'].astype(int, errors='ignore')

Some cases you may have to convert the columns first to str and then again to int


text:
Q: How to configure TexStudio editor to use Xindy? I am using TexStudio editor for LaTeXing, I want to use Xindy engine though for indexing, in the commands of TexStudio, I found there is a default command for texdindy as in the image below. But how to use xindy then? Do I have to use xindy explicitly in texstudio or texindy will do the job? is there any possibility also to assign a dedicated key for using xindy and how to generate an index with that?
I hope the answer would contain a MWE showing the goodies of xindy by using TexStudio editor, with some explanation of how to make sure that xindy, and not other default engines like makeindex, is doing the sorting and collating job.
Notes:

*

*I am using TexStudio 2.5.2 version

*xindy does not come with MikTeX distribution, you have to install it manually, here is a post for that, although I didn't make it myself, that's why I installed TexLive distribution instead, xindy ships already, and you don't need to install perl separately if you are using windows, or even bother yourself with any other stuff.

A: So this can be done in two steps thanks to  Qrrbrbirlbel afterall, in order to call xindy for indexing:

*

*Set texindy as your default index tool by going to optioins -> Configure TexStudio -> Build, Note: make sure to tick the show advanced options, as in the picture below:

 2. You need to use the shell escape for xelatex or pdflatex, I use xelatex compilation engine for the pdf file, go to commands and add the -shell-escape as in the picture below:

Now it's time for Hello World experiment in a MWE, I borrowed one from here:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[finnish]{babel}
%\usepackage[utf8]{inputenc} % cannot be used with xelatex
\usepackage[texindy]{imakeidx}
\makeindex
\begin{document}
Hello world
\index{j\"allivaara}
\index{porvoo}
\index{kirjakielt\"a}
\index{sanota}
\index{vanhaa}
\printindex
\end{document}

Result: