问:
The server responded with a status of 500 AJAX Post
I have this javascript function which should redirect me to

http://localhost:8888/ID OF A PRODUCT/add-to-cart".

But instead I got this:

http://localhost:8888/undefined/add-to-cart".

```<code>$('.add-to-cart').on('click', function () {
        var productId = $(this).find('.indexImg').attr('id');

        $.ajax(productId+"/add-to-cart",
        {

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

image}}" id="{{$product->id}}">

Can someone help me to get ID of a product ?

HTML:

```<code> @foreach($products as $product)
  <div class="col-md-3">
        <div class="box-product">
            <div class="img-wrapper item">
                <a href="/product/{{$product->id}}/{{$product->slug}}">
                    <a class="thumbnail" href="/product/{{$product->id}}/{{$product->slug}}" style="margin-bottom: 0px; border: none;">
                    <img class="indexImg" src="{{$product->image}}" id="{{$product->id}}">
                    </a>
                </a>
            <div class="tags">
            @if($product->discount > 0)
                <span class="label-tags"><span class="label label-danger">Išpardavimas</span></span>
            @endif
                <span class="label-tags"><span class="label label-info">Nauja</span></span>
            </div>
            <div class="option">
                <i class="fa fa-shopping-cart add-to-cart" aria-hidden="true" style="color: white"></i>
            </div>
        </div>
</code>```

答:
.find is try to find inside current element u need to go up then find indexImg</p>

```<code>    $('.add-to-cart').on('click', function () {
       var productId = $(this).parents('.box-product').find('.indexImg').attr('id');

       $.ajax(productId+"/add-to-cart",
       {

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

Body:
I have this javascript function which should redirect me to

http://localhost:8888/ID OF A PRODUCT/add-to-cart".

But instead I got this:

http://localhost:8888/undefined/add-to-cart".

$('.add-to-cart').on('click', function () {
        var productId = $(this).find('.indexImg').attr('id');

        $.ajax(productId+"/add-to-cart",
        {

        });
    });

image}}" id="{{$product->id}}">

Can someone help me to get ID of a product ?

HTML:

 @foreach($products as $product)

                id}}/{{$product->slug}}">
                    id}}/{{$product->slug}}" style="margin-bottom: 0px; border: none;">
                    image}}" id="{{$product->id}}">

            @if($product->discount > 0)
                Išpardavimas
            @endif
                Nauja

Body:
.find is try to find inside current element u need to go up then find indexImg

    $('.add-to-cart').on('click', function () {
       var productId = $(this).parents('.box-product').find('.indexImg').attr('id');

       $.ajax(productId+"/add-to-cart",
       {

       });
    });


来源: stackexchange

问:
bluetooth error(11,resource are temporarily unavailable)
when I running program on raspberry pi to send data to Arduino it work properly but stopped sending data suddenly and return back an error

error message "

```<code>socket.send('0')
bluetooth error(11,resource are temporarily unavailable)
</code>```

this program aims to send 0 to Arduino if Arduino receives 0 buzzers will not alarm else it alarm ..for 2 minutes all things going well but suddenly buzzer alarm but the 2 Bluetooth in 'pi' and 'Arduino' still connected not disconnected.

I search for the error and find it is because the buffer in pi is full and it turns into the block but I can't solve the problem anyone can help me?
thanks.

here is the code

```<code>import bluetooth
import time
bd_addr = "98:D3:31:FB:19:AF"
port = 1
sock = bluetooth.BluetoothSocket (bluetooth.RFCOMM)
sock.connect((bd_addr,port))
while 1:
        sock.send("0")
time.sleep(2)
sock.close()
</code>```

arduino code

```<code>#include <SoftwareSerial.h>
SoftwareSerial bt (5,6);
int LEDPin = 13; //LED PIN on Arduino
int btdata; // the data given from the computer
void setup()  {   bt.begin(9600);   pinMode (LEDPin, OUTPUT); }
void loop() {
    if (bt.available()) {
        btdata = bt.read();
        if (btdata == '1') {
            //if 1
            digitalWrite (LEDPin,HIGH);
            bt.println ("LED OFF!");
         }
         else {
             //if 0
             digitalWrite (LEDPin,LOW);
             bt.println ("LED ON!");
         }
    } else {   digitalWrite(LEDPin, HIGH);
            delay (100); //prepare for data
    }
}
</code>```

答:
I think you are flooding it, as you have no delay in your while. You are generating data to send faster than it can actually send them, which eventually fills up the buffer. Simply add a time.sleep(0.5) in your while and decrease the value 0.5 by testing which one works best without filling up the buffer.

This is my try at making your code more resilient :

```<code>import bluetooth
import time
bd_addr = "98:D3:31:FB:19:AF"
port = 1
sock = bluetooth.BluetoothSocket (bluetooth.RFCOMM)
sock.connect((bd_addr,port))
while 1:
    try:
        sock.send("0")
        time.sleep(0.1)
        sock.recv(1024)
    except bluetooth.btcommon.BluetoothError as error:
        print "Caught BluetoothError: ", error
        time.sleep(5)
        sock.connect((bd_addr,port))
time.sleep(2)
sock.close()
</code>```

What this does is :

Wait a little before sending a new packet : Prevent your computer from generating data faster than it can send it, which eventually fills the buffer

Read the incomming data, thus consuming it from the inbound buffer : the arduino actually answers your requests, and that fills up the inbound buffer. If you don't empty it once in a while, it will overflow and your socket will be rendered unusable

Monitor for connection errors, and tries to recover from them by closing and reopening the socket

I would also modify the arduino code like this :

```<code>#include <SoftwareSerial.h>
SoftwareSerial bt (5,6);
int LEDPin = 13; //LED PIN on Arduino
int btdata; // the data given from the computer
void setup()  {   bt.begin(9600);   pinMode (LEDPin, OUTPUT); }
void loop() {
    if (bt.available()) {
        btdata = bt.read();
        if (btdata == '1') {
            //if 1
            digitalWrite (LEDPin,HIGH);
            bt.println ("LED OFF!");
         }
         else {
             //if 0
             digitalWrite (LEDPin,LOW);
             bt.println ("LED ON!");
         }
         delay(1000);
    } else {   digitalWrite(LEDPin, HIGH);
            delay (10); //prepare for data
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
when I running program on raspberry pi to send data to Arduino it work properly but stopped sending data suddenly and return back an error

error message "

socket.send('0')
bluetooth error(11,resource are temporarily unavailable)

this program aims to send 0 to Arduino if Arduino receives 0 buzzers will not alarm else it alarm ..for 2 minutes all things going well but suddenly buzzer alarm but the 2 Bluetooth in 'pi' and 'Arduino' still connected not disconnected.

I search for the error and find it is because the buffer in pi is full and it turns into the block but I can't solve the problem anyone can help me?
thanks.

here is the code

import bluetooth
import time
bd_addr = "98:D3:31:FB:19:AF"
port = 1
sock = bluetooth.BluetoothSocket (bluetooth.RFCOMM)
sock.connect((bd_addr,port))
while 1:
        sock.send("0")
time.sleep(2)
sock.close()

arduino code

#include <SoftwareSerial.h>
SoftwareSerial bt (5,6);
int LEDPin = 13; //LED PIN on Arduino
int btdata; // the data given from the computer
void setup()  {   bt.begin(9600);   pinMode (LEDPin, OUTPUT); }
void loop() {
    if (bt.available()) {
        btdata = bt.read();
        if (btdata == '1') {
            //if 1
            digitalWrite (LEDPin,HIGH);
            bt.println ("LED OFF!");
         }
         else {
             //if 0
             digitalWrite (LEDPin,LOW);
             bt.println ("LED ON!");
         }
    } else {   digitalWrite(LEDPin, HIGH);
            delay (100); //prepare for data
    }
}

Body:
I think you are flooding it, as you have no delay in your while. You are generating data to send faster than it can actually send them, which eventually fills up the buffer. Simply add a time.sleep(0.5) in your while and decrease the value 0.5 by testing which one works best without filling up the buffer.

This is my try at making your code more resilient :

import bluetooth
import time
bd_addr = "98:D3:31:FB:19:AF"
port = 1
sock = bluetooth.BluetoothSocket (bluetooth.RFCOMM)
sock.connect((bd_addr,port))
while 1:
    try:
        sock.send("0")
        time.sleep(0.1)
        sock.recv(1024)
    except bluetooth.btcommon.BluetoothError as error:
        print "Caught BluetoothError: ", error
        time.sleep(5)
        sock.connect((bd_addr,port))
time.sleep(2)
sock.close()

What this does is :

Wait a little before sending a new packet : Prevent your computer from generating data faster than it can send it, which eventually fills the buffer

Read the incomming data, thus consuming it from the inbound buffer : the arduino actually answers your requests, and that fills up the inbound buffer. If you don't empty it once in a while, it will overflow and your socket will be rendered unusable

Monitor for connection errors, and tries to recover from them by closing and reopening the socket

I would also modify the arduino code like this :

#include <SoftwareSerial.h>
SoftwareSerial bt (5,6);
int LEDPin = 13; //LED PIN on Arduino
int btdata; // the data given from the computer
void setup()  {   bt.begin(9600);   pinMode (LEDPin, OUTPUT); }
void loop() {
    if (bt.available()) {
        btdata = bt.read();
        if (btdata == '1') {
            //if 1
            digitalWrite (LEDPin,HIGH);
            bt.println ("LED OFF!");
         }
         else {
             //if 0
             digitalWrite (LEDPin,LOW);
             bt.println ("LED ON!");
         }
         delay(1000);
    } else {   digitalWrite(LEDPin, HIGH);
            delay (10); //prepare for data
    }
}


问:
Cast List<int> to List<string> in .NET 2.0
Can you cast a List<int> to List<string> somehow?

I know I could loop through and .ToString() the thing, but a cast would be awesome.

I'm in C# 2.0 (so no LINQ).

答:
Is C# 2.0 able to do List<T>.Convert? If so, I think your best guess would be to use that with a delegate:

```<code>List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Convert(delegate (int i) { return i.ToString(); });
</code>```

Something along those lines.

Glenn's answer is probably the correct code ;-)

OwnerDisplayName: lomaxx

Body:
Is C# 2.0 able to do List<T>.Convert? If so, I think your best guess would be to use that with a delegate:

List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Convert(delegate (int i) { return i.ToString(); });

Something along those lines.

Glenn's answer is probably the correct code ;-)

OwnerDisplayName: Erik van Brakel

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Erik van Brakel


问:
How do I delete all the rows of a table with a recursive structure (MySQL)?
I have a table in my DB, in which every row has a parent id which is the id of another row in the table (the table represents a tree-like structure). I would like to empty the table. But when I perform

```<code>DELETE FROM table_name WHERE true;
</code>```

I get an error (foreign key constraint). How do I empty the table anyway?

Clarification: I want to delete the whole table's contents, not the tables themselves.

答:
This should do the trick:</p>

```<code>TRUNCATE table_name;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a table in my DB, in which every row has a parent id which is the id of another row in the table (the table represents a tree-like structure). I would like to empty the table. But when I perform

