问:
vb.net 2015: How to get value from datagridviewcomboboxcell?
For some reason I'm having issues trying to get the value from the data grid combo box cell. This is the error I get when I click the button:

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.'

I've tried to get the value by referencing the rows and columns as well as by the combobox name.

I'm sure it is an easy fix for most of you, so any help would be greatly appreciated :-)

I removed the code for the labels and textboxes as they are working correctly and didn't want to made the code any longer than needed.

```<code>Imports System.Windows.Forms

Public Class Custom_Tab_Page
Inherits TabPage

Private dynamic_Button As New Button
Private cdgv As New DataGridView
Private gridComboBoxDays As New DataGridViewComboBoxCell
Private dynamic_Tab_Page As New TabPage

Public Sub New(ByVal name As String)
    Me.Text = name

    INITIALIZE_TEXTBOX()
    INITIALIZE_BUTTON()
    InitializetDataGridView()

End Sub

Protected Sub INITIALIZE_BUTTON()
    dynamic_Button = New Button
    With dynamic_Button
        .Top = 10
        .Left = 190
        .Visible = True
        .AutoSize = True
        .Text = "Calculate"
        AddHandler .Click, AddressOf Button_Click
    End With

    Me.Controls.Add(dynamic_Button)

End Sub

Protected Sub Button_Click(ByVal sender As Object, ByVal e As EventArgs)

    If dynamic_Label IsNot Nothing Then
        With dynamic_Textbox
            .Text = cdgv.Rows(0).Cells(0).Value
        End With
    End If
End Sub

Private Sub InitializetDataGridView()

    Dim cdgv = New DataGridView()
    With cdgv
        .Top = 200
        .Left = 200
        .RowHeadersVisible = False
        .ColumnCount = 3
        .RowCount = 2
        .ScrollBars = ScrollBars.None
        .ColumnHeadersHeight = 63
        .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None
        .AllowUserToAddRows = False
        .RowsDefaultCellStyle.NullValue = 0.ToString
    End With

    Dim gridComboBoxDays = New DataGridViewComboBoxCell
    For x As Integer = 0 To 31
        gridComboBoxDays.Items.Add(x.ToString) 'Populate the Combobox
    Next

    Dim gridComboBoxHours As New DataGridViewComboBoxCell
    For x As Integer = 0 To 23
        gridComboBoxHours.Items.Add(x.ToString) 'Populate the Combobox
    Next

    Dim gridComboBoxMinutes As New DataGridViewComboBoxCell
    For x As Integer = 0 To 59
        gridComboBoxMinutes.Items.Add(x.ToString) 'Populate the Combobox
    Next

    For Loop_Counter As Integer = 0 To cdgv.ColumnCount - 1
        cdgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        cdgv.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        cdgv.Columns(Loop_Counter).Width = 65
    Next
    '
    '   Set The header values based on units selected
    '
    cdgv.Columns(0).HeaderCell.Value = "Time Since" & vbCrLf & "Last Flight" & vbCrLf & "(days)"
    cdgv.Columns(1).HeaderCell.Value = "Time Since" & vbCrLf & "Last Flight" & vbCrLf & "(hours)"
    cdgv.Columns(2).HeaderCell.Value = "Time Since" & vbCrLf & "Last Flight" & vbCrLf & "(minutes)"
    '
    '   Set the overall height And width of the dgv_Gases_Used
    '
    cdgv.Width = cdgv.Columns(0).Width + cdgv.Columns(1).Width + cdgv.Columns(2).Width + 3
    cdgv.Height = cdgv.RowCount * cdgv.RowTemplate.Height + cdgv.ColumnHeadersHeight
    '

    cdgv.Item(0, 0) = gridComboBoxDays
    cdgv.Item(1, 0) = gridComboBoxHours
    cdgv.Item(2, 0) = gridComboBoxMinutes

    Me.Controls.Add(cdgv)

End Sub
End Class
</code>```

答:
You have to add some verification

```<code> If dynamic_Label IsNot Nothing AnAlso
     cdgv.Rows.Count > 0  Then

    With dynamic_Textbox

        If not cdgv.Rows(0).Cells(0) is Nothing Then

            .Text = cdgv.Rows(0).Cells(0).Value

         Else

             .Text = ""

         End If

    End With

End If
</code>```

EDIT 1

After reading your comment i think you have to check the way that you are adding the dataGridViewComboboxCell to the dataGridView and how to read from it.

below some useful Links:

Setting a DataGridViewComboBoxCell

How to programatically populate a DataGridViewComboBoxColumn in VB.net?

How To Add A DataGridViewComboBoxCell to a Bound DataGridView DataSource (Programatically)

Reading Value From DataGridViewComboBoxCell

Get the SelectedItem of DataGridViewComboBoxCell VB.NET

Get DataGridViewComboboxColumn SelectedValue (VB.Net)

How to get selected DataGridViewComboBoxColumn values in vb.net?

Read Combobox selected Value From Datagridview instead of bound value

Maybe you should use SelectedValue instead of Value

Body:
For some reason I'm having issues trying to get the value from the data grid combo box cell. This is the error I get when I click the button:

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.'

I've tried to get the value by referencing the rows and columns as well as by the combobox name.

I'm sure it is an easy fix for most of you, so any help would be greatly appreciated :-)

I removed the code for the labels and textboxes as they are working correctly and didn't want to made the code any longer than needed.

Imports System.Windows.Forms

Public Class Custom_Tab_Page
Inherits TabPage

Private dynamic_Button As New Button
Private cdgv As New DataGridView
Private gridComboBoxDays As New DataGridViewComboBoxCell
Private dynamic_Tab_Page As New TabPage

Public Sub New(ByVal name As String)
    Me.Text = name

    INITIALIZE_TEXTBOX()
    INITIALIZE_BUTTON()
    InitializetDataGridView()

End Sub

Protected Sub INITIALIZE_BUTTON()
    dynamic_Button = New Button
    With dynamic_Button
        .Top = 10
        .Left = 190
        .Visible = True
        .AutoSize = True
        .Text = "Calculate"
        AddHandler .Click, AddressOf Button_Click
    End With

    Me.Controls.Add(dynamic_Button)

End Sub

Protected Sub Button_Click(ByVal sender As Object, ByVal e As EventArgs)

    If dynamic_Label IsNot Nothing Then
        With dynamic_Textbox
            .Text = cdgv.Rows(0).Cells(0).Value
        End With
    End If
End Sub

Private Sub InitializetDataGridView()

    Dim cdgv = New DataGridView()
    With cdgv
        .Top = 200
        .Left = 200
        .RowHeadersVisible = False
        .ColumnCount = 3
        .RowCount = 2
        .ScrollBars = ScrollBars.None
        .ColumnHeadersHeight = 63
        .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None
        .AllowUserToAddRows = False
        .RowsDefaultCellStyle.NullValue = 0.ToString
    End With

    Dim gridComboBoxDays = New DataGridViewComboBoxCell
    For x As Integer = 0 To 31
        gridComboBoxDays.Items.Add(x.ToString) 'Populate the Combobox
    Next

    Dim gridComboBoxHours As New DataGridViewComboBoxCell
    For x As Integer = 0 To 23
        gridComboBoxHours.Items.Add(x.ToString) 'Populate the Combobox
    Next

    Dim gridComboBoxMinutes As New DataGridViewComboBoxCell
    For x As Integer = 0 To 59
        gridComboBoxMinutes.Items.Add(x.ToString) 'Populate the Combobox
    Next

    For Loop_Counter As Integer = 0 To cdgv.ColumnCount - 1
        cdgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        cdgv.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        cdgv.Columns(Loop_Counter).Width = 65
    Next
    '
    '   Set The header values based on units selected
    '
    cdgv.Columns(0).HeaderCell.Value = "Time Since" & vbCrLf & "Last Flight" & vbCrLf & "(days)"
    cdgv.Columns(1).HeaderCell.Value = "Time Since" & vbCrLf & "Last Flight" & vbCrLf & "(hours)"
    cdgv.Columns(2).HeaderCell.Value = "Time Since" & vbCrLf & "Last Flight" & vbCrLf & "(minutes)"
    '
    '   Set the overall height And width of the dgv_Gases_Used
    '
    cdgv.Width = cdgv.Columns(0).Width + cdgv.Columns(1).Width + cdgv.Columns(2).Width + 3
    cdgv.Height = cdgv.RowCount * cdgv.RowTemplate.Height + cdgv.ColumnHeadersHeight
    '

    cdgv.Item(0, 0) = gridComboBoxDays
    cdgv.Item(1, 0) = gridComboBoxHours
    cdgv.Item(2, 0) = gridComboBoxMinutes

    Me.Controls.Add(cdgv)

End Sub
End Class

Body:
You have to add some verification

 If dynamic_Label IsNot Nothing AnAlso
     cdgv.Rows.Count > 0  Then

    With dynamic_Textbox

        If not cdgv.Rows(0).Cells(0) is Nothing Then

            .Text = cdgv.Rows(0).Cells(0).Value

         Else

             .Text = ""

         End If

    End With

End If

EDIT 1

After reading your comment i think you have to check the way that you are adding the dataGridViewComboboxCell to the dataGridView and how to read from it.

below some useful Links:

Setting a DataGridViewComboBoxCell

How to programatically populate a DataGridViewComboBoxColumn in VB.net?

How To Add A DataGridViewComboBoxCell to a Bound DataGridView DataSource (Programatically)

Reading Value From DataGridViewComboBoxCell

Get the SelectedItem of DataGridViewComboBoxCell VB.NET

Get DataGridViewComboboxColumn SelectedValue (VB.Net)

How to get selected DataGridViewComboBoxColumn values in vb.net?

Read Combobox selected Value From Datagridview instead of bound value

Maybe you should use SelectedValue instead of Value


来源: stackexchange

问:
Internals of how the HashMap put() and get() methods work (basic logic only )
When we put a key instance say "key" and a Value instance say "value" in  a HashMap class using put() method , what does the HashMap class do internally . How does it retrieve the value back when we say hashMap.get(key) ?

Edit: I do not want details here , basically trying to understand the bigger picture and the role of equals() and hashcode() method in put() and get() operations.

答:
From java 8 onwords, there is a performance improvement for HashMap objects where there are lots of collisions in the keys by using balanced trees rather than linked lists to store map entries. The principal idea is that once the number of items in a hash bucket grows beyond a certain threshold, that bucket will switch from using a linked list of entries to a balanced tree. In the case of high hash collisions, this will improve worst-case performance from O(n) to O(log n).

