text:
Q: Changing the color of a JButton, when another JButton is clicked I have a problem with one my projects. I am working on a quite simple "board game". When I click the one of the buttons, I need for the adjencent buttons to change colors. I am not sure how to reference the other buttons. Here is the Button object:
package city;

import java.awt.Color;
import javax.swing.JButton;

public class Button extends JButton {

public String color;
public Color lightBlue = Color.CYAN;
public Color lightRed = Color.PINK;
public Color darkBlue = Color.BLUE;
public Color darkRed = Color.RED;
public Color gray = Color.GRAY;
public Color defaultColor = Color.WHITE;

public int x;
public int y;

public void canMoveLightRed() {

  }
}

And here is the main code:
package city;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;

public class GameBoard extends JFrame implements ActionListener {

// The overall box count in chess board
public static final int squareCount = 64;

public GameBoard(String title) {

    Color defaultColor = Color.WHITE;
    Color darkRedColor = Color.RED;
    Color darkBlueColor = Color.BLUE;
    Color lightBlueColor = Color.CYAN;
    Color lightRedColor = Color.PINK;

    Button squareButton = null;

    for (int i = 1; i <= squareCount; i++) {
        squareButton = new Button();
        squareButton.setBackground(defaultColor);
        add(squareButton);
        squareButton.addActionListener(this);

        //Sets the tooltip text of the coordinates of the square
        if (i == 1) {
            squareButton.setToolTipText("A1");
            squareButton.setActionCommand("A1");
        }

        if (i == 2) {
            squareButton.setToolTipText("A2");
        }

        if (i == 3) {
            squareButton.setToolTipText("A3");
        }

        if (i == 4) {
            squareButton.setToolTipText("A4");
        }

        if (i == 5) {
            squareButton.setToolTipText("A5");
        }

        if (i == 6) {
            squareButton.setToolTipText("A6");
        }

        if (i == 7) {
            squareButton.setToolTipText("A7");
        }

        if (i == 8) {
            squareButton.setToolTipText("A8");
        }

        //Sets the text for the Gate squares
        if (i == 4) {
            squareButton.setText("Red's");
        }

        if (i == 60) {
            squareButton.setText("Blue's");
        }

        if (i == 5 || i == 61) {
            squareButton.setText("Gate");
        }

        //Sets the color for Red Soldiers
        if (i == 1 || i == 2 || i == 3 || i == 5 || i == 6 || i == 7 || i == 8) {
            squareButton.setBackground(lightRedColor);
            squareButton.setActionCommand("Red Soldier");
        }

        //Sets the color for the Red Ram
        if (i == 4 || i == 12) {
            squareButton.setBackground(darkRedColor);
            squareButton.setActionCommand("Red Ram");
        }

        //Sets the color for Blue Soldiers
        if (i == 57 || i == 58 || i == 59 || i == 60 || i == 62 || i == 63 || i == 64) {
            squareButton.setBackground(lightBlueColor);
            squareButton.setActionCommand("Blue Soldier");
        }

        //Sets the color for the Blue Ram
        if (i == 53 || i == 61) {
            squareButton.setBackground(darkBlueColor);
            squareButton.setActionCommand("Blue Ram");

        }
    }

    this.setTitle(title); // Setting the title of board
    this.setLayout(new GridLayout(8, 18)); // GridLayout will arrange elements in Grid Manager 8 X 8
    this.setSize(650, 650); // Size of the chess board
    this.setVisible(true); // Sets the board visible
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // If you close the window, the program will terminate
    this.setResizable(false); //The window is not resizable anymore ;)
}

public void actionPerformed(ActionEvent ae) {
    String action = ae.getActionCommand();
    if(action.equals("A1")){
        System.out.println("lul");
    }

    if (action.equals("Red Soldier")) {
        System.out.println("Red Soldier");
    }
    if (action.equals("Red Ram")) {
        System.out.println("Red Ram");
    }
    if (action.equals("Blue Soldier")) {
        System.out.println("Blue Soldier");
    }
    if (action.equals("Blue Ram")) {
        System.out.println("Blue Ram");
    }
}

public static void main(String[] args) {

    String title = "City - A Two-Player Strategic Game";

    GameBoard gameBoard = new GameBoard(title); // Creating the instance of gameBoard
  }
}

Thanks for any help and good luck everyone with a similar problem!


text:
Q: Allow Anonymous users to add Dexterity objects I have a Dexterity-based container that holds inside a Dexterity-based item. I need to let Anonymous users to add objects of this type inside the container.
I already created a rolemap.xml file with the following:
<?xml version="1.0"?>
<rolemap>
  <permissions>
    <permission name="my.package: Add My Type" acquire="True">
      <role name="Anonymous"/>
    </permission>
  </permissions>
</rolemap>

I declared the permission on configure.zcml:
<permission
    id="my.package.AddMyType"
    title="my.package: Add My Type"
    />

and finally I added a custom add view like this one:
class MyAddView(dexterity.AddForm):
    grok.name('MyType')
    grok.require('my.package.AddMyType')

the form is already showing up for anonymous users but, when I press the save button I'm redirected to the login form.
also, logged in users are also able to see the form and this is supposed not to be happening.
what else I have to do?

A: thanks to David Glick, who guided me, I ended up with a very simple solution involving the add method of the AddForm class:
class MyAddView(dexterity.AddForm):
    grok.name('MyType')
    grok.require('my.package.AddMyType')

    def update(self):
        # check here if the user is anonymous and raise exception if not
        super(AddView, self).update()

    def add(self, object):
        container = aq_inner(self.context)
        addContentToContainer(container, object, checkConstraints=False)
        self.immediate_view = container.absolute_url()

to understand it better, you may want to take a look at the original code in plone.dexterity.
one important thing you may also note is that you probably need to fix your workflow permissions to remove Owner role from some of them, or you could end with content editable by anonymous users also.

redpajama_set_name: RedPajamaStackExchange