DELETE FROM table_name WHERE true;

I get an error (foreign key constraint). How do I empty the table anyway?

Clarification: I want to delete the whole table's contents, not the tables themselves.

Body:
This should do the trick:

TRUNCATE table_name;


问:
angular comments attributes inside template
Can I comment attribute inside html markup?

I need to do something like that:

```<code><hero-detail
     <!--comments goes here-->
     hero="currentHero">
</hero-detail>
</code>```

But this does not work. How can it be done?

答:
This is invalid HTML. Angular only works with valid HTML.<br>
HTML comments are only allowed outside or inside elements, but not of the element itself. </p>

Body:
Can I comment attribute inside html markup?

I need to do something like that:

<hero-detail

     hero="currentHero">
</hero-detail>

But this does not work. How can it be done?

Body:
This is invalid HTML. Angular only works with valid HTML.

HTML comments are only allowed outside or inside elements, but not of the element itself.


问:
How can I return a class from an async method
Is it possible to return a class from an async method? I get an error message that there is an GetAwaiter missing? Don't know what this means.

```<code>StatusButton.Click += async (sender, e) =>
        {
            ...
            byte[] TheResponse = new byte[1024];
            await TheResponse = client.Read(); // <---- GetAwaiter ?
        };

public class Client
{
    ...

    public async Task<byte[]> Read()
    {
        var ns = tcpClient.GetStream();
        byte[] Result = new byte[1024];
        await ns.ReadAsync(Result, 0, Result.Length);
        return Result;
    }
}
</code>```

答:
Many thanks, now it runs. Had to made some changes. Here they are: Maybe someone can use it.</p>

```<code>    protected override void OnCreate(Bundle bundle)
    {
        ...

        OpenButton.Click += delegate
        {
            SendCommand('O');
            ThreadPool.QueueUserWorkItem(o => ShutDown());
        };

        ...
    }

    async void SendCommand(Char Command)
    {
        ... //Command not used in this part of code

        const string sn = "SEND_NONCE";

        byte[] data = System.Text.Encoding.ASCII.GetBytes(sn);

        Client client = new Client();

        TcpClientPacket TheData = new TcpClientPacket(sn.Length);

        TheData.Buffer = data;
        TheData.Length = sn.Length;

        bool IsConnected = await client.InitializeAsync(HostUrl, Port);

        ...

        await client.WriteAsync(TheData);

        TcpClientPacket TheResponse = await client.ReadAsync(16);

        ...

    }

    public class Client
    {
        private TcpClient tcpClient;

        public async Task <bool> InitializeAsync(string ip, int port)
        {
            tcpClient = new TcpClient();
            try
            {
                await tcpClient.ConnectAsync(ip, port);
            }
            catch
            {
                return false;
            }
            return tcpClient.Connected;
        }

        public void Deactivate()
        {
            tcpClient.Close();
        }

        public async Task WriteAsync(TcpClientPacket Data)
        {
            var ns = tcpClient.GetStream();
            await ns.WriteAsync(Data.Buffer, 0, Data.Length);
        }

        public async Task<TcpClientPacket> ReadAsync(int ExpectedLength)
        {
            var ns = tcpClient.GetStream();
            TcpClientPacket Result = new TcpClientPacket(ExpectedLength);
            Result.Length = await ns.ReadAsync(Result.Buffer, 0, ExpectedLength);
            return Result;
        }

    }

    public class TcpClientPacket
    {
        public byte[] Buffer;
        public int Length;

        public TcpClientPacket(int Size)
        {
            Buffer = new byte[Size];
            Length = 0;
        }
    }
</code>```

Body:
Is it possible to return a class from an async method? I get an error message that there is an GetAwaiter missing? Don't know what this means.

StatusButton.Click += async (sender, e) =>
        {
            ...
            byte[] TheResponse = new byte[1024];
            await TheResponse = client.Read(); // <---- GetAwaiter ?
        };

public class Client
{
    ...

    public async Task<byte[]> Read()
    {
        var ns = tcpClient.GetStream();
        byte[] Result = new byte[1024];
        await ns.ReadAsync(Result, 0, Result.Length);
        return Result;
    }
}

Body:
Many thanks, now it runs. Had to made some changes. Here they are: Maybe someone can use it.

    protected override void OnCreate(Bundle bundle)
    {
        ...

        OpenButton.Click += delegate
        {
            SendCommand('O');
            ThreadPool.QueueUserWorkItem(o => ShutDown());
        };

        ...
    }

    async void SendCommand(Char Command)
    {
        ... //Command not used in this part of code

        const string sn = "SEND_NONCE";

        byte[] data = System.Text.Encoding.ASCII.GetBytes(sn);

        Client client = new Client();

        TcpClientPacket TheData = new TcpClientPacket(sn.Length);

        TheData.Buffer = data;
        TheData.Length = sn.Length;

        bool IsConnected = await client.InitializeAsync(HostUrl, Port);

        ...

        await client.WriteAsync(TheData);

        TcpClientPacket TheResponse = await client.ReadAsync(16);

        ...

    }

    public class Client
    {
        private TcpClient tcpClient;

        public async Task <bool> InitializeAsync(string ip, int port)
        {
            tcpClient = new TcpClient();
            try
            {
                await tcpClient.ConnectAsync(ip, port);
            }
            catch
            {
                return false;
            }
            return tcpClient.Connected;
        }

        public void Deactivate()
        {
            tcpClient.Close();
        }

        public async Task WriteAsync(TcpClientPacket Data)
        {
            var ns = tcpClient.GetStream();
            await ns.WriteAsync(Data.Buffer, 0, Data.Length);
        }

        public async Task<TcpClientPacket> ReadAsync(int ExpectedLength)
        {
            var ns = tcpClient.GetStream();
            TcpClientPacket Result = new TcpClientPacket(ExpectedLength);
            Result.Length = await ns.ReadAsync(Result.Buffer, 0, ExpectedLength);
            return Result;
        }

    }

    public class TcpClientPacket
    {
        public byte[] Buffer;
        public int Length;

        public TcpClientPacket(int Size)
        {
            Buffer = new byte[Size];
            Length = 0;
        }
    }


问:
How to easily insert values to tables which have different amount of attributes?
I am making a 3-layered architecture database application with C# Windows Form application and an Excel file. Problem is, I have three tables and they have different amount of attributes. I want to user chooses which table he/she want to insert and update.

The basic solution is making three different forms to add values to each table, because for different amount of inputs I need different amount of textboxes. But it's too troublesome and amateurish, I think.

Can you give me some advise to do this easily?

答:
Something that you could try is using a DataGridView.

A drop-down could be used to determine what table the user would like to modify. Based on this input, query your database and bind the results with the DataGridView.

A reference you could start with "https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/data-entry-in-the-windows-forms-datagridview-control"


问:
Pyinstaller --onefile ImportError: No module named 'win32api'
Problem statement:

I can't seem to run

```<code>'PyInstaller --onefile myfile.py'
</code>```

on a file containing

```<code>import wmi
</code>```

It cannot find win32api. I get a popup warning saying python has stopped etc. My console says "ImportError: No module named 'win32api'". I can run 'import win32api', 'import win32com', and 'import WMI' in python directly in the same environment without issue. I fundamentally don't understand what is wrong here.

Error message:

```<code>3469 INFO: Loading module hook "hook-pywintypes.py"...
Fatal Python error: Py_Initialize: can't initialize sys standard streams
ImportError: No module named 'win32api'
</code>```

I have tried:

PyInstaller - ImportError: No module named win32api - 'import os' works fine for PyInstaller and runs fine in python.

No module named 'win32api' - Not very helpful

How to install pywin32 module in windows 7 - This is where I got the SF link (python3.5 amd64 pywin32 version)

ImportError: no module named win32api -
 I thought it might be a path thing, but my installation appears to be in the correct place: "C:\Users\myuser\AppData\Local\Continuum\Anaconda3\pkgs\pywin32-220-py35_2\Lib\site-packages\win32"

I can run 'PyInstaller --onefile myscript.py' on other files, and have without issue as long as they don't use the wmi module.

I looked at the win32com _init__.py line 5 where it's messing up and it's just an import statement for win32api.

System:

Windows 7 x64, Python 3.5.3 64bit, Anaconda 4.3.14 64bit, using pyinstaller 3.2.3 (recommended by this thread), with pywin32 220 (with sourceforge download [I know, I tried pip, conda, and easy_install]) and I'm running it in cmder as an admin.

答: In my case, I couldn't use the module in the python shell, even if original one could. When I execute python shell as an administrator option, it was solved. Try it with administrator execution. I used python version 3.5.2 with windows x64bits.</p>

Body:
Problem statement:

I can't seem to run

'PyInstaller --onefile myfile.py'

on a file containing

import wmi

It cannot find win32api. I get a popup warning saying python has stopped etc. My console says "ImportError: No module named 'win32api'". I can run 'import win32api', 'import win32com', and 'import WMI' in python directly in the same environment without issue. I fundamentally don't understand what is wrong here.

Error message:

3469 INFO: Loading module hook "hook-pywintypes.py"...
Fatal Python error: Py_Initialize: can't initialize sys standard streams
ImportError: No module named 'win32api'

I have tried:

PyInstaller - ImportError: No module named win32api - 'import os' works fine for PyInstaller and runs fine in python.

No module named 'win32api' - Not very helpful

How to install pywin32 module in windows 7 - This is where I got the SF link (python3.5 amd64 pywin32 version)

ImportError: no module named win32api -
 I thought it might be a path thing, but my installation appears to be in the correct place: "C:\Users\myuser\AppData\Local\Continuum\Anaconda3\pkgs\pywin32-220-py35_2\Lib\site-packages\win32"

I can run 'PyInstaller --onefile myscript.py' on other files, and have without issue as long as they don't use the wmi module.

I looked at the win32com _init__.py line 5 where it's messing up and it's just an import statement for win32api.

System:

Windows 7 x64, Python 3.5.3 64bit, Anaconda 4.3.14 64bit, using pyinstaller 3.2.3 (recommended by this thread), with pywin32 220 (with sourceforge download [I know, I tried pip, conda, and easy_install]) and I'm running it in cmder as an admin.


问:
python3 exchangelib credentials
Im trying to log into an exchangeserver with the exchangelib.
When I try to run the script it gives me an error:
 File "/usr/local/lib/python3.5/dist-packages/exchangelib/protocol.py", line 61, in init
    assert isinstance(credentials, Credentials)
AssertionError

From what I can understand it says my credential variabel is not of the right type. I have tried both with and without autodiscover enabled. I get the same error.
Here is the relevant code.

```<code>credents = Credentials(username='domain\\aaa.fh', password= 'password'),

  config = Configuration(server='domain.aaa.no', credentials= credents)

  account = Account(
          primary_smtp_address='fh@domain.no',
          config=config,
          autodiscover=True,
          access_type=DELEGATE)
</code>```

答:
Try this way:</p>

