text:
Q: How to set view of map for new location using latitute and longitude with React-leaflet I am unable to set view of the map for the input IP address while the Marker can move to the new location on the map for given input IP address. Map seems to stay at initial location whereas the Marker moves to new location.
So, When I type in a new IP address in input, it should change the map to a new location.
import React, { useEffect, useState} from "react";
import Result from "../src/Components/Result";
import {MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';

function App() {
  const APP_KEY = PERSONAL_KEY;

  const [IPdata, SetIPData] = useState([]);
  const [search, setSearch] = useState("");
  const [query, setQuery] = useState("8.8.8.8");
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    getIp();
    setLoaded(true);

  }, [query]);

  async function getIp() {
    const response = await fetch(`https://geo.ipify.org/api/v1?apiKey=${APP_KEY}&ipAddress=${query}`);
    const data = await response.json();
    console.log(data);
    SetIPData(data)
  }

  function handleChange(event) {
    setSearch(event.target.value);
    console.log(event.target.value);

  }

  function handleSubmit(event) {
    event.preventDefault();
    setQuery(search);
    setSearch('');

  }

  return (
    loaded ? (

 IP Address Tracker

            <form onSubmit={handleSubmit} className="search-form">
              <input className="search-input" type="text" placeholder="Search for any IP address or domain" onChange={handleChange} />
              <button className="search-button" type="submit"> Go! </button>
            </form>

            <Result
              heading={"IP Address"}
              searchResult={IPdata.ip}
            />

            <Result
              heading={"Location"}
              searchResult={IPdata?.location?.country}
            />

            <Result
              heading={"Timezone"}
              searchResult={"UTC" + IPdata?.location?.timezone}
            />

            <Result
              heading={"ISP"}
              searchResult={IPdata.isp}
            />

        {IPdata.location && (

          <MapContainer
            center={[IPdata.location?.lat, IPdata.location?.lng]}
            zoom={13}
            scrollWheelZoom={true}

          >
            <TileLayer
              attribution='© OpenStreetMap contributors'
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            <Marker position={[IPdata?.location?.lat, IPdata?.location?.lng]}>
              <Popup>Your IP Location</Popup>
            </Marker>
          </MapContainer>
        )
        }

) :
Loading...

  )

}

export default App;

A: You cannot change the center with state because of this...

Except for its children, MapContainer props are immutable: changing
them after they have been set a first time will have no effect on the
Map instance or its container.

However, I believe it may work if you add a key prop. You can try to see if it works.
      <MapContainer
        center={[IPdata.location?.lat, IPdata.location?.lng]}
        zoom={13}
        scrollWheelZoom={true}
        key={`${IPdata.location?.lat}${IPdata.location?.lng}`}
      >

Updated: There's another solution provided here using setView -> React leaflet center attribute does not change when the center state changes
function ChangeView({ center, zoom }) {
  const map = useMap();
  map.setView(center, zoom);
  return null;
}

function Map({ center, zoom }) {
  return (

      <MapContainer center={center} zoom={zoom} scrollWheelZoom={false}>
        <ChangeView center={center} zoom={zoom} />
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='© OpenStreetMap contributors'
        />
      </MapContainer>

  );
}


text:
Q: multiple datatypes in one column I'm building a predictive model to predict who of the student will pass the course based on the time they spent on each task in minutes.
Course   StudentID  Task1   Task2   Task3 ...
AA       3547       2       9       2
AA       3548       5       2       5
AA       3549       1       7       3
AA       3550       2       9       2
AA       3551       5       2       5
AA       3542       2       9       2
BB       3543       5       2       5
BB       3544       1       7       3
BB       3555       2       9       2
CC       3556       5       2       5

However, every task in every course is different e.g. if Task1 in course AA is a question and answer, it might be a video to watch or a wiki to read. I feel feeding the data as it is to the network would be inappropriate and just wondering if there's any way to sort this out. I thought of adding a column next to each task but that would impossible due to the great number of tasks and students. Below is the type of task in each course:
Course  Task1   Task2   Task3
AA      Q/A     Video   Wiki
BB      Video   Wiki    Q/A
CC      Wiki    Wiki    Video

A: I would say adding a column to each of the tasks is the clean way to do this.
However if you do not want to add one additional column for each of the tasks, then you can have a tuple of each of the tasks.
The tasks tuple would be like (taskId, timeSpent)
Course  Student T1  T2
AA  357 (2, 22) (21, 14)
AA  358 (9, 33) (6, 35)
BB  359 (4, 19) (14, 19)
BB  360 (8, 34) (3, 28)
CC  361 (6, 9)  (6, 19)
CC  362 (3, 14) (5, 22)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Form can't find save method I've a problem and I don't know where it comes from.
I've this form :
class LinkWidgetToDashboardForm(forms.Form):
    widget = forms.MultipleChoiceField(
                choices =  [(w.pk, w.name) for w in Widget.objects.all()]
            )

Nothing special, but I can't save, navigator returns me
'LinkWidgetToDashboardForm' object has no attribute 'save'

and in fact if I apply a dir() over my form instance, there is no save method.
Just for information
def linkWidgetToDashboard(request):
    if request.method == 'POST':
        form = LinkWidgetToDashboardForm(request.POST)
        if form.is_valid():
            o = form.save(commit=False)
            o.dashboard = Dashboard.object.get(pk=1)
            o.widget = form.cleaned_data['widget']
            o.save()
    return HttpResponse('')

Any idea ?

A: It is available for ModelForm not Form. Your form derives from forms.Form.
On saving it ModelForm will return you the instance of the model that its been defined. Normal form does not know which object to create so they cannot do that.
Refer ModelForms.

A: It is not clear what you are trying to "save" as the field in your form is already populated with the records from the database.
It looks like what you want to do is update the selected object with a dashboard, in that case, use this:
if form.is_valid():
    widget = Widget.objects.get(pk=form.cleaned_data['widget'])
    widget.dashboard = Dashboard.objects.get(pk=1)
    widget.save()

However, this type of functionality is built-in with ModelForms, which are forms that are linked directly to models and have the database save logic.

A: No need for that language here, please.
Only ModelForms have save methods. A normal form doesn't have one, as it makes no sense - what would it save to?


text:
Q: Removing the end [ and ] from php Json result for Android Java code My PHP code is this:
$userdetails = mysqli_query($con, "SELECT *FROM aircraft_status");

#$row = mysql_fetch_row($userdetails) ;

while($rows=mysqli_fetch_array($userdetails)){
$status[]= array($rows['Aircraft']=>$rows['Status']);
}
#Output the JSON data
echo json_encode($status);

and gives this:
[{"A70_870":"1"},{"A70_871":"1"},{"A70_872":"1"},{"A70_873":"1"},{"A70_874":"1"},{"A70_875":"1"},{"A70_876":"2"},{"A70_877":"1"},{"A70_878":"2"},{"A70_879":"2"},{"A70_880":"2"},{"A70_881":"0"},{"A70_882":"0"},{"A70_883":"0"},{"A70_884":"0"},{"A70_885":"0"}]

The java code that reads it is this:
// Create a JSON object from the request response
    JSONObject jsonObject = new JSONObject(result);

    //Retrieve the data from the JSON object
        n870 = jsonObject.getInt("A70_870");
        n871 = jsonObject.getInt("A70_871");
        n872 = jsonObject.getInt("A70_872");
        n873 = jsonObject.getInt("A70_873");
        n874 = jsonObject.getInt("A70_874");
        n875 = jsonObject.getInt("A70_875");
        n876 = jsonObject.getInt("A70_876");
        n877 = jsonObject.getInt("A70_877");
        n878 = jsonObject.getInt("A70_878");
        n879 = jsonObject.getInt("A70_879");
        n880 = jsonObject.getInt("A70_880");
        n881 = jsonObject.getInt("A70_881");
        n882 = jsonObject.getInt("A70_882");
        n883 = jsonObject.getInt("A70_883");
        n884 = jsonObject.getInt("A70_884");
        n885 = jsonObject.getInt("A70_885");

When i run my android app I seem to keep getting the error:
"of type org.json.JSONArray cannot be converted into Json object"

However when I send the app dummy code without the square brackets, it seems to work fine! How do I get rid of those [ and ] brackets on the ends???
Alternatively is there a way to accept the json as it is and adapt the java to read it?

A: echo json_encode($status, JSON_FORCE_OBJECT);

Demo: http://codepad.viper-7.com/lrYKv6
or
echo json_encode((Object) $status);

Demo; http://codepad.viper-7.com/RPtchU

A: Instead of using JSonobject, use JSONArray
   JSONArray array = new JSONArray(sourceString);

Later loop through the array and do the business logic.
http://www.json.org/javadoc/org/json/JSONArray.html

A: You get an JSONArray, Not Object, you could create an Object holding an array, or parsing the array.
Refering to this post

A: Maybe with this kind of json structure?
$status[$rows['Aircraft']]= $rows['Status'];

A: Solution #1 (Java)
How about a helper method like this:
private int getProp(String name, JSONArray arr) throws Exception {
    for (int i = 0; i < arr.length(); ++i) {
        JSONObject obj = arr.getJSONObject(i);
        if (obj.has(name))
            return obj.getInt(name);
    }
    throw new Exception("Key not found");
}

Then you could use it like:
JSONArray jsonArray = new JSONArray(result); // note the *JSONArray* vs your *JSONObject*
n870 = getProp("A70_870", jsonArray);
n871 = getProp("A70_871", jsonArray);
...

Note I haven't tested this code, so you may need to make some changes...
Alternate solution (PHP)
It's been awhile since I've worked with PHP, but you might be able to leave your Java code intact and change your PHP int the while-loop body to:
$status[$rows['Aircraft']] = $rows['Status'];


text:
Q: Do I need to worry about session state? Hi all hope you can help.
I am primarily a windows developer (winforms and wpf/mvvm) and it's been 10 years since my last web application, so this is probably a daft question.
I have just redeveloped a customer satisfaction questionnaire and as I had to figure out this from scratch thought I would use MVC 3 and Razor.
The Questionnaire is a single page web site with a controller that looks something like this.
    Function Index(BrandName As String, CaseID As Integer, EventID As Integer) As ActionResult

        ViewData("Scores") = Scores

        Dim questionnaire As New Questionnaire

        questionnaire.CaseID = CaseID
        questionnaire.EventID = EventID
        questionnaire.BrandName = BrandName

        //Get Some specific branding from the database
        questionnaire.FullBrandName = "FullNameFromDatabaseTable"

        Return View(questionnaire)

    End Function

    Function Save(questionnaire As Questionnaire) As ActionResult

        If TryUpdateModel(questionnaire) Then
            SaveQuestionnaireToDatabase(questionnaire)
        Else
            Return RedirectToAction("Index")
        End If

        Return View()

    End Function

I have stripped out some database code and some stuff to get a signed image url as i don't think its relevant.
I am not sure I fully understand the magic that is happening between view and controller which is the real reason for my question.
This is going up into azure along with everything else, I am asking the question about session state because this will be load balanced accross two instances.  No authentication is required to access the page as it can only be completed once.
Many Thanks
p.s I couldn't get vb style quotes to work so put in the c# one.