text:
Q: VBA Scraping End With or Object Errors (no solution from other examples) I have gone through every other possible post which is some variation of this but cant see to figure out why the compiler keeps complaining on the code that is bolded. I have tried seeing if I have declared my objects with a "Set" and even seen if my "End With" block was properly done. I have compared with other code as well but I am pulling my hair on this one. Any help to point me in the right direction so I can start scraping the listings and pour the information into Excel.
Thanks again V3==================================================================
Code in Question
Even though I am using the classnames from the results page VBA only grabs "randomly" instead of the entire "column" of results (class name= "results col" which I tried to grab by making a new "case" but I am wondering if it should go first instead of last. Thanks a bunch again.
Do While .Busy Or .readyState <> 4
  DoEvents
Loop

For Each ele In .document.all
Select Case ele.classname
**Case "jobtitle turnstileLink" 'The jobname result
RowCount = RowCount + 1
**Case "company" 'the company name '
sht.Range("A" & RowCount) = ele.innertext
**Case "location" 'location of job '
sht.Range("B" & RowCount) = ele.innertext
**Case "summary" 'Job Description '
sht.Range("C" & RowCount) = ele.innertext
End Select
Next

=========================================
Sub test()
Dim eRow As Long
Dim ele As Object
'Dim IE As Object
Dim objIE
'Dim objElement As Object
'Dim objCollection As Object
Dim sht
Dim myJobType, myZip As String
Dim zipcode, What As Object  'Created this Dim objects '
'Dim Sheet1 As Worksheets 'referencing sheets?' this causes error
'referencing the "sheet1" with ws variable '
Dim ws As Worksheet

'Duplicate'
'Set ws = Sheets("Sheet1")

Set sht = Worksheets("Sheet1")

RowCount = 1
sht.Range("A" & RowCount) = "Title"
sht.Range("B" & RowCount) = "Company"
sht.Range("C" & RowCount) = "Location"
sht.Range("D" & RowCount) = "Description"

'===============================================================================
'eRow = Sheet1.Cells(rows.Count, 1).End(xlUp).Offset(1, 0).Row
'you reference Sheet1, which is not set previously (while sht is)

'eRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
'=============================================================================

eRow = sht.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

Set objIE = CreateObject("InternetExplorer.Application")

myJobType = InputBox("Enter type of job eg. sales, administration")
myZip = InputBox("Enter zipcode of area where you wish to work")

With objIE
.Visible = True
.navigate "http://www.indeed.com"

MsgBox "Visting Webpage"
Do While .Busy Or .readyState <> 4
DoEvents
Loop

'Enter job name/type '
Set What = .document.getElementsByName("q")
What.Item(0).Value = myJobType

'changed WHERE to 'l' as that is the name of the zipcode textbox
Set zipcode = .document.getElementsByName("l")
'objectVariableIssue not set
zipcode.Item(0).Value = myZip

'Click webpage button' , changed to "fj" which is the find jobs button
.document.getElementById("fj").Click

'code throwing object errors'
'===================================================================='
'Complains of object required error 424
''.document.getElementById("submit").Click

'This "clicks" the submit button'
'This is complaining of object error, along with the line commented
'out previously.

'runtime error 91,object variable or  block variable not set.
'IE.document.forms(0).click

'IE.document.getElementById("jobsdotcom").Click'
'============================================================='

'======================================================================'
'Wait for webpage to fully load, and loop through elements'
'This is the  second DoEvents Loop We dont need this
'Do While .Busy Or .readyState <> 4
'MsgBox "Visting Website"
  'DoEvents
'Loop
'============================================================================='

Do While .Busy Or .readyState <> 4
  DoEvents
Loop

For Each ele In .document.all
Select Case ele.classname
Case "jobtitle turnstileLink" 'The jobname result
RowCount = RowCount + 1
Case "company" 'the company name '
sht.Range("A" & RowCount) = ele.innertext
Case "location" 'location of job '
sht.Range("B" & RowCount) = ele.innertext
Case "summary" 'Job Description '
sht.Range("C" & RowCount) = ele.innertext
Case "row result"
sht.Range("D" & RowCount) = ele.innertext
    End Select
Next

Set objIE = Nothing
End With 'Moved from before
End Sub

V3==================================================================
myZip = InputBox("Enter zipcode of area where you wish to work")
V2==========================================================
Thanks a bunch, I think I became younger just from that you guys. Here are some changes I made below Excel now complains on:
eRow = Sheet1.Cells(Rows.count, 1).End(xlUp).Offset(1, 0).Row

I have declared Sheet 1 with
Dim sht
Set ws = Sheets("Sheet1")

But I still get the error "Run Timer Error 91, Object variable with block variable not set"
Thank You x1 Million.
Sub test()
Dim eRow As Long
Dim ele As Object
'Dim IE As Object
Dim objIE
'Dim objElement As Object
'Dim objCollection As Object
Dim sht
Dim myJobType, myZip As Object
Dim zipcode, What As Object  'Created this Dim objects '
Dim Sheet1 As Worksheets 'referencing sheets?'
'referencing the "sheet1" with ws variable '
Dim ws As Worksheet

Set ws = Sheets("Sheet1")

Set sht = Worksheets("Sheet1")

RowCount = 1
sht.Range("A" & RowCount) = "Title"
sht.Range("B" & RowCount) = "Company"
sht.Range("C" & RowCount) = "Location"
sht.Range("D" & RowCount) = "Description"

'eRow = Sheet1.Cells(rows.Count, 1).End(xlUp).Offset(1, 0).Row
'you reference Sheet1, which is not set previously (while sht is)

eRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

Set objIE = CreateObject("InternetExplorer.Application")

myJobType = InputBox("Enter type of job eg. sales, administration")
myZip = InputBox("Enter zipcode of area where you wish to work")

With objIE
.Visible = True
.navigate "http://www.indeed.com"

Do While .Busy Or .readyState <> 4
  DoEvents
Loop

'Enter job name/type '
Set What = .document.getElementsByName("q")
What.Item(0).Value = myJobType

'changed WHERE to 'l' as that is the name of the zipcode textbox
Set zipcode = .document.getElementsByName("l")
'objectVariableIssue not set
zipcode.Item(0).Value = myZip

'code throwing object errors'
'===================================================================='
'Complains of object required error 424
''.document.getElementById("submit").Click

'This "clicks" the submit button'
'This is complaining of object error, along with the line commented
'out previously.

'runtime error 91,object variable or  block variable not set.
'IE.document.forms(0).click

'IE.document.getElementById("jobsdotcom").Click'
'============================================================='
'Click webpage button' , changed to "fj" which is the find jobs button
.document.getElementById("fj").Click

'Wait for webpage to fully load, and loop through elements'
Do While .Busy Or .readyState <> 4
  DoEvents
Loop

For Each ele In .document.all
Select Case ele.classname
Case "Result"
RowCount = RowCount + 1
Case "Title"
sht.Range("A" & RowCount) = ele.innertext
Case "Company"
sht.Range("B" & RowCount) = ele.innertext
Case "Location"
sht.Range("C" & RowCount) = ele.innertext
Case "Description"
sht.Range("D" & RowCount) = ele.innertext
End Select
Next

Set objIE = Nothing
End With 'Moved from before
End Sub

==========================================================================
V1
Sub test()
Dim eRow As Long
Dim ele As Object
'Dim IE As Object
Dim objIE
'Dim objElement As Object
'Dim objCollection As Object
Dim sht
Dim myJobType, myZip
Dim zipcode, what

Set sht = Worksheets("Sheet1")

RowCount = 1
sht.Range("A" & RowCount) = "Title"
sht.Range("B" & RowCount) = "Company"
sht.Range("C" & RowCount) = "Location"
sht.Range("D" & RowCount) = "Description"

eRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

Set objIE = CreateObject("InternetExplorer.Application")

myJobType = InputBox("Enter type of job eg. sales, administration")
myZip = InputBox("Enter zipcode of area where you wish to work")

With objIE
.Visible = True
.navigate "http://www.indeed.com"

Do While .Busy Or .readyState <> 4
  DoEvents
Loop

'Enter job name/type '
Set what = .document.getElementsByName("q")
what.Item(0).Value = myJobType

Set zipcode = .document.getElementsByName("where")
'objectVariableIssue not set
zipcode.Item(0).Value = myZip

'code throwing object errors'
'===================================================================='
'Complains of object required error 424
''.document.getElementById("submit").Click

'This "clicks" the submit button'
'This is complaining of object error, along with the line commented
'out previously.

'runtime error 91,object variable or  block variable not set.
'IE.document.forms(0).click

'IE.document.getElementById("jobsdotcom").Click'
'============================================================='
'Click webpage button'
.document.getElementById("input_submit").Click

'Wait for webpage to fully load, and loop through elements'
Do While .Busy Or .readyState <> 4
  DoEvents
Loop

For Each ele In .document.all
Select Case ele.classname
Case "Result"
RowCount = RowCount + 1
Case "Title"
sht.Range("A" & RowCount) = ele.innertext
Case "Company"
sht.Range("B" & RowCount) = ele.innertext
Case "Location"
sht.Range("C" & RowCount) = ele.innertext
Case "Description"
sht.Range("D" & RowCount) = ele.innertext
End Select
Next

Set objIE = Nothing
End With 'Moved from before End Sub
End Sub

A: as for the "ZIP code" error you must type
Set zipcode = .document.getElementsByName("l")

since "l" (not "where") is the actual name of the ZIP textbox
moreover, I'd point out the following:
in
eRow = Sheet1.Cells(rows.Count, 1).End(xlUp).Offset(1, 0).Row

you reference Sheet1, which is not set previously (while sht is)
in
Case "Location"

you're using "strange" quotation marks (different than those used in the rest of the code)

A: This line raises a 91 error because you literally do not have in scope a variable called IE:
IE.document.forms(0).click

This line raises the 424 error because there is no such element. Whenever you get the this sort of error, this means that something which should be an object, is actually a Nothing.
.document.getElementById("submit").Click

On the requested URL, there is no such element ID as "submit". The getElementByID method will return Nothing, if the specified ID does not exist on the document.
Assuming you intend to click the "Find Jobs" button, use the appropriate ID value, "fj"

To help trap this, my preferred method is using an appropriate object variable, like:
Dim btn as Object
Set btn = .document.getElementById("submit")
If btn Is Nothing
    MsgBox "submit button doesn't exist!", vbCritical
    Exit Sub
End If
btn.Click()


text:
Q: How do I install Cinnamon themes on Ubuntu 12.04?
Possible Duplicate:
How to theme the Cinnamon Desktop?

I just installed Ubuntu 12.04, but I prefer Cinnamon. I installed the
ppa:gwendal-lebihan-dev/cinnamon-nightly
And Cinnamon works. Some of the icons are blank. If I go to the cinnamon-spices website and download a theme...I'm told to extract it into the /usr/share/themes directory.
When I attempt this, I get an error that says:
"You don't have the right permissions to extract archives in the folder 'file:///usr/share/themes'".
I assume that since I'm unable to log in as root, that there's another way to accomplish this?
How?


text:
Q: Reading multiple csv lines into single row in R I have a csv file with multiple rows per unique id that I need to format into a single row of a dataframe.  After reading in this file, I end up with an initial dataframe:
id  week   v1  v2
01  week1  3   2
01  week2  5   2
01  week3  2   3
02  week1  1   2
02  week2  5   5
03  week1  4   1
03  week2  4   3
03  week3  4   2
[etc...]

I want pull all the instances of v1 for a given id, so I grab all the unique id
uniqid<-unique(data$id)

and then iterate over these from 1:length(uniqid)
temp <- subset(data,data$id==uniqid[i])

and pull each week data into a temp variable
week1 <- temp$v1[temp$week=="week1]

so I can reform the dataframe using rbind
output <- rbind(output,data.frame(ID=uniqid[i],week1,week2,week3))

My problem is, for example with id=02, there is no week3, so the rbind breaks.  It appears the week3 variable is never created; it doesn't show as NA.  How can I test to see if the variable was created and set it to NA (or 0) so the rbind won't fail?  Or is there a completely different/more efficient way to accomplish this?

A: You can use recast function from reshape2 package.
DF
##   id  week v1 v2
## 1  1 week1  3  2
## 2  1 week2  5  2
## 3  1 week3  2  3
## 4  2 week1  1  2
## 5  2 week2  5  5
## 6  3 week1  4  1
## 7  3 week2  4  3
## 8  3 week3  4  2

require(reshape2)
temp <- recast(DF, id ~ week, measure.var = "v1")
result <- temp$data
row.names(result) <- temp$labels[[1]]$id
colnames(result) <- temp$labels[[2]]$week
result
##   week1 week2 week3
## 1     3     5     2
## 2     1     5    NA
## 3     4     4     4

or as @AnandaMahto suggested, just use dcast
dcast(DF, id ~ week, value.var = "v1")
##   id week1 week2 week3
## 1  1     3     5     2
## 2  2     1     5    NA
## 3  3     4     4     4

A: In base R, you can use reshape:
> reshape(mydf, direction = "wide", idvar="id", timevar="week")
  id v1.week1 v2.week1 v1.week2 v2.week2 v1.week3 v2.week3
1  1        3        2        5        2        2        3
4  2        1        2        5        5       NA       NA
6  3        4        1        4        3        4        2

If you want to drop the "v2" column from the output, you can do that before you reshape the data, or you can drop it from within the function.
> reshape(mydf, direction = "wide", idvar="id", timevar="week", drop="v2")
  id v1.week1 v1.week2 v1.week3
1  1        3        5        2
4  2        1        5       NA
6  3        4        4        4


text:
Q: How to use variables/strings as SQLITE3 table name ("CREATE TABLE %s AS (SELECT * FROM anime WHERE color = %s" % (userid, color))

I am trying to use %s but I get the error RuntimeError: near "1": syntax error

A: It looks like you may be missing a parenthesis in your SQL query.
("CREATE TABLE %s AS (SELECT * FROM anime WHERE color = %s)" % (userid, color))


text:
Q: Ensure shell script is launched with correct shell Our shell script's first line reads
#!/bin/bash

According to my (limited) Linux shell knowledge this causes to use /bin/bash to launch the application when the user invokes this script directly, e.g., using
$ ./myscript.sh

Unfortunately, the script works not as expected, when the user launches it using
$ sh ./myscript.sh

How can I catch the case that the "wrong" shell executes this script and show the user an appropriate error message?

A: case "$BASH" in
  *bash) :;;
  *) echo >&2 "$0: please run this with bash."; exit 1;;
esac

Or you could just do it for them:
case "$BASH" in
  *bash) :;;
  *) exec bash "$0" "$@";;
esac


text:
Q: How to view view.xml file in debugger? I am running my project locally, where I can see view.xml file and can debug it using breakpoint.
However, when I try to open same file in debugger in my online system, it does not show me this file. Is there any way I can access this file, same way I can locally?

A: there are 2 ways you can access all the files of project.
1) put this tag in your URL, and reload the page sap-ui-debug=true. This will access all the files inside your project.
Like fiorilaunchpad.html?sap-client=100&sap-ui-debug=true
2)

*

*Press CTRL+ALT+SHIFT+P. This will open Technical Information Dialog box. There, tick "Use Debug Sources"

*When Prompted, press OK

Step 2 will make app loading slower since it try to access all the resources inside the project.