```<code>config = Configuration(
                    server='mail.example.com',
                    credentials=Credentials(username='Domain\username', password='password'),
                    auth_type=NTLM
                    )
account = Account(primary_smtp_address='Emailaddress@domain.com', config=config,
                           access_type=DELEGATE)
</code>```

Title: python3 exchangelib credentials

Body:
Im trying to log into an exchangeserver with the exchangelib.
When I try to run the script it gives me an error:
 File "/usr/local/lib/python3.5/dist-packages/exchangelib/protocol.py", line 61, in init
    assert isinstance(credentials, Credentials)
AssertionError

From what I can understand it says my credential variabel is not of the right type. I have tried both with and without autodiscover enabled. I get the same error.
Here is the relevant code.

credents = Credentials(username='domain\\aaa.fh', password= 'password'),

  config = Configuration(server='domain.aaa.no', credentials= credents)

  account = Account(
          primary_smtp_address='fh@domain.no',
          config=config,
          autodiscover=True,
          access_type=DELEGATE)

Body:
Try this way:

config = Configuration(
                    server='mail.example.com',
                    credentials=Credentials(username='Domain\username', password='password'),
                    auth_type=NTLM
                    )
account = Account(primary_smtp_address='Emailaddress@domain.com', config=config,
                           access_type=DELEGATE)


问:
angular2 use external javascript file
I want to place my online game that I made that with pure javascript and html5 canvas in my angular2 project.

I wrote my scripts in external file and add the script tag in the head on angular index.html and in my component's typescript I declared my onload function like this:

```<code>declare var startGame1: any;
</code>```

the startGame1 is a method that make the canvas ready for my game.

the problem is when I call startGame1() in AfterViewInit I get errors like this:

```<code>Unhandled Promise rejection: Error in :0:0 caused by: Cannot read property 'clearRect' of undefined ; Zone: angular ; Task: Promise.then ; Value:
ViewWrappedError {__zone_symbol__error: Error: Error in :0:0 caused by: Cannot read property 'clearRect' of undefined at ViewWrappedErro……} Error: Error in :0:0 caused by: Cannot read property 'clearRect' of undefined
</code>```

答:
I suggest you to load the external js using the .angular-cli.json.

In the apps -> scripts and insert the relative path of your external .js in the array.

And inside the app folder, create a .d.ts file to insert your declare var startGame1: any;. For example:

myGame.d.ts

```<code>declare var startGame1: any;
</code>```

The myGame.d.ts will be loaded automatically by the webpack and then define your startGame1 for your app.

Title: angular2 use external javascript file

Body:
I want to place my online game that I made that with pure javascript and html5 canvas in my angular2 project.

I wrote my scripts in external file and add the script tag in the head on angular index.html and in my component's typescript I declared my onload function like this:

declare var startGame1: any;

the startGame1 is a method that make the canvas ready for my game.

the problem is when I call startGame1() in AfterViewInit I get errors like this:

Unhandled Promise rejection: Error in :0:0 caused by: Cannot read property 'clearRect' of undefined ; Zone: angular ; Task: Promise.then ; Value:
ViewWrappedError {__zone_symbol__error: Error: Error in :0:0 caused by: Cannot read property 'clearRect' of undefined at ViewWrappedErro……} Error: Error in :0:0 caused by: Cannot read property 'clearRect' of undefined

Body:
I suggest you to load the external js using the .angular-cli.json.

In the apps -> scripts and insert the relative path of your external .js in the array.

And inside the app folder, create a .d.ts file to insert your declare var startGame1: any;. For example:

myGame.d.ts

declare var startGame1: any;

The myGame.d.ts will be loaded automatically by the webpack and then define your startGame1 for your app.


答:
When you create your foreign key relationships, you need to specify on delete cascade.

EDIT: There's a pretty good reference right here: http://en.wikipedia.org/wiki/Foreign_key

Title: How do I delete all the rows of a table with a recursive structure (MySQL)?


问:
Copying formatted Word text into Access
I am trying to adapt VBA from this page copy formatted text into access using vba so that it loops through all files selected or all files in a specific folder. Is this possible? Thanks.</p>

答:
You can do one of two things: don't split the filepicker function and the import function, or return a collection or an array from your filepicker function.

I'm going to choose the latter for educational value:

Pick the files

```<code>Public Function FilesToOpen() As Collection

    ' This function will essentially allow you to browse to MS-Word document
    ' and then store the path of that file for use in the GetWordContent function

    Dim fDialog As Object 'Office.FileDialog
    Dim varFile As Variant

    Set fDialog = Application.FileDialog(3)
    Set FilesToOpen = New Collection
    With fDialog
        .AllowMultiSelect = True
        .Title = "Select Word document to import"
        .Filters.Clear
        .Filters.Add "Word files", "*.doc?"

        If _
            .Show = True _
        Then
            For Each varFile In .SelectedItems
                FilesToOpen.Add varFile
            Next
        End If
    End With
End Function
</code>```

And open them

```<code>Private Sub cmdGetWordData_Click()

    ' This subroutine runs on your command button; it will call both the FileToOpen function and GetWordContent subroutine
    ' to retrieve the text contents of your chosen MS-Word Document.
    ' It will then store both the path the text contents of of your chosen MS-Word Document in 2 fields in a table in Access.

    ' NOTE: this code assumes that your Access database has:
    ' - a table called tblWordDump
    ' - a memo text field in this table called WordDocDataSrc to store the path of MS-Word file imported
    ' - a memo text field in this table called WordDocData with the TextFormat property set to "Rich Text",
    '   which will store the text and text formating of the MS-Word file imported

    Dim collFiles As Collection
    Dim strWordContent As Variant

    ' Select files via File Dialogue

    Set collFiles = FilesToOpen
    Dim oneFile As Variant

    ' Conditionals when a file was or wasn't selected

    If _
        collFiles.Count <> 0 _
    Then
        For Each oneFile In collFiles

            DoCmd.GoToRecord , , acNewRec

            GetWordContent CStr(oneFile)
        Next oneFile

        MsgBox "Import Successful", vbInformation Or vbOKOnly

    Else

        MsgBox "No File Selected", vbExclamation Or vbOKOnly

    End If

End Sub
</code>```

Note that I attempted to change as little as possible and have not done anything with the GetWordContent function.

Title: Copying formatted Word text into Access

Body:
You can do one of two things: don't split the filepicker function and the import function, or return a collection or an array from your filepicker function.

I'm going to choose the latter for educational value:

Pick the files

Public Function FilesToOpen() As Collection

    ' This function will essentially allow you to browse to MS-Word document
    ' and then store the path of that file for use in the GetWordContent function

    Dim fDialog As Object 'Office.FileDialog
    Dim varFile As Variant

    Set fDialog = Application.FileDialog(3)
    Set FilesToOpen = New Collection
    With fDialog
        .AllowMultiSelect = True
        .Title = "Select Word document to import"
        .Filters.Clear
        .Filters.Add "Word files", "*.doc?"

        If _
            .Show = True _
        Then
            For Each varFile In .SelectedItems
                FilesToOpen.Add varFile
            Next
        End If
    End With
End Function

And open them

Private Sub cmdGetWordData_Click()

    ' This subroutine runs on your command button; it will call both the FileToOpen function and GetWordContent subroutine
    ' to retrieve the text contents of your chosen MS-Word Document.
    ' It will then store both the path the text contents of of your chosen MS-Word Document in 2 fields in a table in Access.

    ' NOTE: this code assumes that your Access database has:
    ' - a table called tblWordDump
    ' - a memo text field in this table called WordDocDataSrc to store the path of MS-Word file imported
    ' - a memo text field in this table called WordDocData with the TextFormat property set to "Rich Text",
    '   which will store the text and text formating of the MS-Word file imported

    Dim collFiles As Collection
    Dim strWordContent As Variant

    ' Select files via File Dialogue

    Set collFiles = FilesToOpen
    Dim oneFile As Variant

    ' Conditionals when a file was or wasn't selected

    If _
        collFiles.Count <> 0 _
    Then
        For Each oneFile In collFiles

            DoCmd.GoToRecord , , acNewRec

            GetWordContent CStr(oneFile)
        Next oneFile

        MsgBox "Import Successful", vbInformation Or vbOKOnly

    Else

        MsgBox "No File Selected", vbExclamation Or vbOKOnly

    End If

End Sub

Note that I attempted to change as little as possible and have not done anything with the GetWordContent function.


问:
How to create a byte[] image intent to share with Email
I am trying to create a byte[] image intent to share with the email app on my Xamarin.Android application. So far I have the following:

```<code>public void ShareAsync(byte[] image, string message)
{
    if (string.IsNullOrEmpty(message) || image == null)
        return;

    var sharingIntent = new Intent();
    sharingIntent.SetAction(Intent.ActionSend);
    sharingIntent.SetType("image/*");
    sharingIntent.PutExtra(Intent.ExtraStream, image);
    sharingIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
    Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity.StartActivity(Intent.CreateChooser(sharingIntent, message));
}
</code>```

This pops up the share dialog and I can click the email app but it returns a blank email.

Is it possible to share a byte[] with the email app so that the image appears as part of the body or an attachment?

答:
You can directly pass file uri in intent
try this</p>

```<code>        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("image/*");

        share.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_text));
        share.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_subject));

        share.putExtra(Intent.EXTRA_STREAM,
                Uri.parse("file:///" + "your image path"));
        startActivity(Intent.createChooser(share, "Share"));
</code>```

Body:
I am trying to create a byte[] image intent to share with the email app on my Xamarin.Android application. So far I have the following:

public void ShareAsync(byte[] image, string message)
{
    if (string.IsNullOrEmpty(message) || image == null)
        return;

    var sharingIntent = new Intent();
    sharingIntent.SetAction(Intent.ActionSend);
    sharingIntent.SetType("image/*");
    sharingIntent.PutExtra(Intent.ExtraStream, image);
    sharingIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
    Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity.StartActivity(Intent.CreateChooser(sharingIntent, message));
}

This pops up the share dialog and I can click the email app but it returns a blank email.

Is it possible to share a byte[] with the email app so that the image appears as part of the body or an attachment?

Body:
You can directly pass file uri in intent
try this

        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("image/*");

        share.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_text));
        share.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_subject));

        share.putExtra(Intent.EXTRA_STREAM,
                Uri.parse("file:///" + "your image path"));
        startActivity(Intent.createChooser(share, "Share"));


问:
Ng-grid filter with 2 condition
I have requirement to filter table based on

single column and

across column comparison.

I am using ng-grid to populate table.  It gives feature to filter based on single column.

For across column comparison I am using grid.refresh() function. this function calls grid.registerRowsProcessor( $scope.columnComparionFilter, 200 )function. I have prepared columnComparionFilter function that returns renderableRows based on filter. Below is sample code:

```<code>// function to filter two column based on condition
$scope.columnComparionFilter= function(renderableRows){
    // if filter option selection changed
    if($scope.change){
        if($scope.column1 == undefined)
            return renderableRows;
        if($scope.column2 == undefined)
            return renderableRows;
        if($scope.column1 == $scope.column2){
            console.log('columns for comparision should be different.')
            return renderableRows;
        }
        if($scope.selectedFilter.name == 'compare'){
            renderableRows.forEach( function( row ) {
                if(row.entity[$scope.column1.field] == row.entity[$scope.column2.field])
                    row.visible = true;
                else
                    row.visible = false;
            });
        }else if($scope.selectedFilter.name == 'distinct'){
            renderableRows.forEach( function( row ) {
                if(row.entity[$scope.column1.field] != row.entity[$scope.column2.field])
                    row.visible = true;
                else
                    row.visible = false;
            });
        }
    }
    return renderableRows;
};
</code>```

Both filter works fine alone.
But when I tries working both together. It filters based on by default single filter only. It eliminates across column filter.

Can any one help me to solve this?

答:
Actually grid.registerRowsProcessor() is core function used by single column filter of ng-grid. So when I tried to use same function for across filtering, It lead synchronization problem and single column filter over ruled my customised function.

I have used an alternative for modifying ng-grid data. I have solved it using notifyDataChange() function. inside external filter function columnComparionFilter I am preparing subset of data based on filter and then I am changing gridOptions.data to subset data. See below code:

```<code>// function to filter two column based on condition
$scope.columnComparionFilter= function(renderableRows){
    // if filter option selection changed
    if($scope.change){
        if($scope.column1 == undefined){
            console.log('Please select first column to compare.')
            return;
        }
        if($scope.column2 == undefined){
            console.log('Please select second column to compare.')
            return;
        }
        if($scope.column1 == $scope.column2){
            console.log('columns for comparision should be different.')
            return;
        }
        if($scope.selectedFilter.name == 'compare'){
            renderableRows.forEach( function( row ) {
                if(row[$scope.column1.field] == row[$scope.column2.field])
                    filterData.push(row)
            });
        }else if($scope.selectedFilter.name == 'distinct'){
            renderableRows.forEach( function( row ) {
                if(row[$scope.column1.field] != row[$scope.column2.field])
                    filterData.push(row)
            });
        }
        $scope.gridOptions.data = angular.copy(filterData);
        $scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.ALL);
        return;
    }
};
</code>```

Title: Ng-grid filter with 2 condition

Body:
I have requirement to filter table based on

single column and

across column comparison.

I am using ng-grid to populate table.  It gives feature to filter based on single column.

For across column comparison I am using grid.refresh() function. this function calls grid.registerRowsProcessor( $scope.columnComparionFilter, 200 )function. I have prepared columnComparionFilter function that returns renderableRows based on filter. Below is sample code:

// function to filter two column based on condition
$scope.columnComparionFilter= function(renderableRows){
    // if filter option selection changed
    if($scope.change){
        if($scope.column1 == undefined)
            return renderableRows;
        if($scope.column2 == undefined)
            return renderableRows;
        if($scope.column1 == $scope.column2){
            console.log('columns for comparision should be different.')
            return renderableRows;
        }
        if($scope.selectedFilter.name == 'compare'){
            renderableRows.forEach( function( row ) {
                if(row.entity[$scope.column1.field] == row.entity[$scope.column2.field])
                    row.visible = true;
                else
                    row.visible = false;
            });
        }else if($scope.selectedFilter.name == 'distinct'){
            renderableRows.forEach( function( row ) {
                if(row.entity[$scope.column1.field] != row.entity[$scope.column2.field])
                    row.visible = true;
                else
                    row.visible = false;
            });
        }
    }
    return renderableRows;
};

Both filter works fine alone.
But when I tries working both together. It filters based on by default single filter only. It eliminates across column filter.

Can any one help me to solve this?

Body:
Actually grid.registerRowsProcessor() is core function used by single column filter of ng-grid. So when I tried to use same function for across filtering, It lead synchronization problem and single column filter over ruled my customised function.

I have used an alternative for modifying ng-grid data. I have solved it using notifyDataChange() function. inside external filter function columnComparionFilter I am preparing subset of data based on filter and then I am changing gridOptions.data to subset data. See below code:

// function to filter two column based on condition
$scope.columnComparionFilter= function(renderableRows){
    // if filter option selection changed
    if($scope.change){
        if($scope.column1 == undefined){
            console.log('Please select first column to compare.')
            return;
        }
        if($scope.column2 == undefined){
            console.log('Please select second column to compare.')
            return;
        }
        if($scope.column1 == $scope.column2){
            console.log('columns for comparision should be different.')
            return;
        }
        if($scope.selectedFilter.name == 'compare'){
            renderableRows.forEach( function( row ) {
                if(row[$scope.column1.field] == row[$scope.column2.field])
                    filterData.push(row)
            });
        }else if($scope.selectedFilter.name == 'distinct'){
            renderableRows.forEach( function( row ) {
                if(row[$scope.column1.field] != row[$scope.column2.field])
                    filterData.push(row)
            });
        }
        $scope.gridOptions.data = angular.copy(filterData);
        $scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.ALL);
        return;
    }
};


问:
SQL Query assistance - Looping through data query
I have two tables. Config and Data. Config table has info to define what I call "Predefined Points". The columns are configId, machineId, iotype, ioid, subfield and predeftype. I have a second table that contains all the data for all the items in the config table linked by configId. Data table contains configId, timestamp, value.

I am trying to return each row from the config table with 2 new columns in the result which would be min timestamp of this particular predefined point and max timestamp of this particular predefined point.

Pseudocode would be

```<code>select a.*, min(b.timestamp), max(b.timestamp) from TrendConfig a join TrendData b on a.configId = b.configId where configId = (select configId from TrendConfig)
</code>```

Where the subquery would return multiple values.

Any idea how to formulate this?

答:
Try an inner join:

select a.*, b.min(timestamp), b.max(timestamp)
from config a
inner join data b
on a.configId = b.configID

Body:
I have two tables. Config and Data. Config table has info to define what I call "Predefined Points". The columns are configId, machineId, iotype, ioid, subfield and predeftype. I have a second table that contains all the data for all the items in the config table linked by configId. Data table contains configId, timestamp, value.

I am trying to return each row from the config table with 2 new columns in the result which would be min timestamp of this particular predefined point and max timestamp of this particular predefined point.

Pseudocode would be

select a.*, min(b.timestamp), max(b.timestamp) from TrendConfig a join TrendData b on a.configId = b.configId where configId = (select configId from TrendConfig)

Where the subquery would return multiple values.

Any idea how to formulate this?


问:
mysql get row number from table where a column value is equal to a specific value
I have a table where results of modeltest are given in a column in descending order. Now I want to get the row number of a specific row. Here is the example table:

So when i will search a with userid=44, it should return 3. Again when i will search with userid=11, it should return 4. How can I do this ? If anyone could kindly help me out.

答:
for example:

```<code>$stmt = PDO::prepare('SELECT id FROM table WHERE userid = ?');
$userId = 44;

$stmt->execute([$userId]);
$result = $stmt->fetch(PDO::FETCH_OBJ);

echo $result->id;
</code>```

http://php.net/manual/en/book.pdo.php

Body:
for example:

$stmt = PDO::prepare('SELECT id FROM table WHERE userid = ?');
$userId = 44;

$stmt->execute([$userId]);
$result = $stmt->fetch(PDO::FETCH_OBJ);

echo $result->id;

http://php.net/manual/en/book.pdo.php


问:
CSS Text-overflow Ellipsis Not Displaying Correctly
I have a
 tag to display some information but it should be restricted to 2 lines and if the text is greater then it should show "..." at end. I tried many solutions but i am not able to get exactly what i am looking for. i have tried below css.

```<code>.mw {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: 2;
   line-height: 20px;
   max-height: 40px;
   width:100px;
   border:1px solid #ccc;
}
</code>```

but i am getting three different outputs for three different text in
.

TestingTestingTestingTestingTestingTesting

TestingTesting TestingTestingTestingTesting

TestingTesting TestingTesting TestingTesting

答:
Try this it will work on all browsers it will ellipsis after two lines.

.mw {
      display: block;
      /* Fallback for non-webkit */
      display: -webkit-box;
      max-height: 28pt;
      /* Fallback for non-webkit */
      font-size: 10pt;
      line-height: 1.4;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      -ms-text-overflow: ellipsis;
      -o-text-overflow: ellipsis;
      text-overflow: ellipsis;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="mw">all long text will come here.all long text will come here.all long text will come here.all long text will come here.all long text will come here.all long text will come here.all long text will come here.all long text will come here.all long text will come here.all long text will come here.</p></code>```

Body:
I have a
 tag to display some information but it should be restricted to 2 lines and if the text is greater then it should show "..." at end. I tried many solutions but i am not able to get exactly what i am looking for. i have tried below css.

.mw {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: 2;
   line-height: 20px;
   max-height: 40px;
   width:100px;
   border:1px solid #ccc;
}

but i am getting three different outputs for three different text in
.

TestingTestingTestingTestingTestingTesting

TestingTesting TestingTestingTestingTesting

TestingTesting TestingTesting TestingTesting

Body:
Try this it will work on all browsers it will ellipsis after two lines.

.mw {
      display: block;
      /* Fallback for non-webkit */
      display: -webkit-box;
      max-height: 28pt;
      /* Fallback for non-webkit */
      font-size: 10pt;
      line-height: 1.4;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      -ms-text-overflow: ellipsis;
      -o-text-overflow: ellipsis;
      text-overflow: ellipsis;
    }

<p class="mw">all long text will come here.all long text will come here.all long text will come here.all long text will come here.all long text will come here.all long text will come here.all long text will come here.all long text will come here.all long text will come here.all long text will come here.</p>


问:
How to pass an array of structure as [in, out] paramenter in COM interface definition
I'm having some problems in passing an array of structures in the definition of COM interface. For example, I'm trying to define a series of variables Ids in one read function and I'm expecting the reply function (the same function) will bring back an array of values that corresponds to the previously defined variable Ids:

[helpstring("method ReadVariables")] HRESULT ReadVariables([in]
  VARIANT varIds, [out] _valStruct* retVals);

For _valStruct, the definition is:

```<code>struct _valStruct
{
   int varId;
   double varVal;
   int timeStamp;
   double funcId;
....

}
</code>```

I'm not familiar with COM and I just know some basic types, such as int, double, etc... I sincerely some experts here will give me some detailed example code or related information. Your help is greatly appreciated... Thanks!!!

答:
Man, it's been ages since I did something like that!
Anyway, according to code I have dug up from 2002, I used SAFEARRAY .. but maybe only for VB interoperability, like so:

```<code>[id(9), helpstring("method Keys")] HRESULT Keys([out, retval] SAFEARRAY(ComInt128)* pKeys);
</code>```

You can then use API functions such as SafeArrayAllocDescriptor and SafeArrayAllocData to create your array and SafeArrayAccessData/SafeArrayUnAccessData to manage the contents.

Hope this helps.

Body:
I'm having some problems in passing an array of structures in the definition of COM interface. For example, I'm trying to define a series of variables Ids in one read function and I'm expecting the reply function (the same function) will bring back an array of values that corresponds to the previously defined variable Ids:

[helpstring("method ReadVariables")] HRESULT ReadVariables([in]
  VARIANT varIds, [out] _valStruct* retVals);

For _valStruct, the definition is:

struct _valStruct
{
   int varId;
   double varVal;
   int timeStamp;
   double funcId;
....

}

I'm not familiar with COM and I just know some basic types, such as int, double, etc... I sincerely some experts here will give me some detailed example code or related information. Your help is greatly appreciated... Thanks!!!

Body:
Man, it's been ages since I did something like that!
Anyway, according to code I have dug up from 2002, I used SAFEARRAY .. but maybe only for VB interoperability, like so:

[id(9), helpstring("method Keys")] HRESULT Keys([out, retval] SAFEARRAY(ComInt128)* pKeys);

You can then use API functions such as SafeArrayAllocDescriptor and SafeArrayAllocData to create your array and SafeArrayAccessData/SafeArrayUnAccessData to manage the contents.

Hope this helps.


问:
what does constant property means in swift?
I am learning SWIFT. I don't understand one sentence while reading book. What does the sentence below means?: </p>

<blockquote>
  <p>“Add a constant property called elementList to ViewController.swift
  and initialize it with the following element names: let elementList =
  ["Carbon", "Gold", "Chlorine", "Sodium"]”
  does it mean create new class or I have to create struct? </p>
</blockquote>

答:
```<code>class ViewController: UIViewController {
    var intValue = 1 //This is a property, but it is variable. That means its value can be changed in future.
    let doubleValue = 3.14 // This is a property too, but it is constant. That means its value can't be change
    // Both `intValue` & `doubleValue` will be in memory till ViewController's existence.

}
</code>```

IN YOUR CASE:

```<code>let elementList = ["Carbon", "Gold", "Chlorine", "Sodium"]
</code>```

elementList is a array of String, since let keyword denotes that it is a constant property

To Add a constant property called elementList to ViewController.swift and initialize it. IT WOULD LOOK SOMETHING LIKE THIS

```<code>class ViewController: UIViewController {
    let elementList = ["Carbon", "Gold", "Chlorine", "Sodium"]

    //..
}
</code>```

Body:
I am learning SWIFT. I don't understand one sentence while reading book. What does the sentence below means?:

“Add a constant property called elementList to ViewController.swift
  and initialize it with the following element names: let elementList =
  ["Carbon", "Gold", "Chlorine", "Sodium"]”
  does it mean create new class or I have to create struct?

Body:
class ViewController: UIViewController {
    var intValue = 1 //This is a property, but it is variable. That means its value can be changed in future.
    let doubleValue = 3.14 // This is a property too, but it is constant. That means its value can't be change
    // Both `intValue` & `doubleValue` will be in memory till ViewController's existence.

}

IN YOUR CASE:

let elementList = ["Carbon", "Gold", "Chlorine", "Sodium"]

elementList is a array of String, since let keyword denotes that it is a constant property

To Add a constant property called elementList to ViewController.swift and initialize it. IT WOULD LOOK SOMETHING LIKE THIS

class ViewController: UIViewController {
    let elementList = ["Carbon", "Gold", "Chlorine", "Sodium"]

    //..
}


问:
Bootstrap panel: collapsed on mobile but expanded on desktop, how?
How can I as simply as possible remove the class "in" from the div with id "panel-login" if the screen are smaller than 1199px (Bootstrap's xs, sm and md modes). I guess some kind of JS or JQuery could solve it but I'm not very good at either.

```<code><div class="panel-group">
<div class="panel panel-default">
    <div class="panel-heading">

        <div class="row">

            <div class="col-xs-10">
                <h4 class="panel-title">Login</h4>
            </div>

            <div class="col-xs-2 text-right">
                <a data-toggle="collapse" href="#panel-login"><i class="fa fa-bars"></i></a>
            </div>

        </div>

    </div>

    <div id="panel-login" class="panel-collapse collapse in">

        <div class="panel-body">

            <ul>
                <li><a href="<?=$php_self?>?page=login&view=signup">Create account</a></li>
                <li><a href="<?=$php_self?>?page=login&view=reset_password">Reset password</a></li>
                <li><a href="<?=$php_self?>?page=login&view=reactivate_account">Reactivate account</a></li>
            </ul>

        </div><!-- end panel-body -->

    </div>

</div><!-- end panel-default -->
</code>```

答:
HTML

In you panel-heading element just add

```<code><span class="pull-right clickable"><i class="glyphicon glyphicon-chevron-down"></i></span>
</code>```

And in your panel-body element add "collapse":

JAVASCRIPT

```<code>$(document).on('click', '.panel-heading span.clickable', function(e){
    var $this = $(this);
    var d = $this.parents('.panel').find('.panel-body');
        if(!d.hasClass('collapse in')) {
            d.slideDown();
            d.addClass('in');
            $this.find('i').removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
        }
        else {
            d.slideUp();
            d.removeClass('in');
            $this.find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
        }
})
</code>```

Once you've added the javascript snippet globally you are able to toogle every panel by just adding the HTML snippet.

To make it collapsed for mobile devices just trigger the collapse() function for mobile devices,like

```<code>if (($(window).width()) > 767) {
    $('.collapse').collapse();
}
</code>```

OR you could check if the hamburger menu is visible

```<code>if (!$('.navbar-toggle').is(':visible')) {
  $('.collapse').collapse();
}
</code>```

Body:
How can I as simply as possible remove the class "in" from the div with id "panel-login" if the screen are smaller than 1199px (Bootstrap's xs, sm and md modes). I guess some kind of JS or JQuery could solve it but I'm not very good at either.

Login

<a href="<?=$php_self?>?page=login&view=signup">Create account

<a href="<?=$php_self?>?page=login&view=reset_password">Reset password

<a href="<?=$php_self?>?page=login&view=reactivate_account">Reactivate account

Body:
HTML

In you panel-heading element just add

<span class="pull-right clickable"><i class="glyphicon glyphicon-chevron-down"></i></span>

And in your panel-body element add "collapse":

<div class="panel-body collapse">

JAVASCRIPT

$(document).on('click', '.panel-heading span.clickable', function(e){
    var $this = $(this);
    var d = $this.parents('.panel').find('.panel-body');
        if(!d.hasClass('collapse in')) {
            d.slideDown();
            d.addClass('in');
            $this.find('i').removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
        }
        else {
            d.slideUp();
            d.removeClass('in');
            $this.find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
        }
})

Once you've added the javascript snippet globally you are able to toogle every panel by just adding the HTML snippet.

To make it collapsed for mobile devices just trigger the collapse() function for mobile devices,like

if (($(window).width()) > 767) {
    $('.collapse').collapse();
}

OR you could check if the hamburger menu is visible

if (!$('.navbar-toggle').is(':visible')) {
  $('.collapse').collapse();
}


问:
How to place a div beside input box on focus?
I have a scenario,that I used css for extending search box on focus,when I focussed on search box then the search box must decrease and the cancel button must be placed beside of search box.

Css:

```<code>.clrble .frmcntr {
background:url("images/search.png") no-repeat 110px center;
text-align: center;
border-radius: 4px;
border: medium none;
cursor: pointer;
font-size: 20px;
font-family:SFUIDisplay;
padding: 6px 10px 6px 10px;
transition: all 0.5s ease 0s;
width: 95%;
background-color:rgba(247, 247, 247, 1);
 }

: content-box;
font-size: 100%;

.clrble .frmcntr:focus {
    width: 70%;
    text-align: left;
    background-color: #fff;
    border-color: #66CC75;
    -webkit-box-shadow: 0 0 5px rgba(109,207,246,.5);
    -moz-box-shadow: 0 0 5px rgba(109,207,246,.5);
    box-shadow: 0 0 5px rgba(109,207,246,.5);
    background-color:rgba(247, 247, 247, 1);
    background:url("images/search.png") no-repeat  10px center;
    padding-left:40px;
}

.clrble .frmcntr {
    -webkit-appearance: textfield;
    -webkit-box-sizing

}
</code>```

Here is my plunker link:

https://plnkr.co/edit/Z7mfglWEoDyjbDfFDbLM?p=preview

And the expected output will be like this:

Is it possible with Angularjs or JavaScript?

答:
Possible solution would be to position the div you want absolutely. Then on focus of the input, make the div visible or slide it into view;

Using your plunk, add the following CSS:

```<code>.clrble{
  position: relative;
}
.frmcntr:focus + .btn{
  display: block;
}

.btn{display: none; position: absolute; right: 0;}
</code>```

and here's the HTML:

```<code><div class="clrble">
    <input type="text"  placeholder="Search" class="frmcntr">
    <div class="btn">button here</div>
</div>
</code>```

It's not perfect, but i think it will point you in the right direction.

Body:
I have a scenario,that I used css for extending search box on focus,when I focussed on search box then the search box must decrease and the cancel button must be placed beside of search box.

Css:

.clrble .frmcntr {
background:url("images/search.png") no-repeat 110px center;
text-align: center;
border-radius: 4px;
border: medium none;
cursor: pointer;
font-size: 20px;
font-family:SFUIDisplay;
padding: 6px 10px 6px 10px;
transition: all 0.5s ease 0s;
width: 95%;
background-color:rgba(247, 247, 247, 1);
 }

: content-box;
font-size: 100%;

.clrble .frmcntr:focus {
    width: 70%;
    text-align: left;
    background-color: #fff;
    border-color: #66CC75;
    -webkit-box-shadow: 0 0 5px rgba(109,207,246,.5);
    -moz-box-shadow: 0 0 5px rgba(109,207,246,.5);
    box-shadow: 0 0 5px rgba(109,207,246,.5);
    background-color:rgba(247, 247, 247, 1);
    background:url("images/search.png") no-repeat  10px center;
    padding-left:40px;
}

.clrble .frmcntr {
    -webkit-appearance: textfield;
    -webkit-box-sizing

}

Here is my plunker link:

https://plnkr.co/edit/Z7mfglWEoDyjbDfFDbLM?p=preview

And the expected output will be like this:

Is it possible with Angularjs or JavaScript?

Body:
Possible solution would be to position the div you want absolutely. Then on focus of the input, make the div visible or slide it into view;

Using your plunk, add the following CSS:

.clrble{
  position: relative;
}
.frmcntr:focus + .btn{
  display: block;
}

.btn{display: none; position: absolute; right: 0;}

and here's the HTML:

<div class="clrble">
    <input type="text"  placeholder="Search" class="frmcntr">
    <div class="btn">button here</div>
</div>

It's not perfect, but i think it will point you in the right direction.


问:
Word2Vec Vocabulary not definded error
I am new to python and word2vec and keep getting a "you must first build vocabulary before training the model" error. What is wrong with my code?

Here is my code:

```<code>file_object=open("SupremeCourt.txt","w")
from gensim.models import word2vec

data = word2vec.Text8Corpus('SupremeCourt.txt')
model = word2vec.Word2Vec(data, size=200)

out=model.most_similar()

print(out[1])
print(out[2])
</code>```

答:
I could see some wrong things in your code like the file is opened in write mode and the model which you have loaded doesn't contain the word which you want to find the most similar words.
I would like to suggest to use the predefined models like google_news_vectors to load in the gensim or to build your own word2vec model so that you won't get the error.
the usage of most_similar in gensim is out = model.most_similar("word-name")

```<code>file_object=open("SupremeCourt.txt","r")
from gensim.models import word2vec

data = word2vec.Text8Corpus('SupremeCourt.txt')
model = word2vec.Word2Vec(data, size=200)#use google news vectors here

out=model.most_similar("word")
print(out)
</code>```

Title: Word2Vec Vocabulary not definded error

Body:
I am new to python and word2vec and keep getting a "you must first build vocabulary before training the model" error. What is wrong with my code?

Here is my code:

file_object=open("SupremeCourt.txt","w")
from gensim.models import word2vec

data = word2vec.Text8Corpus('SupremeCourt.txt')
model = word2vec.Word2Vec(data, size=200)

out=model.most_similar()

print(out[1])
print(out[2])

Body:
I could see some wrong things in your code like the file is opened in write mode and the model which you have loaded doesn't contain the word which you want to find the most similar words.
I would like to suggest to use the predefined models like google_news_vectors to load in the gensim or to build your own word2vec model so that you won't get the error.
the usage of most_similar in gensim is out = model.most_similar("word-name")

file_object=open("SupremeCourt.txt","r")
from gensim.models import word2vec

data = word2vec.Text8Corpus('SupremeCourt.txt')
model = word2vec.Word2Vec(data, size=200)#use google news vectors here

out=model.most_similar("word")
print(out)


问:
Program is not inserting into the database
My program doesn't insert into the database, tried various means, I'm new to php and tried to test myself with this but I'm finding it difficult to get. i think the problem is at the connection to the database but I'm not getting it </p>

```<code><!DOCTYPE html>
<html>
    <head>
        <title>LIST</title>
    </head>
    <body>
        <h1> TODO LIST </h1>
        <?php
            if(isset($_POST["submit"])){
                $servername = "localhost";
                $username = "root";
                $password = "";

                try {
                    //create a database conneection
                    $conn = mysqli_connect("localhost", "root", "");
                    if(!$conn){
                        die("Database connection failed: ". mysql_error());
                    }
                    $sql = "INSERT INTO tasks (task, date, time) VALUES (:task, :date, :time)";
                    $query = $conn->prepare($sql);
                    $query->execute(array(':task'=>$task,
                        ':date'=>$date,':time'=>$time));
                }
                catch(PDOException $e)
                {
                    echo "Connection failed: " . $e->getMessage();
                }
            }
        ?>

        <form action = "todolist.php" method = "post">
          Task: <input type="text" name="task" id="task"><br/>
          Date: <input type="date" name="date" id="date"><br/>
          Time: <input type="time" name="time" id="time"><br/>
        <input type = "submit" value = "submit" name="submit">
        </form>
    </body>
</html>
</code>```

答:
You are not select any database.
Try something like this.</p>

```<code>$conn = mysqli_connect("localhost", "root", "", "Yourdatabasename");
</code>```

Body:
My program doesn't insert into the database, tried various means, I'm new to php and tried to test myself with this but I'm finding it difficult to get. i think the problem is at the connection to the database but I'm not getting it

<!DOCTYPE html>

        <title>LIST</title>

 TODO LIST

        <?php
            if(isset($_POST["submit"])){
                $servername = "localhost";
                $username = "root";
                $password = "";

                try {
                    //create a database conneection
                    $conn = mysqli_connect("localhost", "root", "");
                    if(!$conn){
                        die("Database connection failed: ". mysql_error());
                    }
                    $sql = "INSERT INTO tasks (task, date, time) VALUES (:task, :date, :time)";
                    $query = $conn->prepare($sql);
                    $query->execute(array(':task'=>$task,
                        ':date'=>$date,':time'=>$time));
                }
                catch(PDOException $e)
                {
                    echo "Connection failed: " . $e->getMessage();
                }
            }
        ?>

        <form action = "todolist.php" method = "post">
          Task: <input type="text" name="task" id="task">

          Date: <input type="date" name="date" id="date">

          Time: <input type="time" name="time" id="time">

        <input type = "submit" value = "submit" name="submit">
        </form>

Body:
You are not select any database.
Try something like this.

$conn = mysqli_connect("localhost", "root", "", "Yourdatabasename");


问:
prevent page repositioning after editing with jQuery
I'm updating several image src attributes on a page, and they are updated properly, but when jQuery updates those items, the page scrolls down to those items (they are below the 'fold') - how can I stop the page from auto-scrolling down to the changes I'm making with jQuery?  I see the same behavior with IE and FireFox

```<code>// insert images into current page
$("img.nominphoto",$(".nominwrap")).each(function(){
  var userItemID=$(this).attr("title");
    $(this).attr("src",hashImageURLs[userItemID]);
});
</code>```

Thanks

答:
You may be able to fines it by using $(window).scrollTop and maybe hooking to the image's load method using .one() so it only triggers then releases (reset scrollTop when it's completed loading)--but this is a hack at best.

If you're not already (and assuming the images are fixed-height and width) it's "proper" to specify the width/height of an image. This allows the renderer to layout the page (despite missing or updated content), but also prevents any image(s) [re]loading from having adverse effects later on.

Body:
I'm updating several image src attributes on a page, and they are updated properly, but when jQuery updates those items, the page scrolls down to those items (they are below the 'fold') - how can I stop the page from auto-scrolling down to the changes I'm making with jQuery?  I see the same behavior with IE and FireFox

// insert images into current page
$("img.nominphoto",$(".nominwrap")).each(function(){
  var userItemID=$(this).attr("title");
    $(this).attr("src",hashImageURLs[userItemID]);
});

Thanks


问:
How to stretch div height to fill parent div - CSS
I have a page with divs like shown in the layout / screenshot below:

The code is here:

html,
body {
  margin: 0;
  padding: 0;
  border: 0;
}

#B,
#C,
#D {
  position: absolute;
}

#A {
  top: 0;
  width: 100%;
  height: 35px;
  background-color: #99CC00;
}

#B {
  top: 35px;
  width: 200px;
  bottom: 35px;
  background-color: #999999;
  z-index: 100;
  border: solid 4px #00CC00;
}

#B2 {
  margin-top: -35px;
  bottom: 0;
  background-color: #FFFFFF;
  width: 200px;
  overflow: scroll;
}

#B1 {
  height: 35px;
  width: 35px;
  margin-left: 200px;
  background-color: #CC0066;
}

#C {
  top: 35px;
  left: 200px;
  right: 0;
  bottom: 35px;
  background-color: #CCCCCC;
}

#D {
  bottom: 0;
  width: 100%;
  height: 35px;
  background-color: #3399FF;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div id="A">A</div>
  <div id="B">
    <div id="B1">B1</div>
    <div id="B2">B2</div>
  </div>
  <div id="C">C</div>
  <div id="D">D</div>
</div></code>```

I want to adjust the height of B2 div to fill (or stretch to) entire B div (marked with a green border in the image) and don't want to cross the footer D div. Here is a working fiddle link(updated). How can I solve this??

答:
Suppose you have

```
<p>With normal CSS, you can do the following. See a working app https://github.com/onmyway133/Lyrics/blob/master/index.html</p>
<pre class="lang-css prettyprint-override"><code>#root {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}
</code>```

With flexbox, you can

html, body {
  height: 100%
}
body {
  display: flex;
  align-items: stretch;
}

#root {
  width: 100%
}
```

Body:
I have a page with divs like shown in the layout / screenshot below:

The code is here:

html,
body {
  margin: 0;
  padding: 0;
  border: 0;
}

#B,
#C,
#D {
  position: absolute;
}

#A {
  top: 0;
  width: 100%;
  height: 35px;
  background-color: #99CC00;
}

#B {
  top: 35px;
  width: 200px;
  bottom: 35px;
  background-color: #999999;
  z-index: 100;
  border: solid 4px #00CC00;
}

#B2 {
  margin-top: -35px;
  bottom: 0;
  background-color: #FFFFFF;
  width: 200px;
  overflow: scroll;
}

#B1 {
  height: 35px;
  width: 35px;
  margin-left: 200px;
  background-color: #CC0066;
}

#C {
  top: 35px;
  left: 200px;
  right: 0;
  bottom: 35px;
  background-color: #CCCCCC;
}

#D {
  bottom: 0;
  width: 100%;
  height: 35px;
  background-color: #3399FF;
}

A

B1

B2

C

D

I want to adjust the height of B2 div to fill (or stretch to) entire B div (marked with a green border in the image) and don't want to cross the footer D div. Here is a working fiddle link(updated). How can I solve this??

Body:
Suppose you have

<body>
  <div id="root" />
</body>

With normal CSS, you can do the following. See a working app https://github.com/onmyway133/Lyrics/blob/master/index.html

#root {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}

With flexbox, you can

html, body {
  height: 100%
}
body {
  display: flex;
  align-items: stretch;
}

#root {
  width: 100%
}


问:
MYSQL Error 1406 "Data to long" in blob field
I obtain this error when I try to insert a text that is approx. 85K long in a blob field.

I tried also to change the field to longblob ant to turn off strict mode, but with no result.

Thanks for your answer

答: Can you change the data type into LONGTEXT and then try again


问:
Detect a cutout/semicircle in an image
Below is a binary image in which I would like to detect the "hills", semicircles, cutouts.. In the image below in the red circle. The detection does not have to be precise, I just need to know that something like this is in the picture. I am thinking about the algorithm which would use kind of line sweep approach and count the black pixels on the line and evaluate that with some kind of "cleveristic", but before that I would like to know if I am missing any technique that would be easier or more robust. I have tried the HoughCircles, but with no good results, because the circles have quite huge radius and there is many of them (houghCircles takes grayscale image as input).

答:
Counting pixels should be fine in this simple situation. If you face more complex scenarios with other things you don't want to count in, you should consider a blob detector.
This method searches for regions of connected pixels. Once you have blobs you can easily sort them by size, shape, position which helps to get rid of unwanted things.

https://www.learnopencv.com/blob-detection-using-opencv-python-c/

This is a very basic technique. Please read a book on image processing fundamentals befor you continue. It will make life much easier.

Title: Detect a cutout/semicircle in an image


问:
How to downcast when it's necessary?
I am facing a downcast issue in my company software and I can't manage to find a workaround. (It's something put in place and I cannot change the whole conception)

I will try to give you the whole context with an example: Basically, we have 2 software components, let's say BrickHigh, BrickLow. BrickLow can use everything from BrickHigh but BrickHigh can't see Bricklow.

In BrickHigh there is an Animal class (dozens of attributes) with its DAO :

```<code>public class Animal .. {
 //attributes...
}
</code>```

In BrickLow I have created a Cat class (dozens of unmapped attributes aswell) which extends Animal.

```<code>public class Cat extends Animal {
//attributes
}
</code>```

What was intended to do is to have a super class(Animal) with every mapped attribute. But I cannot use my animal class in my application because it would be too many changes since the whole app uses Cat.

But obviously, I cannot cast my Animal to Cat after getting it from the DAO since Java doesn't allow it, and I need every information from Animal.

Since my BrickHigh doesn't see my BrickLow, there are no such things as Animal animal = new Cat(); possible.

My first idea was to create a constructor in Cat that would take an Animal as parameter

```<code>public Cat(Animal a) {
 super(a);
}
</code>```

But what my constructor must be in my Animal class? It doesn't seem to work.

答:
But what my constructor must be in my Animal class? It doesn't seem to work.

Something like this:

```<code>   public Animal(Animal other) {
      this.field1 = other.field1;
      this.field2 = other.field2;
      // etc
   }