A: If you have any content that needs to be shared / accessed across instances, simply use the AppFabric Cache, which went live about two weeks ago. I provided a link in this SO answer. The nice thing is that you can use the cache provider with just a few lines of code to set up, then call Put() and Get() for serializable key/value pairs. When you set up the cache, you can also enable a custom asp.net session state provider with a simple web config change - the Azure portal will auto-generate the xml for you.

A: It doesn't look like you are doing anything that touches the session, so there's no concern about which server the post goes to. All the information to process the request is submitted with the form.
You can take a look here (specifically section titled Implementing Add New Product ) to remove some of the mystery of how form data is mapped back to server side information.


text:
Q: auto-indent python string and write in an HTML file I have a string in python that I have to write to an HTML file. Is there any routine in Python that takes in a string such as
"( Root ( AB ( ABC ) ( CBA ) ) ( CD ( CDE ) ( FGH ) ) )".
and writes it in an indented form to an HTML file?
(Root
    (AB
        (ABC)
        (CBA)
    )
    (CD
        (CDE)
        (FGH)
    )
)

A: Here is a solution that works just roughly put together
def format(text):
  depth = 0
  result = ''
  text = text.replace(' ', '')
  for i in range(len(text)):
    c = text[i]
    if c == '(':
      depth += 1
      result += '\n' + '  ' * depth + '('
    elif c == ')':
      depth -= 1
      if text[i-1] != ')':
        result += ')'
      else:
        result += '\n' + '  ' * depth + ')'
    else:
      result += c
  return result.strip()

s = "( Root ( AB ( ABC ) ( CBA ) ) ( CD ( CDE ) ( FGH ) ) )"
print(format(s))

<script src="//repl.it/embed/IS2q/5.js"></script>

You should understand why people aren't so enthusiastic to answer this question. You are entering into the department of parsing but ignoring the complexities of it. To achieve your goal correctly you would need a defined grammar of the original format then you would need to parse based on that grammar. The resulting internal structure, i.e. the parse tree/syntax tree, would then need be formatted into the desired form.
My suggestion would be to use a well established standard such as json to represent your data instead of a custom one, i.e. the original text.


text:
Q: Why is this C code buggy? On another question, Jerry Coffin pointed out the following:

It's (probably) not really related to your question, but while (!feof(fileptr)){ is pretty much a guaranteed bug.

I figured I would start a separate question since that comment is somewhat off-topic.  Could someone explain this to me?  This was the first program I've written in straight C before.

A: The reason for this statement is that feof is still (initially) false when the end of the file has been reached -- it only becomes true after the first failed attempt to read past the end of the file.
Hence
char mychar;
while(!feof(fileptr))
{
    fread(&mychar, sizeof(char), 1, fileptr);
    fprintf(stderr, "The char is '%c'.\n", mychar);
}

will process one char too many.
The correct way is to check the return value of fread (or whatever function you're using to read) or, alternatively, to call feof after the function that does the reading. For example:
char mychar;
while(fread(&mychar, sizeof(char), 1, fileptr) > 0)
    fprintf(stderr, "The char is '%c'.\n", mychar);

A: Google finds this: http://www.drpaulcarter.com/cs/common-c-errors.php#4.2
It says "The author has yet to see any student use the feof() function correctly!"
To summarize, the C file functions like fread and fwrite return status values anyway which you <blink>should not ignore</blink>. Checking the value of feof is one of those bolting the stable door after the horse has already fled kind of things.

A: The C FAQ list has an answer along with answers to many other such frequently asked questions:

In C, end-of-file is only indicated after an input routine has tried to read, and failed.


text:
Q: Add multiple headers to java http request I would like to add multiple headers to a java HTTP request, I think this is possible using the headers() method in the httpRequest builder, but I can't seem to figure out how:
 HttpRequest request = HttpRequest.newBuilder()
            .POST()
            .headers(/*add mutple headers here*/)
            .uri(getUrl())
            .build();

A: You can add multiple headers by invoking header(String,String) multiple times...
HttpRequest request2 = HttpRequest.newBuilder()
  .header("key1", "value1")
  .header("key2", "value2")
  ... stuff ...
  .build();

.. or you may use the varargs headers(String...) methods
HttpRequest request = HttpRequest.newBuilder()
  .headers("key1", "value1", "key2", "value2")
  ... stuff ...
  .build();

A: The method headers allow you to pass a single key/value or a list of key/value https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpRequest.Builder.html#headers(java.lang.String...).
 HttpRequest request = HttpRequest.newBuilder()
            .POST()
            .headers("key1", "value1", "key2", "value2", "key3", "value3")
            .uri(getUrl())
            .build();


text:
Q: How can I run Arm MAP without GUI? I am using Arm MAP, part of Arm Forge. Whenever I use the "map" command to call the Arm MAP tool, then it shows the MAP GUI. Is it possible to call the MAP without GUI? I want to use it on the command line.

A: You can use map --profile to generate the .map file without using a GUI. map --help shows more options.
To explore the data in a .map file the GUI is recommended but this can be run on any machine. If you aim to integrate it with other tools (regression testing, continuous integration, comparing multiple runs) then the export options to CSV or JSON will help you.


text:
Q: SQLite JOIN table with relation I am trying to figure out where do I have a problem in this piece of code.
public static void main(String[] args) throws ClassNotFoundException, SQLException {

    Class.forName("org.sqlite.JDBC");
    Connection conn = DriverManager.getConnection("jdbc:sqlite:STUDENTS.db");
    Statement stat = conn.createStatement();
    //ResultSet rs = stat.executeQuery("select * from tabulka_faktov");
    ResultSet rs = stat.executeQuery("SELECT tabulka_faktov.MENO, tabulka_faktov.PREDMET1, tabulka_faktov.PREDMET2 FROM tabulka_faktov " +
            "INNER JOIN meno_ID ON tabulka_faktov.MENO = meno_ID.MENO");
    while (rs.next()) {
        System.out.println(rs.getString("MENO"));
        System.out.println("predmet 1 = " + rs.getString("PREDMET1"));
        System.out.println("predmet 2 = " + rs.getString("PREDMET2"));
        //System.out.println("volitelny = " + rs.getString("VOLITELNY_PREDMET"));
    }
    rs.close();
    conn.close();
}

It doesn't return me an error but I get nothing from this code, just Process finished with exit code 0.
My DB looks like this

I am using SQLite database
Can you guys tell me where do I have an error?
Thanks

A: Change "rs.getString()" into "rs.getNString()"


text:
Q: adding data to multidimensional array I know that I should be using a list of arrays or instantiating a new class for each new row. I am currently trying to implement a jagged array however I cannot get it to work.
I am trying to search an existing jagged array (that works and is all good) for the account type "STUDENT" and put them into a new array and then add a new piece of information to each student. However when I do this I get a NullReferenceException and I do not know why this is occurring.
I am an A-Level computer science student and was told that I should avoid using pointers, yield statements and IENumerators which is why I have tried to avoid linked lists.
Code (csharp):
 public string[] users;
 public string[][] userArray;
 public string[] User = new string[3];
 private string userDataString;
 private int j;
 public string[][] StudentArray;

   public string[][] UserSorting(string[][] userArray)
{
    j = 0;
    //for each row in user array
    for (int i = 0; i <= userArray.Length; i++)
    {
        //Compares the stored account type to STUDENT
        if (userArray[i][5] == "STUDENT")
        {
            //for each user value copy into the new array
            for (int x = 0; x <= 5; x++)
            {

                StudentArray[j][x] = userArray[i][x];
                Debug.Log(StudentArray[j][x]);
            }
            //moves onto the next line ready for the next iteration
            j++;
        }
    }

    return StudentArray;
}

}

A: There're several mistakes in your code.
First of all, when looping an array (or anything that implements IEnumerable), the condition must be index < array.Length and not <=, if the Length is 6, the indexes will go from 0 to 5, trying to access index 6 will throw an out of bound exception.
Second, you should always check if userArray[i] != null before checking for its content: if may well be that one index of userArray has not been declared, and that would throw an exception.
Third, you have to be sure that StudentArray has been declared, with the same number of elements as userArray, since you can't modify the length of arrays like you do with Lists.
Finally, for all the previous reasons, you should start to use Lists instead of arrays, they're a lot more easier to modify and mantain.
Anyway, to fix all the mistakes I listed, the code should look like this:
public string[][] userArray;
public string[][] StudentArray;
public int j;

private void Start() {
    //First index length just an example
    userArray = new string[3][];
    StudentArray = new string[userArray.Length][];
    //These 2 declarations are just to let you see that the code can skip undeclared arrays
    userArray[0] = new string[6];
    userArray[0][5] = "STUDENT";
    userArray[2] = new string[8];
    UserSorting(userArray);
}

public string[][] UserSorting(string[][] userArray) {
    j = 0;
    //for each row in user array
    for (int i = 0; i < userArray.Length; i++) {
        //Compares the stored account type to STUDENT
        if (userArray[i] != null) {
            if (userArray[i][5] == "STUDENT") {
                //for each user value copy into the new array
                StudentArray[j] = new string[userArray[i].Length];
                for (int x = 0; x < userArray[i].Length; x++) {
                    StudentArray[j][x] = userArray[i][x];
                    Debug.Log(StudentArray[j][x]);
                }
                //moves onto the next line ready for the next iteration
                j++;
            }
        }
    }
    return StudentArray;
}

A: Following up on Galandil's code. One important thing is to never try to do too many things at once. It makes it way harder to debug
public string[][] userArray;
public string[][] StudentArray;

public void UserSorting(string[][] userArray)
{
    List<string[]> studentList = new List<string[]>();

    //for each row in user array
    for (int userIndex = 0; userIndex < userArray.Length; userIndex++)
    {
        //Compares the stored account type to STUDENT
        if (userArray[userIndex] != null && userArray[userIndex].Length > 5 && userArray[userIndex][5] == "STUDENT")
        {
            string[] userAttributes = userArray[userIndex];

            //for each user value copy into the new array
            string[] studentAttributes = new string[userAttributes.Length];

            for (int attributeIndex = 0; attributeIndex < userAttributes.Length; attributeIndex++)
            {
                studentAttributes[attributeIndex] = userAttributes[attributeIndex];
                Debug.Log(studentAttributes[attributeIndex]);
            }

            studentList.Add(studentAttributes);
        }
    }
    StudentArray = studentList.ToArray();
}


text:
Q: Norm of the residual Let A be the tridiagonal finite-element matrix for the one-dimensional diffusion equation, let $Ax = 0, A \in R^{nxn}$ Implement the weighted-Jacobi and Gauss-Seidel iterations to solve $Ax = 0$. Consider relative reduction in residual norm $\frac{\|0−Ax^l\|}{\|0−Ax^{l−1}\|}, l$ is the number of iteration. What can you say about the "asymptotic" convergence as $l$ gets large? Does this depend on $n$?
My intuition says, that since we are getting closer to the solution with each iteration $\|0−Ax^l\|$ and $\|0−Ax^{l−1}\|$ would be equal for large $l$, so the fraction goes to $1$, and this doesn't seem to depend on $n$. But I'm not sure, can someone give me a formal proof?