Basically when a bucket becomes too big (currently: TREEIFY_THRESHOLD = 8), HashMap dynamically replaces it with an ad-hoc implementation of tree map. This way rather than having pessimistic O(n) we get much better O(log n).

Bins (elements or nodes) of TreeNodes may be traversed and used like any others, but additionally support faster lookup when overpopulated. However, since the vast majority of bins in normal use are not overpopulated, checking for existence of tree bins may be delayed in the course of table methods.

Tree bins (i.e., bins whose elements are all TreeNodes) are ordered primarily by hashCode, but in the case of ties, if two elements are of the same “class C implements Comparable<C>“, type then their compareTo() method is used for ordering.

Because TreeNodes are about twice the size of regular nodes, we use them only when bins contain enough nodes. And when they become too small (due to removal or resizing) they are converted back to plain bins (currently: UNTREEIFY_THRESHOLD = 6). In usages with well-distributed user hashCodes, tree bins are rarely used.

Link to java doc

Collection framework enhancements

ContentLicense: CC BY-SA 3.0


问:
Polymerfire - Cannot read property 'push' of undefined
I have problem similar to this, except that I'm using polymer template from this.

I imported all polymerfire references both in the page where <firebase-app> is declared and in the page where <firebase-query> is used. Not working.

I found later that the template uses polymerfire which version is v0.9.4 instead of the latest v0.10.3. I tried uninstalling and re-installing the new version. Nothing changed.

For additional information, here's a snippet of the code:

src/app-auth/app-auth-firebase.html

```<code><link rel="import" href="../../bower_components/polymerfire/polymerfire.html">
<link rel="import" href="../../bower_components/polymerfire/firebase-app.html">
<link rel="import" href="../../bower_components/polymerfire/firebase-auth.html">
<link rel="import" href="../../bower_components/polymerfire/firebase-query.html">
...
<firebase-app name="pwa-demo" api-key="abc" auth-domain="abc" database-url="abc"></firebase-app>

<firebase-auth id="auth" app-name="pwa-demo" signed-in="{{_signedIn}}" user="{{_user}}"on-error="_onAuthError"></firebase-auth>
</code>```

src/app-pages/app-page-new-stuff/app-page-new-stuff.html

```<code><link rel="import" href="../../../bower_components/polymerfire/firebase-auth.html">
<link rel="import" href="../../../bower_components/polymerfire/firebase-query.html">
<link rel="import" href="../../../bower_components/polymerfire/polymerfire.html">
...
<firebase-auth user="{{user}}"></firebase-auth>

<firebase-query id="stuffquery" app-name="pwa-demo" path="/users/[[user.uid]]/events" data="{{events}}"> </firebase-query>
...
_onFormSubmit: function() {
    this.$.stuffquery.ref.push({
        title: this.$.piTitle.value
    });
}
</code>```

Is there anything else that I'm missing? Please help.

EDIT:
I found two other weird things, which might be helpful. First, I couldn't do both retrieving the data and pushing the data from and to my app. Second, when I attempt to run firebase.database() in browser console, I got "Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app)."

Anyone?

答:
After days of frustration, it works. Apparently.

TL;DR

What I did is updating polymerfire and omitting the name attribute from any firebase element.

Explanation

Looking at this, it seems firebase initializes the app in __computeApp method and name is an optional variable but will be used in initialization if it is provided. Ignore it and everything should be okay. In my case, it works both for <firebase-app>, <firebase-auth>, and <firebase-query> (for pushing data, because i'm still stuck in using firebase-query for fetching data)

While it works in my case, it might not necessarily the right solution. It might not work in your case. It took me days to figure it out so for those who are in similar problems, one of these might help:

Inspect firebase query attribute. Refer to this

Try import polymerfire/polymerfire.html in the same html file where <firebase-app> is declared. Refer to this

Update polymerfire. Simply uninstall and reinstall it might solve the case (for those with outdated version of polymerfire)

Omit name attribute from any firebase element. I know my <firebase-app> is successfully initialized when I type firebase.database() in browser console, it doesn't give error anymore.

Hope it helps.

Body:
I have problem similar to this, except that I'm using polymer template from this.

I imported all polymerfire references both in the page where <firebase-app> is declared and in the page where <firebase-query> is used. Not working.

I found later that the template uses polymerfire which version is v0.9.4 instead of the latest v0.10.3. I tried uninstalling and re-installing the new version. Nothing changed.

For additional information, here's a snippet of the code:

src/app-auth/app-auth-firebase.html

<link rel="import" href="../../bower_components/polymerfire/polymerfire.html">
<link rel="import" href="../../bower_components/polymerfire/firebase-app.html">
<link rel="import" href="../../bower_components/polymerfire/firebase-auth.html">
<link rel="import" href="../../bower_components/polymerfire/firebase-query.html">
...
<firebase-app name="pwa-demo" api-key="abc" auth-domain="abc" database-url="abc"></firebase-app>

<firebase-auth id="auth" app-name="pwa-demo" signed-in="{{_signedIn}}" user="{{_user}}"on-error="_onAuthError"></firebase-auth>

src/app-pages/app-page-new-stuff/app-page-new-stuff.html

<link rel="import" href="../../../bower_components/polymerfire/firebase-auth.html">
<link rel="import" href="../../../bower_components/polymerfire/firebase-query.html">
<link rel="import" href="../../../bower_components/polymerfire/polymerfire.html">
...
<firebase-auth user="{{user}}"></firebase-auth>

<firebase-query id="stuffquery" app-name="pwa-demo" path="/users/[[user.uid]]/events" data="{{events}}"> </firebase-query>
...
_onFormSubmit: function() {
    this.$.stuffquery.ref.push({
        title: this.$.piTitle.value
    });
}

Is there anything else that I'm missing? Please help.

EDIT:
I found two other weird things, which might be helpful. First, I couldn't do both retrieving the data and pushing the data from and to my app. Second, when I attempt to run firebase.database() in browser console, I got "Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app)."

Anyone?


问:
Best way to replace part of array with another array
I'm looking for the most pythonic way of doing something like that:</p>

```<code>a = [1,2,3,4,5,6,7,8]
b = ['a','b','c']
c = replace(a,b,2)

c is now [1,2,'a','b','c',6,7,8]
</code>```

答:
Okay, here is another simple way to do this:
(Edit: forgot slicing a to copy it into c)

```<code>a = [1,2,3,4,5,6,7,8]
b = ['a','b','c']
c=a[:]
c[2:5]=b
print(c)
</code>```

Or, when you want to replace in place:

```<code>a = [1,2,3,4,5,6,7,8]
b = ['a','b','c']
a[2:5]=b
print(a)
</code>```

Hope I helped!

Body:
I'm looking for the most pythonic way of doing something like that:

a = [1,2,3,4,5,6,7,8]
b = ['a','b','c']
c = replace(a,b,2)

c is now [1,2,'a','b','c',6,7,8]

Body:
Okay, here is another simple way to do this:
(Edit: forgot slicing a to copy it into c)

a = [1,2,3,4,5,6,7,8]
b = ['a','b','c']
c=a[:]
c[2:5]=b
print(c)

Or, when you want to replace in place:

a = [1,2,3,4,5,6,7,8]
b = ['a','b','c']
a[2:5]=b
print(a)

Hope I helped!


问:
Where is Gradle Project so I can import it? (Android Studio)
I'm 99% positive this is a total nub question but I downloaded the pocketsphinx demo project: https://github.com/cmusphinx/pocketsphinx-android-demo and was told in the tutorial to just import the project into Android Studio and then all the dependencies would be pulled automatically.  I don't doubt this is the case but when I tried importing the project I got a dialog asking me to "Import Gradle Project".  I'm confused because it sounds like it's looking for a component of the project but there's nothing I could find in there that AS was looking for.  Is this included in the project or do I have to download Gradle?

Edit:

I try to import the project

I hit okay and this pops up:

答:
You can check if your machine has gradle by running gradle -v. If the command is not found, you do you not have gradle installed. If you do not have gradle installed on your machine, you need to take the steps to install for your machine.

If you are running a linux based machine the steps located at http://gradle.org/install will assist you. However if you are running a windows machine, the steps are a bit different and can vary depending on which version of windows you are using. This tutorial can help you http://howtoprogram.xyz/2016/09/14/install-gradle-windows/.

Once you have successfully installed gradle, set your gradle home to the location of the folder you choose.


问:
Returning unique_ptr from functions
unique_ptr<T> does not allow copy construction, instead it supports move semantics. Yet, I can return a unique_ptr<T> from a function and assign the returned value to a variable.

```<code>#include <iostream>
#include <memory>

using namespace std;

unique_ptr<int> foo()
{
  unique_ptr<int> p( new int(10) );

  return p;                   // 1
  //return move( p );         // 2
}

int main()
{
  unique_ptr<int> p = foo();

  cout << *p << endl;
  return 0;
}
</code>```

The code above compiles and works as intended. So how is it that line 1 doesn't invoke the copy constructor and result in compiler errors? If I had to use line 2 instead it'd make sense (using line 2 works as well, but we're not required to do so).

I know C++0x allows this exception to unique_ptr since the return value is a temporary object that will be destroyed as soon as the function exits, thus guaranteeing the uniqueness of the returned pointer. I'm curious about how this is implemented, is it special cased in the compiler or is there some other clause in the language specification that this exploits?

答:
is there some other clause in the language specification that this exploits?

Yes, see 12.8 §34 and §35:

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object [...]
  This elision of copy/move operations, called copy elision, is permitted [...]
  in a return statement in a function with a class return type, when the expression is the name of
  a non-volatile automatic object with the same cv-unqualified type as the function return type [...]

When the criteria for elision of a copy operation are met and the object to be copied is designated by an lvalue,
  overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.

Just wanted to add one more point that returning by value should be the default choice here because a named value in the return statement in the worst case, i.e. without elisions in C++11, C++14 and C++17 is treated as an rvalue.  So for example the following function compiles with the -fno-elide-constructors flag

```<code>std::unique_ptr<int> get_unique() {
  auto ptr = std::unique_ptr<int>{new int{2}}; // <- 1
  return ptr; // <- 2, moved into the to be returned unique_ptr
}

...

auto int_uptr = get_unique(); // <- 3
</code>```

With the flag set on compilation there are two moves (1 and 2) happening in this function and then one move later on (3).

Title: Returning unique_ptr from functions

Body:
unique_ptr<T> does not allow copy construction, instead it supports move semantics. Yet, I can return a unique_ptr<T> from a function and assign the returned value to a variable.

#include <iostream>
#include <memory>

using namespace std;

unique_ptr<int> foo()
{
  unique_ptr<int> p( new int(10) );

  return p;                   // 1
  //return move( p );         // 2
}

int main()
{
  unique_ptr<int> p = foo();

  cout << *p << endl;
  return 0;
}

The code above compiles and works as intended. So how is it that line 1 doesn't invoke the copy constructor and result in compiler errors? If I had to use line 2 instead it'd make sense (using line 2 works as well, but we're not required to do so).

I know C++0x allows this exception to unique_ptr since the return value is a temporary object that will be destroyed as soon as the function exits, thus guaranteeing the uniqueness of the returned pointer. I'm curious about how this is implemented, is it special cased in the compiler or is there some other clause in the language specification that this exploits?

Body:
is there some other clause in the language specification that this exploits?

Yes, see 12.8 §34 and §35:

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object [...]
  This elision of copy/move operations, called copy elision, is permitted [...]
  in a return statement in a function with a class return type, when the expression is the name of
  a non-volatile automatic object with the same cv-unqualified type as the function return type [...]

When the criteria for elision of a copy operation are met and the object to be copied is designated by an lvalue,
  overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.

Just wanted to add one more point that returning by value should be the default choice here because a named value in the return statement in the worst case, i.e. without elisions in C++11, C++14 and C++17 is treated as an rvalue.  So for example the following function compiles with the -fno-elide-constructors flag

std::unique_ptr<int> get_unique() {
  auto ptr = std::unique_ptr<int>{new int{2}}; // <- 1
  return ptr; // <- 2, moved into the to be returned unique_ptr
}

...

auto int_uptr = get_unique(); // <- 3

With the flag set on compilation there are two moves (1 and 2) happening in this function and then one move later on (3).


问:
How to have different actions happen every second and then repeat every four seconds
My title may be kind of confusing, but I essentially want to draw a different set of shapes every four seconds then start over. For example, second one I want to draw triangles, second two I want to draw lines, second three I want to draws rectangles, and second four I want to draw ovals. The for second five I want this process to repeat. My Idea was to use the remainder which works up to second seven. Also is this possible to do without importing any additional modules. Any help would be great and if something was not clear please ask.

Thanks,
Scott

Here is my current code to run if you want:

```<code>from tkinter import *
from random import *

#creates a class
class mainWindow():
    def __init__(self,theWindow,winName):

        #Sets values for variable
        self.running = 0

        #makes theWindow and instnace var
        self.theWindow = theWindow

        #creates the main frames
        self.mainFrame = Frame(theWindow,width=600,height=200,bg="light gray")
        self.secondframe = Frame(theWindow,width=600, height =287, bg = "green")

        self.mainFrame.grid()
        self.secondframe.grid()

        # gives the window a title
        theWindow.title(winName)

        # do not resize window based on widgets
        self.mainFrame.grid_propagate(False)

        # window location
        theWindow.geometry('+500+300')

        #Makes it so the window wont resize
        self.theWindow.resizable(0,0)

        #
        self.theWindow.wm_attributes("-topmost",1)

`enter code here`#Creates the three frames that will be used

        #Inerts a blank label to help with formating
        self.blank1 = Label(self.mainFrame, bg= "light gray", height =3, width=19)
        self.blank1.grid(row=0, column=0, rowspan =1)

        #Creates and places the start button
        self.startbutton = Label(self.mainFrame,text = "Start", bg= "green", height =1, width=10,relief=RAISED)
        self.startbutton.bind("<Button-1>", self.startTimer)
        self.startbutton.grid(row=0, column=2, rowspan =1, sticky = E)

        #Creates and places the stop button
        self.stopbutton = Label(self.mainFrame,text = "Stop", bg= "red", height =1, width=10,relief=RAISED)
        self.stopbutton.bind("<Button-1>", self.endTimer)
        self.stopbutton.grid(row=0, column=3, rowspan =1, sticky =W)

        #Creates and places the timer
        self.timerLabel = Label(self.mainFrame,text = "Time: 0", bg= "white", height =2, width=14,relief=SUNKEN)
        self.timerLabel.bind("<Button-1>",)
        self.timerLabel.grid(row=3, column=2, columnspan =2, pady =25)

        #draws the canvas
        self.drawCanvas = Canvas(self.secondframe,width=598,height=285, bg= "light green")
        self.drawCanvas.grid()

    #Function for strting the timer
    def startTimer(self,event):
        if self.running == 0:
            self.running = 1
            self.countElapse(0)

    #function for ening the timer
    def endTimer(self,event):
        if self.running == 1:
            self.running = 0
            self.timecount = 0
            self.drawCanvas.delete(ALL)
            self.timerLabel.configure(text = "Time: %d" %0)

    #function for showing the time
    def countElapse(self,localTime = NONE):
        #self.timerLabel.configure()
        if self.running:
            if localTime is not NONE:
                self.timecount = localTime
            self.timerLabel.configure(text ="Time: "+str(self.timecount+1))
            self.timecount = self.timecount+1
            self.drawshapes(self.timecount)
            self.mainFrame.after(1000,self.countElapse)

    #function for drawing the shpaes
    def drawshapes(self,timecount):

        self.drawCanvas.delete(ALL)
        color = ["red","white","purple","green","lime green", "cyan", "black","light blue","blue","pink","brown","gray"]
        numshapes = 100
        counter = 0
        print(self.timecount)

        var = self.timecount

        #draws ovals
        if var % 4 ==0:
            while counter != numshapes:
                counter += 1
                x = randint(10,600)
                y = randint(10,600)
                x1 = randint(10,600)
                y1 = randint(10,600)

                #draws the shape
                self.drawCanvas.create_oval(x,y,x1,y1,fill=choice(color))

        #draws rectangles
        elif var % 3 ==0:
            while counter != numshapes:
                counter += 1
                x = randint(10,600)
                y = randint(10,600)
                x1 = randint(10,600)
                y1 = randint(10,600)
                self.drawCanvas.create_rectangle(x,y,x1,y1,fill= choice(color))

        #draws Lines
        elif var % 2 ==0:
            while counter != numshapes:
                counter += 1
                x = randint(10,600)
                y = randint(10,600)
                x1 = randint(10,600)
                y1 = randint(10,600)
                self.drawCanvas.create_line(x,y,x1,y1,fill= choice(color))

        #draws triangles
        elif var % 1 ==0:
            while counter != numshapes:
                counter += 1
                x = randint(10,600)
                y = randint(10,600)
                x1 = randint(10,600)
                y1 = randint(10,600)
                x2 = randint(10,600)
                y2 = randint(10,600)
                self.drawCanvas.create_polygon(x,y,x1,y1,x2,y2,fill= choice(color))

def main():
    # create a tkinter object
    mainWin = Tk()
    # create a mainWindow object
    theMainWin = mainWindow(mainWin,"Scott Rodgers")
    # keep the window displaying
    mainWin.mainloop()

#calls main
main()
</code>```

答:
What you are looking for is how to use the .after method.

Here is how it works.

```<code>Lbl = Label()
Lbl.pack()
Lbl.after([Amount of milliseconds], lamba: [Function])
</code>```

For more advanced notation,

```<code>after(delay_ms, callback=None, *args)
</code>```

What this does is that it registers an alarm callback that is called after a given time

Body:
My title may be kind of confusing, but I essentially want to draw a different set of shapes every four seconds then start over. For example, second one I want to draw triangles, second two I want to draw lines, second three I want to draws rectangles, and second four I want to draw ovals. The for second five I want this process to repeat. My Idea was to use the remainder which works up to second seven. Also is this possible to do without importing any additional modules. Any help would be great and if something was not clear please ask.

Thanks,
Scott

Here is my current code to run if you want:

from tkinter import *
from random import *

#creates a class
class mainWindow():
    def __init__(self,theWindow,winName):

        #Sets values for variable
        self.running = 0

        #makes theWindow and instnace var
        self.theWindow = theWindow

        #creates the main frames
        self.mainFrame = Frame(theWindow,width=600,height=200,bg="light gray")
        self.secondframe = Frame(theWindow,width=600, height =287, bg = "green")

        self.mainFrame.grid()
        self.secondframe.grid()

        # gives the window a title
        theWindow.title(winName)

        # do not resize window based on widgets
        self.mainFrame.grid_propagate(False)

        # window location
        theWindow.geometry('+500+300')

        #Makes it so the window wont resize
        self.theWindow.resizable(0,0)

        #
        self.theWindow.wm_attributes("-topmost",1)

`enter code here`#Creates the three frames that will be used

        #Inerts a blank label to help with formating
        self.blank1 = Label(self.mainFrame, bg= "light gray", height =3, width=19)
        self.blank1.grid(row=0, column=0, rowspan =1)

        #Creates and places the start button
        self.startbutton = Label(self.mainFrame,text = "Start", bg= "green", height =1, width=10,relief=RAISED)
        self.startbutton.bind("<Button-1>", self.startTimer)
        self.startbutton.grid(row=0, column=2, rowspan =1, sticky = E)

        #Creates and places the stop button
        self.stopbutton = Label(self.mainFrame,text = "Stop", bg= "red", height =1, width=10,relief=RAISED)
        self.stopbutton.bind("<Button-1>", self.endTimer)
        self.stopbutton.grid(row=0, column=3, rowspan =1, sticky =W)

        #Creates and places the timer
        self.timerLabel = Label(self.mainFrame,text = "Time: 0", bg= "white", height =2, width=14,relief=SUNKEN)
        self.timerLabel.bind("<Button-1>",)
        self.timerLabel.grid(row=3, column=2, columnspan =2, pady =25)

        #draws the canvas
        self.drawCanvas = Canvas(self.secondframe,width=598,height=285, bg= "light green")
        self.drawCanvas.grid()

    #Function for strting the timer
    def startTimer(self,event):
        if self.running == 0:
            self.running = 1
            self.countElapse(0)

    #function for ening the timer
    def endTimer(self,event):
        if self.running == 1:
            self.running = 0
            self.timecount = 0
            self.drawCanvas.delete(ALL)
            self.timerLabel.configure(text = "Time: %d" %0)

    #function for showing the time
    def countElapse(self,localTime = NONE):
        #self.timerLabel.configure()
        if self.running:
            if localTime is not NONE:
                self.timecount = localTime
            self.timerLabel.configure(text ="Time: "+str(self.timecount+1))
            self.timecount = self.timecount+1
            self.drawshapes(self.timecount)
            self.mainFrame.after(1000,self.countElapse)

    #function for drawing the shpaes
    def drawshapes(self,timecount):

        self.drawCanvas.delete(ALL)
        color = ["red","white","purple","green","lime green", "cyan", "black","light blue","blue","pink","brown","gray"]
        numshapes = 100
        counter = 0
        print(self.timecount)

        var = self.timecount

        #draws ovals
        if var % 4 ==0:
            while counter != numshapes:
                counter += 1
                x = randint(10,600)
                y = randint(10,600)
                x1 = randint(10,600)
                y1 = randint(10,600)

                #draws the shape
                self.drawCanvas.create_oval(x,y,x1,y1,fill=choice(color))

        #draws rectangles
        elif var % 3 ==0:
            while counter != numshapes:
                counter += 1
                x = randint(10,600)
                y = randint(10,600)
                x1 = randint(10,600)
                y1 = randint(10,600)
                self.drawCanvas.create_rectangle(x,y,x1,y1,fill= choice(color))

        #draws Lines
        elif var % 2 ==0:
            while counter != numshapes:
                counter += 1
                x = randint(10,600)
                y = randint(10,600)
                x1 = randint(10,600)
                y1 = randint(10,600)
                self.drawCanvas.create_line(x,y,x1,y1,fill= choice(color))

        #draws triangles
        elif var % 1 ==0:
            while counter != numshapes:
                counter += 1
                x = randint(10,600)
                y = randint(10,600)
                x1 = randint(10,600)
                y1 = randint(10,600)
                x2 = randint(10,600)
                y2 = randint(10,600)
                self.drawCanvas.create_polygon(x,y,x1,y1,x2,y2,fill= choice(color))

def main():
    # create a tkinter object
    mainWin = Tk()
    # create a mainWindow object
    theMainWin = mainWindow(mainWin,"Scott Rodgers")
    # keep the window displaying
    mainWin.mainloop()

#calls main
main()

Body:
What you are looking for is how to use the .after method.

Here is how it works.

Lbl = Label()
Lbl.pack()
Lbl.after([Amount of milliseconds], lamba: [Function])

For more advanced notation,

after(delay_ms, callback=None, *args)

What this does is that it registers an alarm callback that is called after a given time


问:
vb.net getting value from a new name sql database
```<code> Dim cd As SqlCommand = New SqlCommand("select datepart(mm,Birthday) as MonthDates from Information where Name='" & cbname.Text & "'", con)
            Dim reader1 As SqlDataReader = cd.ExecuteReader
            While reader1.Read
                Dim mon As Integer = reader1("MonthDates")
                lblbday.Text = mon
</code>```

I used this code to assume that the new named column in SQL will be read in vb net but its not reading the new named Column "MonthDates".

What is wrong with the code? Please help. Thank you in advance!

答:
You should dispose connection after query (in my example USING do this):</p>

```<code>Using con As New SqlConnection(....)
    Dim cd As SqlCommand = New SqlCommand("select datepart(mm,Birthday) as MonthDates from Information where Name='" & cbname.Text & "'", con)
    Dim mon As Integer = cd.ExecuteScalar()
    lblbday.Text = mon
End Using
</code>```

Body:
 Dim cd As SqlCommand = New SqlCommand("select datepart(mm,Birthday) as MonthDates from Information where Name='" & cbname.Text & "'", con)
            Dim reader1 As SqlDataReader = cd.ExecuteReader
            While reader1.Read
                Dim mon As Integer = reader1("MonthDates")
                lblbday.Text = mon

I used this code to assume that the new named column in SQL will be read in vb net but its not reading the new named Column "MonthDates".

What is wrong with the code? Please help. Thank you in advance!

Body:
You should dispose connection after query (in my example USING do this):

Using con As New SqlConnection(....)
    Dim cd As SqlCommand = New SqlCommand("select datepart(mm,Birthday) as MonthDates from Information where Name='" & cbname.Text & "'", con)
    Dim mon As Integer = cd.ExecuteScalar()
    lblbday.Text = mon
End Using


问:
kafka-consumer-groups.sh equivalent?
I am using 0.10.2 version. I would like to know does any Kafka java API can  fetch the offset info like using:

```<code>./bin/kafka-consumer-groups.sh --bootstrap-server 192.168.0.28:9092 --describe --group test
</code>```

Since I want to show all this offset information in my application without using the CLI.

答:
I don't think there's an equivalent in the Java client; I just looked at that script and it calls a scala class ConsumerGroupCommand.

I am not familiar with scala, but it looks like that class doesn't expose the internal classes (e,g, ZkConsumerGroupService) that implement the command so it doesn't look like it can be invoked from a user app.

Looks like it writes directly to stdout anyway, rather than producing an object with the results.

I suppose you could run it and capture stdout...

```<code>ConsumerGroupCommand.main(new String[] {"--bootstrap-server", "localhost:9092",
            "--describe",
            "--group", "test"});
</code>```

Or, you'd have to lift a bunch of code from that class.

Title: kafka-consumer-groups.sh equivalent?

Body:
I am using 0.10.2 version. I would like to know does any Kafka java API can  fetch the offset info like using:

./bin/kafka-consumer-groups.sh --bootstrap-server 192.168.0.28:9092 --describe --group test

Since I want to show all this offset information in my application without using the CLI.

Body:
I don't think there's an equivalent in the Java client; I just looked at that script and it calls a scala class ConsumerGroupCommand.

I am not familiar with scala, but it looks like that class doesn't expose the internal classes (e,g, ZkConsumerGroupService) that implement the command so it doesn't look like it can be invoked from a user app.

Looks like it writes directly to stdout anyway, rather than producing an object with the results.

I suppose you could run it and capture stdout...

ConsumerGroupCommand.main(new String[] {"--bootstrap-server", "localhost:9092",
            "--describe",
            "--group", "test"});

Or, you'd have to lift a bunch of code from that class.


问:
PHP Largest Possible Integer Constant
Was reading the PHP manual on integer overflow in the manual and was wondering: is there a PHP pre-defined constant for the current largest integer value possible? Something equivalent to the JavaScript Number.MAX_VALUE constant.

答:
From here:</p>

```<code>PHP_INT_MAX (integer)
    Available since PHP 4.4.0 and PHP 5.0.5
</code>```

ContentLicense: CC BY-SA 2.5

Title: PHP Largest Possible Integer Constant

Body:
From here:

PHP_INT_MAX (integer)
    Available since PHP 4.4.0 and PHP 5.0.5


问:
Get the value of a input number in jQuery
I'm working on a form, and I want to get in real time the current value of an input field of type number, as this one :

$(":input").bind('keyup mouseup', function () {
  var coins = $("#coins").val();
  $("#reward").text(coins);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="coins" type="number" name="coins" value="1" max="999" min="1">

<p id="potential">Potential reward : <b id="reward"></b></p></code>```

But nothing happen when I run it. It says that the value of coins is null. I don't know what I am doing wrong...
Anyone could help ?

答:
Code shown works fine when user makes edits.

If you need it to display when page loads just trigger one of the events

$(":input").on('keyup mouseup', function () {
  var coins = $("#coins").val();
  $("#reward").text(coins);
}).trigger('mouseup');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="coins" type="number" name="coins" value="1" max="999" min="1">

<p id="potential">Potential reward : <b id="reward"></b></p></code>```

Note that bind() is deprecated in favor of using on()

Body:
I'm working on a form, and I want to get in real time the current value of an input field of type number, as this one :

$(":input").bind('keyup mouseup', function () {
  var coins = $("#coins").val();
  $("#reward").text(coins);
});

<input id="coins" type="number" name="coins" value="1" max="999" min="1">

Potential reward :

But nothing happen when I run it. It says that the value of coins is null. I don't know what I am doing wrong...
Anyone could help ?

Body:
Code shown works fine when user makes edits.

If you need it to display when page loads just trigger one of the events

$(":input").on('keyup mouseup', function () {
  var coins = $("#coins").val();
  $("#reward").text(coins);
}).trigger('mouseup');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="coins" type="number" name="coins" value="1" max="999" min="1">

<p id="potential">Potential reward : <b id="reward"></b></p>

Note that bind() is deprecated in favor of using on()


问:
Python Flask website from endless data loop?
I've built some websites using Flask before, including one which used websockets, but this time I'm not sure how to begin.

I currently have an endless loop in Python which gets sensor data from a ZeroMQ socket. It roughly looks like this:

```<code>import zeromq
socket = zeromq.create_socket()
while True:
    data_dict = socket.receive_json()
    print data_dict  # {'temperature': 34.6, 'speed': 12.8, etc.}
</code>```

I now want to create a dashboard showing the incoming sensor data in real time in some nice charts. Since it's in Python and I'm familiar with Flask and websockets I would like to use that.

The websites I built before were basic request/reply based ones though. How on earth would I create a Flask website from a continuous loop?

答:
The Web page will only be interested on the latest value within a reasonable interval from the user's point of view..., say, 3 seconds, so you can retrieve values in the background using a separate thread.

This is an example of how to use the threading module to update a latest value in the background:

```<code>import threading
import random
import time

_last_value = None

def get_last_value():
    return _last_value

def retrieve_value():
    global _last_value
    while True:
        _last_value = random.randint(1, 100)
        time.sleep(3)

threading.Thread(target=retrieve_value, daemon=True).start()

for i in range(20):
    print(i, get_last_value())
    time.sleep(1)
</code>```

In your case, it would be something like:

```<code>import threading
import zeromq

_socket = zeromq.create_socket()
_last_data_dict = {}

def get_latest_data():
    return _last_data_dict

def retrieve_value():
    global _last_data_dict
    while True:
        _last_data_dict = _socket.receive_json()

threading.Thread(target=retrieve_value, daemon=True).start()
</code>```

Body:
I've built some websites using Flask before, including one which used websockets, but this time I'm not sure how to begin.

I currently have an endless loop in Python which gets sensor data from a ZeroMQ socket. It roughly looks like this:

import zeromq
socket = zeromq.create_socket()
while True:
    data_dict = socket.receive_json()
    print data_dict  # {'temperature': 34.6, 'speed': 12.8, etc.}

I now want to create a dashboard showing the incoming sensor data in real time in some nice charts. Since it's in Python and I'm familiar with Flask and websockets I would like to use that.

The websites I built before were basic request/reply based ones though. How on earth would I create a Flask website from a continuous loop?

Body:
The Web page will only be interested on the latest value within a reasonable interval from the user's point of view..., say, 3 seconds, so you can retrieve values in the background using a separate thread.

This is an example of how to use the threading module to update a latest value in the background:

import threading
import random
import time

_last_value = None

def get_last_value():
    return _last_value

def retrieve_value():
    global _last_value
    while True:
        _last_value = random.randint(1, 100)
        time.sleep(3)

threading.Thread(target=retrieve_value, daemon=True).start()

for i in range(20):
    print(i, get_last_value())
    time.sleep(1)

In your case, it would be something like:

import threading
import zeromq

_socket = zeromq.create_socket()
_last_data_dict = {}

def get_latest_data():
    return _last_data_dict

def retrieve_value():
    global _last_data_dict
    while True:
        _last_data_dict = _socket.receive_json()

threading.Thread(target=retrieve_value, daemon=True).start()


问:
jQuery Ajax clicks doesn't work unless page is refreshed
I've been messing around with some JS and ajax in my PHP project and I am facing some problems. The ajax only seems to work when the page is refreshed after clicking or just refresh to click. I'm using jquery 3.2.1.

I was first using .live() but that is deprecated now and I read that .on() is an alternative so I am using that now.

This is my JS part:

```<code>  $(".up_vote").on("click", function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'upvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $(".down_vote").on("click", function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'downvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $("#btnpost").click(function() {
    var post = $("#post_feed").val();
    if (post == "") {
      alert("This can't be empty.");
      return false;
    } else {
      $.ajax({
        type: "POST",
        data: {
          'post_feed': post,
          'action': 'post'
        },
        url: '<?php echo $url; ?>/includes/functions.php',
        dataType: 'json',
        success: function(response) {
          if (response.ResponseCode == 200) {
            $("#post_feed").val("");
            $('#feed_div').load('<?php echo $url; ?>/index.php #feed_div');
          } else {
            alert(response.Message);
          }
        }
      });
    }
  });
});
</code>```

Is there anything I am missing or done wrong?

答:
You can try with below given code.</p>

```<code>$(document).on("click",".up_vote",function() {
    alert("click");
});
</code>```

Body:
I've been messing around with some JS and ajax in my PHP project and I am facing some problems. The ajax only seems to work when the page is refreshed after clicking or just refresh to click. I'm using jquery 3.2.1.

I was first using .live() but that is deprecated now and I read that .on() is an alternative so I am using that now.

This is my JS part:

  $(".up_vote").on("click", function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'upvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $(".down_vote").on("click", function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'downvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $("#btnpost").click(function() {
    var post = $("#post_feed").val();
    if (post == "") {
      alert("This can't be empty.");
      return false;
    } else {
      $.ajax({
        type: "POST",
        data: {
          'post_feed': post,
          'action': 'post'
        },
        url: '<?php echo $url; ?>/includes/functions.php',
        dataType: 'json',
        success: function(response) {
          if (response.ResponseCode == 200) {
            $("#post_feed").val("");
            $('#feed_div').load('<?php echo $url; ?>/index.php #feed_div');
          } else {
            alert(response.Message);
          }
        }
      });
    }
  });
});

Is there anything I am missing or done wrong?

Body:
You can try with below given code.

$(document).on("click",".up_vote",function() {
    alert("click");
});


问:
Erlang newbie - concurrency and message passing
I'm still new to programming and brand new erlang (2 week newbie!). I edited slightly so atleast it'll compile and run. But I still can't figure out the concept of sending the results to a "joiner process" to join all the seperate results.

It does split and send the "chunks" an received to count the chunks. Just don't know how to get all those processes to join their individual results. I sort of understand the concept below, but have no idea how that's implimented. I've been trying for many days and hours to get it to this point, but can't get it to do anything without getting errors or unbound variables, etc.

```<code>-module (ccharcount1d).
-compile(export_all).

load(F)->
 {ok, Bin} = file:read_file(F),
  List=binary_to_list(Bin),
  Ls=string:to_lower(List),
  Length=round(length(List)/20),
  Collect_Results = spawn(ccharcount1d, collect_results, []),

  Sl=split(Ls,Length),

  io:fwrite("Loaded, Split, and sent to multiple processes~n").

%%splits txt file into "chunks" and sends those "chunks" to be processed
split([],_)->[];
split(List,Length)->
S1=string:substr(List,1,Length),
case length(List) > Length of
   true->S2=string:substr(List,Length+1,length(List)),
   Process_Split = spawn(ccharcount1d,receive_splits,[]),
   Process_Split ! {self(), S1};

   false->S2=[],
   Process_Split = spawn(ccharcount1d,receive_splits,[]),
   Process_Split ! {self(), S1}

 end,

[S1]++split(S2,Length).

%%recieves the split "chunks" and counts the results
receive_splits()->
    receive
        {From, S1} ->
            Result=go(S1)
            %Collect_Results ! Result
    end.

collect_results()->
    receive
        {Process_Split, Result} ->
            Result=join([],Result)
    end.

join([],[])->[];
join([],R)->R;
join([H1 |T1],[H2|T2])->
{C,N}=H1,
{C1,N1}=H2,
[{C1,N+N1}]++join(T1,T2).

count(Ch, [],N)->N;
count(Ch, [H|T],N) ->
   case Ch==H of
   true-> count(Ch,T,N+1);
   false -> count(Ch,T,N)
end.

go(L)->
Alph=[$a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l,$m,$n,$o,$p,$q,$r,$s,$t,$u,$v,$w,$x,$y,$z],
rgo(Alph,L,[]).

rgo([H|T],L,Result)->
N=count(H,L,0),
Result2=Result++[{[H],N}],
rgo(T,L,Result2);

rgo([],L,Result)-> Result.
</code>```

答:
You need to synchronize the output of go function.
Don't spawn function inside go because i am seeing that all results are going to different process(receive_results).

Best solutions is spawn one process for joining result inside load function only(this process takes self() as Input so that it can send final result back to load function).Then pass that join process reference(J_PID) to all worker processes which will send back result to join process.Join process is loop of kind of receive_results.Loop terminates when all chunks are processed.Add a clause to terminate join process.While terminating, join process will send back result to load function.

Sudo code:

J_PID = spawn join(self())

spilt(J_PID,....)

wait_for_result(receive Result -> R)

Body:
I'm still new to programming and brand new erlang (2 week newbie!). I edited slightly so atleast it'll compile and run. But I still can't figure out the concept of sending the results to a "joiner process" to join all the seperate results.

It does split and send the "chunks" an received to count the chunks. Just don't know how to get all those processes to join their individual results. I sort of understand the concept below, but have no idea how that's implimented. I've been trying for many days and hours to get it to this point, but can't get it to do anything without getting errors or unbound variables, etc.

-module (ccharcount1d).
-compile(export_all).

load(F)->
 {ok, Bin} = file:read_file(F),
  List=binary_to_list(Bin),
  Ls=string:to_lower(List),
  Length=round(length(List)/20),
  Collect_Results = spawn(ccharcount1d, collect_results, []),

  Sl=split(Ls,Length),

  io:fwrite("Loaded, Split, and sent to multiple processes~n").

%%splits txt file into "chunks" and sends those "chunks" to be processed
split([],_)->[];
split(List,Length)->
S1=string:substr(List,1,Length),
case length(List) > Length of
   true->S2=string:substr(List,Length+1,length(List)),
   Process_Split = spawn(ccharcount1d,receive_splits,[]),
   Process_Split ! {self(), S1};

   false->S2=[],
   Process_Split = spawn(ccharcount1d,receive_splits,[]),
   Process_Split ! {self(), S1}

 end,

[S1]++split(S2,Length).

%%recieves the split "chunks" and counts the results
receive_splits()->
    receive
        {From, S1} ->
            Result=go(S1)
            %Collect_Results ! Result
    end.

collect_results()->
    receive
        {Process_Split, Result} ->
            Result=join([],Result)
    end.

join([],[])->[];
join([],R)->R;
join([H1 |T1],[H2|T2])->
{C,N}=H1,
{C1,N1}=H2,
[{C1,N+N1}]++join(T1,T2).

count(Ch, [],N)->N;
count(Ch, [H|T],N) ->
   case Ch==H of
   true-> count(Ch,T,N+1);
   false -> count(Ch,T,N)
end.

go(L)->
Alph=[$a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l,$m,$n,$o,$p,$q,$r,$s,$t,$u,$v,$w,$x,$y,$z],
rgo(Alph,L,[]).

rgo([H|T],L,Result)->
N=count(H,L,0),
Result2=Result++[{[H],N}],
rgo(T,L,Result2);

rgo([],L,Result)-> Result.


问:
Equivalent of shell 'cd' command to change the working directory?
cd is the shell command to change the working directory.

How do I change the current working directory in Python?

答: os.chdir() is the right way.

OwnerDisplayName: Peter

ContentLicense: CC BY-SA 4.0

Body: os.chdir() is the right way.

OwnerDisplayName: Federico Ramponi


问:
using only one button to play and pause a Mediaplayer in Android
I am new to Android, my requirement is to use only one button for playing and pause using media player class?</p>

答:
Once you have your MediaPlayer set up, I would just set up in your onCreate() and onResume() methods, a check to see if the MediaPlayer is currently playing (MediaPlayer's isPlaying() method should work for you), and if it is playing, set the button's image and click handler to change it to a pause button. If the MediaPlayer isn't playing, then set it to be a play button.

You'll also need to handle listening for events such as when the MediaPlayer stops (finishes playing the audio file), as well as inverting the button state when you press it (i.e. pressing play changes button to pause, and vice versa).


问:
scala: set None to Option
I am trying to set the variable foo initialized as var foo = Some(0.0) to None but I am getting None.type doesn't conform to expected type Some[Double]. What is the correct way to specify that the variable has no value?

答:
Since foo is Some[Double], you can't assign a None.type to it as they are different types (it doesn't matter that they share a common base). In order for you to be able to do that, you need to explicitly declare the type of foo to be Option[Double]:

```<code>scala> var foo: Option[Double] = Some(0.0)
foo: Option[Double] = Some(0.0)

scala> foo = None
foo: Option[Double] = None
</code>```

Or use Option.apply:

```<code>scala> var foo = Option(0.0)
foo: Option[Double] = Some(0.0)

scala> foo = None
foo: Option[Double] = None
</code>```

Title: scala: set None to Option

Body:
Since foo is Some[Double], you can't assign a None.type to it as they are different types (it doesn't matter that they share a common base). In order for you to be able to do that, you need to explicitly declare the type of foo to be Option[Double]:

scala> var foo: Option[Double] = Some(0.0)
foo: Option[Double] = Some(0.0)

scala> foo = None
foo: Option[Double] = None

Or use Option.apply:

scala> var foo = Option(0.0)
foo: Option[Double] = Some(0.0)

scala> foo = None
foo: Option[Double] = None


问:
Insert controller data on html page
I'm trying to use ng-repeat to print a set of comments from the dishDetailController in blockquote. I've tried but I do not know how to do this. Any help would be appreciated, thanks. Here is the code. </p>

<p>
                </p>

```<code>            <head>
                <meta charset="utf-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <!-- The above 3 meta tags *must* come first in the head; any other head
                     content must come *after* these tags -->
                <title>Ristorante Con Fusion: Menu</title>
                <!-- Bootstrap -->
                <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
                <link href="../bower_components/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet">
                <link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet">
                <link href="styles/bootstrap-social.css" rel="stylesheet">
                <link href="styles/mystyles.css" rel="stylesheet">

                <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
                <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
                <!--[if lt IE 9]>
                <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
                <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
                <![endif]-->
            </head>

            <body>

            <div class="container">
                <div class="row row-content">
                    <div class="col-xs-12" ng-controller="dishDetailController as dish">
                        <ul class="media-list">
                            <li class="media">
                                <div class="media-left media-middle">
                                    <a href="#">
                                        <img class="media-object img-thumbnail"
                                             ng-src="{{dish.image}}" alt="Uthapizza">
                                    </a>
                                </div>
                                <div class="media-body">
                                    <h2 class="media-heading">{{dish.name}}
                                        <span class="label label-danger">{{dish.label}}</span>
                                        <span class="badge">{{dish.price | currency}}</span>
                                    </h2>
                                    <p>{{dish.description}}</p>
                                </div>
                            </li>
                        </ul>
                    </div>
                    <div class="col-xs-9 col-xs-offset-1">
                        <h3>Customer Comments</h3>
                        <blockquote>
                            <!--In this blockquote. -->
                        </blockquote>
                    </div>
                </div>

            </div>

            <script src="../bower_components/angular/angular.min.js"></script>
            <script>

                var app = angular.module('confusionApp', []);

                app.controller('dishDetailController', function ($scope) {

                    var dish = {
                        name: 'Uthapizza',
                        image: 'images/uthapizza.png',
                        category: 'mains',
                        label: 'Hot',
                        price: '4.99',
                        description: 'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
                        comments: [
                            {
                                rating: 5,
                                comment: "Imagine all the eatables, living in conFusion!",
                                author: "John Lemon",
                                date: "2012-10-16T17:57:28.556094Z"
                            },
                            {
                                rating: 4,
                                comment: "Sends anyone to heaven, I wish I could get my mother-in-law to eat it!",
                                author: "Paul McVites",
                                date: "2014-09-05T17:57:28.556094Z"
                            },
                            {
                                rating: 3,
                                comment: "Eat it, just eat it!",
                                author: "Michael Jaikishan",
                                date: "2015-02-13T17:57:28.556094Z"
                            },
                            {
                                rating: 4,
                                comment: "Ultimate, Reaching for the stars!",
                                author: "Ringo Starry",
                                date: "2013-12-02T17:57:28.556094Z"
                            },
                            {
                                rating: 2,
                                comment: "It's your birthday, we're gonna party!",
                                author: "25 Cent",
                                date: "2011-12-02T17:57:28.556094Z"
                            }

                        ]
                    };

                    $scope.dish = dish;

                });

            </script>

            </body>

            </html>
</code>```

答:
Try this</p>

```<code><blockquote ng-repeat="item in dish.comments">
      {{item.comment}} - {{item.author}}
</blockquote>
</code>```

Title: Insert controller data on html page

Body:
I'm trying to use ng-repeat to print a set of comments from the dishDetailController in blockquote. I've tried but I do not know how to do this. Any help would be appreciated, thanks. Here is the code.

                <meta charset="utf-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1">

                <title>Ristorante Con Fusion: Menu</title>

                <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
                <link href="../bower_components/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet">
                <link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet">
                <link href="styles/bootstrap-social.css" rel="stylesheet">
                <link href="styles/mystyles.css" rel="stylesheet">

{{dish.name}}
                                        {{dish.label}}
                                        {{dish.price | currency}}

{{dish.description}}

Customer Comments

Body:
Try this

<blockquote ng-repeat="item in dish.comments">
      {{item.comment}} - {{item.author}}
</blockquote>


问:
Sharepoint: Calculated Column replace all spaces
Seems like it would be a simple thing really (and it may be), but I'm trying to take the string data of a column and then through a calculated column, replace all the spaces with %20's so that the HTML link in the workflow produced email will actually not break off at the first space.

For example, we have this in our source column:

file:///Z:/data/This is our report.rpt

And would like to end up with this in the calculated column:

file:///Z:/data/This%20is%20our%20report.rpt

Already used the REPLACE, and made up a ghastly super nested REPLACE/SEARCH version, but the problem there is that you have to nest for EACH potential space, and if you don't know how many up front, it doesn't work, or will miss some.

Have any of you come across this scenario and how did you handle it?

Thanks in advance!

答:
I was able to solve this issue for my circumstances by using a series of calculated columns.

In the first calculated column (C1) I entered a formula to remove the first space, something like this:

```<code>=IF(ISNUMBER(FIND(" ",[Title])),REPLACE([Title],FIND(" ",[Title]),1,"%20"),[Title])
</code>```

In the second Calculated column (C2) I used:

```<code>=IF(ISNUMBER(FIND(" ",[C1])),REPLACE([C1],FIND(" ",[C1]),1,"%20"),[C1]).
</code>```

In my case, I wanted to encode upto four spaces, so I used 3 calculated columns (C1, C2, C3) in the same fashion and got the desired result.

This is not as efficient as using a single calculated column, but if SUBSTITUTE will not work in your SharePoint environment, and you cannot use an event handler or workflow, it may offer a workable alternative.

I actually used a slightly different formula, but it was on a work machine to which I don't have access at the moment, so I just grabbed this formula from a similar S.O. question.  Any formula that will replace the first occurrence of a space with "%20" will work, the trick is to a) make sure the formula returns the original string unchanged if it does not have more spaces in it, and b) test, test, test. Create a view of your list that has the field you are trying to encode, plus the calculated fields, and see if you are getting the results you want.

OwnerDisplayName: curtisk

Body:
I was able to solve this issue for my circumstances by using a series of calculated columns.

In the first calculated column (C1) I entered a formula to remove the first space, something like this:

=IF(ISNUMBER(FIND(" ",[Title])),REPLACE([Title],FIND(" ",[Title]),1,"%20"),[Title])

In the second Calculated column (C2) I used:

=IF(ISNUMBER(FIND(" ",[C1])),REPLACE([C1],FIND(" ",[C1]),1,"%20"),[C1]).

In my case, I wanted to encode upto four spaces, so I used 3 calculated columns (C1, C2, C3) in the same fashion and got the desired result.

This is not as efficient as using a single calculated column, but if SUBSTITUTE will not work in your SharePoint environment, and you cannot use an event handler or workflow, it may offer a workable alternative.

I actually used a slightly different formula, but it was on a work machine to which I don't have access at the moment, so I just grabbed this formula from a similar S.O. question.  Any formula that will replace the first occurrence of a space with "%20" will work, the trick is to a) make sure the formula returns the original string unchanged if it does not have more spaces in it, and b) test, test, test. Create a view of your list that has the field you are trying to encode, plus the calculated fields, and see if you are getting the results you want.


问:
filtering a list for one absolute condition
I have a list of arrays called x

```<code>[array([ -1.5768,  10.843 ,   2.5462,  -2.9362,   0.    ]),
 array([-0.38214,  8.3909 ,  2.1624 , -3.7405 ,  0.     ]),
 array([-0.24811, -0.17797,  4.9068 ,  0.15429,  0.     ]),
 array([-0.96511,  9.4111 ,  1.7305 , -4.8629 ,  0.     ]),
 array([-1.6162 ,  0.80908,  8.1628 ,  0.60817,  0.     ])]
</code>```

I want to check if the first column of each row is greater than >0.
([ -1.5768, -0.38214,..... )]

If ALL the rows match this condition I want to return a "yes"
else I want to return a "no".

I'm able to return a "yes" or "no" for each row (so the output will be many yeses or noes  but I just want the output to be one yes or no.

```<code>for row in x:
    if row[0] > 0:
        print ('yes')
    else: print('no')
</code>```

Body:
I have a list of arrays called x

[array([ -1.5768,  10.843 ,   2.5462,  -2.9362,   0.    ]),
 array([-0.38214,  8.3909 ,  2.1624 , -3.7405 ,  0.     ]),
 array([-0.24811, -0.17797,  4.9068 ,  0.15429,  0.     ]),
 array([-0.96511,  9.4111 ,  1.7305 , -4.8629 ,  0.     ]),
 array([-1.6162 ,  0.80908,  8.1628 ,  0.60817,  0.     ])]

I want to check if the first column of each row is greater than >0.
([ -1.5768, -0.38214,..... )]

If ALL the rows match this condition I want to return a "yes"
else I want to return a "no".

I'm able to return a "yes" or "no" for each row (so the output will be many yeses or noes  but I just want the output to be one yes or no.

for row in x:
    if row[0] > 0:
        print ('yes')
    else: print('no')

Body:
In python you can use a generator expression within all() function:

In [7]: arr = [[ -1.5768,  10.843 ,   2.5462,  -2.9362,   0.    ],
   ...:  [-0.38214,  8.3909 ,  2.1624 , -3.7405 ,  0.     ],
   ...:  [-0.24811, -0.17797,  4.9068 ,  0.15429,  0.     ],
   ...:  [-0.96511,  9.4111 ,  1.7305 , -4.8629 ,  0.     ],
   ...:  [-1.6162 ,  0.80908,  8.1628 ,  0.60817,  0.     ]]

In [8]:

In [8]: all(i[0] > 0 for i in arr)
Out[8]: False

In [9]: all(i[0] < 0 for i in arr)
Out[9]: True

In numpy you can do it just with a simple comparison and array.all() attribute:

In [11]: import numpy as np

In [12]: arr = np.array(arr)

In [14]: (arr[:, 0] > 0).all()
Out[14]: False

In [15]: (arr[:, 0] < 0).all()
Out[15]: True


问:
HDFS Space Assignment (Size / Used / Available)
I read some references but I still cannot figure out clearly how the basic total size available to store files on the HDFS system is determined. </p>

<p>If I have a 1TB Disk with HDFS service running will the dfs part "grow" naturally as I add files to it, or is there a part of the disk that is assigned to the DFS by default ? </p>

答:
Yes, the disk usage for HDFS will grow as the files are added to it.
By default, Datanodes will try to use all of the space available in their storage directories dfs.datanode.data.dir.

Configured Capacity of a Datanode is

```<code>Total Storage Capacity - Reserved Storage
</code>```

Reserved Storage is 0B by default. If you wish to reserve some space on the storage for non-HDFS usage, add this property in the hdfs-site.xml of the datanodes

```<code><property>
  <name>dfs.datanode.du.reserved</name>
  <value>107374182400</value> <!-- 100 GB reserved -->
  <description>Reserved space in bytes per volume. Always leave this much space free for non dfs use</description>
</property>
</code>```

Body:
I read some references but I still cannot figure out clearly how the basic total size available to store files on the HDFS system is determined.

If I have a 1TB Disk with HDFS service running will the dfs part "grow" naturally as I add files to it, or is there a part of the disk that is assigned to the DFS by default ?

Body:
Yes, the disk usage for HDFS will grow as the files are added to it.
By default, Datanodes will try to use all of the space available in their storage directories dfs.datanode.data.dir.

Configured Capacity of a Datanode is

Total Storage Capacity - Reserved Storage

Reserved Storage is 0B by default. If you wish to reserve some space on the storage for non-HDFS usage, add this property in the hdfs-site.xml of the datanodes

<property>
  <name>dfs.datanode.du.reserved</name>
  <value>107374182400</value> <!-- 100 GB reserved -->
  <description>Reserved space in bytes per volume. Always leave this much space free for non dfs use</description>
</property>


答:
You could use the following:</p>

```<code>$(document).on('input', '#coin', function(){
    var coins = $("#coins").val();
    $("#reward").text(coins);
})
</code>```

Title: Get the value of a input number in jQuery

Body:
You could use the following:

$(document).on('input', '#coin', function(){
    var coins = $("#coins").val();
    $("#reward").text(coins);
})


问:
Adding CheckBox to DefaultTableModel
I have a DefaultTableModel which is populated with an Object[][] array.

Now I want to add a column with checkBoxes and perform operations accordingly.

When I add the checkbox into the Object[][] array and view it, I get text displayed

'javax.swing.JCheckBox[,0,0,0x0....', how do I get it to show a checkbox and add actions to it?

答:
You could use a custom table cell renderer.

See here

http://www.exampledepot.com/egs/javax.swing.table/CustRend.html

Title: Adding CheckBox to DefaultTableModel


问:
Need help in URL rewriting sub-domains
I recently registered a domain name kbcsurveyors.com. Then, I created two sub-domains, which created two new folders in the root folder.

My motive is that if I type kbcsurveyors.com/preinspection, it should point to preinspection.kbcsurveyors.com. Same for other sub domains.

In my .htaccess, which I placed inside root of mydomainname.com, I have written following lines:

```<code>RewriteEngine  On
RewriteBase /
RewriteRule ^preinspection/(.*)$          https://kbcsurveyors.com/$1 [L,NC,QSA]    # Handle requests for "Preinspection"
</code>```

But this file structure does not work. How do I write the .htaccess file to achieve what I want?

Regards

EDIT

I have asked a fresh question as this one has been messed up. Here is the link:How to rewrite rules for sub-domains

答:
If you want to redirect requests for a subdirectory to the appropriate domain, you can use the rules you have (or similar), but need to specify the scheme http:// and may use the R|redirect flag

```<code>RewriteRule ^sub-domain1 http://sub-domain1.mydomainname.com [R,NC,L]
</code>```

If you also want to forward the requested path, you must capture it and use in the target

```<code>RewriteRule ^sub-domain1/(.*)$ http://sub-domain1.mydomainname.com/$1 [R,NC,L]
</code>```

Title: Need help in URL rewriting sub-domains

Body:
I recently registered a domain name kbcsurveyors.com. Then, I created two sub-domains, which created two new folders in the root folder.

My motive is that if I type kbcsurveyors.com/preinspection, it should point to preinspection.kbcsurveyors.com. Same for other sub domains.

In my .htaccess, which I placed inside root of mydomainname.com, I have written following lines:

RewriteEngine  On
RewriteBase /
RewriteRule ^preinspection/(.*)$          https://kbcsurveyors.com/$1 [L,NC,QSA]    # Handle requests for "Preinspection"

But this file structure does not work. How do I write the .htaccess file to achieve what I want?

Regards

EDIT

I have asked a fresh question as this one has been messed up. Here is the link:How to rewrite rules for sub-domains

Body:
If you want to redirect requests for a subdirectory to the appropriate domain, you can use the rules you have (or similar), but need to specify the scheme http:// and may use the R|redirect flag

RewriteRule ^sub-domain1 http://sub-domain1.mydomainname.com [R,NC,L]

If you also want to forward the requested path, you must capture it and use in the target

RewriteRule ^sub-domain1/(.*)$ http://sub-domain1.mydomainname.com/$1 [R,NC,L]


问:
simulate key in games
I have a problem. I made some program with c# to help me in games. The logic is very simple. I used SendKey() method and low-level procs and they works correclly in software but doesn't work in games. any body has some idea?
Thank you all.</p>

答:
Avoiding Send keys is a pretty basic anti-cheat measure. And you did just explain why :D

Send Key only works if the other side is reacting to what the Windowing System is telling it. Games often use raw input, to have better reactiontimes and avoid everything Windows might do to the input. And this rather simply cheat/bot approach too.

Title: simulate key in games


问:
Having trouble putting 4 images in a 2 by 2 square to fit on half of the page in HTML/CSS
I've tried everything. Need Help PLEASE! Wanting to get the wire frame images in a 2 by 2 on the right side of the page. Being able to be responsive at the sametime.

any help will be appreciated soo much!

.flex-container {
    display: -webkit-flex;
 display: flex;
 -webkit-flex-direction: row;
 column-count:2;
 width: 100%;
 height: 25%;

}

.flex-item1 {

    font-family: sans-serif;
    width: 400px;
    height:auto;
    padding:50px;
    margin: 0,0,40px,0;
    text-align: justify;

}

.flex-item2 {

    font-family: sans-serif;
    width: 100px;
    height: 100px;
    align-items:center;
    display:flex;
    flex-wrap: wrap;

}

h1{

    text-align: center;
}

h2 {
    text-align: center;
    font-family: sans-serif;
    margin: 0;
    padding-left:200%;
    padding-top: 20px;
    width: 100%;
    height: auto;

}
.wireframe-container{

    position:fixed;
    width:100%;
    max-width: 100%;
    height: auto;
    margin: 0 auto;
    padding: 0px;
    text-align:center;

}

.wire{

    position:relative;
    display:inline-block;
    width:30%; max-width:180px;
    vertical-align: middle;
    margin:0 10px;
    padding-left:10px;

}

.desc {

    margin: 10px;
    padding-bottom:100px;

}

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" type="text/css" href="Assignment 1.css"/>

<title>Page Title</title>

</head>

<body>

  <img src="ass 1 background.png" class="responsive-image">

<div class="flex-container">

    <div class="flex-item1">
    Creating an app designed for mobile devices (smart phones and tablets). Able to use the smart phones camera or tablet to view the picture in real-time. Jager is centred around the old-style game of I Spy/Scavenger hunt played usually by kids. This focus would be part of the Mahuki Gamelab team. Creating games used for education in fun ways to help get children involved in the seasonal museum exhibitions.
        <br><br>
       <h1>Abstract</h1>
        <br><br>
    To create a game for mobile devices, tablets and smart phones. An app that uses augmented reality technology to involve users in the environment around them. The game is a scavenger hunt / I SPY type of game played using your smart phone or tablet’s built-in camera to view the world through. The app will generate an object to make the user search for from a list of pre-programmed items and paths. The app will give users a hint or a clue to the general area or direction of the object. A timer and a score will be used to create competition between children.  Students should be able to compare scores and time, from a type of leader board system. Animations and buttons will be projected onto user’s screens in real time off the objects. Users can gain achievements and badges for doing certain task also.
    </div>

<div class="flex-item2">

    <h2>Wireframes</h2>

     <div class="wireframes-container">

         <div class="wire">

           <img src="wire1.png"style="width:10em; height:15em;" />

           <div class="desc">phone</div>

            <img src="wire2.png"style="width:15em; height:15em;" />

            <div class="desc">tablet</div>

         <img src="wire4.png"style="width:10em; height:15em;" />

        <div class="desc">AR mode</div>

         <img src="wire3.png"style="width:15em; height:15em;" />
        <div class="desc">AR mode</div>

        </div>

        </div>

    </div>

    </div>

</body>

</html></code>```

答:
Can you use Bootstrap? It is very usefull to order elements in DOM.

Just divide the elements in columns, and if you need to put some elements in the same line use the class "row"

Body:
I've tried everything. Need Help PLEASE! Wanting to get the wire frame images in a 2 by 2 on the right side of the page. Being able to be responsive at the sametime.

any help will be appreciated soo much!

.flex-container {
    display: -webkit-flex;
 display: flex;
 -webkit-flex-direction: row;
 column-count:2;
 width: 100%;
 height: 25%;

}

.flex-item1 {

    font-family: sans-serif;
    width: 400px;
    height:auto;
    padding:50px;
    margin: 0,0,40px,0;
    text-align: justify;

}

.flex-item2 {

    font-family: sans-serif;
    width: 100px;
    height: 100px;
    align-items:center;
    display:flex;
    flex-wrap: wrap;

}

h1{

    text-align: center;
}

h2 {
    text-align: center;
    font-family: sans-serif;
    margin: 0;
    padding-left:200%;
    padding-top: 20px;
    width: 100%;
    height: auto;

}
.wireframe-container{

    position:fixed;
    width:100%;
    max-width: 100%;
    height: auto;
    margin: 0 auto;
    padding: 0px;
    text-align:center;

}

.wire{

    position:relative;
    display:inline-block;
    width:30%; max-width:180px;
    vertical-align: middle;
    margin:0 10px;
    padding-left:10px;

}

.desc {

    margin: 10px;
    padding-bottom:100px;

}

<!DOCTYPE html>

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

<title>Page Title</title>

    Creating an app designed for mobile devices (smart phones and tablets). Able to use the smart phones camera or tablet to view the picture in real-time. Jager is centred around the old-style game of I Spy/Scavenger hunt played usually by kids. This focus would be part of the Mahuki Gamelab team. Creating games used for education in fun ways to help get children involved in the seasonal museum exhibitions.

Abstract

    To create a game for mobile devices, tablets and smart phones. An app that uses augmented reality technology to involve users in the environment around them. The game is a scavenger hunt / I SPY type of game played using your smart phone or tablet’s built-in camera to view the world through. The app will generate an object to make the user search for from a list of pre-programmed items and paths. The app will give users a hint or a clue to the general area or direction of the object. A timer and a score will be used to create competition between children.  Students should be able to compare scores and time, from a type of leader board system. Animations and buttons will be projected onto user’s screens in real time off the objects. Users can gain achievements and badges for doing certain task also.

Wireframes

phone

tablet

AR mode

AR mode


问:
Proper way to create singleton ES6
What is the proper way to create singleton in JS since ES2015?
I know of many ways such as:

```<code>(() => {
  let instance;
  class Singleton{
    constructor(){
     instance = instance || this;
    }
  }
window.Singleton = Singleton; // or sth to export this class
})();
var a = new Singleton();
var b = new Singleton(); // a is the same as b
</code>```

But it doesn't seem like a good way to use "new" operator with a Singleton  class. So my question is whether there is a "proper" way to create a Singleton in ES6

答:
```<code>var a = (function () {

  // can put private vars/methods here.
  var a = 3;
  var b = 5;
  var sum = () => a+b;

  return {// your singleton object
           getSum: sum
           // ...
         };

}());
</code>```

Title: Proper way to create singleton ES6

Body:
What is the proper way to create singleton in JS since ES2015?
I know of many ways such as:

(() => {
  let instance;
  class Singleton{
    constructor(){
     instance = instance || this;
    }
  }
window.Singleton = Singleton; // or sth to export this class
})();
var a = new Singleton();
var b = new Singleton(); // a is the same as b

But it doesn't seem like a good way to use "new" operator with a Singleton  class. So my question is whether there is a "proper" way to create a Singleton in ES6


问:
get data from mqtt broker -6lbr
I followed this tutorial :

Running the CC26xx Contiki Examples

but instead of using the cc26xx-demo I used the cc26xx-web-demo and successfully manged to get everything up and running and I can access the 6lbr web page, when I access the sensorTag page I see a mqtt configuration page as shown:

and if I click index in the sensorTag page (pic above) I get to see the data:

the question is , how can I write a simple nodejs js file that uses the mqtt broker information to grab all the sensorTag sensors data and save it in an local object.

I tried to do run this example but no luck

```<code>var mqtt = require('mqtt')
client = mqtt.createClient(1883, '192.168.1.109');
client.subscribe(what do I write here);
client.on('message', function(topic, message) { console.log(message); });
</code>```

I don't know what I'm doing wrong

UPDATE:

mqtt configuration page :

javascript file :

and I run the js with node and listen on port 1883:

tcpdump seems to detect mqqt packets on 1883 port but I can't to seem to be able to console.log the sensor data when I run the js file with node ??

I went on the contiki wiki and came across this info
"You can also subscribe to topics and receive commands, but this will only work if you use "Org ID" != 'quickstart'. Thus, if you provide a different Org ID (do not forget the auth token!), the device will subscribe to:

iot-2/cmd/+/fmt/json"

does this mean that the topic to subscribe to is quickstart but even if that's so, I used '+/#'  which subrcibes to all topics and still got nothing printing on the console ?

答:
Hope this works for you:</p>

```<code>var mqtt = require('mqtt');
var fs = require('fs');

var options = { port: PORT, host: HOST };/*user, password and others authentication if there.*/
var client = mqtt.connect('HOST', options);
client.on('connect', function ()
{
    client.subscribe("topic, command or data");

    client.publish("topic, command or data", data, function () {
    });
});

client.on('error', function () { });
client.on('offline', function () { });
client.on('message', function (topic, message) {
    console.log(message.toString());
});
</code>```

Title: get data from mqtt broker -6lbr

Body:
I followed this tutorial :

Running the CC26xx Contiki Examples

but instead of using the cc26xx-demo I used the cc26xx-web-demo and successfully manged to get everything up and running and I can access the 6lbr web page, when I access the sensorTag page I see a mqtt configuration page as shown:

and if I click index in the sensorTag page (pic above) I get to see the data:

the question is , how can I write a simple nodejs js file that uses the mqtt broker information to grab all the sensorTag sensors data and save it in an local object.

I tried to do run this example but no luck

var mqtt = require('mqtt')
client = mqtt.createClient(1883, '192.168.1.109');
client.subscribe(what do I write here);
client.on('message', function(topic, message) { console.log(message); });

I don't know what I'm doing wrong

UPDATE:

mqtt configuration page :

javascript file :

and I run the js with node and listen on port 1883:

tcpdump seems to detect mqqt packets on 1883 port but I can't to seem to be able to console.log the sensor data when I run the js file with node ??

I went on the contiki wiki and came across this info
"You can also subscribe to topics and receive commands, but this will only work if you use "Org ID" != 'quickstart'. Thus, if you provide a different Org ID (do not forget the auth token!), the device will subscribe to:

iot-2/cmd/+/fmt/json"

does this mean that the topic to subscribe to is quickstart but even if that's so, I used '+/#'  which subrcibes to all topics and still got nothing printing on the console ?

Body:
Hope this works for you:

var mqtt = require('mqtt');
var fs = require('fs');

var options = { port: PORT, host: HOST };/*user, password and others authentication if there.*/
var client = mqtt.connect('HOST', options);
client.on('connect', function ()
{
    client.subscribe("topic, command or data");

    client.publish("topic, command or data", data, function () {
    });
});

client.on('error', function () { });
client.on('offline', function () { });
client.on('message', function (topic, message) {
    console.log(message.toString());
});


问:
phpMyAdmin - #1130 - Host 'SERVER' is not allowed to connect to this MySQL server
I run WAMPServer on a Windows server 2012 r2, I want to run a database on it using phpMyAdmin, everything is working but when I try to login from the Windows server I get this error:

is the error that I see.

I get the same error when I try to login from a other computer.

There are allot of people having this problem so I searched all over the internet but all I can find are query's that can fix this problem.. But I can't login so I can't do anything with those query's.

I hope someone can fix this problem for me, I would really appreciate it!

The two errors I get on the picture:

```<code>#1130 - Host 'SERVER' is not allowed to connect to this MySQL server
mysqli_real_connect(): (HY000/1130): Host 'SERVER' is not allowed to connect to this MySQL server
</code>```

答:
WAMPServer is configired to be a single user developer tool. Therefore the security is configured to protect the beginner.

Therefore:

The phpMyAdmin alias is configured to only accept connections from the PC running WAMPServer.

As in any sensibe default config of MYSQL the root and any other
pre-configured MYSQL user accounts are also configured to only be
accessible from the PC running MYSQL.

So to allow you to run phpMyAdmin from another host (PC) you need to amend the Alias configuration for phpMyAdmin.

So edit \wamp\alias\phpmyadmin.conf (NOTE your version may be different) and amend the Require setting to allow access from specific, or all the Ip Addresses in yor subnet.

```<code>Alias /phpmyadmin "D:/wamp/apps/phpmyadmin4.7.0/"

<Directory "D:/wamp/apps/phpmyadmin4.7.0/">
    Options Indexes FollowSymLinks MultiViews
  AllowOverride all
  <ifDefine APACHE24>
        Require local

        ## Add access allowed from your subnet
        Require ip 192.168.1

    </ifDefine>
    <ifDefine !APACHE24>
        Order Deny,Allow
    Deny from all
    Allow from localhost ::1 127.0.0.1
    </ifDefine>

# To import big file you can increase values
  php_admin_value upload_max_filesize 128M
  php_admin_value post_max_size 128M
  php_admin_value max_execution_time 360
  php_admin_value max_input_time 360
</Directory>
</code>```

Now you should be able to run phpMyAdmin from another PC

You must now create a user within MYSQL that is allowed to access the database(s) that that user requires access to from whichever remote IP Addresses that user is allowed to access the database from. You should go to the Server and using phpMyAdmin, login as root from there, remember root can only login from the PC running MYSQL.

I suggest you do not amend the access rights of root but instead create a new user and give whatever access that user is allowed to which ever databases that user is allowed to access.

For example,

```<code>CREATE USER 'raul'@'192.168.1.%' IDENTIFIED BY 'mypass' PASSWORD EXPIRE NEVER;
</code>```

Will allow you to login from any of the ip addresses in the 192.168.1 subnet. Amend this to fit your actual situation.

And then allow that user access to the databases he will require.

```<code>GRANT ALL ON test.* TO 'raul'@'localhost';
</code>```

This is all possible using point and click via phpMyAdmin

Body:
I run WAMPServer on a Windows server 2012 r2, I want to run a database on it using phpMyAdmin, everything is working but when I try to login from the Windows server I get this error:

is the error that I see.

I get the same error when I try to login from a other computer.

There are allot of people having this problem so I searched all over the internet but all I can find are query's that can fix this problem.. But I can't login so I can't do anything with those query's.

I hope someone can fix this problem for me, I would really appreciate it!

The two errors I get on the picture:

#1130 - Host 'SERVER' is not allowed to connect to this MySQL server
mysqli_real_connect(): (HY000/1130): Host 'SERVER' is not allowed to connect to this MySQL server

Body:
WAMPServer is configired to be a single user developer tool. Therefore the security is configured to protect the beginner.

Therefore:

The phpMyAdmin alias is configured to only accept connections from the PC running WAMPServer.

As in any sensibe default config of MYSQL the root and any other
pre-configured MYSQL user accounts are also configured to only be
accessible from the PC running MYSQL.

So to allow you to run phpMyAdmin from another host (PC) you need to amend the Alias configuration for phpMyAdmin.

So edit \wamp\alias\phpmyadmin.conf (NOTE your version may be different) and amend the Require setting to allow access from specific, or all the Ip Addresses in yor subnet.

Alias /phpmyadmin "D:/wamp/apps/phpmyadmin4.7.0/"

<Directory "D:/wamp/apps/phpmyadmin4.7.0/">
    Options Indexes FollowSymLinks MultiViews
  AllowOverride all
  <ifDefine APACHE24>
        Require local

        ## Add access allowed from your subnet
        Require ip 192.168.1

    </ifDefine>
    <ifDefine !APACHE24>
        Order Deny,Allow
    Deny from all
    Allow from localhost ::1 127.0.0.1
    </ifDefine>

# To import big file you can increase values
  php_admin_value upload_max_filesize 128M
  php_admin_value post_max_size 128M
  php_admin_value max_execution_time 360
  php_admin_value max_input_time 360
</Directory>

Now you should be able to run phpMyAdmin from another PC

You must now create a user within MYSQL that is allowed to access the database(s) that that user requires access to from whichever remote IP Addresses that user is allowed to access the database from. You should go to the Server and using phpMyAdmin, login as root from there, remember root can only login from the PC running MYSQL.

I suggest you do not amend the access rights of root but instead create a new user and give whatever access that user is allowed to which ever databases that user is allowed to access.

For example,

CREATE USER 'raul'@'192.168.1.%' IDENTIFIED BY 'mypass' PASSWORD EXPIRE NEVER;

Will allow you to login from any of the ip addresses in the 192.168.1 subnet. Amend this to fit your actual situation.

And then allow that user access to the databases he will require.

GRANT ALL ON test.* TO 'raul'@'localhost';

This is all possible using point and click via phpMyAdmin