</code>```

However, I think may be better off using the Object Factory pattern; i.e. have your DAO class take a parameter which is a factory object that can create Animal instances.  When you use the DAO (from BrickHigh) in code that uses the BrickLow APIs, you instantiate if with a factory that produces Cat instances rather than Animal instances.

Title: How to downcast when it's necessary?

Body:
I am facing a downcast issue in my company software and I can't manage to find a workaround. (It's something put in place and I cannot change the whole conception)

I will try to give you the whole context with an example: Basically, we have 2 software components, let's say BrickHigh, BrickLow. BrickLow can use everything from BrickHigh but BrickHigh can't see Bricklow.

In BrickHigh there is an Animal class (dozens of attributes) with its DAO :

public class Animal .. {
 //attributes...
}

In BrickLow I have created a Cat class (dozens of unmapped attributes aswell) which extends Animal.

public class Cat extends Animal {
//attributes
}

What was intended to do is to have a super class(Animal) with every mapped attribute. But I cannot use my animal class in my application because it would be too many changes since the whole app uses Cat.

But obviously, I cannot cast my Animal to Cat after getting it from the DAO since Java doesn't allow it, and I need every information from Animal.

Since my BrickHigh doesn't see my BrickLow, there are no such things as Animal animal = new Cat(); possible.

My first idea was to create a constructor in Cat that would take an Animal as parameter

public Cat(Animal a) {
 super(a);
}

But what my constructor must be in my Animal class? It doesn't seem to work.

Body:
But what my constructor must be in my Animal class? It doesn't seem to work.

Something like this:

   public Animal(Animal other) {
      this.field1 = other.field1;
      this.field2 = other.field2;
      // etc
   }

However, I think may be better off using the Object Factory pattern; i.e. have your DAO class take a parameter which is a factory object that can create Animal instances.  When you use the DAO (from BrickHigh) in code that uses the BrickLow APIs, you instantiate if with a factory that produces Cat instances rather than Animal instances.


问:
List view itemclick event appcelerator
I have a JSON defined in the code with and image, a title, a date and  a url. This will be used to populate the list view. On the click event of any list item, I need to navigate to a different controller and render the view in it having the videoplayer that plays the video according to the clicked list item's url and i want to display the date and title too.
I am not understanding how to code this in the itemClick event. Please help!

This is my .js file for DashboardController.

```<code>Alloy.createController('VideoPlayerController',videoInfo[i]).getView();
var sections = [];
//JSON to populate the listview
var videoInfo = [{
    pic : "/Images/playButton.png",
    info : "This in the the title for the first video.",
    date : "03/07/2017",
    url : "https://youtu.be/zkOSR0ZRb9khttps://youtu.be/zkOSR0ZRb9k"
}, {
    pic : "/Images/playButton.png",
    info : "This in the the title for the second video.",
    date : "03/07/2017",
    url : "https://youtu.be/zkOSR0ZRb9khttps://youtu.be/zkOSR0ZRb9k"
}, {
    pic : "/Images/playButton.png",
    info : "This in the the title for the third video.",
    date : "03/07/2017",
    url : "https://youtu.be/zkOSR0ZRb9khttps://youtu.be/zkOSR0ZRb9k"
}];