A: Without further information on $A$ there is no way to answer your questions. Regarding your intuition, depending on $A$, the methods may not even converge for every initial approximation, so the "getting closer to the solution with each iteration..." may not occur.


text:
Q: NBeats does not work for long-term daily time series data. How can I process my data to correct this? I am following the code as per this notebook: https://www.kaggle.com/code/stpeteishii/google-stock-prediction-darts/notebook
It's a really simple implementation of the NBeats model, and it takes into account 400 days of the Google stockprice. However, when I increase the database to take into account all 4000 days, the N-Beats forecast is completely thrown of and gives a completely incorrect forecast with a mape of over 100.
I understand that one possibility is due to the seasonal nature of the stockprice. I tried the Dicky Fueller test (not using the Darts library) and it is indeed seasonal data. However, when I try to inspect seasonality with the Darts library as follows:
from darts.utils.statistics import plot_acf, check_seasonality

plot_acf(train, m=365, alpha=0.05)
I get a max lag error.

Can someone please help me as to how to forecast stock market data of a 10 year daily timeseries using the darts library? Also, I'd be extremely grateful if someone could give me some additional tips when it comes to forecasting stock data with darts since there's not much info/tutorials available online.
I've gone through the entire docs and I've got a good hang of working with darts using the darts open-source databases, however none of the examples seem to work with stock market data.
Any help would be greatly appreciated.
Thanks!


text:
Q: Error with less in Sublime Text 2 I have an error compiling my less file with ST2. I setup these plugins:
LESS
LESS build
SublimeOnSaveBuild
less2css

And I am trying to compile these example:
.generate-columns(4);

.generate-columns(@n, @i: 1) when (@i =< @n) {
  .column-@{i} {
    width: (@i * 100% / @n);
  }
  .generate-columns(@n, (@i + 1));
}

And I get this error:
Expected ')' but found ' ' on line 8 in file '......\public\css\prueba.less':
  [7]:   }
  [8]:   .generate-columns(@n, (@i + 1));
       ----------------------------^
  [9]: }
[Done - Failed]
[Finished in 0.2s with exit code -5]

The example is from Less official web: http://lesscss.org/features/#loops-feature
Can anybody help me please? Is it a bug from plugin?
Thanks a lot, best regards.

A: Thanks to seven-phases-max, I realized that I was using a plugin with old Less version. Finally, everything is working ok with these plugins:
LESS
Less2Css

And I set Build in automatic. If saving you get this error: "error: less2css error: [WinError 2]", you can install node.js and then run in the terminal "npm install less -g". If you don´t want to install node.js, you can install LESS.js for Windows (https://github.com/duncansmart/less.js-windows) and add it to system path.


text:
Q: truncate syslog - is the info in that log lost irretrievably? I remember using this to get syslog emptied so I could view it more easily.
But does that mean than any errors, etc in syslog are irretrievably lost?
Thanks.
sudo truncate -s 0 /var/log/syslog

A: Yes, unless you have backups.
truncate's -s option is referring to size. So the size of the file was set to 0 bytes.
By default, Ubuntu will logrotate /var/log/syslog after it reaches a certain size. So perhaps the errors you're looking for are in syslog.1, syslog.2.gz, etc.


text:
Q: Decimal Separator From Control Panel Customize Setting I create an application with VB.NET
As instructed in MSDN I've changed Culture to en-US. It works to override decimal separator to dot if user sets regional format to whatever language with comma separator.
Public Sub New()

    Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
    Thread.CurrentThread.CurrentUICulture = New CultureInfo("en-US")

    InitializeComponent()

End Sub

Now the problem is, how can I override decimal separator if user changed system's decimal separator from Control Panel > Region And Language > Additional Settings (in Format tab)?
CultureInfo is not able to override those custom settings. I need to override all the comma decimal separator to dot without using replace string function.

A: Set the NumberFormat property of the CultureInfo:
Dim myCI As New CultureInfo("en-US", False)
myCI.NumberFormat.CurrencyDecimalSeparator = "."

Thread.CurrentThread.CurrentCulture
   = Thread.CurrentThread.CurrentUICulture
   = myCI


text:
Q: Wordpress and Paths I am setting up a Wordpress site for educational purposes.. the content that I want to show in the wordpress blogs (videos) does however not reside in the wp-content directory but in the Root directory of the server of which Wordpress is a Subdirectory on the same server
Server root
-root
--worpress <-- wordpress
--content <-- my video content going many levels deep
in my Posts i do not want to use the ip address but rather a function that is written into my WordPress functions where i can once define the server ip address of this server before hand and call it in every post and page !
So.. how/where do i define the ip address and how do i call it in my wordpress post to make mediaelement.js media player find the video file?
Any suggestions appreciated

A: A simpler way may be to just use symlinks. So say the media player expects the files to be at wp-content/videos directory, but you want the videos to be placed in /var/www/videos directory. You can create a symlink to this videos directory inside the wp-content directory.
ln -s /path/to/wp-content/videos /var/www/videos

Depending on configuration, You may also need to add FollowSymLinks to your .htaccess file to allow symlinks.
Edit: Post clarification
You can move the wp-content directory to outside the Wordpress directory, by modifying your wp-config.php.
define('WP_CONTENT_DIR', '/path/to/content');

To move just the plugins directory,
define('WP_PLUGIN_DIR', '/path/to/plugins');

To move the directory where uploads are stored,
define('UPLOADS', '/path/to/uploads');


text:
Q: Search if filename with matching 4 digits exists in a directory I am checking if filename - 'Dev Finance GRM CONS ASPAC_Sales_3069_WI2_2020_GrsSalesAdj_Manual Upload Planning_1000records.csv' exists in a path
I am generating multiple files in the same path with similar name, but a unique pin ('3069') in the above case. This '3069' is stored in a unique variable 'upload_pin'
upload_pin = 3069 (and I want to search if a .csv file including this upload_pin exists in my path)
Tried this:
path = r"\\OPCITSNAPADCON2.jnj.com\tm1\cons\grm_aspac\user_in\Manual Upload Current Plan\Archive"
csv_files = glob.glob(os.path(path + '/*.csv'))
for filename in csv_files:
    if upload_pin in filename:
               print(filename)

A: Try
# get file names of all csv files in the directory
os.chdir('...')
all_csv_files = glob.glob("*.csv")

# provide your pin
upload_pin = 3069

# for each one of your files
# if the file name contains the target pin, print the file name
for file in all_csv_files:
    if (str(upload_pin) in file):
        print(file)

A: This worked for me
import os

upload_pin = 3069
for filename in os.listdir():
    if filename.endswith(".csv") and filename.find(str(upload_pin))>=0:
        print(filename)


text:
Q: I can't move my JLabel with Key Binding? I am trying to make a game in Java where pressing spacebar moves the box in the window. I am using Key Binding to accomplish this task. The problem is that I can't figure out how to use an ActionListener on the box itself, which is a JLabel. Here is the code below:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

public class Game {

private static JFrame frame     = new JFrame();
private static JPanel gamePanel = new JPanel();
private static Action playerAction = new PlayerListener();
private static JLabel box = new JLabel();
private static int x = 250;
private static int y = 250;

public static void main(String[] args) {

    frame.add(boxPanel());
    frame.setTitle("Block Game");
    frame.setSize(500,500);
    frame.setLocationRelativeTo(null);
    frame.setFocusable(true);

    box.addActionListener(playerAction);

    frame.setVisible(true);

}

static JPanel boxPanel() {
    ImageIcon boxIcon = new ImageIcon("box.png");
    box.setIcon(boxIcon);

    box.setSize(30,30);
    box.setLocation(x,y);

    box.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "doPlayerAction");
    box.getActionMap().put("doPlayerAction", playerAction);

    gamePanel.setLayout(null);
    gamePanel.add(box);
    frame.add(gamePanel);

    return gamePanel;
}

static class PlayerListener extends AbstractAction {

    public void actionPerformed(ActionEvent e) {

        System.out.println("SPACEBAR");

    }

}
}

I tried changing the box to a JButton and working with that instead, but I have found that "SPACEBAR" only prints out when I click on the box itself. Any help is greatly appreciated. Thanks!

A: Your "core" problem revolves around box.getInputMap(), change it to something more like box.getInputMap(WHEN_IN_FOCUSED_WINDOW) which will mean that the API will respond to key events whenever the window has focus, regardless what other components might have focus.
I'd also suggestsomething more like box.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "doPlayerAction"), as the mechanism which KeyStroke uses to parse String to a KeyStroke is more complicated then it might seem, normally requiring additional information like pressed, released or typed, it's just easier to use the virtual keys
I would also bind the keys to the gamePanel as a general preference, as it should be the container making decisions about what to do, but that's just me.
Have a look at How to Use Key Bindings for more details


text:
Q: Which sequences arise as the eventuality filter of a sequence? Let $X$ denote a topological space. Can we characterize  the filters on $X$ that arise as the eventuality filter of a sequence?

A: It's clear that such an eventuality filter of a sequence must contain a countable set $A \in \mathcal{F}$.
Look at the set of all countable subsets of $A$. These have empty intersection or some countable or finite intersection. Try to think of a sequence that has tails that behave like that.


text:
Q: Updating a column in R I have a dataframe:
df = data.frame(matrix(rnorm(5), nrow=5))

To that i add a discrete variable
df$discrete <- c(0,1,0,1,0)

And i put on some meaningful colnames:
colnames (df) <- c("start", "discrete")

Now i want to create a new variable that is the first variable + 10 - but only if my discrete variable has the value 1
df$new_var <- as.numeric(10)

df$new_var[df$discrete == 1]  <- df$start + 10

And i get an error: Warning message: In df$new_var[df$discrete == 1] <- df$start + 10 : number of items to replace is not a multiple of replacement length
and my tables has not updated as expected. Whats going on?
df = data.frame(matrix(rnorm(5), nrow=5))
df$discrete <- c(0,1,0,1,0)
colnames (df) <- c("start", "discrete")
df$new_var <- as.numeric(10)
df$new_var[df$discrete == 1]  <- df$start + 10

A: You're trying to assign a subset of a dataframe column (df$new_var[df$discrete == 1]) the data in an entire dataframe column (altered a bit): df$start + 10
Try this instead, which subsets both sides.
df$new_var[df$discrete == 1]  <- df$start[df$discrete == 1] + 10