text:
Q: Spring @ContextHierarchy with custom initializer using addActiveProfile gives NoSuchBeanDefinitionException We are using @ContextHierarchy in our tests to enable context caching but allow some texts to customise the context. I have a problem that one test needs to activate a specific Spring profile which activates a bean which is injected back into the test.
I have a feeling this is not possible but am looking for confirmation. Logically the parent context has already been initialised, so am willing to believe Spring will have a problem re-wiring the parent context based on a profile being activated in a test that is essentially just adding a child context through @ContextHierarchy. But I couldn't find anyone describing this problem after some googling.
The base test class looks like this:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextHierarchy(
    @ContextConfiguration(classes = BaseConfig.class, initializers =  TestContextInitialiser.class)
)
public abstract class BaseTest extends AbstractTransactionalJUnit4SpringContextTests {
...
}

The concrete test class looks like this:
@ContextHierarchy(
    @ContextConfiguration(initializers = NotificationTest.CustomInitializer.class)
)
public class NotificationTest extends BaseTest {
    @Autowired
    private EventsConfig eventsConfig; // bean that needs to be activated via profile

    ...

    public static class CustomInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
        @Override
        public void initialize(ConfigurableApplicationContext applicationContext) {
            applicationContext.getEnvironment().addActiveProfile("EVENTS_ENABLED");
        }
    }
}

The EventsConfig class uses @Profile...
@Component
@Profile("EVENTS_ENABLED")
public class EventsConfig {
    ...
}

And the error from Spring:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [xxx.EventsConfig] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I would expect that Spring would at least warn/error in this situation and explain that the parent context cannot be modified with new profiles.
Any input/guidance appreciated. Is this or something similar possible? It will be a pain to have to refactor this test to avoid use of the base class.
Thanks


text:
Q: Android - Adding content to another tab onclick Hey guys I have a soundboard with Buttons and all works great. I started messing around with TabHost to make all my sounds in one tab, then ON LONG PRESS the user has the option to save a sound to a Favorites tab or as a Ringtone. The ringtone part works, but I dont know how to save the sound to the Favorites tab.
Right now the app works fine as far as playing sounds in the first tab and such, but I am lost on how to make my buttons appear in my Favorites tab!
HERE's MY MENU:
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("Save as...");
    menu.add(0, v.getId(), 0, "Ringtone");
    menu.add(0, v.getId(), 0, "Favorite");

}

@Override
public boolean onContextItemSelected(MenuItem item) {
    if (item.getTitle() == "Ringtone") {
        getButtonPressed(item.getItemId());

    }
    else if(item.getTitle() == "Favorite"){

    }

            else {
        return false;
    }
    return true;
}

This is what my buttons look like:
Button s67 = (Button) findViewById(R.id.button67);
    s67.setText(this.getString(R.string.quote67));
    s67.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            tempId = R.raw.sandcastles;
            setId(tempId);

            try {
                playSound(tempId);
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    });
    registerForContextMenu(s67);

I'm guessing I need some kind of method to pass a parameter to when item.getTitle() is equal to "Favorite" but I just need a swift kick in the right direction. Please advise! Thanks!


text:
Q: Unable to serve expressjs app from subfolder I am new to express and nginx.
I have made a simple express app and configure nginx:
location /exapi {
    proxy_pass http://localhost:8010;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

My expressjs app is:
    var express = require('express')
var app = express()

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(8010, function () {
  console.log('Example app listening on port 8010!')
})

When I access my vps VPS_IP/exapi, I get response Cannot GET /exapi, but when I use http://VPS_IP:8010 it is working as expected.
How can I access my express app from VPS_IP/exapi?

A: Try rewrite in nginx:
location ~* ^/exapi {
    rewrite ^/exapi/(.*) /$1 break;
    subfilter /exapi /;

    proxy_set_header Host $host;
    proxy_redirect off;
    proxy_pass http://localhost:8010;
}


text:
Q: How to use With on previously defined expressions The command With[{x = 1}, x] outputs 1.
The command t = x; With[{x = 1}, t] outputs x.
I expected this second input to give the same answer. How can I modify my code so it behaves in this way?

A: t = x; With[{x = 1}, Evaluate[t]]

A: I think you are confusing the behaviour of With and Block
t = x; Block[{x = 1}, t]
(* 1 *)


text:
Q: Sorting String based on similarities consider the following Strings:

*

*he llo

*goodbye

*hello

*=   (goodbye)

*(he)(llo)

*good bye

*helium

I'm trying to sort these in such a way that similar words comes together, I know

*

*alphanumerical sorting is not an option

*removing special chars ",-_ and etc then comparing is certainly helpful but results won't be as good as I hope for.

NOTE :
there might be few different desired ouput for this, one of which is :
DESIRED OUTPUT:

*

*hello

*he llo

*(he)(llo)

*helium

*goodbye

*good bye

*=   (goodbye)

so my question is that if there is a java package that compares strings and ultimately sort them based on it .
I've heard of terms such as n-gram and skip-gram but didn't quite understand them. I'm not even sure if they can be useful for me at all.
UPDATE:
finding similarities is certainly part of my question but the main problem is the sorting part.

A: Here's one possible approach.
Calculate the edit distance/Levenshtein distance between each pair of strings and then you use view the strings as a complete graph where the edge weights come from the edit distance. Choose a threshold for those weights and remove all the weights that to high. Then find the cliques in this graph. If your threshold is fairly low perhaps even finding connected components would be an option.
Note:
Perhaps it would be better to substitute some edit distance with one of the similarity measures in the link that @dognose posted.
Also, note that finding cliques will be very slow if you have a large numbers of strings


text:
Q: PostgreSQL, about FORCE NOT NULL I have an issue using FORCE NOT NULL in PostgreSQL.
I have a table with 10 columns and I need to load data to it from a CSV file.
I'm using the following query, which works perfectly:
COPY "myschema"."mytable"
FROM '/var/www/myapp/myfile.csv'
DELIMITERS '|'
CSV
FORCE NOT NULL
attr1, attr2, attr3, attr4, attr5, attr6, attr7, attr8, attr9, attr10;

I need to know how to do this without explicitly coping all the columns as arguments to the FORCE NOT NULL because I have more tables with hundreds of columns that require this.
I tried FORCE NOT NULL *, FORCE NOT NULL * but the query returns an error. I can't find a solution to this on the Internet.
Thanks in advance for the help you can provide me!

A: FORCE NOT NULL * is not valid postgresql. A patch for this was almost passed but rejected.
Read this mailing list for the discussion.


text:
Q: How to create directory on Android and IOS? I create a Xamarin app and i want to serialize some data.
FileWorker class for Android:
public class FileWorker : IFileWorker
{
    public Task<IEnumerable<string>> GetFilesAsync(string folder)
    {
        IEnumerable<string> filenames = from filepath in Directory.EnumerateFiles(GetDocsPath() + "/" + folder)
                                        select Path.GetFileName(filepath);
        return Task<IEnumerable<string>>.FromResult(filenames);
    }

    string GetFilePath(string filename)
    {
        return Path.Combine(GetDocsPath(), filename);
    }

    string GetDocsPath()
    {
        return System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
    }

    public Task SerializeAsync<T>(string filename, T obj)
    {
        string filepath = GetFilePath(filename);
        DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(T));
        FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate);
        formatter.WriteObject(fs, obj);
        return Task.FromResult(true);
    }

    public Task<T> DeserializeAsync<T>(string filename)
    {
        DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(T));
        T obj;
        FileStream fs = new FileStream(filename, FileMode.OpenOrCreate);
        obj = (T)formatter.ReadObject(fs);
        return Task.FromResult(obj);
    }
}

And Add method:
public async void AddObjectAsync(object obj)
{
    var fv = DependencyService.Get<IFileWorker>();
    string path = AppSettings.ObjectsFolder + "/";
    try
    {
        await fv.SerializeAsync(path + "obj", obj);
    }
    catch (Exception e) { }
}

But i catch Exception in this function:

System.IO.DirectoryNotFoundException

How to create this directory on Android (and IOS, if same Exception is possible)?

A: you can use the normal C# System.IO methods
using System.IO;

DirectoryInfo di = Directory.CreateDirectory(path);


text:
Q: Concatenating book chapters at the PDF level There are some LaTeX packages which conflict with each other. When assembling a book from different chapters provided by different contributors, it might be not too easy to resolve these conflicts. In such cases, a possible workaround is to compile the chapters in isolation, adjusting page and chapter offsets, and then to concatenate at the PDF level.
Obviously, chapter cross-references, a global index, glossary, list of pictures, table of contents, bibliography, ... need extra work, which could be automated to a certain extent. Given such an automation, the merging then might be much easier than trying to merge at the TeX level. The only thing that would require manual (?) labor is to add hyperlinked chapter cross-references, a non-issue for a printed book.
Would this be a feasible workflow for a publisher? Is anyone aware of an implementation, perhaps as "intellectual property" of a publisher? Would there be other drawbacks?
The following questions are similar, but not the same: Compile separate document chapters into book w/o duplicate references? How do I create a book with separately produced chapters?

A: a publisher would be very happy, if one chapter has to compile with latex, another with pdflatex and at least one with xelatex. If only a printed version should be published, this can be done with some pdfhacks. However, if a PDF should also be published, I think at least some guidelines should be defined.


text:
Q: Representing the predicted value $\hat{Y}_h$ as a linear function of $Y_1, \dots, Y_n$ A question asks me to represent $\hat{Y}_h$ as a linear function of the observations $Y_1, \dots, Y_n$.
What I have attempted:
\begin{align}
\hat{Y}_h & = \hat{\beta}_0 + \hat{\beta}_1 X_h\\
& = (\overline{Y} - \hat{\beta}_1 \overline{X}) + \hat{\beta}_1 X_h\\
& = \overline{Y}  + \hat{\beta}_1 (X_h-\overline{X})\\
& = \overline{Y} - \frac{S_{xy}}{S_{xx}} (X_h - \overline{X})\\
& = \frac{1}{n}\sum_{i=1}^n Y_i - \frac{\sum_{i=1}^n (X_i-\overline{X})(Y_i-\overline{Y})}{\sum_{i=1}^n(X_i-\overline{X})^2}(X_h - \overline{X})
\end{align}
From here it just seems like I've made a mess out of it. I'm not sure if this start is even correct, and if it is I'm not sure how to proceed from here. Any hints would be greatly appreciated.
Edit
As per Dave's comment:
$$
\hat{Y}_1 = \hat{\beta}_0 + \hat{\beta}_1 X_1 \qquad \text{and} \qquad Y_1 = \beta_0 + \beta_1X_1
$$
$$
\hat{Y}_2 = \hat{\beta}_0 + \hat{\beta}_1 X_2 \qquad \text{and} \qquad Y_2 = \beta_0 + \beta_1X_2
$$
$$
\hat{Y}_3 = \hat{\beta}_0 + \hat{\beta}_1 X_3 \qquad \text{and} \qquad Y_3 = \beta_0 + \beta_1X_3
$$
I figured, since $X_1 = \frac{Y_1 - \beta_0}{\beta_1}$, I can get
$$
\hat{Y}_1 = \hat{\beta}_0 + \hat{\beta}_1 \frac{Y_1 - \beta_0}{\beta_1}
$$
I still seem somewhat stuck, however...