function populateListView() {
    Ti.API.trace("[DashboardController.js  >>  populateListView() >>]");
    if (!_.isEmpty(videoInfo)) {
        for (var i = 0; i < videoInfo.length; i++) {
            var item = {
                template : "videoTemplate",
                iconId : {
                    image : videoInfo[i].pic
                },
                titleId : {
                    text : videoInfo[i].info
                },
                dateId : {
                    text : videoInfo[i].date
                },
                urlId : {
                    text : videoInfo[i].url
                },
                properties : {
                    backgroundColor : "transparent"
                }
            };
            sections.push(item);
        }
       $.listSection.setItems(sections);
    }
}
populateListView();
$.lView.addEventListener('click',function(e){
    var dataItem = $.listSection.getItemAt(e.itemIndex);
});
</code>```

And the .xml file for DashboardController isthis :

```<code><Alloy>
    <View id="win2" class="container">
        <View id = "v1" class ="view1"  layout ="horizontal" >
            <Button class="btnBack" ></Button>
            <Label  class = "label1">LIST VIEW EXAMPLE</Label>
        </View>
        <View class="view2">
            <TextField id = "txtSearch"></TextField>
        </View>
        <ListView id = "lView" class = "list1" >
             <Templates>
                    <ItemTemplate name="videoTemplate">
                        <View class = "viewTemplate" layout = "horizontal" >
                            <ImageView bindId="iconId"  id="pic"  />
                            <View class = "viewTitle" layout = "vertical" >
                                <Label bindId="titleId" id="info" />
                                <View class="viewDtUrl" layout="horizontal" >
                                    <Label bindId="dateId" id="date" />
                                    <Label bindId="urlId" id ="url" />
                                </View>
                            </View>
                        </View>
                    </ItemTemplate>
            </Templates>
            <ListSection id = "listSection">
            </ListSection>
        </ListView>
    </View>
</Alloy>
</code>```

This is the .xml file of the controller that will be rendering the video player (VideoPlayerController) is this:

```<code><Alloy>
    <View class="container">
        <VideoPlayer class = "video"></VideoPlayer>
        <View class="videoView">
            <Label class="titleInfo"></Label>
            <View class = "infoLabel">
                <Label class="dateInfo"></Label>
                <Label class="urlInfo"></Label>
            </View>>
        </View>
    </View>
</Alloy>
</code>```

答:
You are very close.  Here are a couple of items:

Move the first line in DashboarController.js, Alloy.createController('VideoPlayerController',videoInfo[i]).getView(); down into the lView event listener.

The listview event we want to listen for is called itemclick, not click, so change that.

The videoInfo array is serving as our data collection.  The itemclick callback will be returned the index of the row clicked, and this will match the order of our videoInfo array, so we can just pass it to createController as: videoInfo[e.itemIndex]

Lastly, createController is returning a view with .getView(), in our case, this probably a TiUIWindow object, so we need to open that window with .open().

This gives us:

```<code>$.lView.addEventListener('itemclick', function (e) {
    Alloy.createController('VideoPlayerController', videoInfo[e.itemIndex]).getView().open();
});
</code>```

Now in our VideoPlayerController.js, we'll have something like:

```<code>var args = $.args;
console.log('video url:' + args.url);
</code>```

From there, you can use the data passed to args to set up the rest of your window.

Title: List view itemclick event appcelerator

Body:
I have a JSON defined in the code with and image, a title, a date and  a url. This will be used to populate the list view. On the click event of any list item, I need to navigate to a different controller and render the view in it having the videoplayer that plays the video according to the clicked list item's url and i want to display the date and title too.
I am not understanding how to code this in the itemClick event. Please help!

This is my .js file for DashboardController.

Alloy.createController('VideoPlayerController',videoInfo[i]).getView();
var sections = [];
//JSON to populate the listview
var videoInfo = [{
    pic : "/Images/playButton.png",
    info : "This in the the title for the first video.",
    date : "03/07/2017",
    url : "https://youtu.be/zkOSR0ZRb9khttps://youtu.be/zkOSR0ZRb9k"
}, {
    pic : "/Images/playButton.png",
    info : "This in the the title for the second video.",
    date : "03/07/2017",
    url : "https://youtu.be/zkOSR0ZRb9khttps://youtu.be/zkOSR0ZRb9k"
}, {
    pic : "/Images/playButton.png",
    info : "This in the the title for the third video.",
    date : "03/07/2017",
    url : "https://youtu.be/zkOSR0ZRb9khttps://youtu.be/zkOSR0ZRb9k"
}];

function populateListView() {
    Ti.API.trace("[DashboardController.js  >>  populateListView() >>]");
    if (!_.isEmpty(videoInfo)) {
        for (var i = 0; i < videoInfo.length; i++) {
            var item = {
                template : "videoTemplate",
                iconId : {
                    image : videoInfo[i].pic
                },
                titleId : {
                    text : videoInfo[i].info
                },
                dateId : {
                    text : videoInfo[i].date
                },
                urlId : {
                    text : videoInfo[i].url
                },
                properties : {
                    backgroundColor : "transparent"
                }
            };
            sections.push(item);
        }
       $.listSection.setItems(sections);
    }
}
populateListView();
$.lView.addEventListener('click',function(e){
    var dataItem = $.listSection.getItemAt(e.itemIndex);
});

And the .xml file for DashboardController isthis :

<Alloy>
    <View id="win2" class="container">
        <View id = "v1" class ="view1"  layout ="horizontal" >
            <Button class="btnBack" ></Button>
            LIST VIEW EXAMPLE
        </View>
        <View class="view2">
            <TextField id = "txtSearch"></TextField>
        </View>
        <ListView id = "lView" class = "list1" >
             <Templates>
                    <ItemTemplate name="videoTemplate">
                        <View class = "viewTemplate" layout = "horizontal" >
                            <ImageView bindId="iconId"  id="pic"  />
                            <View class = "viewTitle" layout = "vertical" >

                                <View class="viewDtUrl" layout="horizontal" >

                                </View>
                            </View>
                        </View>
                    </ItemTemplate>
            </Templates>
            <ListSection id = "listSection">
            </ListSection>
        </ListView>
    </View>
</Alloy>

This is the .xml file of the controller that will be rendering the video player (VideoPlayerController) is this:

<Alloy>
    <View class="container">
        <VideoPlayer class = "video"></VideoPlayer>
        <View class="videoView">

            <View class = "infoLabel">

            </View>>
        </View>
    </View>
</Alloy>

Body:
You are very close.  Here are a couple of items:

Move the first line in DashboarController.js, Alloy.createController('VideoPlayerController',videoInfo[i]).getView(); down into the lView event listener.

The listview event we want to listen for is called itemclick, not click, so change that.

The videoInfo array is serving as our data collection.  The itemclick callback will be returned the index of the row clicked, and this will match the order of our videoInfo array, so we can just pass it to createController as: videoInfo[e.itemIndex]

Lastly, createController is returning a view with .getView(), in our case, this probably a TiUIWindow object, so we need to open that window with .open().

This gives us:

$.lView.addEventListener('itemclick', function (e) {
    Alloy.createController('VideoPlayerController', videoInfo[e.itemIndex]).getView().open();
});

Now in our VideoPlayerController.js, we'll have something like:

var args = $.args;
console.log('video url:' + args.url);

From there, you can use the data passed to args to set up the rest of your window.


问:
Dynamically autosize DIV on resolution change
I I have div. Inside of this div, i placed countdown timer. I need to make it responsive. It is responsive if I refresh page after I resolution change( if changeing browser size and setting exact resolution ), but when you zoom page or changing my browser size it is keeping same big size. Here is picture:
picture of countdown while i am zooming

var timer,
  $win = $(window);

$win.on('resize', function() {
  clearTimeout(timer);
  timer = setTimeout(function() {
    $("#DateCountdown").height($win.height());
  }, 500);

});
$("#DateCountdown").TimeCircles({
  "animation": "smooth",
  "bg_width": 0.5,
  "fg_width": 0.03,
  "circle_bg_color": "#111111111",
  "time": {
    "Days": {
      "text": "Дней",
      "color": "#FFCC66",
      "show": true
    },
    "Hours": {
      "text": "Часов",
      "color": "#99CCFF",
      "show": true
    },
    "Minutes": {
      "text": "Минут",
      "color": "#BBFFBB",
      "show": true
    },
    "Seconds": {
      "text": "Секунд",
      "color": "#ff8080",
      "show": true
    }
  }
});

(function($) {```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/**
 * This element is created inside your target element
 * It is used so that your own element will not need to be altered
 **/