text:
Q: using jQuery to change, only the elements that were loaded via ajax For each checkbox on the web page, I replace it with a slider that I borrowed from jsfiddle.net/gnQUe/170/
This is done by going through the elements when the document is loaded.
Now the problem is that when more content is loaded via ajax, the new checkboxes are not transformed.
To solve the problem, I used AjaxComplete event to go through all the elements again and replace the checkboxes with sliders.
Now the problem happens that elements that were already replaced, get two sliders. To avoid that I check if the checkbox is hidden and next element is div of class "slider-frame", then don't process the re-process the element.
But I have a lot of other such controls as well, and I am presume I am not the only one that has this problem. Is there another easy way around it?
There exists jQuery live/on( http://api.jquery.com/on/ ) event but it requires an event as an argument? whereas I would like to change the look of my controls when they are rendered.
Another example of the same problem is to extend some controls that are loaded via ajax with jQuerys autocomplete plugin.
Is there a better way to accomplish this other than changing some attributes on the element.
To summarize, on document load I would like to process every element in DOM, but when more elements are loaded via ajax then I want to change only the new elements.

A: I would assume that when the element's are transformed into a slider, a class is added to them. So just add a not clause.
$(".MySelector").not(".SomeClassThatSliderAddsToElement").slider({});

So in the case of your code do something like this
$('.slider-button').not(".sliderloaded").addClass("sliderloaded").toggle(function(){
    $(this).addClass('on').html('YES');
    $('#slider').val(true);
},function(){
    $(this).removeClass('on').html('NO');
    $('#slider').val(false);
});

Since you said you do not want to add anything else, how about you change the toggle function to click.
$(document).on("click", ".slider-button", function(){
   var elem = $(this);
   elem.toggleClass("on");
   var state = elem.hasClass("on");
   elem.text(state?"YES":"NO");
   elem.parent().next().val(state);
});

Running fiddle: http://jsfiddle.net/d9uFs/


text:
Q: Why does haskell throw this error? Trying to write function that numerize items of list and returns list of tuples with numbers, ya I know I can do it with 'zip' function, but task is to write it with recursion: so I get

cannot construct an infinite type: a = [a] when generalizing type(s) for numerize'

What am I doing wrong?
numerize' :: [a] -> Int -> [(a, Int)]
numerize' [] _ = []
numerize' [x] n = [(x, n)]
numerize' [x:xs] n = (x, n) : numerize' xs (n + 1)

A: [x:xs]

should be
(x:xs)


text:
Q: how to convert asquerable and igrouping to ienumrable When I use this linq I am getting error

The model item passed into the dictionary is of type 'System.Linq.Enumerable+WhereSelectEnumerableIterator'2[System.Char,System.Char]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[groupBylinq.Models.employee]'.

This is my action
public ActionResult Index()
{
    var result = from n in db.employees.Where(x => x.gender=="female")
        .GroupBy(x => x.employee_sno).ToList() select n;
    return View(result);
}

A: Result of GroupBy method is structure like [grouping_key, array[employee]]. But your view expect an array of employees. To achieve this you can do next
return View(result.SelectMany(v=>v).ToList());

But are you sure that you need GroupBy operator?


text:
Q: Sum and conditions in linear programming - Cplex // OPL Is there an easy way to apply a condition into a sum in OPL or to get around this problem ?
For example is it possible to do something like :
 forall (i in Factories)
    forall( j in Time)
        Stock[i][j] == sum (i_ in Factories where j-LeadTime[i_][i]>0) (expression)

The only way I found to get around this problem is to extend my dataset in order to avoid out of range exception but in my case that don't make any sense so I would like to apply a condition into the sum before.

A: The : operator is the correct way to add conditions to a sum statement.  You want something like the following.
 forall (i in Factories)
    forall( j in Time)
        Stock[i][j] == sum (i_ in Factories : j-LeadTime[i_][i]>0) (expression)

where isn't part of the OPL language.


text:
Q: Wix Error message 2343 In Windows Installer XML (WIX) My code compiles OK but after you accept the licence Agreement, you get the following error message: "The installer has encoutered an unexpected error installing this package. This may indicate a problem with this package. The error code is 2343. I tried to make the desktop shortcut optional after succeeding with creating one, but after deciding against it, I tried to undo the changes and got the error. My code is as follows, and since I don't know where the problem is, I can't single out a code snippet.
<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <Product Id="*" Name="MemberManagement" Language="1033" Version="1.0.0.0" Manufacturer="RFIdentity LLC" UpgradeCode="d525ca33-b610-43f8-8f02-22b5da56c72c">
    <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />

    <MediaTemplate EmbedCab="yes" />

    <Feature Id="ProductFeature" Title="MemberManagement" Level="1">
      <ComponentGroupRef Id="Files" />
      <ComponentRef Id="ApplicationShortcutDesktop"/>
      <ComponentRef Id="CMP_InboxDir" />
      <ComponentRef Id="CMP_PicturesDir"/>
      <ComponentRef Id="CMP_EmployeesDir"/>
      <ComponentRef Id="CMP_MembersDir" />
      <ComponentRef Id="CMP_00385TXT" />
      <ComponentRef Id="CMP_10104TXT" />
      <ComponentRef Id="CMP_AForgeDLL"/>
      <ComponentRef Id="CMP_AForgeXML"/>
      <ComponentRef Id="CMP_AForge.VideoDLL"/>
      <ComponentRef Id="CMP_AForge.VideoXML"/>
      <ComponentRef Id="CMP_AForge.Video.DirectShowDLL"/>
      <ComponentRef Id="CMP_AForge.Video.DirectShowXML"/>
      <ComponentRef Id="CMP_AlienRFID2DLL"/>
      <ComponentRef Id="CMP_ConfigXML"/>
      <ComponentRef Id="CMP_ConfigRFIdentityCommXML"/>
      <ComponentRef Id="CMP_DashboardXML"/>
      <ComponentRef Id="CMP_GAO236004ReaderDLL"/>
      <ComponentRef Id="CMP_MemberManagementEXE"/>
      <ComponentRef Id="CMP_Microsoft.ReportViewer.CommonDLL"/>
      <ComponentRef Id="CMP_Microsoft.ReportViewer.ProcessingObjectModelDLL"/>
      <ComponentRef Id="CMP_Microsoft.ReportViewer.WinFormsDLL"/>
      <ComponentRef Id="CMP_Microsoft.SqlServer.TypesDLL"/>
      <ComponentRef Id="CMP_Newtonsoft.JsonDLL"/>
      <ComponentRef Id="CMP_NodaTimeDLL"/>
      <ComponentRef Id="CMP_System.Net.Http.FormattingDLL"/>
      <ComponentRef Id="CMP_OutboxDir"/>
      <ComponentRef Id="CMP_GhostePNG"/>
      <ComponentRef Id="CMP_GhostmPNG"/>
    </Feature>
    <MajorUpgrade Schedule="afterInstallValidate"
                  AllowDowngrades="no"
                  DowngradeErrorMessage="You Cannot Downgrade"/>
  </Product>

  <Fragment>
    <Directory Id="TARGETDIR" Name="SourceDir">

      <Directory Id="DesktopFolder"
                 Name="Desktop">
        <Component Id="ApplicationShortcutDesktop"
                   Guid="*">
          <Shortcut Id="ApplicationDesktopShortcut"
                    Name="RF Identity MMS"
                    Description="MemberManagement"
                    Target="[MEMBERMANAGEMENTDIRPROPERTY]MemberManagement.exe"
                    WorkingDirectory="MEMBERMANAGEMENTDIRPROPERTY" />
          <RemoveFolder Id="DesktopFolder" On="uninstall"/>
          <RegistryValue Root="HKCU"
                         Key="C:\Program Files (x86)\Member Management\MemberManagement.exe"
                         Name="installed"
                         Type="integer"
                         Value="1"
                         KeyPath="yes" />
        </Component>
      </Directory>
      <Directory Id="ProgramFilesFolder">
          <Directory Id="InboxDir"
                     Name="Inbox" />
          <Directory Id="OutboxDir"
                     Name="Outbox" />
          <Directory Id="PicturesDir"
                     Name="Pictures">
            <Directory Id="EmployeesDir"
                       Name="Employees">
              <Component Id="CMP_GhostePNG"
     Guid="7E5F6F79-52AC-4B8C-837D-A04AD4B5115B">
                <File Id="FILE_MemberManagement_Pictures_MembersPNG"
                      Source="Ghost.png"
                      KeyPath="yes" />
              </Component>
            </Directory>

            <Directory Id="MembersDir"
                       Name="Members">
              <Component Id="CMP_GhostmPNG"
     Guid="3DA40D25-F724-4572-B529-45DE9B155687">
                <File Id="FILE_MemberManagement_Pictures_EmployeesPNG"
                      Source="Ghost.png"
                      KeyPath="yes" />
              </Component>
            </Directory>
          </Directory>

        </Directory>

      <Directory Id="RFIdentity" Name="RFIdentity LLC">

        <Directory Id="MEMBERMANAGEMENTDIRPROPERTY" Name="MemberManagement">
        </Directory>
 </Directory>
      </Directory>

  </Fragment>

  <Fragment>
      <!--Files-->
    <ComponentGroup Id="Files" Directory="TARGETDIR">
      <Component Id="CMP_00385TXT"
                 Guid="DB1B8002-EBE0-40BC-953B-FFD97209FC0A">
        <File Id="FILE_MemberManagement_00385TXT"
              Source="00385.txt"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_10104TXT"
                 Guid="1696EAA7-ED90-4527-936D-8122CDA145DD">
        <File Id="FILE_MemberManagement_10104TXT"
              Source="10104.txt"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_AForgeDLL"
                 Guid="3F5A2372-639B-4048-A1DF-9AE2D92DB8CE">
        <File Id="FILE_MemberManagement_AForgeDLL"
              Source="AForge.dll"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_AForgeXML"
           Guid="2C519B46-9C77-4ABB-8B2D-7912DB1A46AC">
        <File Id="FILE_MemberManagement_AForgeXML"
              Source="AForge.xml"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_AForge.VideoDLL"
     Guid="1E571689-51A3-4C8E-A3EB-31E2F49EDAB9">
        <File Id="FILE_MemberManagement_AForge.VideoDLL"
              Source="AForge.Video.dll"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_AForge.VideoXML"
     Guid="3881A2B7-EE13-4814-8370-0B51803ABB2C">
        <File Id="FILE_MemberManagement.AForge.VideoXML"
              Source="AForge.Video.xml"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_AForge.Video.DirectShowDLL"
     Guid="B7865DCF-12EC-40DF-B7CE-FCBED97DE12A">
        <File Id="FILE_MemberManagement_AForge.Video.DirectShowDLL"
              Source="AForge.Video.DirectShow.dll"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_AForge.Video.DirectShowXML"
     Guid="09E0A00E-CB2F-40A1-9AF6-A9EDF5B7C10D">
        <File Id="FILE_MemberManagement_AForge.Video.DirectShowXML"
              Source="AForge.Video.DirectShow.xml"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_AlienRFID2DLL"
     Guid="FBB8FE0C-C403-42C3-A279-A87319DA7A1C">
        <File Id="FILE_MemberManagement_AlienRFID2DLL"
              Source="AlienRFID2.dll"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_ConfigXML"
     Guid="E078DA58-EAF0-4B93-BBE3-9CCFE136B10E">
        <File Id="FILE_MemberManagement_ConfigXML"
              Source="Config.xml"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_ConfigRFIdentityCommXML"
     Guid="0AC563E1-145B-4972-AA4D-4BF54D5C1D9A">
        <File Id="FILE_MemberManagement_ConfigRFIdentityCommXML"
              Source="ConfigRFIdentityComm.xml"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_DashboardXML"
     Guid="D5A375AA-2578-4C5C-8D95-83DBDA8363BA">
        <File Id="FILE_MemberManagement_DashboardXML"
              Source="Dashboard.xml"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_GAO236004ReaderDLL"
     Guid="91AAE974-DF3B-4410-9199-1961891ED0AD">
        <File Id="FILE_MemberManagement_GAO236004ReaderDLL"
              Source="GAO236004Reader.dll"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_MemberManagementEXE"
     Guid="0E5AEA14-4692-49CD-971A-7A5A7475ECD3">
        <File Id="FILE_MemberManagement_MemberManagementEXE"
              Source="MemberManagement.exe"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_Microsoft.ReportViewer.CommonDLL"
     Guid="17CE9ABB-1CC0-4939-998B-0C41F31477A2">
        <File Id="FILE_MemberManagement.Microsoft.ReportViewer.CommonDLL"
              Source="Microsoft.ReportViewer.Common.dll"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_Microsoft.ReportViewer.ProcessingObjectModelDLL"
     Guid="02E729E4-F7DE-42CB-B192-6A4EF0F7438B">
        <File Id="FILE_MemberManagement_Microsoft.ReportViewer.ProcessingObjectModelDLL"
              Source="Microsoft.ReportViewer.ProcessingObjectModel.dll"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_Microsoft.ReportViewer.WinFormsDLL"
     Guid="ECDB56C5-0CF9-4574-941F-417B08C68C98">
        <File Id="FILE_MemberManagement_Microsoft.ReportViewer.WinFormsDLL"
              Source="Microsoft.ReportViewer.WinForms.dll"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_Microsoft.SqlServer.TypesDLL"
     Guid="BD62B42E-05FA-4B19-AE38-59DC52DA60B5">
        <File Id="FILE_MemberManagement.Microsoft.SqlServer.TypesDLL"
              Source="Microsoft.SqlServer.Types.dll"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_Newtonsoft.JsonDLL"
     Guid="CACC1E96-EC82-4946-A2F0-592A7EB236ED">
        <File Id="FILE_MemberManagement.Newtonsoft.JsonDLL"
              Source="Newtonsoft.Json.dll"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_NodaTimeDLL"
     Guid="BC333575-BEA8-4D0F-BF69-50907BAF8273">
        <File Id="FILE_MemberManagement_NodaTimeDLL"
              Source="NodaTime.dll"
              KeyPath="yes" />
      </Component>
      <Component Id="CMP_System.Net.Http.FormattingDLL"
     Guid="386D83B7-62D7-4F7B-8FFD-C7D1395C1FBD">
        <File Id="FILE_MemberManagement_System.Net.Http.FormattingDLL"
              Source="System.Net.Http.Formatting.dll"
              KeyPath="yes" />
      </Component>
    </ComponentGroup>
    <!--Folders-->
    <UIRef Id="WixUI_InstallDir" />

    <DirectoryRef Id="InboxDir">
      <Component Id="CMP_InboxDir"
                 Guid="65052C92-432D-4DA9-A7E9-8DABD5E4BF84"
                 KeyPath="yes">
        <CreateFolder />
      </Component>
    </DirectoryRef>
    <DirectoryRef Id="OutboxDir">
      <Component Id="CMP_OutboxDir"
                 Guid="F1589519-FF2A-40D3-A218-5A414EF44EDD"
                 KeyPath="yes">
        <CreateFolder />
      </Component>
    </DirectoryRef>
    <DirectoryRef Id="PicturesDir">
      <Component Id="CMP_PicturesDir"
                 Guid="B43CA519-8037-402B-A6EE-AA69C0ECE47A"
                 KeyPath="yes">
        <CreateFolder />
      </Component>
    </DirectoryRef>
    <DirectoryRef Id="EmployeesDir">
      <Component Id="CMP_EmployeesDir"
                 Guid="D6D4916B-B657-478B-B01A-0CF9B7485809"
                 KeyPath="yes">
        <CreateFolder />
      </Component>
    </DirectoryRef>
    <DirectoryRef Id="MembersDir">
      <Component Id="CMP_MembersDir"
                 Guid="85BD631F-0CD0-4B2A-B846-AC7929FA1751"
                 KeyPath="yes">

        <CreateFolder />
      </Component>
    </DirectoryRef>
<Property Id="WIXUI_INSTALLDIR"
          Value="MemberManagementFolder" />

    <WixVariable Id="WixUIBannerBmp" Value="banner.bmp"/>
    <WixVariable Id="WixUIDialogBmp" Value="InstallBackground.bmp"/>
    <WixVariable Id="WixUILiscenseRtf" Value="LiscenceAgreement.rtf"/>
  </Fragment>

</Wix>


text:
Q: Flexible way of passing key event to currently selected tab, using notebook from tkinter As far as I can tell, I cannot bind a keypress to the current tab since it won't have the focus. I was imagining that I could do a bind_all instead and then it would call a function in the tab's child. Something like this,
class A(Frame):
  ...
  def onSpacebar(self):
    <do something>

class B(Frame):
  ...
  def onSpacebar(self):
    <do something>

class Tabbed(Frame):
  def __init__(self, **kw):
    ...
    self.nb = Notebook(self)
    self.nb.add(A(nb), text=A.getTitle())
    self.nb.add(B(nb), text=B.getTitle())

    self.bind_all("<space>", self.onSpacebar)

  def onSpacebar(self,e=None):
    self.nb.select().child().onSpacebar() <---something equivalent

Is it possible to reference object A or B in something like this way?
I know there are plenty of ways of accomplishing this with using the index and saving off A and B, using dicts, etc.
This is a simple example for illustration. Imagine if there were 20 tabs, and some tabs may not be added, depending on some parameter. Therefore, not depending on tab names or indexes would be great. Or maybe there is completely better solution for binding the spacebar(or any other key) to a tab.
Thanks.


text:
Q: How to decode Google spreadsheet's Json respose as a Php Array My google Docs Spreadsheet call returns this response in the json format
(I only need everything after "rows")
please look at the formatted response here : )
I use php's json_decode function to parse the data and use it (Yes, I am awful at php) This code returns NULL, and according to the documentation, NULL is returned "if the json cannot be decoded".