text:
Q: LED indicators intensity standards I am trying to find any resources on the LED parameters (i.e. preferred intensity and luminosity ranges) that are used as indicators in various home appliances, such as Networked devices (i.e. routers) or TV sets. The general concern I have is to have indicators that do not pollute light and are not aggressive to the eye, but I am trying to find any numbers that can be used to describe this functionality. I would appreciate all feedback.

A: ICNIRP have updated their hazard assessment of LEDs for 2020 in this statement and there are exposure guidelines in this document which seems comprehensive and could point you to product safety standards.

A: Such "official" resource may be hard to find because it depends too much on the situations where and when the indicators are used.
It's always better to test yourself in real life than relying on a table written by someone who had a completely different idea than yours. If you want a LED light to be strong or weak, you make am experiment and check if it's good.
Standard LED used for indicators are technically limited to 20 mA. This is the technical upper limit. But you should use this only if you really want a strong light output, to make it visible from far away and high ambiant light conditions. For example, outdoor, under the summer sun.
Indoor you can divide the intensity by 5 or 10 depending on how much light there is in the room, for the same visual effect. And in the dark you can divide it by 20 or 40. It means if you put 0.5 mA, your LED will still be enough visible in a completely dark room.
It depends very much on where the indicator will be used.
The most annoying place can be sleeping rooms. In cars, indicators, especially the blue "high lights" one, are often too strong and disturb nightly driving.
Yet the same light may be almost unnoticeable in the day light.
If you are concerned about that, the smart way is to control the intensity by routing the LED supply through resistors depending on the situation to achieve intensity smart control.
It also depends where the LED will be positioned: On the side of a box, or straight in front of your eyes?
And when and why the LED has to be observed: Is it only intended for the repair guy, once in ten years, if ever, or is it something that factory workers have to keep an eye on 24/7?
LED colour is also very important: Most agressive are green and blue. Warm colours like red and orange are soft to the eyes despite that red symbolises danger and green is the symbol of nature.
This is because the visual impact of a colour on a surface (eg. the colour of a paint) is opposite to the impact of the colour of a light.
A red marking will catch your attention more than a blue one. But a blue indicator light will be more present than a a red one.
White is very neutral visually and a good choice, too often discarded because we think colour is cool stuff. In fact white is quite "design" if you ask me.
And finally, you have the energy concern. In many case you will use only 2 mA just to save power. When you have 50 LEDs on a panel working 24/7, it makes a difference after one year.


text:
Q: Deploying UWP to remote device I am learning UWP and would like to develop Apps on a laptop and remote deploy them on a Surface Pro6. I am unable find a solution and would appreciate if someone can help. I can write small Apps but cannot deploy on a remote device.

A: Eventually got it to run. First, you must have Visual Studio Remote Tools installed on the remote machine (I found you need it on both machines).
Enable Developers mode (Systems/for Developers) on development machine and on remote machine.
Make sure your certificate for you App is yours (not from an example code copied from internet, I ran into permission issues, even after I deleted and recreated a new one).
Then from Visual Studio, select Project/Properties, the select Debug. Enter Remote machine information. Click on the Find button. (Make sure Visual Studio Remote Tools is running on the remote device.)
I had issues with authentication, so I had to set Authentication Mode to None (which is not safe???) on development and remote machine. They should be same on both machines.
Now you can select Debug, type of deployment (x64 for example) and click on Remote Machine.
I created a very simple HelloWorld app to iron out deployment issues. It finally worked after days of trying.


text:
Q: How to get a comma seperated value for the following DB table scenario How to get the following output from a table in MSSQL 2005 ?
Input
-----

main_idn notice_id       group_name    employer_name
    1         20        State Client      Unknown
    2         20        Canada Corp       Unknown
    3         20        Unknown           Pacific Bell
    4         30        State Client      Unknown
    5         30        Reality Corp      Unknown
    6         30        Unknown           Bell Labs
    7         30        Unknown           AT&T

Output
------

notice_idn  group_name                                    employer_name
20          State Client,Canada Corp,Unknown              Unknown , Unknown , Pacific Labs
30          State Client,Reality Corp.Unknown,Unknown     Unknown , Unknown , Bell Labs ,  AT&T

In something like MYSQL I can write a simple query like :
from table get notice_idn , group_concat(group_name) as group_name , group_concat(employer_name) as emp_name group by notice_idn

A: The solution is already given here which I like, however would you please try with below solution though both are same kind of solution, thanks for your time.
SELECT outerT.notice_idn,

       STUFF(ISNULL((SELECT ', ' + innerT.group_name
                FROM TargetTableName innerT
               WHERE innerT.notice_id = outerT.notice_id
            GROUP BY innerT.notice_id, innerT.group_name
             FOR XML PATH (''), TYPE).value('.','VARCHAR(MAX)'), ''), 1, 1, '') group_name,

       STUFF(ISNULL((SELECT ', ' + innerT.employer_name
                FROM TargetTableName innerT
               WHERE innerT.notice_id = outerT.notice_id
            GROUP BY innerT.notice_id, innerT.employer_name
             FOR XML PATH (''), TYPE).value('.','VARCHAR(MAX)'), ''), 1, 1, '') employer_name

FROM TargetTableName outerT
GROUP BY outerT.notice_id


text:
Q: "No suitable conversion function from 'std::string' to 'const char *' exists" I'm trying to write a simple loop that takes a string and goes through each character of said string and stores it inside another string (the same string every time). I want to use this loop to perform simple tasks, such as displaying a word in reverse, or displaying each character in a separate line (which is where the example provided below comes from). My code goes something like this:
#include <string>
using namespace std;

int main(){
   c++
   string word;
   string ch;
   cout << "Please enter a word." << endl;
   cin >> word;

   int wordlength;
   int i;

   wordlength = size(word);

   for (i = 0; i < wordlength; i++) {
       word.copy(ch, 1, i);
       cout << ch << endl;
   }
}

But whenever I use this code, I get the error in the title:
"No suitable conversion function from 'std::string' to 'const char *' exists"
What am I doing wrong?

A: simply use string
#include <string>
using namespace std;
string word;
char *c;
  cout << "Please enter a word." << endl;
  cin >> word;

  int wordlength,  i;

    wordlength = word.size();

    for (i = 0; i < wordlength; ++i) {

     ch = word[i];

     cout << ch << endl;

   }

works either way too word[i] = ch;

A: Size of string:
wordlength = word.size();

string::copy should be:
char ch;
....
word.copy(&ch, 1, i);

A: From the c++ reference
size_t copy (char* s, size_t len, size_t pos = 0) const;
Essentially copy requires a char pointer/array as its first arg but you put a string so it threw an error.


text:
Q: How to close window prompt in Cypress I,m new using cypress and i need help to handling window prompt. I don,t know how to accept o cancel the following screenshot. Thank you Prompt
That ptompt is impossible to select any button, has no DOM, i tried cy.contains, cy.stub

A: Which version of cypress do you have?
You could try directly login without filling out the login:
cy.request({
      method: 'POST',
      url: `YOUR URL OF CURRENT PAGE`,
      body: {
        userName: 'yyy',
        password: 'xxx',
      },
    });

After that you need a cy.visit('URL AFTER LOGIN')


text:
Q: NSTimer issue in Objective-C I am working on a Kid's Book App for iPad. It has a UIView which loads UIImageView to display UIImages (JPEG's), user can swipe on images to browse through pages. I have also added some interactivity to some of the pages by adding another UIImageView which would load a PNG file and on Tap Gesture I animate them. One one of the pages I have an animation of leaf's falling on the screen (page 10) and I am using NSTimer for this, it works fine, however when I swipe and move to next page, the animation is still happening. I want the animation to run ONLY on page 10 and should stop immediately if I move to page 9 (backward swipe) or page 11 (forward swipe). I tried to put a condition (if (pageNum == 10)) and it stops after few seconds, so I can still see few leafs falling on previous/forward pages. I guess I understand why its happening but don't know how to fix it. Below is the code snippet:
- (void)handleTap:(UITapGestureRecognizer *)recognizer {
    NSLog(@"ChildrenBookViewController ==> handleTap.");
    switch (((UIGestureRecognizer *)recognizer).view.tag)
    {
        case 1:
            //Some animation for Page 1
            break;
        case 2:
            //Some animation for Page 2
            break;
        //....
        case 10:
            // load our leaf image we will use the same image over and over
            leafImage = [UIImage imageNamed:@"leaf_small.png"];
            // start a timet that will fire 20 times per second
            timer = [NSTimer scheduledTimerWithTimeInterval:(0.05) target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
            break;
        case 11:
            //Some animation for Page 11
            break;
        default:
            NSLog(@"ChildrenBookViewController ==> handleTap. Switch Case: DEFAULT");
            break;
    }
}

// Timer event is called whenever the timer fires
- (void)onTimer
{
    if (pageNum == 10)
    {
        // build a view from our leaf image
        UIImageView* leafView = [[UIImageView alloc] initWithImage:leafImage];

        // use the random() function to randomize up our leaf attributes
        int startX = round(random() % 1024);
        int endX = round(random() % 1024);
        double scale = 1 / round(random() % 100) + 1.0;
        double speed = 1 / round(random() % 100) + 1.0;

        // set the leaf start position
        leafView.frame = CGRectMake(startX, -100.0, 25.0 * scale, 25.0 * scale);
        //leafView.alpha = 0.25;

        // put the leaf in our main view
        [self.view addSubview:leafView];

        [UIView beginAnimations:nil context:leafView];
        // set up how fast the leaf will fall
        [UIView setAnimationDuration:5 * speed];

        // set the postion where leaf will move to
        leafView.frame = CGRectMake(endX, 500.0, 25.0 * scale, 25.0 * scale);

        // set a stop callback so we can cleanup the leaf when it reaches the
        // end of its animation
        [UIView setAnimationDidStopSelector:@selector(onAnimationComplete:finished:context:)];
        [UIView setAnimationDelegate:self];
        [UIView commitAnimations];
    }else{
        if (timer) {
            [timer invalidate];
            timer = nil;
        }
    }
}
- (void)onAnimationComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    UIImageView *leafView = context;
    [leafView removeFromSuperview];
    [leafView release];
}

A: Instead of invalidating your timer in onTimer method, you should invalidate it in the callback you set for the swipe gesture (changing pages) page 9 and 11 cases. That way the timer will be invalidated as soon as the user swipes to switch pages.
EDIT: As @Alex noticed, this will only stop requesting more animations, but the already running will continue... I assume you have a reference to leafView so, you should call
[leafView.layer removeAllAnimations] and then remove it from superview or hide it or whatever you want...