.time_circles {
  position: relative;
  width: 100%;
  height: 100%;
}

/**
 * This is all the elements used to house all text used
 * in time circles
 **/

.time_circles>div {
  position: absolute;
  text-align: center;
}

/**
 * Titles (Days, Hours, etc)
 **/

.time_circles>div>h4 {
  color: #ffffff;
  font-size: 11pt;
  margin: 0;
  padding: 0;
  text-align: center;
  text-transform: uppercase;
  font-family: 'Century Gothic', Arial;
  line-height: 1;
}

/**
 * Time numbers, ie: 12
 **/

.time_circles>div>span {
  color: #ffffff;
  margin: 0;
  padding: 0;
  display: block;
  width: 100%;
  text-align: center;
  font-family: 'Century Gothic', Arial;
  line-height: 1;
  font-weight: bold;
}</code>```

До следующего урожая осталось

```
</div>
</div>
</p>

<p>Here is script for width and height which is working onload. How to do it dynamically without refresh</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>        // Determine the needed width and height of TimeCircles
        var height = this.element.offsetHeight;
        var width = this.element.offsetWidth;
        if (height === 0)
            height = $(this.element).height();
        if (width === 0)
            width = $(this.element).width();

        if (height === 0 && width > 0)
            height = width / this.data.drawn_units.length;
        else if (width === 0 && height > 0)
            width = height * this.data.drawn_units.length;

        // Create our canvas and set it to the appropriate size
        var canvasElement = document.createElement('canvas');
        canvasElement.width = width;
        canvasElement.height = height;

        // Add canvas elements
        this.data.attributes.canvas = $(canvasElement);
        this.data.attributes.canvas.appendTo(this.container);

        // Check if the browser has browser support
        var canvasSupported = isCanvasSupported();
        // If the browser doesn't have browser support, check if explorer canvas is loaded
        // (A javascript library that adds canvas support to browsers that don't have it)
        if(!canvasSupported && typeof G_vmlCanvasManager !== "undefined") {
            G_vmlCanvasManager.initElement(canvasElement);
            limited_mode = true;
            canvasSupported = true;
        }
        if(canvasSupported) {
            this.data.attributes.context = canvasElement.getContext('2d');
        }

        this.data.attributes.item_size = Math.min(width / this.data.drawn_units.length, height);
        this.data.attributes.line_width = this.data.attributes.item_size * this.config.fg_width;
        this.data.attributes.radius = ((this.data.attributes.item_size * 0.8) - this.data.attributes.line_width) / 2;
        this.data.attributes.outer_radius = this.data.attributes.radius + 0.5 * Math.max(this.data.attributes.line_width, this.data.attributes.line_width * this.config.bg_width);</code>```

答:
You can use the window onresize event for this.

Check here for reference: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onresize

Simple code example:

```<code>var onResizeHandler = function() {
    // add your resize handling here
}

window.onresize = onResizeHandler;
</code>```

Click here to see this example in action.

Body:
I I have div. Inside of this div, i placed countdown timer. I need to make it responsive. It is responsive if I refresh page after I resolution change( if changeing browser size and setting exact resolution ), but when you zoom page or changing my browser size it is keeping same big size. Here is picture:
picture of countdown while i am zooming

var timer,
  $win = $(window);

$win.on('resize', function() {
  clearTimeout(timer);
  timer = setTimeout(function() {
    $("#DateCountdown").height($win.height());
  }, 500);

});
$("#DateCountdown").TimeCircles({
  "animation": "smooth",
  "bg_width": 0.5,
  "fg_width": 0.03,
  "circle_bg_color": "#111111111",
  "time": {
    "Days": {
      "text": "Дней",
      "color": "#FFCC66",
      "show": true
    },
    "Hours": {
      "text": "Часов",
      "color": "#99CCFF",
      "show": true
    },
    "Minutes": {
      "text": "Минут",
      "color": "#BBFFBB",
      "show": true
    },
    "Seconds": {
      "text": "Секунд",
      "color": "#ff8080",
      "show": true
    }
  }
});

(function($) {

/**
 * This element is created inside your target element
 * It is used so that your own element will not need to be altered
 **/

.time_circles {
  position: relative;
  width: 100%;
  height: 100%;
}

/**
 * This is all the elements used to house all text used
 * in time circles
 **/

.time_circles>div {
  position: absolute;
  text-align: center;
}

/**
 * Titles (Days, Hours, etc)
 **/

.time_circles>div>h4 {
  color: #ffffff;
  font-size: 11pt;
  margin: 0;
  padding: 0;
  text-align: center;
  text-transform: uppercase;
  font-family: 'Century Gothic', Arial;
  line-height: 1;
}

/**
 * Time numbers, ie: 12
 **/

.time_circles>div>span {
  color: #ffffff;
  margin: 0;
  padding: 0;
  display: block;
  width: 100%;
  text-align: center;
  font-family: 'Century Gothic', Arial;
  line-height: 1;
  font-weight: bold;
}

До следующего урожая осталось

Here is script for width and height which is working onload. How to do it dynamically without refresh

        // Determine the needed width and height of TimeCircles
        var height = this.element.offsetHeight;
        var width = this.element.offsetWidth;
        if (height === 0)
            height = $(this.element).height();
        if (width === 0)
            width = $(this.element).width();

        if (height === 0 && width > 0)
            height = width / this.data.drawn_units.length;
        else if (width === 0 && height > 0)
            width = height * this.data.drawn_units.length;

        // Create our canvas and set it to the appropriate size
        var canvasElement = document.createElement('canvas');
        canvasElement.width = width;
        canvasElement.height = height;

        // Add canvas elements
        this.data.attributes.canvas = $(canvasElement);
        this.data.attributes.canvas.appendTo(this.container);

        // Check if the browser has browser support
        var canvasSupported = isCanvasSupported();
        // If the browser doesn't have browser support, check if explorer canvas is loaded
        // (A javascript library that adds canvas support to browsers that don't have it)
        if(!canvasSupported && typeof G_vmlCanvasManager !== "undefined") {
            G_vmlCanvasManager.initElement(canvasElement);
            limited_mode = true;
            canvasSupported = true;
        }
        if(canvasSupported) {
            this.data.attributes.context = canvasElement.getContext('2d');
        }

        this.data.attributes.item_size = Math.min(width / this.data.drawn_units.length, height);
        this.data.attributes.line_width = this.data.attributes.item_size * this.config.fg_width;
        this.data.attributes.radius = ((this.data.attributes.item_size * 0.8) - this.data.attributes.line_width) / 2;
        this.data.attributes.outer_radius = this.data.attributes.radius + 0.5 * Math.max(this.data.attributes.line_width, this.data.attributes.line_width * this.config.bg_width);

Body:
You can use the window onresize event for this.

Check here for reference: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onresize

Simple code example:

var onResizeHandler = function() {
    // add your resize handling here
}

window.onresize = onResizeHandler;

Click here to see this example in action.


问:
Does Scala run on the JamVM
Does Scala 2.8 run on the JamVM? </p>

答:
Scala produces 100% valid Bytecode.

So the real question becomes: "Is JamVM compatible with valid Java bytecode?"

That one I can't answer, but I suspect that it is :)

Title: Does Scala run on the JamVM

Body: Does Scala 2.8 run on the JamVM?


问:
Java Void to Scala Unit
I have a java library method requiring a class of Void as a parameter. for example, in com.mongodb.async.client.MongoCollection:

```<code>void insertOne(TDocument document, SingleResultCallback<Void> callback);
</code>```

I'm accessing this method from scala. Scala uses the type Unit as equivalent of Void (correct me if I'm wrong please)

How can I pass a SingleResultCallback[Unit] (instead of SingleResultCallback[Void]) to this method? The compiler is not allowing this. Shouldn't it be picking this up?

答:
Java's Void is from my experience usually used with null as its only value, where as Unit also only has one value: ().
SingleResultCallback is just a SAM type of (T, Throwable) => Unit. This means we can convert these from and to Unit if we want:

```<code>def toUnit(cb: SingleResultCallback[Void]): SingleResultCallback[Unit] =
  (u, throwable) => cb(null, throwable)

def fromUnit(cb: SingleResultCallback[Unit]): SingleResultCallback[Void] =
  (v, throwable) => cb((), throwable)
</code>```

This is assuming you use Scala 2.12.*. Otherwise you will need to construct an Instance of SingleResultCallback using new.

Title: Java Void to Scala Unit

Body:
I have a java library method requiring a class of Void as a parameter. for example, in com.mongodb.async.client.MongoCollection:

void insertOne(TDocument document, SingleResultCallback<Void> callback);

I'm accessing this method from scala. Scala uses the type Unit as equivalent of Void (correct me if I'm wrong please)

How can I pass a SingleResultCallback[Unit] (instead of SingleResultCallback[Void]) to this method? The compiler is not allowing this. Shouldn't it be picking this up?

Body:
Java's Void is from my experience usually used with null as its only value, where as Unit also only has one value: ().
SingleResultCallback is just a SAM type of (T, Throwable) => Unit. This means we can convert these from and to Unit if we want:

def toUnit(cb: SingleResultCallback[Void]): SingleResultCallback[Unit] =
  (u, throwable) => cb(null, throwable)

def fromUnit(cb: SingleResultCallback[Unit]): SingleResultCallback[Void] =
  (v, throwable) => cb((), throwable)

This is assuming you use Scala 2.12.*. Otherwise you will need to construct an Instance of SingleResultCallback using new.