$json = file_get_contents($jsonurl);
  $json_output = json_decode($json);
var_dump ($json_output); // Returns NULL

Basically, what i want to accomplish is to make a simple array from the first row values of the Json response.
like this
$array = {'john','John Handcock','email@yahoo.com','2929292','blanc'}

You guys are genius, I would appreciate your insight and help on this very much!
Answer as "sberry2A" mentions bellow, the response is not valid Json, google offers the Zend Json library for this purpose, tho I decided to parse the tsv-excel version instead :)

A: The data in the link you provided is not valid JSON.  What you have provided appears to be the decoded version.  You can tell that is in not JSON because the array keys are not quoted.  For instance, version should be 'version'.
Your data should look more like this
'{"version":"0.6","reqId":"requestIDnumber","status":"ok","sig":"65724392","table":{"cols":[{"id":"A","label":"slug","type":"string", "pattern":""},{"id":"B","label":"name","type":"string","pattern":""},{"id":"C","label":"email","type":"string","pattern":""},{"id":"D","label" :"nsid","type":"number","pattern":"#0.###############"},{"id":"E","label":"theme","type":"string","pattern":""}],"rows":[{"c":[{"v":"mo"},{"v": "Mohammad Taheri"},{"v":"email@yahoo.com"},{"v":"2929292.0","f":"2929292"},{"v":"blanc"}]}]}}'

$json = '{"version":"0.6","reqId":"requestIDnumber","status":"ok","sig":"65724392","table":{"cols":[{"id":"A","label":"slug","type":"string", "pattern":""},{"id":"B","label":"name","type":"string","pattern":""},{"id":"C","label":"email","type":"string","pattern":""},{"id":"D","label" :"nsid","type":"number","pattern":"#0.###############"},{"id":"E","label":"theme","type":"string","pattern":""}],"rows":[{"c":[{"v":"mo"},{"v": "Mohammad Taheri"},{"v":"email@yahoo.com"},{"v":"2929292.0","f":"2929292"},{"v":"blanc"}]}]}}';
$data = json_decode($json);
print_r($data->table->rows);

//output
Array ( [0] => stdClass Object ( [c] => Array ( [0] => stdClass Object ( [v] => mo ) [1] => stdClass Object ( [v] => Mohammad Taheri ) [2] => stdClass Object ( [v] => email@yahoo.com ) [3] => stdClass Object ( [v] => 2929292.0 [f] => 2929292 ) [4] => stdClass Object ( [v] => blanc ) ) ) )

A: Did you try removing the callback function from the response myData(...)?

A: $json = file_get_contents($jsonfile);
$data = json_decode($json);
print_r($data);

A: The PEAR package Services_Json is able to parse JSON with unquoted keys. So, strip the callback and parse with Services_Json and I believe that will work.
http://mike.teczno.com/JSON/doc/


text:
Q: how to redirct logs to files or suppress printing log to console screen when the log operationed in another code file pythonHelper.py:
import logging
log = logging.getLogger(__name__)
class PythonHelper():
    def __init__(self):
        log.info("message1")
        pass
    def func(self):
        log.info("message2")
        pass
    def main(self):
        self.func()

runner.py:
from pythonHelper import PythonHelper
class Runner(PythonHelper):
    pass

if __name__ == "__main__":
    a = Runner()
    a.main()
    # do something on a:
    # which would print "message1" and "message2"
    # to console screen and store them into files.

I cannot do any change in pythonHelper.py file. But I would like to suppress printing logs on console screen because printing is slow... How could I implement it? I only have a silly method using "command > output.txt" but I expect a method that change or add something in my runner code.

A: If I got your point you can add the file handler:
import logging
from pythonHelper import PythonHelper

logging.getLogger().setLevel(logging.DEBUG) # Set this level for demo only
fh = logging.FileHandler('output.log') # here the handler
logging.getLogger().addHandler(fh)   # added to the logging

class Runner(PythonHelper):
    def new_func(self):
        pass

if __name__ == "__main__":
    a = Runner()
    a.func()

you can read more here using-logging-in-multiple-modules


text:
Q: __int64 for GCC as a Preprocessor Option Usually Microsoft code uses __int64 which is not understood by GCC.
I know I can write it as a macro like this:
#define __int64 long long

But I don't want to do this, due to code portability.
I'm trying to give GCC the following Preprocessor Option:
-D__int64="long long"

I get the following error due to the space between the two long's:
gcc.exe: error: long: No such file or directory

How to fix it ?

A: You could use int64_t, the standard name for that type, but it will only work if the code does #include <stdint.h>, and that's perhaps hoping for too much.
Otherwise you could try to "sneak" in a typedef in some common header:
typedef long long __int64;

Perhaps doing that only if GCC is detected.
Fixing it "your way" should certainly be possible, it looks like some quoting issue.

A: Sounds like you have a double-eval issue if your example doesn't work.  If you can't figure out why that is happening you can try using gcc's -include or -imacros option.  You would create a new file gcc_extra_definess with the #defines you want to add, and call gcc -include gcc_extra_defines ... to get gcc to read that file and include it before reading the source file.  This is a bit easier than a bunch of -D options for defining multiple things, particularly if you have quoting issues or want things other than macros.