text:
Q: iOS Unable to use Books API on google I am scanning ISBN code and searching the book on the basis of that code on google in my iOS app. I created the app on google.I have keys for browser apps and I also created keys for iOS app.
Now here is the API I am using:-
https://www.googleapis.com/books/v1/volumes?q=isbn=9783161484100&key={API Key}

When I am passing browser app key its giving fine results in my iOS app also.
But when I am passing iOS API Key , then its giving response like this:-
{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "accessNotConfigured",
    "message": "Access Not Configured"
   }
  ],
  "code": 403,
  "message": "Access Not Configured"
 }
}

I knows that there are 1,000 request limit in a day. But I did only 18 request till now. Then why this response is coming from iOS API Key. Is there some other way to implement book search functionality in iOS.

A: Is your bundle identifier in google api console and bundle id in Xcode project are same?

A: There have been some issues w/ Google's API and Bundle IDs in their other apps.
As such - (in the Youtube API as well), Google suggested creating an API Key for "any app".
To do this -
In the Google Developer Console under your project's API & Auth:
Create New Key -> iOS Key, just click create with the bundle ID field left empty.


text:
Q: Find modifies the Access Time I have to find those files which have been modified before one day. There are lots of files which are modified before one day. I am doing find ./ -type f -mtime -1. But, I observed that my disk util went to 100%. It was probably because of the access time modification for each file. Is there any way to find files without modification of the access time?