A: Looks like a quoting problem caused by gcc seeing only
gcc ... -D__int64=long long

Can you show us the script or Makefile snippet you use? What shell is it?


text:
Q: MaxReceivedMessageSize Error when Calling Batch Service from Application but not from SoapUI I have a very annoying issue when sending a request to a web service.
One of the parameters of the request message is Batch, which can be set to either Y or N. When I set this to N there is no issue, and I get a response containing details for a single order.
However, when I set Batch to Y, I see this error:

Additional information: The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element.

To resolve this, I tried setting the MaxReceivedMessageSize before calling the service:
public Provider.GetMessageResponse GetOrders(bool acceptBatch)
{
    var httpBinding = new BasicHttpBinding();
    httpBinding.MaxReceivedMessageSize = 2097152;
    httpBinding.MaxBufferSize = 2097152;

    var request = BuildRequest(acceptBatch);
    var client = new Provider.PullServiceClient();
    var response = client.PullGetMessage(SecurityToken, request);
    return response;
}

However, I still see the error message (even though I can see that httpBinding.MaxReceivedMessageSize has indeed been increased after running that code), and the service (not hosted by me) tells me that the messages have been collected (which does make sense, as it seems as if the messages are only being blocked once they reach my system).
Furthermore, when I execute the exact same request from the SoapUI application using xml, I do receive a batch response without any issues, and I can see a long list of all available orders.
So does this MaxReceivedMessageSize property only apply to my application and not the whole system? If that is the case, why does the code above not resolve this?

A: After looking at what overloaded constructors there were for Provider.PullServiceClient, I managed to resolve this issue by including the following parameters:
var binding = new BasicHttpBinding() { MaxReceivedMessageSize = 2097152, MaxBufferSize = 2097152 };
var endpoint = new EndpointAddress("http://test.providerporal.co.za/testservice/pullservice.svc");

var client = new Provider.PullServiceClient(binding, endpoint);

So I guess this limit is somehow related to my application, but the HttpBinding needed to be bound to request itself. Hopefully this helps someone else.


text:
Q: Is $B^TAB>0$ if $B>0$ and $A >0$? If matrix $A$ is positive definite and matrix $B$ is positive definite, is $B^TAB$ positive definite?

A: Yes. For any $v\neq0$,
$$v^T(B^TAB)v=(Bv)^TA(Bv)>0$$
because $Bv\neq0$. Note that we only need that $A$ is positive definite and $B$ is non-singular.


text:
Q: Cannot Get Pygtk to Display Label in Hbox I'm extremely new to Pygtk and Stackoverflow in general. I'm trying to build a small dictionary application: I have one master VBox and an Hbox containing two Vboxes divided by a Vseparator. I am trying to display text through a label in the right-hand Vbox, but it will not appear. Here's my pitiful code:
    import gtk
    import pygtk
    from Wordlist import *
    pygtk.require('2.0')
      def click_handler(button):
        for i in nouns:
          print i
          k = gtk.Label(str=i)
          k.show()
          meaningvbox.pack_start(k,True,True,0)

    window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    window.set_size_request(300,400)
    window.set_title("English-Japanese Reference")
    window.show()
    window.connect("delete-event", gtk.main_quit)
    vbox = gtk.VBox(False,0)
    window.add(vbox)
    vbox.show()
    hbox = gtk.HBox(True,0)
    vbox.pack_end(hbox,False)
    hbox.show()
    hbox2 = gtk.HBox(True,0)
    vbox.pack_end(hbox2,False)
    hbox2.show()
    vsep = gtk.VSeparator()
    vbox.pack_start(vsep)
    vsep.show()
    dichbox = gtk.HBox()  #### These are boxes created to store the words
    vbox.pack_start(dichbox)
    wordvbox = gtk.VBox()
    dichbox.pack_start(wordvbox)
    wordvbox.show()
    meaningvbox = gtk.VBox()
    dichbox.pack_start(meaningvbox)
    meaningvbox.show()
    label = gtk.Label(str="hi")
    meaningvbox.pack_start(label)
    label.show()
    verbButton = gtk.Button(label="Verbs")
    hbox.pack_end(verbButton,True,False)
    verbButton.set_size_request(100,30)
    verbButton.show()
    nounButton = gtk.Button(label="Nouns")
    nounButton.set_size_request(100,30)
    hbox.pack_end(nounButton,True,False)
    nounButton.show()
    nounButton.connect("clicked", click_handler)
    familyButton = gtk.Button(label="Family")
    familyButton.set_size_request(100,30)
    hbox.pack_end(familyButton,True,False)
    familyButton.show()
    particleButton = gtk.Button(label="Particles")
    hbox2.pack_end(particleButton,True,False)
    particleButton.set_size_request(100,30)
    particleButton.show()
    adjectiveButton = gtk.Button(label="Adjectives")
    adjectiveButton.set_size_request(100,30)
    hbox2.pack_end(adjectiveButton,True,False)
    adjectiveButton.show()
    pronounButton = gtk.Button(label="Pronouns")
    pronounButton.set_size_request(100,30)
    hbox2.pack_end(pronounButton,True,False)
    pronounButton.show()
    def main():
        gtk.mainloop()

    main()

A: You forgot to call dichbox.show().
I would also recommend to restructure your code and group similar function calls, use show_all() instead of many show()s  and use a class for the whole window.
That's what it would look like:
import pygtk
pygtk.require('2.0')
import gtk
from Wordlist import *

class Window(gtk.Window):
    def __init__(self):
        gtk.Window.__init__(self,gtk.WINDOW_TOPLEVEL)
        self.set_size_request(300,400)
        self.set_title("English-Japanese Reference")
        self.connect("delete-event", gtk.main_quit)

        verbButton = gtk.Button(label="Verbs")
        nounButton = gtk.Button(label="Nouns")
        nounButton.connect("clicked", self.click_handler)
        familyButton = gtk.Button(label="Family")
        particleButton = gtk.Button(label="Particles")
        adjectiveButton = gtk.Button(label="Adjectives")
        pronounButton = gtk.Button(label="Pronouns")

        verbButton.set_size_request(100,30)
        nounButton.set_size_request(100,30)
        familyButton.set_size_request(100,30)
        particleButton.set_size_request(100,30)
        adjectiveButton.set_size_request(100,30)
        pronounButton.set_size_request(100,30)

        hbox = gtk.HBox(True,0)
        hbox.pack_end(verbButton, True, False)
        hbox.pack_end(nounButton, True, False)
        hbox.pack_end(familyButton, True, False)

        hbox2 = gtk.HBox(True,0)
        hbox2.pack_end(particleButton, True, False)
        hbox2.pack_end(adjectiveButton, True, False)
        hbox2.pack_end(pronounButton, True, False)

        label = gtk.Label("hi")
        self.meaningvbox = gtk.VBox()
        self.meaningvbox.pack_start(label)
        wordvbox = gtk.VBox()
        vsep = gtk.VSeparator()
        dichbox = gtk.HBox()
        dichbox.pack_start(wordvbox)
        dichbox.pack_start(vsep)
        dichbox.pack_start(self.meaningvbox)

        vbox = gtk.VBox(False, 0)
        vbox.pack_end(hbox, False)
        vbox.pack_end(hbox2, False)
        vbox.pack_start(dichbox)

        self.add(vbox)
        self.show_all()

    def click_handler(self,button):
        for i in nouns:
            k = gtk.Label(i)
            k.show()
            self.meaningvbox.pack_start(k, True, True, 0)

def main():
    win = Window()
    gtk.main()

main()


text:
Q: plot.gam and draw.gam produce different smooths for same GAMM object when using factor smooths I've been experimenting with plotting different GAMMs using the plot.gam function from the mgcv package and draw.gam function from the gratia package. When plotting a GAMM with a beta distribution (using factor smooths as 'random effects'), I noticed the smooths were different. In large, they have the same shape, but the smooths do differ, and I was wondering if I have coded something wrong, or if there are differences between the functions I have overlooked when dealing with factor smooths? Without factor smooths, these differences were not present.
I have the newest version of the package gratia installed.
My concrete question is: Is there a reason for these differences in the smooths?
Here is a reproducible example:
devtools::install_github('gavinsimpson/gratia')
library(gratia)

data <- gamSim(4, 400) %>%
  mutate(rand = rep(letters[1:4], each = 100), rand = as.factor(rand))

model_3 <- bam(
  y ~
    s(x2, by = fac) +
    s(x2, rand, by = fac, bs = "fs", m = 1),
  data = data
)

draw(model_3, fun = plogis, constant = (coef(model_3)[1]),
     select = c(1,2,3)) & theme_bw()

plot(model_3,
     shade = TRUE,
     shade.col = "lightblue",
     shift = coef(model_3)[1],
     trans = plogis,
     seWithMean = T,
     pages = 1)

Would be grateful for input! Thanks!

A: This was a bug introduced in 0.7.0-1 when I edited the code to fix a separate problem and made a silly mistake. I didn't catch it as this wasn't being tested before and I didn't notice the error when I looked at the test output when I edited the code and wrote tests.
The issue was that while the constant was being added in the add_constant() call, the code didn't return the modified object. Instead the original object was being return by add_constant().
I have fixed this locally and will push the fix to GitHub shortly. Look for version 0.7.0-5


text:
Q: Number of Acute Angle in an N sides polygon Let P be a convex polygon of n sides containing a maximal number of acute angles. If one of the angles of P is chosen random, what percent represents the probability that the angle chosen will be acute?
I know if I take a decagon (10-gon) the most it will have is 3. Because the angles of the 10-gon need to sum up to $8\cdot 180^\circ = 1440^\circ$. If there are $4$ acute angles, then they sum up to less than $360^\circ$, which means the remaining $6$ angles need to sum up to more than $1080^\circ$, impossible since each one is at most $180^\circ$.
On the other hand, to have $3$ acute angles, draw four consecutive segments that almost form a square, and connect the two end vertices with six short segments.
How can I set this up with smaller cases to get the probability to then expand to the n-case

A: The maximum number of acute angles is always $3$ - effectively, take an equilateral triangle and curve out one (or more) of the edges slightly with a series of short edges. And you cannot ever have $4$ acute angles for the reasons you gave.
So the probability of choosing an acute angle in such a polygon is always $\frac {\large 3}{\large n}$


text:
Q: ATMega chips come with the Arduino bootloader Do the Arduino Duemilanove USB Board with Atmega328 come with the Arduino bootloader?

A: Yes - all boards with ATMega labelled Arduino come with the bootloader. Individual chips will say specifically, generaly if ordered from an Arduino supplier then they will have bootloader, whilst if ordered from generic electronic supplier they will not.


text:
Q: Count how many consecutive days a user log in I have a table that contains every login a user makes. I need to count how many consecutive days a user log in.
I just compute the count by selecting all timestamp and cycling them with php.
Is there a more practical way to do this with mysql?
I have a users_login table with user and datetime column:
SELECT `datetime` FROM `users_login` WHERE `user_id`=`3123` order by `datetime` desc;

Right now I implemented a for loop to scan every datetime and check if the timestamp is inside the day range.
Should I keep track of the count at every login? I means, having a column consec_days starting from 0 and increasing by one at every daily login?


text:
Q: simple blob detection with kinect SDK as far as I understand the official Kinect 1.5 SDK, it comes with Face Tracking and Skeleton Tracking. How about simple blob detection? All I want to do, is to track a round / elliptic object. I can't find any code for that in the SDK, so should I use opencv or some other library for that?
(my code is in c++)
EDIT1 is it possible to tune the face tracker so it would detect round shapes in general (instead of faces)?
EDIT2
here's depth processing code from an example shipped with the SDK. How do I get OpenCV to extract a blob from it?
void CDepthBasics::ProcessDepth()
{
    HRESULT hr;
    NUI_IMAGE_FRAME imageFrame;

    // Attempt to get the depth frame
    hr = m_pNuiSensor->NuiImageStreamGetNextFrame(m_pDepthStreamHandle, 0, &imageFrame);
    if (FAILED(hr))
    {
        return;
    }

    INuiFrameTexture * pTexture = imageFrame.pFrameTexture;
    NUI_LOCKED_RECT LockedRect;

    // Lock the frame data so the Kinect knows not to modify it while we're reading it
    pTexture->LockRect(0, &LockedRect, NULL, 0);

    // Make sure we've received valid data
    if (LockedRect.Pitch != 0)
    {
        BYTE * rgbrun = m_depthRGBX;
        const USHORT * pBufferRun = (const USHORT *)LockedRect.pBits;

        // end pixel is start + width*height - 1
        const USHORT * pBufferEnd = pBufferRun + (cDepthWidth * cDepthHeight);

        while ( pBufferRun < pBufferEnd )
        {
            // discard the portion of the depth that contains only the player index
            USHORT depth = NuiDepthPixelToDepth(*pBufferRun);

            // to convert to a byte we're looking at only the lower 8 bits
            // by discarding the most significant rather than least significant data
            // we're preserving detail, although the intensity will "wrap"
            BYTE intensity = static_cast<BYTE>(depth % 256);

            // Write out blue byte
            *(rgbrun++) = intensity

            // Write out green byte
            *(rgbrun++) = intensity;

            // Write out red byte
            *(rgbrun++) = intensity;

            // We're outputting BGR, the last byte in the 32 bits is unused so skip it
            // If we were outputting BGRA, we would write alpha here.
            ++rgbrun;

            // Increment our index into the Kinect's depth buffer
            ++pBufferRun;

        }

        // Draw the data with Direct2D
        m_pDrawDepth->Draw(m_depthRGBX, cDepthWidth * cDepthHeight * cBytesPerPixel);
    }

    // We're done with the texture so unlock it
    pTexture->UnlockRect(0);

    // Release the frame
    m_pNuiSensor->NuiImageStreamReleaseFrame(m_pDepthStreamHandle, &imageFrame);
}

A: You could use this, since OpenCV sadly doesn't support handling blobs by itself:
http://opencv.willowgarage.com/wiki/cvBlobsLib

A: Once you've got the image you need from the Kinect feel free to use any image processing library with the result.
You can use OpenCV's Hough Circle Transform to detect circles. You might need to convert from the Kinect image format to cv::Mat first.
I imagine OpenCV is not the only library with that functionality. If you're interested, lookup Hough Transforms in general.
I don't think tuning the face tracker is the way to go though.


text:
Q: Extracting a specific value from a div class I have a div tag which looks something like this:

some content here

I understand that I can get the id of this div using jquery like this:
$(this).closest("div").attr("id")

But how do I extract just the portlet_15 from the above class where 15 could be any number?
Here is an extract of the code showing where I am currently getting and sending off the id of the div:
$.ajax({
    url: 'some web service,
    type: 'POST',
    data: { strID:$(that).closest("div").attr("id"), strClass:"need to send the class value too right here, in this case it would be portlet_15" },
    error: function(xhr, status, error) {
        //some error message;
    },
    success: function() {
        //some success task
    }
});

I have included a note in the data part of the code above where the class should go.

A: Your existing code is a bit confusing, since you don't tell what this refers to. If it refers to your particular div element, then using closest isn't correct because that already traverses up the DOM hierarchy.
But otherwise if you'd like to get all those CSS classes of a particular element, this is what you have to call:
$(this).attr("class").split(" ");
// in your case this would return an array of classes:
// ["portlet", "portlet_15", "portlet_content_15", "new"]

this of course refers to the element in question. Then you can easily parse individual classes the way that you like. If you'd like to extract the number out, you'll likely use a regular expression:
/portlet_(\d+)/i;

Use data- attributes
But as others suggested, getting data across would be much better if you'd do that using data-attributes as in:

         some content here

in this case both portlet-related classes are provided as data attributes, that you can easily access using:
$(this).data("portlet"); // would return 15
$(this).data("portletContent"); // would return 15
$(this).data("portlet-content"); // would return 15

The last two are variation of accessing the same data attribute with a hyphen'd name.

A: try this:
var c = $('#here').attr("class").split(' ')[1];
var cls = c.substr(-2);

http://jsfiddle.net/caCPv/1/

A: You can also do a regex like this:
var found = $('#here').attr("class").match(/portlet_\d{1,3}/);

A: Maibe using a regex:
var element = $(that).closest("div");
var strClass = element.attr("class").match(/portlet_\d+/i);

And in your ajax:
data: { strID: element.attr("id"), strClass: strClass[0] },


text:
Q: Need to change SQL query in android studio database to return multiple results I have a functioning database within my android app that returns one result queries.  I am trying to return multiple results for a Wine keyword but every time I try the app crashes when i run it.  I am fairly new to android coding so I could be missing something obvious.
The first .java is the search function.  The second one is the query activity.
package com.example.winedatabase;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseAccess {
    private SQLiteOpenHelper openHelper;
    private SQLiteDatabase db;
    private static DatabaseAccess instance;
    Cursor c = null;

    //private constructor so that object creation from outside is avoided
    private DatabaseAccess(Context context){
        this.openHelper = new DatabaseOpenHelper(context);

    }

    //to return the single instance of database
    public static DatabaseAccess getInstance(Context context){
        if(instance == null){
            instance= new DatabaseAccess(context);

        }
        return instance;
    }

    //to open the database
    public void open(){
        this.db = openHelper.getWritableDatabase();
    }
    //closing the database connection
    public void close(){
        if (db != null) {
            this.db.close();
        }
    }
    //method to query and return the result from the database
    public String getKeyword(String winename){
        c = db.rawQuery(" select WineName from Wine where WineName LIKE %'"+winename+"'%", new String[]{});
        StringBuffer buffer = new StringBuffer();
        while(c.moveToNext()){
            String description = c.getString(0);
            buffer.append(""+description);
        }
        return buffer.toString();
    }

}

package com.example.winedatabase;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class KeywordSearch extends AppCompatActivity {

    public EditText name;
    public Button query_button;
    public TextView result_address;

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

        name = findViewById(R.id.name);
        query_button = findViewById(R.id.query_button);
        result_address = findViewById(R.id.result);

        //set onClickListnener to query button

        query_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //create the instance of database access class and open database connection

                DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
                databaseAccess.open();

                //get string value of edittext

                String n = name.getText().toString();
                String description = databaseAccess.getKeyword(n);  //used the get address method to get address

                //set text to result field
                result_address.setText(description);
                databaseAccess.close();
                //database connection closed

            }
        });
    }
}

A: Your query is syntactically wrong. The wildcard % and the parameter winename should be enclosed inside single quotes, but also it is recommended and safer to pass the parameter winename in the 2nd argument of rawQuery().
Change to this:
c = db.rawQuery(
    "select WineName from Wine where WineName LIKE '%' || ? || '%'",
    new String[]{winename}
);


text:
Q: jQuery asp:Menu link replacement I have an  control that has a horizontal layout, and is supplied data by an XML file based on the user.  When I run launch the page from localhost, the mouseover on the HOME node gets replaced by the jQuery script.  When I click on another node in the menu, the page renders (postback), but the script does not replace the HREF on the Home menu node.
The source of the Menu control renders like this:

Home

Sales

I have the following script in my ASPX page.

How to I get the script to fire off on each click of the menu?
** I understand this might be a hacky solution.  A sitemap file doesn't suit my purpose, so I'm trying to get around the limitation of not being able to set the URL on the top node of the menu (https://stackoverflow.com/questions/19797424/setting-url-of-top-node-in-aspmenu-control).


text:
Q: How to traverse in jQuery within AJAX function? I am having difficulty traversing with jQuery.  I have a form with a dynamic set of dropdown boxes, and am trying to call particular actions based on element class instead of id, as this form can be cloned in my application.
Any ideas why my traversing isn't working?  Is my $(this) call becoming voided somehow?
HTML:

    Item:
    <select class="item" name="item" id="item">
        <option value="">Select</option>
        ...
    </select>

    Options:
    <select class="options" name="options" id="options">

        ...
    /select>

Javascript:
$(".item").change(function () {

  var group_id = $(this).val();

   $.ajax({
        type: "POST",
        url: "../../db/items.php?id=" + group_id,
        dataType: "json",
        success: function(data){
            $(this).parent().next().children('select.options').empty();
            $(this).parent().next().children('select.options').append('<option value="">Select</option>');
            $.each(data, function(i, val){
               $(this).parent().next().children('select.options').append('<option value="' + val.group_id + '">' + val.name + '</option>');
            });
            $(this).parent().next().children('select.options').focus();
        },
        beforeSend: function(){
            $(this).parent().next().children('select.options').empty();
            $(this).parent().next().children('select.options').append('<option value="">Loading...</option>');
        },
        error: function(){
            $(this).parent().next().children('select.options').attr('disabled', true);
            $(this).parent().next().children('select.options').empty();
            $(this).parent().next().children('select.options').append('<option value="">No Options</option>');
        }
    })

});

A: this is no longer the DOM element that the event was triggered on. You can set the value of this by using the context option of $.ajax:
$(".item").change(function () {
    $.ajax({
        /* options */
        context: this,
        success: function () {
            // this is now the element that was changed
        }
    });
});

You could also store the value of this in a variable and use it in your callback:
$(".item").change(function () {

  var group_id = $(this).val();
  var self = this;

   $.ajax({
        type: "POST",
        url: "../../db/items.php?id=" + group_id,
        dataType: "json",
        success: function(data){
            // use "self" instead of "this"
        }
    })

});

Another note: You should consider caching your selectors for greater performance (and readability). Also, you can chain together jQuery function calls:
var $children = $(this).parent().next().children('select.options')
    .empty()
    .append('<option value="">Select</option>');

$.each(data, function(i, val){
   $children.append('<option value="' + val.group_id + '">' + val.name + '</option>');
});
$children.focus();

A:  var group_id = $(this).val();
 var myThis = $(this);

   $.ajax({
        type: "POST",
        url: "../../db/items.php?id=" + group_id,
        dataType: "json",
        success: function(data){
            myThis.parent().next().children('select.options').empty();
        ...

A: Yup, $this now refers to the success function in your ajax call. Add this line.
$(".item").change(function () {

  var group_id = $(this).val();
  var item = $(this); // Added line

Now in your ajax function use item where you use $this.


text:
Q: Android async image load So I have an activity with an ImageView. My goal is to have the activity start and asynchronously fetch the image I need in there. While the image is being fetched, I'd like to display some sort of spinning loading symbol in place of the image. I've tried using AsyncTask as a separate class, but ran into issues relating to modifying the views of another activity. I tried an anonymous Runnable class inside the activity, but it doesn't seem to be yielding the effects I expect. Can anyone advise?
SOLVED: Simply needed a handler in the activity
    final Handler handler = new Handler() {
          public void  handleMessage(Message msg) {
              ImageView qrCode =  (ImageView)findViewById(R.id.qr);
              qrCode.setImageBitmap((Bitmap)msg.obj);
          }
     };

    new Thread(new Runnable(){

            public void run() {
                BitmapFactory.Options bmOptions;
                bmOptions = new BitmapFactory.Options();
                bmOptions.inSampleSize = 1;
                int retry = 0;
                Bitmap bm = null;
                while(retry < 50 && bm == null){
                    bm = LoadImage(image_URL, bmOptions);
                    if(bm == null){
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    retry++;
                }
                Message msg = new Message();
                msg.obj = bm;
                handler.sendMessage(msg);
                return;
            }

    }).start();
    `

A: Place a progress dialog inside of the view with the imageview.
set the imageview ImageView.visibility(View.INVISIBLE);
In your preExecute() in your AsyncTask
Show the spinning dialog, and then do the fetching in the doInBackground() of the AsyncTask
In onPostExecute() show your imageview by changing the visibility and dismiss the dialog or sets its visibility to View.GONE

A: Android's developer guide for threading should help you out.  It has AsyncTask examples that pretty much do exactly what you're asking for:
Android Threading Guide
If you don't implement the publishProgress() method, and only implement doInBackground to get the data, and onPostExecute to update the UI, then it should by default give you the spinning icon to indicate that it's loading.  Keep in mind that onPostExecute runs on the main UI thread so you can't make any network calls from there

A: I did something similar and did according to this tutorial:
http://evancharlton.com/thoughts/lazy-loading-images-in-a-listview


text:
Q: Importing module from string in the Python C API Importing Python modules from files is relatively easy with the Python C API with PyImport_Import() however I would need to use functions stored in strings. Is there a way to import python modules from strings (to clarify: there is no file; the code is in a string) or will I have to save the strings as temp files?

A: No need to use temp files. Use this code:
const char *MyModuleName = "blah";
const char *MyModuleCode = "print 'Hello world!'";
PyObject *pyModule = PyModule_New(MyModuleName);
// Set properties on the new module object
PyModule_AddStringConstant(pyModule, "__file__", "");
PyObject *localDict = PyModule_GetDict(pyModule);   // Returns a borrowed reference: no need to Py_DECREF() it once we are done
PyObject *builtins = PyEval_GetBuiltins();  // Returns a borrowed reference: no need to Py_DECREF() it once we are done
PyDict_SetItemString(localDict, "__builtins__", builtins);

// Define code in the newly created module
PyObject *pyValue = PyRun_String(MyModuleCode, Py_file_input, localDict, localDict);
if (pyValue == NULL) {
    // Handle error
}
else
    Py_DECREF(pyValue);

This is code taken from a real commercial application (I've slightly modified it by removing error handling and other non-needed details).
Just set the wanted module name in MyModuleName and the Python code in MyModuleCode and you are done!

A: If my understanding is correct, you could use PyImport_ImportModule which takes a const char* name to specify the module to be imported.
Since my understanding was incorrect:
It would generally be better to dump the contents to a .py file and then execute them with PyRun_File but, if you have strings and want to work with those I guess you could use Py_CompileString to compile it to a code object and then feed it to PyEval_EvalCode for evaluation.

A: I've had success following the strategy laid out by Dimitirs.
            Py_Initialize();
            PyObject *module = Py_CompileString(
                // language: Python
                R"EOT(
fake_policy = {
      "maxConnections": 4,
      "policyDir": "/tmp",
      "enableVhostPolicy": True,
      "enableVhostNamePatterns": False,
})EOT",
                "test_module", Py_file_input);
            REQUIRE(module != nullptr);

            PyObject *pModuleObj = PyImport_ExecCodeModule("test_module", module);
            REQUIRE(pModuleObj != nullptr);
            // better to check with an if, use PyErr_Print() or such to read the error

            PyObject *pAttrObj = PyObject_GetAttrString(pModuleObj, "fake_policy");
            REQUIRE(pAttrObj != nullptr);

            auto *entity = reinterpret_cast<qd_entity_t *>(pAttrObj);
            REQUIRE(qd_entity_has(entity, "enableVhostNamePatterns"));  // sanity check for the test input

            // call Py_DecRef s

I used https://awasu.com/weblog/embedding-python/calling-python-code-from-your-program/ as another reference, when writing this.


text:
Q: Grant the original question the upvotes if another is closed as a duplicate of it I have occasionally seen questions which have lot of duplicates, yet aren't as highly voted as one might expect given the views.
So I suggest that all upvotes (or some percent of it) on the duplicate be also applied to the original (up to some maximum, with consideration of duplicate's age, perhaps).
These questions have, after all, helped many users, and this might be one way to grant some proportionate reward from people who can't reward it (new users lacking the upvote privilege). I'd just like it if some measure of the approval that the dupe generated be applied to the original.
As an example, consider this Ask Ubuntu question, which has as of this writing, 29 upvotes. It has well over 150 posts linked to it, some of which are upvoted. Guessing that 80% of these are actually duplicates of it, and 10% of these have an upvote, and say 60% (rounded up to next int) of the upvotes are given to it, it would get some 8 upvotes more. Not much, but still a definite boost to that question.
I'm not trying to punish duplicates (as intended in Prevent upvotes for duplicates, or carry upvotes to master question), or completely transfer all votes from duplicate to original. I'd just like it if some measure of the approval that the dupe generated be applied to the original.

A: This question is going to require a somewhat theoretical/philosophical answer. So, let's dig in. What does reputation really represent, anyway?
There are a couple of conflicting ideas on this point, and both need to be addressed. The first (and the one I'm partial to) is that it's a measure of trust the community has in a user to act in the best interests of the site. The other is that it's a measure of how many people you've helped - i.e. how 'reputable' your posts are.

As a measure of trust, dumping large amounts of reputation onto someone is... somewhat defective.
Reputation is a rough approximation of the trust we hold in someone to act in the best interest of the site. That's why we really don't want to be giving users large amounts of privileges at a time, and it's why the reputation graph is scaled the way it is. The more destructive a privilege, the more time you have to spend watching other people use it in order to gain access to it.
For example, 10k users gain the ability to delete questions. While this action can be reversed, in order to be undone it first has to be spotted, and so it's relatively high up on the 'destructiveness' meter. Only moderators have access to any tools which truly destroy information, and those are highly specific and very limited in capability. (Excluding staff for obvious reasons.)
Giving a user any significant amount of reputation either shortens the amount of time they spend watching and learning how to use Stack Exchange's tools, or just gives it to them without telling them how to use it. That's a problem, particularly when a question generates a ton of reputation for a user.

As a measure of how many people you've helped, this proposal is... not entirely accurate.
Much of the time, when a question is closed as a duplicate, it's either better or equally good at conveying information as the duplicate. When I search Stack Overflow, and find a duplicate that answers the question, rarely do I actually need to follow the link through.
And even supposing it did help, if I upvote the duplicate post, it's because that post helped me, not its duplicate target. I may not even have seen the duplicate. Perhaps the duplicate was poorly-formed, and I actually would have downvoted it. Or, alternately, and worse, perhaps the duplicate is in error, and my upvoting it would give reputation to a completely irrelevant question.
In other words, when votes are transferred without user review, there's a lot of room for potential error, and it may no longer represent the number of people you have helped.

"Every user always has exactly one vote."
There's an unspoken philosophy - and it goes unspoken not because we don't challenge it, but simply because it's rarely challenged at all. "Every user always has exactly one vote."
There's a balance here that should be obvious, but frankly, I wouldn't want my vote to count twice for different people anyway. I want to see the content that I'm voting on and evaluate it, and if I haven't seen it, I don't want to vote on it. This is precisely what the system currently does.
Holding two votes doubles my voting power, and that's not something I want to have happen, particularly when I haven't necessarily reviewed both things I'm voting on.


text:
Q: AZURE AD ADAL "error":"invalid_grant","error_description":"AADSTS70000: Transmission data parser failure: Authorization Code is malformed or invalid I am trying to Authenticate using AZURE AD. I took the java client code from the git [https://github.com/Azure-Samples/active-directory-java-webapp-openidconnect][1].
I am able to make the authorize call and get the Authorization code. By passing the authorization code to get the access token using the acquireTokenByAuthorizationCode method from the oauth2 jar. Here I am getting the below error.

"error":"invalid_grant","error_description":"AADSTS70000: Transmission data parser failure: Authorization Code is malformed or invalid.

How to pass the grant_type=authorization_code to the acquireTokenByAuthorizationCode method?
How to check the post request which got fired? I am not able to see it in the network section of the chrome?
Below is the code:
        String authCode = authorizationCode.getValue();
        ClientCredential credential = new ClientCredential(clientId,
                clientSecret);
        AuthenticationContext context;
        AuthenticationResult result = null;
        ExecutorService service = null;
        try {

            ThreadFactory factory = ThreadManager.currentRequestThreadFactory();
            service = Executors.newCachedThreadPool(factory);

            context = new AuthenticationContext(authority + tenant + "/", true,
                    service);

            Future<AuthenticationResult> future = context
                    .acquireTokenByAuthorizationCode(authCode, new URI(
                            currentUri), credential, null);

The post request should be:
String redirectUrl = authority
                        + this.tenant
                        + "/oauth2/v2.0/token?p=b2c_1_abcd&grant_type=authorization_code&resource=https%3a%2f%2fgraph.windows.net&redirect_uri="
                        + URLEncoder.encode(REDIRECT_URL, "UTF-8");
Not sure how to provide the information which is in bold.

A: EDIT after more info
If you are using v2 endpoints, you can't use ADAL.
If you have registered your app in the v2 dev portal, you need to register your app via Azure Portal's Azure AD interface. And then make sure your Azure AD URLs do not include v2.0.

To get a token with authorization code, you use acquireTokenByAuthorizationCode (https://github.com/Azure-Samples/active-directory-java-webapp-openidconnect/blob/master/src/main/java/com/microsoft/aad/adal4jsample/BasicFilter.java#L268-L270):
Future<AuthenticationResult> future = context
                .acquireTokenByAuthorizationCode(authCode, new URI(
                        currentUri), credential, null);

You will not see the request in Chrome because it goes from your web server to Azure AD. The browser is not a part of the chain. And that's a good thing since we are passing the client secret to Azure AD. You can use tools like Fiddler to monitor the traffic.