A: Your disk usage spiked high because the find was scanning through a lot of directories.  Your disk usage monitor is probably reporting both reads and writes in the same graph.
Often, if you do several finds in a row on the same directory structure, the subsequent finds do not access the disk because all the disk blocks the find needs (i.e. the directory listings) are cached in memory from the previous find.
Other than having the blocks already cached in memory, there is no way to reduce the disk load of a find operation (well, you could nice it or stick a sleep in there, but that wouldn't reduce the number of disk accesses required).

A: Normally find doesn't  modify the access time of file .To get the modification time and access time for a file you can use stat command
eg :
$ stat filename

Output
  File: `filename'
  Size: 683             Blocks: 8          IO Block: 4096   regular file
Device: fd00h/64768d    Inode: 34177055    Links: 1
Access: (0777/-rwxrwxrwx)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2012-11-26 03:50:01.000000000 -0500
Modify: 2012-11-26 03:22:04.000000000 -0500
Change: 2012-11-26 03:22:04.000000000 -0500

A: You may want to mess with the noatime attribute in your filesystem mounts.
I believe there is now very little reasons to keep the filesystem updating its atime (there may be some left, for example old mail programs used to use those to know if some files were read since last time the person accessed the mail program... But this should be really old behaviour now). However it still is the default on many filesystems and unix/linux systems. I'd welcome information about why it's still needed nowadays...
More info there : http://tldp.org/LDP/solrhe/Securing-Optimizing-Linux-RH-Edition-v1.3/chap6sec73.html
(I took the first link when I searched for "noatime" in my search engine... Should be good enough, but you can probably find more info elsewhere)


text:
Q: JPA CascadeType.REMOVE inverse I have a db with Customers and Bookings. Each booking has 1 customer, and a customer can have many bookings. So I have a @ManyToOne relationship annotated on the customer member. I want if I delete the customer, the booking will be deleted also. But I'm only able to do it the other way, if the Booking is delete, the Customer is deleted, I dont want that. Here is my code:
@Entity
@NamedQueries({
    @NamedQuery(name = Customer.FIND_ALL, query = "SELECT c FROM Customer c ORDER BY c.name ASC"),
    @NamedQuery(name = Customer.FIND_BY_EMAIL, query = "SELECT c FROM Customer c WHERE c.email = :email")
})
@XmlRootElement
@Table(name = "customer", uniqueConstraints = @UniqueConstraint(columnNames = "email"))
public class Customer  implements Serializable {

private static final long serialVersionUID = 1L;

public static final String FIND_ALL = "Customer.findAll";
public static final String FIND_BY_EMAIL = "Customer.findByEmail";

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;

@NotNull
@NotEmpty
@Size(min = 1, max = 50)
@Pattern(regexp = "[A-Za-z\\s]+")
@Column(name = "name")
private String name;

@Entity
@NamedQueries({
    @NamedQuery(name = Booking.FIND_ALL, query = "SELECT b FROM Booking b ORDER BY b.bookingDate ASC")
})
@XmlRootElement
@Table(name = "booking", uniqueConstraints = @UniqueConstraint(columnNames = {"customer", "booking_date"}))
public class Booking implements Serializable {

private static final long serialVersionUID = -1L;

public static final String FIND_ALL = "Booking.findAll";

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;

@NotNull
@ManyToOne(cascade = {CascadeType.REMOVE})
@JoinColumn(name = "customer")
private Customer customer;

@NotNull
@Future(message = "Bookings must be in future")
@Column(name = "booking_date")
@Temporal(value = TemporalType.DATE)
private Date bookingDate;

So if I delete the Customer, the booking should also be deleted. Any ideas?
Thanks

A: Thanks to Nizet for the tips. It's working now with the code below.
/* Booking class */
@NotNull
@ManyToOne
@JoinColumn(name = "customer")
private Customer customer;

/* Customer class */
@OneToMany(cascade = CascadeType.REMOVE, mappedBy = "taxi")
private Set<Booking> bookings = new HashSet<Booking>();;


text:
Q: Core Bluetooth Restoration Timing Issue I thought I had the whole bluetooth restoration thing working (acting as a central), then I tried the following:
1 - Peripheral sends single bluetooth packet every 1 second
2 - At random time, I kill app (either using the debugger stop, or another app to eat all the memory)
3 - Check if restoration took place
This worked about 80% of the time and the errors were seemingly random.
After two days I was able to reliably reproduce the problem:
1 - Peripheral sends two packets 1000 ms apart
2 - Kill the app programatically (kill(getpid(),SIGKILL) some delta after the first packet (100ms,200ms...) which is some delta before the next packet (900ms, 800ms)
    |--PKT-------850ms------KILL--150ms--PKT--|
3 - Second packet arrives and wakes the app up
What I found is that if the time between app termination and the next packet arriving is greater than about 150ms, restoration takes place as it should 100% of the time.
If the time between app termination and the next packet arriving is less than about 150ms, if I open the app manually within 10 seconds, restoration takes place 100% of the time. If I open the app manually after more than 10 seconds, it's as though no restoration took place. Also, once the app is killed, I watch the bluetooth symbol in the status bar and after exactly 10 seconds the connection is dropped.
Testing took place on an iPhone 4s running 8.1 and then 8.2.
This seems like a bug... I can provide my code if that helps however I've stripped it back to the bare minimum delegate implementations. I've tried putting the central manager on a different queue to no avail. This is real issue for my product as it relies upon session-based, background bluetooth tracking. Any thoughts?

A: This seems to be resolve in iOS 9+


text:
Q: ExpandableListAdapter with Json Array I'm trying to write an application with an ExpandableListAdapter and followed this tutorial but I will integer my data base (MYSQL) with json so i have this problem:
Caused by: java.lang.NullPointerException at
com.example.smart_survey.ExpandableListAdapter.getGroupCount
(ExpandableListAdapter.java:71)

Can someOne Help me please
The class ExpandableListAdapter:
public class ExpandableListAdapter extends BaseExpandableListAdapter {

    private Context _context;
    **private List<String> _listDataHeader= null;** // header titles
    // child data in format of header title, child title
    private HashMap<String, List<String>> _listDataChild;

    public ExpandableListAdapter(Context context, List<String> listDataHeader,
                HashMap<String, List<String>> listChildData) {
        this._context = context;
        **this._listDataHeader = listDataHeader;**
        this._listDataChild = listChildData;
    }

    @Override
    public Object getChild(int groupPosition, int childPosititon) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .get(childPosititon);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(int groupPosition, final int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {

        final String childText = (String) getChild(groupPosition, childPosition);

        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_item, null);
        }

        TextView txtListChild = (TextView) convertView
                .findViewById(R.id.lblListItem);

        txtListChild.setText(childText);
        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return this._listDataHeader.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        return this._listDataHeader.size();
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {
        String headerTitle = (String) getGroup(groupPosition);
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_group, null);
        }

        TextView lblListHeader = (TextView) convertView
                .findViewById(R.id.lblListHeader);
        lblListHeader.setTypeface(null, Typeface.BOLD);
        lblListHeader.setText(headerTitle);

        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

}

The Class QR
public class QR extends Activity {

    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    ArrayList<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    // url to get all products list
    private static String url_all_quests =
        "http://10.0.2.2/android_connect/listquest.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_QUEST = "Question";
    private static final String TAG_REP = "Reponse";
    private static final String TAG_IDE = "idenq";
    private static final String TAG_IDQ = "idquest";
    private static final String TAG_LIBQ = "libquest";
    private static final String TAG_LIBR = "librep";

    // products JSONArray

    String idenq;
    String idquest;
    String libquest,librep;
    Button valider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_quest);
        Intent i = getIntent();
        idenq = i.getStringExtra(TAG_IDE);
        idquest = i.getStringExtra(TAG_IDQ);
        // get the listview
        expListView = (ExpandableListView) findViewById(R.id.list);

        // preparing list data
        new prepareListData().execute();

        listAdapter = new ExpandableListAdapter(this, listDataHeader,
                         listDataChild);

        // setting list adapter
        expListView.setAdapter(listAdapter);

        // Listview Group click listener
        expListView.setOnGroupClickListener(new OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                    int groupPosition, long id) {
                // Toast.makeText(getApplicationContext(),
                // "Group Clicked " + listDataHeader.get(groupPosition),
                // Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        // Listview Group expanded listener
        expListView.setOnGroupExpandListener(new OnGroupExpandListener() {

            @Override
            public void onGroupExpand(int groupPosition) {
                Toast.makeText(getApplicationContext(),
                        listDataHeader.get(groupPosition) + "
                                                     Expanded",
                        Toast.LENGTH_SHORT).show();
            }
        });

        // Listview Group collasped listener
        expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {

            @Override
            public void onGroupCollapse(int groupPosition) {
                Toast.makeText(getApplicationContext(),
                        listDataHeader.get(groupPosition) + "
                                     Collapsed",
                        Toast.LENGTH_SHORT).show();

            }
        });

        // Listview on child click listener
        expListView.setOnChildClickListener(new OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                    int groupPosition, int childPosition, long id) {
                // TODO Auto-generated method stub
                Toast.makeText(
                        getApplicationContext(),
                        listDataHeader.get(groupPosition)
                                + " : "
                                +
                            listDataChild.get(listDataHeader.get(groupPosition)).
                                get(childPosition), Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
        });
    }

    /*
     * Preparing the list data
     */
    class prepareListData extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {
            // Building Parameters
            List<NameValuePair> params1 = new ArrayList<NameValuePair>();
            params1.add(new BasicNameValuePair("idenq", idenq));
            params1.add(new BasicNameValuePair("idquest", idquest));

            params1.add(new BasicNameValuePair("libquest", libquest));

            params1.add(new BasicNameValuePair("librep", librep));
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(
                url_all_quests, "GET", params1);

            listDataHeader = new ArrayList<String>();
            listDataChild = new HashMap<String, List<String>>();
            // products found
            // Getting Array of Products
            JSONArray Question;
            try {
                Question = json.getJSONArray(TAG_QUEST);
                    // looping through All Products
                for (int i = 0; i < Question.length(); i++) {

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();
                    // Storing each json item in variable
                    JSONObject c=Question.getJSONObject(i);
                    String libquest = c.getString(TAG_LIBQ);
                    map.put(TAG_LIBQ, libquest);

                    // Adding child data
                    listDataHeader.add(libquest);

                    // Adding child data
                    List<String> top250 = new ArrayList<String>();
                    top250.add("The Shawshank Redemption");
                    top250.add("The Godfather");
                    top250.add("The Godfather: Part II");
                    top250.add("Pulp Fiction");
                    top250.add("The Good, the Bad and the Ugly");
                    top250.add("The Dark Knight");
                    top250.add("12 Angry Men");
                    listDataChild.put(listDataHeader.get(i), top250); // Header, Child data
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        return null;
        }
    }
}

A: I think your problem is you are populating listDataHeader inside doInBackground in your AsynTask. I've never tried to return an ArrayList from a AsynTask but I think this is going to solve your problem. Change AsynTask to return an ArrayList and implement onPostExecute to populate there your variable. In doInBackground you should populate a local variable and then return it. Something like this:
class prepareListData extends AsyncTask<String, String, ArrayList<String>> {

    protected void onPostExecute(ArrayList<String> result) {
        listDataHeader = result;
    }
    @Override
    protected String doInBackground(String... params) {
    // ......
        return localListDataHeader;
    }
}

Try it and see if it solves your problem.


text:
Q: dual boot Windows/Linux "file not found error" appears before boot menu I have recently installed Ubuntu 11.10 on a computer where I also have a Windows 7 installation, so I have a dual boot computer. Everything works fine, except the fact that before the boot menu appears, I get this error:

file not found

and sometimes, I get this error when I boot into Windows, followed by

Press any key to continue...

Both operating systems work fine but I am worried about these two errors I get.
Can anyone help me fix this error?
Where does this error come from?


text:
Q: convert C# xml resource with base64 encoding back into a GIF file let's say I have a 16x16 GIF image stored in a XML in the exact format below that is part of the C# project as happy_face.xml:
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <file name="happy_face.gif">
R0lGODlhEAAQAPcAAAAAAIAAAACAAICAAAAAgIAAgACAgICAgMDAwP8AAAD/AP//AAAA//8A/wD//////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMwAAZgAAmQAAzAAA/wAzAAAzMwAzZgAzmQAzzAAz/wBmAABmMwBmZgBmmQBmzABm/wCZAACZMwCZZgCZmQCZzACZ/wDMAADMMwDMZgDMmQDMzADM/wD/AAD/MwD/ZgD/mQD/zAD//zMAADMAMzMAZjMAmTMAzDMA/zMzADMzMzMzZjMzmTMzzDMz/zNmADNmMzNmZjNmmTNmzDNm/zOZADOZMzOZZjOZmTOZzDOZ/zPMADPMMzPMZjPMmTPMzDPM/zP/ADP/MzP/ZjP/mTP/zDP//2YAAGYAM2YAZmYAmWYAzGYA/2YzAGYzM2YzZmYzmWYzzGYz/2ZmAGZmM2ZmZmZmmWZmzGZm/2aZAGaZM2aZZmaZmWaZzGaZ/2bMAGbMM2bMZmbMmWbMzGbM/2b/AGb/M2b/Zmb/mWb/zGb//5kAAJkAM5kAZpkAmZkAzJkA/5kzAJkzM5kzZpkzmZkzzJkz/5lmAJlmM5lmZplmmZlmzJlm/5mZAJmZM5mZZpmZmZmZzJmZ/5nMAJnMM5nMZpnMmZnMzJnM/5n/AJn/M5n/Zpn/mZn/zJn//8wAAMwAM8wAZswAmcwAzMwA/8wzAMwzM8wzZswzmcwzzMwz/8xmAMxmM8xmZsxmmcxmzMxm/8yZAMyZM8yZZsyZmcyZzMyZ/8zMAMzMM8zMZszMmczMzMzM/8z/AMz/M8z/Zsz/mcz/zMz///8AAP8AM/8AZv8Amf8AzP8A//8zAP8zM/8zZv8zmf8zzP8z//9mAP9mM/9mZv9mmf9mzP9m//+ZAP+ZM/+ZZv+Zmf+ZzP+Z///MAP/MM//MZv/Mmf/MzP/M////AP//M///Zv//mf//zP///yH5BAEAABAALAAAAAAQABAAAAhTAP8JFIiioMGBCAnqW8gQRUKFDCM6RIhiYUWLDQderMhR30WP/z527NjwY8STFk2ilLjRoEuRMF+yZGnwpMOYKieGLGlSJ0SPEh/utCmU4MuEAQEAOw==
</file>
<root>

Trying to figure out how read this resource happy_face.xml from the project's assembly and save it to disk as name="happy_face.gif" in the same place as the program's EXE. Note that the name of the gif file is stored in the XML file to save to disk...
namespace WpfApp1 {
    static class MyXMLTools {

        // Read XML from EXE assembly and
        // Save XML stored binary file to the local disk
        public static void XmlExtract(
            string NAME = "WpfApp1.happy_face.xml")
        {
            Assembly assembly = Assembly.GetExecutingAssembly();

            using(Stream stream
                    = assembly.GetManifestResourceStream(NAME)) {
               using (StreamReader reader
                   = new StreamReader(stream)) {
                  /// ????
                  /// ???
               }
            }
        }

    } // class
} // namespace

Attempt 2:
namespace WpfApp1 {
    static class MyXMLTools {

        // Read XML from EXE assembly and
        // Save XML stored binary file to the local disk
        public static void XmlExtract(
            string NAME = "WpfApp1.happy_face.xml")
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            Stream stream
                      = assembly.GetManifestResourceStream(NAME)) {
            XMLDocument mapfile = new XmlDocument();
            mapfile.Load(stream);
            stream.close();

           // ??? ???
        }

A: This method extract your data to gif binnary:
public static byte[] XmlExtract(string fileName = "WpfApp1.happy_face.xml")
{
    Assembly assembly = Assembly.GetExecutingAssembly();

    using(Stream stream = assembly.GetManifestResourceStream(fileName))
    {
        string b64 = XDocument.Load(stream).Root.Element("file").Value;
        byte[] gifBinnary = Convert.FromBase64String(b64);
        return gifBinnary;
    }
}

But what do you need to do with them next? Save them to a file and assign it to an image? Or pass them directly to the image like ImageSource?


text:
Q: Can MSTest ignore the nested exceptions and only test against the last? Imagine that you have a function that checks if the provided string value is empty like below:
string IsNotEmpty(string value)
{
    if (!string.IsEmpty(value)) return value
    else throw new Exception("Value is empty");
}

Also imagine that we have many other parts of our code that call this generic function to check if there is a value and if not throw a more specific exception than the generic one. As an example i will provide the below code:
string CheckEmail(string email)
{
    try
    {
        return IsNotEmpty(email);
    }
    catch(Exception ex)
    {
        throw new **EmptyEmailException**("Please provide your email");
    }
}

Now i want to write a MSTest for the CheckEmail function that expects an exception of type EmptyEmailException to be thrown. But unfortunately the test captures only the generic Exception from IsNotEmpty function, it stops execution and the code never tests the second exception.
Things i have done without any success:

*

*I wrote my test with ExpectedException attribute.

*I wrote my test
with Assert.ThrowsException.

*I updated the exception settings in VS
to not brake on exceptions of type Exception, just to see if that
will resolve my issue.

No matter what i do MSTest always reports the first exception and of course my test fails. Below is my current test code:
[TestMethod]
public void When_Validating_SignInRequest_And_Email_IsEmpty_Raise_EmptyEmailException()
{
    var ex = Assert.ThrowsException<EmptyEmailException>(
                () => CheckEmail(string.Empty)
            );
}

Can anyone point me to the right direction?
Thanks.

A: This works fine on my end:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace MyNamespace
{
    public class EmptyEmailException : Exception
    {
        public EmptyEmailException(string message) : base(message)
        { }
    }

    public class MyClass
    {
        public static string IsNotEmpty(string value)
        {
            if (!string.IsNullOrEmpty(value))
                return value;
            else
                throw new Exception("Value is empty");
        }

        public static string CheckEmail(string email)
        {
            try
            {
                return IsNotEmpty(email);
            }
            catch
            {
                throw new EmptyEmailException("Please provide your email");
            }
        }
    }

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            Assert.ThrowsException<EmptyEmailException>(() => MyClass.CheckEmail(string.Empty));
        }
    }
}


text:
Q: icon-arrow-right now showing up in my project from a sample at jsfiddle I copied a bootstrap tab control sample project from jsfiddle at
bootstrap tab control sample with dropdown menus
    ---
to my local workstation as a .htm project (I am Not using visual studio here -- running win7 IE 11).  I added (downloaded) all the referenced .css/.js files referenced in this sample project.  The sample project is working on my workstation.  I even get the down caret on the 2nd menu (tab) item.  but the submenu in the actual sample displays an icon-arrow-right (for an additional submenu).  This icon-arrow-right is not showing up on my work station.
I tried another sample project from jsfiddle using VS2015 which used glyphicons.  I got that working, so I copied the font folder from the VS project to my html project folder and tried using glyphicon-arrow-right in the htm project and referenced bootstrap.min.css but still no arrow-right. I tried a variety of things based on other posts regarding the same problem -- but no luck.
How can I get that icon-arrow-right to show up on my sample project on win7 IE11?
Here's the html code I'm using
html>

  <link rel="stylesheet" type="text/css" href="normalize.css">

  <link rel="stylesheet" type="text/css" href="result-light.css">
  <link rel="stylesheet" type="text/css" href="bootstrap-combined.min.css">
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">

  <title></title>

    Project name

Home

Link

Link

Link

          Dropdown

    2-level Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Another action

Something else here

Nav header

Separated link

One more separated link

          <form action="" class="navbar-search pull-left">
            <input type="text" placeholder="Search" class="search-query span2">
          </form>

Link

              Menu

Regular link

  Dropdown

    2-level Menu

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Another action

Something else here

Separated link

 Menu

Menu

A: When I opened up the debugger I saw that this line of CSS set the URL of that image:
.btn-link[disabled]:hover,.btn-link[disabled]:focus{color:#333333;text-decoration:none;}
[class^="icon-"],[class*=" icon-"]{display:inline-block;width:14px;height:14px;*margin-right:.3em;line-height:14px;vertical-align:text-top;background-image:url("../img/glyphicons-halflings.png");background-position:14px 14px;background-repeat:no-repeat;margin-top:1px;}

This is from bootstrap-combined.min.css line 381
I believe you need to update the url to:
http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/img/glyphicons-halflings.png or whatever path is relevant to that given symbol. It seems as though only a partial piece of the URL to the image is being presented.


text:
Q: Sitecore GeoIP Service is not working with personalization I'm working on Sitecore 7 and I have configured the Sitecore GeoIP module (Sitecore IP Geolocation Service Client 1.2 rev. 150602.zip) on our site.
Sitecore IP Geolocation Service is running on our site's App Center.
When I tried to use its functionality with the personalization, it seems not working.
I created the following condition for a component of a page using the presentation details --> personalize

But when I access the site from the give country, the item is still exists on the page (which need to be hidden).
I did test the GeoIp module using the TestIp.aspx page and it's tracking the ip data correctly.
Can someone please advice on this.
Thanks.
UPDATE
This actually works. There is a ip caching mechanism with the MaxMind service.
When the ip is cached the change that we made from sitecore client is not getting activated for certain time.
Is there are any config change that we can do to change or skip this caching mechanism ?
Thanks.

A: Sitecore's GeoIP/MaxMind module does not resolve GeoIP information in real time. It does this in batch background processes - for performance reasons, no doubt.
I can show you a way to change this, but I would not recommend you do this in practice on any real site as calls to the MaxMind service can take a while and will block your page load until they complete.
You need to add a processor to your httpRequest pipeline, early as possible, that forces a lookup for the client IP. It will then be cached for subsequent page loads.
Sitecore.Analytics.Lookups.LookupManager.GetInformationByIp(string ip)

Where the ip argument will be your request Host.
But as I said, I really would not recommend doing it like this, unless your site is very light weight.
My suggestion to you instead of this, will be to build something up around the GeoLite database that MaxMind provides, free of charge. You will then perform lookups in a local database (instead of a web service) - for an example of how this could be done, look here:
http://sitecoresnippets.blogspot.dk/2011/12/sitecore-geoip-country-resolving-jump.html#.Vhdui_l_NBc


text:
Q: Ubuntu One client not showing correct Usage I am using Ubuntu Studio 12.04 although I have noticed the same in other 12.04 variants.
The dashboard of Ubuntu One says that I have used up 25Gigs of my 25Gigs storage subscription. I am nowhere near the 25Gigs.
Does anyone have any suggestions ?

A: The quota being misreported should not be an issue in newer installs; it's entirely possible you have a lot more content synced from for example your phone or your tablet than you are aware of, if you have enabled automatic syncing from any of those devices. Failing that, please do get in touch with support as suggested.


text:
Q: Java Kafka console-consumer running out of heap space I am running the following command in Console. kafka-console-consumer  and receiving
out of memory error: java.lang.OutOfMemoryError: Java heap space. How can I resolve this? Trying to apply this resource, except I do not have a topics file.
Kafka Connect running out of heap space
Console:
kafka-console-consumer --bootstrap-server localhost:9092 --topic encounter.personEvent

Application.Yml
kafka:
  topic: encounter
  event: personEvent

Error Message below:
ERROR Error processing message, terminating consumer process:  (kafka.tools.ConsoleConsumer$)
java.lang.OutOfMemoryError: Java heap space
    at java.base/java.nio.HeapByteBuffer.<init>(HeapByteBuffer.java:64)
    at java.base/java.nio.ByteBuffer.allocate(ByteBuffer.java:363)
    at org.apache.kafka.common.memory.MemoryPool$1.tryAllocate(MemoryPool.java:30)
    at org.apache.kafka.common.network.NetworkReceive.readFrom(NetworkReceive.java:113)
    at org.apache.kafka.common.network.KafkaChannel.receive(KafkaChannel.java:452)
    at org.apache.kafka.common.network.KafkaChannel.read(KafkaChannel.java:402)
    at org.apache.kafka.common.network.Selector.attemptRead(Selector.java:674)
    at org.apache.kafka.common.network.Selector.pollSelectionKeys(Selector.java:576)
    at org.apache.kafka.common.network.Selector.poll(Selector.java:481)
    at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:551)
    at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:265)
    at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:236)
    at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:215)
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.ensureCoordinatorReady(AbstractCoordinator.java:246)
    at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.poll(ConsumerCoordinator.java:480)
    at org.apache.kafka.clients.consumer.KafkaConsumer.updateAssignmentMetadataIfNeeded(KafkaConsumer.java:1262)
    at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1231)
    at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1211)
    at kafka.tools.ConsoleConsumer$ConsumerWrapper.receive(ConsoleConsumer.scala:454)
    at kafka.tools.ConsoleConsumer$.process(ConsoleConsumer.scala:101)
    at kafka.tools.ConsoleConsumer$.run(ConsoleConsumer.scala:75)
    at kafka.tools.ConsoleConsumer$.main(ConsoleConsumer.scala:52)
    at kafka.tools.ConsoleConsumer.main(ConsoleConsumer.scala)

A: KAFKA_HEAP_OPTS is a shared shell variable across all Kafka CLI scripts, so the answer you're referring to in the linked post is correct.
e.g
KAFKA_HEAP_OPTS='-Xmx1G' kafka-console-consumer --bootstrap-server localhost:9092 --topic encounter.personEvent

my apis are running on localhost:8080/swagger-ui.html. and call Kafka producer event

Then you want an HTTP client to POST an HTTP-request to localhost:8080. That, in turn, generates a Kafka message as you say, which is sent to localhost:9092 (by default). You need to consume from Kafka, not an HTTP server


text:
Q: Javascript - Remove event listener at resize I'm doing some work to make navigation fully accessible by mouse over, keyboard and click, depending on the resolution.
I am looking for that in mobile, only the click works. And hover, click, keyboard for higher resolutions.
Important edit :
It only works perfectly when I load the page at the correct resolution (low or high). BUT, if I resize live, the removeEventListener doesn't work.
Plus : I don't know if my stopImmediatePropagation is the better solution to avoid multiple functions.
Here is the idea of the code.
JS
window.addEventListener("DOMContentLoaded", onLoadFunction);

function onLoadFunction(e) {
  menu_burger();
  onResizeFunction(); //trigger resize function immediately

  window.addEventListener("resize", onResizeFunction);
}

function onResizeFunction(e) {
  if (window.innerWidth > 770) {
    window.removeEventListener('resize', menu_onClick);
    menu_onClick();
    menu_mouseOver();
    menu_onFocus();
    menu_onFocusDetection();
  } else {
    window.removeEventListener('resize', menu_onClick);
    window.removeEventListener('resize', menu_mouseOver);
    window.removeEventListener('resize', menu_onFocusDetection);
    window.removeEventListener('resize', menu_onFocus);
    menu_onClick();
  }
}

// FONCTIONS MENU
const focusDetectionEntry = document.querySelectorAll('.nav-list--focus-detection > li[aria-expanded] > button');
const focusEntry = document.querySelectorAll('.nav-list--focus > li[aria-expanded] > button');
const overEntry = document.querySelectorAll('.nav-list--over > li[aria-expanded] > button');
const clickEntry = document.querySelectorAll('.nav-list--click > li[aria-expanded] > button');

function menu_burger() {
  document.querySelector('.menu-burger').addEventListener('click', function () {
    this.classList.toggle('menu--open');
    document.querySelector('.main-nav-list').classList.toggle('main-nav-list--open');
  });
}

function menu_mouseOver() {
  overEntry.forEach(sub => {
    var subParent = sub.parentElement;
    subParent.addEventListener('mouseover', function(e) {
      subParent.setAttribute('aria-expanded', 'true');
      console.log('OVER IN');
      e.stopImmediatePropagation();
    });

    subParent.addEventListener('mouseout', function(e) {
      subParent.setAttribute('aria-expanded', 'false');
      console.log('OVER OUT');
      e.stopImmediatePropagation();
    });
  })
}

function menu_onClick() {
  clickEntry.forEach(sub => {
    var subParent = sub.parentElement;
    sub.addEventListener('click', function(e) {
      let attrState = subParent.getAttribute('aria-expanded');

      if (attrState === 'false') {
        subParent.setAttribute('aria-expanded', 'true')
      } else if (attrState === 'true') {
        subParent.setAttribute('aria-expanded', 'false');
      }

      console.log('CLICK');
      e.stopImmediatePropagation();
    });
  })
}

function menu_onFocus() {
  focusEntry.forEach(sub => {
    var subParent = sub.parentElement;
    sub.addEventListener('keyup', (e) => {
      console.log('TOUCHE');
      if (e.keyCode === 27) {
        console.log('ECHAP');
        subParent.setAttribute('aria-expanded', 'false');
      }
      e.stopImmediatePropagation();
    });
  })
}

function menu_onFocusDetection() {
  focusDetectionEntry.forEach(sub => {
    var subParent = sub.parentElement;
    sub.addEventListener('focus', function (e) {
      subParent.setAttribute('aria-expanded', 'true');
      console.log('FOCUS');
      e.stopImmediatePropagation();
    });

    subParent.addEventListener('focusout', function (e) {
      console.log('FOCUS OUT');
      //console.log(e.relatedTarget); //target actuel
      if (!subParent.contains(e.relatedTarget)) {
        subParent.setAttribute('aria-expanded', 'false');
      }
      e.stopImmediatePropagation();
    });
  })
}

I tried something like that, but not successfull :
function menu_onFocusDetection() {
  focusDetectionEntry.forEach(sub => {
    var subParent = sub.parentElement;
    // si focus sur le bouton, on modifie sont parent
    function test(ev) {
      subParent.setAttribute('aria-expanded', 'true');
      console.log('FOCUS');
      ev.stopImmediatePropagation();
    }

    // si le focus sort du li
    function test2(ev2) {
      // console.log(ev2.relatedTarget); //target actuel
      console.log('FOCUS OUT');
      if (!subParent.contains(ev2.relatedTarget)) {
        subParent.setAttribute('aria-expanded', 'false');
      }
      ev2.stopImmediatePropagation();
    }

    if (window.innerWidth > 770) {
      sub.addEventListener('focus', test);
      sub.addEventListener('focusout', test2);
    } else {
      sub.removeEventListener('focus', test);
      sub.removeEventListener('focusout', test2);
    }
  })

}

A: Ok, so here it is the answer :
I had to split my function and do the condition in each.
window.addEventListener("DOMContentLoaded", onLoadFunction);
function onLoadFunction(e) {
  onResizeFunction(); //trigger resize function immediately
  window.addEventListener("resize", onResizeFunction);
}

function onResizeFunction(e) {
  menu_onFocusDetection();
}

function initEntries() {
  focusDetectionEntry = document.querySelectorAll('.nav-list--focus-detection > li[aria-expanded] > button');
}

function focus(e) {
  this.parentElement.setAttribute('aria-expanded', 'true');
  e.stopImmediatePropagation();
}

function menu_onFocusDetection() {
  focusDetectionEntry.forEach(sub => {
    var subParent = sub.parentElement;
    if (window.innerWidth > 770) {
      sub.addEventListener('focus', focus);
      subParent.addEventListener('focusout', focusOut);
    } else {
      sub.removeEventListener('focus', focus);
      subParent.removeEventListener('focusout', focusOut);
    }
  });
}

A: Event handlers are executed every time an event occurs, not just the first time. They need to be registered only once.
Move the click and mouseover handlers to standalone function declarations, and register those handlers in the outer block. So basically:
window.addEventListener("load", onLoadFunction);

function onLoadFunction(e) {
  onResizeFunction();// trigger resize function immediately

  window.addEventListener("resize", onResizeFunction);
}

function onResizeFunction(e) {
  if (window.innerWidth > 770) {
    //over + click
    over();
    click();
  } else {
    //only click
    click();
  }

}

function click() {
  console.log('CLICK');
}

function over() {
  console.log('OVER');
}

document.querySelector('.test').addEventListener('click', click);
document.querySelector('.test').addEventListener('mouseover', over);


text:
Q: React Native fetching request from API freezes UI I'm able to fetch messages from the API and render them in the component successfully. However, as the number of messages increases, fetching from the API causes the app to freeze and clicking any event (such as selecting a different tab or button) will be only triggered when the request is done.
I've read about using next-frame to solve this issue but I'm finding difficulties in how to add it to my code. I'd like to know how to implement next-frame inside it.
This is the section of code that fetches messages from the backend:
componentWillMount()
{
    /**load user's messages */
    loadmessages() {
        fetch(server + 'view_user_messages.php', {
            method: 'POST',
            headers: {
                'Accept': 'text/plain',
                'Content-Type': 'text/plain',
            },
            body: JSON.stringify({
                user_idDB: modulevariables.globaluserid
            })
        }).then((response) => response.text())
            .then((responseJson) => {

                var jsonconvertedrows = JSON.parse(responseJson)
                this.setState({ messagestable: jsonconvertedrows })
            }).catch((error) => {
                console.log(error);
            })
    }
}


text:
Q: Schedule WordPress Auto-Updates to only run during business hours We've turned on WordPress Auto-Updates (yey!), but, just in case this does break anything, we'd like to only run Auto-Updates during daylight hours (e.g. 09:00 - 17:30).
We have the "on init" WP-Cron disabled, and are calling it from the servers crontab every 10 minutes.
How can adapt the AutoUpdate, so all updates are run during these times? I've looked at hooks for WP-Cron, but got a little lost.
Additionally - is there a hook that fires once an auto-updated is complete? Our code is in source control, and I'm looking at ways to 'auto-commit' a new branch into our code after an update (rather than having to do it manually).
(The duplicate question doesn't provide any guidance into the hooks to check - simply suggesting to edit the Database - it also talks about WP Cron being fired 'on load' - rather than running on a dedicated cron).
Cheers,
Darren

A: This one is actually surprisingly simple; add this to your wp-config.php file and all automatic updates will be blocked when outside of the specified hours:
// Suspend updates when outside of business hours, 9:00 AM to 5:30 PM
$updates_suspended = (date('Hi') < 0900 || date('Hi') > 1730);

define( 'AUTOMATIC_UPDATER_DISABLED', $updates_suspended );

You can also use these other constants and filters to control which automatic updates are allowed to run if you need to make this more specific.

Make sure you use the server timezone when you set this. The function date() might be configured to use a timezone that is different from your local timezone.

A: Based on "BenCole" answer:
date() is affected by runtime timezone changes which can cause date/time to be incorrectly displayed. better to use WordPress native current_datetime() that "retrieves the current time as an object with the timezone from settings".
        $current_time = current_datetime()->format( 'Hi' );

        $disable_updater = ( $current_time > 900 || $current_time < 1730 );

        define( 'AUTOMATIC_UPDATER_DISABLED', $disable_updater );

A: // An example to allow plugin auto update between "friday 6pm et monday 12am" :
$updates_suspended = !((date('N') == 5 && date('G') > 17) || in_array(date('N'), array(6,7)) || (date('N') == 1 && date('G') < 12)(;
define( 'AUTOMATIC_UPDATER_DISABLED', $updates_suspended );

the value of date('N') is an integer who is the day of the week (1 to monday and 5 to friday)
the value of date('G') is an integer who is the hour of day
If you just want handle with hour of day, use only date('G')
Example : to allow update plugin auto every day only after 11pm and before 6am :
$updates_suspended = !((date('G') < 6 || date('G') > 22));
define( 'AUTOMATIC_UPDATER_DISABLED', $updates_suspended );

This code goes in wp-config.php, it have been tested and it works.
More details on dates here : https://www.php.net/manual/fr/function.date.php


text:
Q: How to search and replace for multiple words in one shot I need to search and replace multiple words. For example, in my file, I want to search for any name of week days that appears with a comma after it: Sat, or Sun, or Mon, or Tue, or Wed, or Thur, or Fri, to a name without comma: Saturday or Sunday or Monday or Tuesday or Wednesday or Thursday or Friday. I know how to do this one by one:
sed 's/Sat,/Saturday/g' myfile.txt > output.txt

But due to the fact that I have to check every week day in multiple files, I need to find a more efficient way to check all the names and replace them at once. I am aware this can be done through scripting but I have not worked on that before. If someone familiar with this, I can learn from it this time and do it myself next time.

A: You can chain multiple sed expressions with -e like this:
sed -e 's/Sat,/Saturday/g' -e 's/Sun,/Sunday/g' <file>

This will replace all occurrences of Sat, with Saturday and all occurrences of Sun, with Sunday.

A: Thought I'd share this solution.  The media subtitles that I download are filled with NSFC (Not Safe For Children) words. This removes objectionable words recursively:
find . -type f -name "*.srt" -exec sed -i 's/\(word1\|word2\|word3\|word4\|word5\|word6\|word7\|word8\)//g' {} +
This verifies their removal:
grep --include=\*.srt -rnwE . -e 'word1|word2|word3|word4|word5|word6|word7|word8'


text:
Q: How to send emails with google using nodemailer after Google disabled less sure app option? I would like to find a way to send email from my app using nodemailer to the users either with some kind of google authentication or any other way. Below mentioned working code has stopped working after Google has disabled less secure app option.
const nodemailer = require('nodemailer')

const sendEmail = async options => {
const transporter = nodemailer.createTransport({
    // host: "smtp.gmail.com",
    // port: "465",
    // secure: true,
    service:'gmail',
    auth: {
        user: "USER_EMAIL",
        pass: "USER_PASSWORD"
    },
    tls:{rejectUnauthorized:false}
})

const message = {
    from: `${process.env.FROM_NAME} <${process.env.FROM_EMAIL}>`,
    to: options.email,
    subject: options.subject,
    text: options.message,
    html: options.message,
    attachments: [
        {
            filename: '.png',
            path: __dirname + '.png',
            cid: '.png'
        }
    ]
}

const info = await transporter.sendMail(message)
console.log('Message sent : %s', info.messageId)
console.log(__dirname)
}
module.exports = sendEmail

A: At the time of writing, Less Secure Apps is no longer supported by google. And you can't use your google account password.
You're gonna have to generate a new app password.
App passwords only work if 2-step verification is turned on.
Follow this steps to get the app password

*

*Go to https://myaccount.google.com/security

*Enable 2FA

*Create App Password for Email

*Copy that password (16 characters) into the pass parameter in Nodemailer auth.

const client = nodemailer.createTransport({
    service: "Gmail",
    auth: {
        user: "username@gmail.com",
        pass: "Google-App-Password-Without-Spaces"
    }
});

client.sendMail(
    {
        from: "sender",
        to: "recipient",
        subject: "Sending it from Heroku",
        text: "Hey, I'm being sent from the cloud"
    }
)

A: You should check out Xoauth2.
Nodmailer supports serval types of Oauth
let transporter = nodemailer.createTransport({
  host: "smtp.gmail.com",
  port: 465,
  secure: true,
  auth: {
    type: "OAuth2",
    user: "user@example.com",
    clientId: "000000000000-xxx0.apps.googleusercontent.com",
    clientSecret: "XxxxxXXxX0xxxxxxxx0XXxX0",
    refreshToken: "1/XXxXxsss-xxxXXXXXxXxx0XXXxxXXx0x00xxx",
    accessToken: "ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x",
    expires: 1484314697598,
  },
});


text:
Q: Width of edge of the bars in R plots Is there a way to set the width the the edge of the bars in R plots?
For example when  I set
test <- read.csv(file="test4.csv",sep=",",head=TRUE)
pdf(file="test.pdf", height=4, width=6)
barplot(as.matrix(test[,2:ncol(test)]), col=heat.colors(10), space=0.5)
dev.off()

I get this.

But the edges of all the bars are very thick compared to the width of the bars themselves, hence the high level of black at the bottom and in the smaller bars.

A: You can set the line width before plotting.
opar <- par(lwd = 0.3)

This will make thinner bars but not affect your axes (as they are set separately).


text:
Q: Where the function ap_run_pre_connection in Apache httpd source code? I'm reading the source code of the Apache2.2 and I found that when I use the prefork module,it call the ap_process_connection to deal with a connection and in this method it calls the ap_run_pre_connection.
When it comes to here,I can find neither ap_run_pre_connection nor pre_connection (I find a macro named AP_DECLARE_HOOK, it linked the ap and _hook_ before the name pre_connection).
Where can I find the next step?

A: You can find the modules that participate in this hook by looking for ap_hook_pre_connection.
AP_IMPLEMENT_HOOK_RUN_ALL(int,pre_connection,(conn_rec *c, void *csd),(c, csd),OK,DECLINED)
AP_IMPLEMENT_HOOK_RUN_ALL means multiple modules that called ap_hook_pre_connection() will be run until an error is returned
/**
 * Implement an Apache core hook that runs until one of the functions
 * returns something other than ok or decline. That return value is
 * then returned from the hook runner. If the hooks run to completion,
 * then ok is returned. Note that if no hook runs it would probably be
 * more correct to return decline, but this currently does not do
 * so. The implementation is called ap_run_<i>name</i>.

The actual impl of ap_run_pre_connection is just a macro that loops through a linked list of registered functions. See apr_hooks.h


text:
Q: What happens to degeneration as a compact star cools down? Compact stellar objects are substained by degeneration of electron (white dwarfs) or neutron (neutron star).
I wonder what happens to this degenerate matter as the star cools down?


text: Q: Tiny mce line breaks I use tiny mce for user to display text. And i use this code to display their text: