问:
How do you access an XML node with a colon (:) in it?
I am trying to access a Taleo RSS/XML feed and parse the data. I am using SimpleXML, and it is loading in all of the regular data correctly, such as <title>, <link>, etc.

However, there are several nodes that are formatted like <taleo:reqId> or <taleo:location>, and I can't seem to figure out how to access that data. It's not being returned by SimpleXML.

```<code>`$xml = simplexml_load_file('https://chp.tbe.taleo.net/chp03/ats/servlet/Rss?org=DRAGADOS&cws=1&WebPage=SRCHR&WebVersion=0&_rss_version=2');`
</code>```

Returns in web browser source:

```<code>`<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="https://chp.tbe.taleo.net/chp03/ats/rss/taleorssfeed.xsl" ?>
<?xml-stylesheet type="text/css" href="https://chp.tbe.taleo.net/chp03/ats/rss/taleorssfeed.css" ?>
<rss xmlns:taleo="urn:TBERss" version="2.0">
<channel>
<title>Dragados Job Feed</title>
<link>https://chp.tbe.taleo.net/dispatcher/servlet/DispatcherServlet?org=DRAGADOS&act=redirectCws&cws=1</link>
<description>Dragados Job Feed</description>
<language>en</language>
<pubDate>Tue, 07 Nov 2017 17:00:40 GMT</pubDate>
<ttl>60</ttl>
<item>
<title>Estimator</title>
<link>https://chp.tbe.taleo.net/chp03/ats/careers/requisition.jsp?org=DRAGADOS&cws=1&rid=1155</link>
<guid>https://chp.tbe.taleo.net/chp03/ats/careers/requisition.jsp?org=DRAGADOS&cws=1&rid=1155</guid>
<description> ..... </description>
<pubDate>Tue, 07 Nov 2017 17:00:40 GMT</pubDate>
<taleo:reqId>1155</taleo:reqId>
<taleo:location>Southern California Branch (bidding)</taleo:location>
<taleo:locationCountry>US</taleo:locationCountry>
<taleo:locationState>US-CA</taleo:locationState>
<taleo:locationCity>Costa Mesa</taleo:locationCity>
<taleo:department>West Coast Bidding</taleo:department>
<taleo:html-description> ... </taleo:html-description>
</item>
...`
</code>```

Returns in SimpleXML:

```<code>`object(SimpleXMLElement)#487 (2) { ["@attributes"]=> array(1) { ["version"]=> string(3) "2.0" } ["channel"]=> object(SimpleXMLElement)#486 (7) { ["title"]=> string(17) "Dragados Job Feed" ["link"]=> string(97) "https://chp.tbe.taleo.net/dispatcher/servlet/DispatcherServlet?org=DRAGADOS&act=redirectCws&cws=1" ["description"]=> string(17) "Dragados Job Feed" ["language"]=> string(2) "en" ["pubDate"]=> string(29) "Tue, 07 Nov 2017 17:00:40 GMT" ["ttl"]=> string(2) "60" ["item"]=> array(79) { [0]=> object(SimpleXMLElement)#485 (5) { ["title"]=> string(9) "Estimator" ["link"]=> string(87) "https://chp.tbe.taleo.net/chp03/ats/careers/requisition.jsp?org=DRAGADOS&cws=1&rid=1155" ["guid"]=> string(87) "https://chp.tbe.taleo.net/chp03/ats/careers/requisition.jsp?org=DRAGADOS&cws=1&rid=1155" ["description"]=> string(3580) " ...   " ["pubDate"]=> string(29) "Tue, 07 Nov 2017 17:00:40 GMT" }
...`
</code>```

答:
I find it easier sometimes to split out the data for different namespaces in this case.  So when going through the <item> data, you can extract all the elements for a specific namespace (the 'taleo' elements in this case) using ->children('namespaceURN') and it then access the data in a similar way to all the other times but using this new set of nodes as the basis.

```<code>foreach ( $xml->channel as $channel )   {
    echo "title=".$channel->title.PHP_EOL;
    foreach ( $channel->item as $item ) {
        echo "pubDate=".$item->pubDate.PHP_EOL;
        // Extract the elements for taleo namespace
        $taleo = $item->children("urn:TBERss");
        echo "taleo:reqId=".$taleo->reqId.PHP_EOL;
    }
}
</code>```

Body:
I am trying to access a Taleo RSS/XML feed and parse the data. I am using SimpleXML, and it is loading in all of the regular data correctly, such as <title>, <link>, etc.

However, there are several nodes that are formatted like <taleo:reqId> or <taleo:location>, and I can't seem to figure out how to access that data. It's not being returned by SimpleXML.

`$xml = simplexml_load_file('https://chp.tbe.taleo.net/chp03/ats/servlet/Rss?org=DRAGADOS&cws=1&WebPage=SRCHR&WebVersion=0&_rss_version=2');`

Returns in web browser source:

`<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="https://chp.tbe.taleo.net/chp03/ats/rss/taleorssfeed.xsl" ?>
<?xml-stylesheet type="text/css" href="https://chp.tbe.taleo.net/chp03/ats/rss/taleorssfeed.css" ?>
<rss xmlns:taleo="urn:TBERss" version="2.0">
<channel>
<title>Dragados Job Feed</title>
<link>https://chp.tbe.taleo.net/dispatcher/servlet/DispatcherServlet?org=DRAGADOS&act=redirectCws&cws=1</link>
<description>Dragados Job Feed</description>
<language>en</language>
<pubDate>Tue, 07 Nov 2017 17:00:40 GMT</pubDate>
<ttl>60</ttl>
<item>
<title>Estimator</title>
<link>https://chp.tbe.taleo.net/chp03/ats/careers/requisition.jsp?org=DRAGADOS&cws=1&rid=1155</link>
<guid>https://chp.tbe.taleo.net/chp03/ats/careers/requisition.jsp?org=DRAGADOS&cws=1&rid=1155</guid>
<description> ..... </description>
<pubDate>Tue, 07 Nov 2017 17:00:40 GMT</pubDate>
<taleo:reqId>1155</taleo:reqId>
<taleo:location>Southern California Branch (bidding)</taleo:location>
<taleo:locationCountry>US</taleo:locationCountry>
<taleo:locationState>US-CA</taleo:locationState>
<taleo:locationCity>Costa Mesa</taleo:locationCity>
<taleo:department>West Coast Bidding</taleo:department>
<taleo:html-description> ... </taleo:html-description>
</item>
...`

Returns in SimpleXML:

`object(SimpleXMLElement)#487 (2) { ["@attributes"]=> array(1) { ["version"]=> string(3) "2.0" } ["channel"]=> object(SimpleXMLElement)#486 (7) { ["title"]=> string(17) "Dragados Job Feed" ["link"]=> string(97) "https://chp.tbe.taleo.net/dispatcher/servlet/DispatcherServlet?org=DRAGADOS&act=redirectCws&cws=1" ["description"]=> string(17) "Dragados Job Feed" ["language"]=> string(2) "en" ["pubDate"]=> string(29) "Tue, 07 Nov 2017 17:00:40 GMT" ["ttl"]=> string(2) "60" ["item"]=> array(79) { [0]=> object(SimpleXMLElement)#485 (5) { ["title"]=> string(9) "Estimator" ["link"]=> string(87) "https://chp.tbe.taleo.net/chp03/ats/careers/requisition.jsp?org=DRAGADOS&cws=1&rid=1155" ["guid"]=> string(87) "https://chp.tbe.taleo.net/chp03/ats/careers/requisition.jsp?org=DRAGADOS&cws=1&rid=1155" ["description"]=> string(3580) " ...   " ["pubDate"]=> string(29) "Tue, 07 Nov 2017 17:00:40 GMT" }
...`

Body:
I find it easier sometimes to split out the data for different namespaces in this case.  So when going through the <item> data, you can extract all the elements for a specific namespace (the 'taleo' elements in this case) using ->children('namespaceURN') and it then access the data in a similar way to all the other times but using this new set of nodes as the basis.

foreach ( $xml->channel as $channel )   {
    echo "title=".$channel->title.PHP_EOL;
    foreach ( $channel->item as $item ) {
        echo "pubDate=".$item->pubDate.PHP_EOL;
        // Extract the elements for taleo namespace
        $taleo = $item->children("urn:TBERss");
        echo "taleo:reqId=".$taleo->reqId.PHP_EOL;
    }
}


来源: stackexchange

问:
how to put background image path from remote web site?
I need grab images from Imgur to My web page background image

```<code> <div style="background-image:url(); width:100%; height:100%;" class="zoom" >
</code>```

My image path is https://imgur.com/a/NbUpX

then how can I put this image to my background image url?

答:
or in your CSS directly as background-image: url("https://i.imgur.com/QdMWFHZ.jpg")

since you need background of webpage it would be part of the body attribute like (CSS):

body  {
    background-image: url("https://i.imgur.com/QdMWFHZ.jpg")
}```

You can test it here

ContentLicense: CC BY-SA 3.0

Body:
I need grab images from Imgur to My web page background image

My image path is https://imgur.com/a/NbUpX

then how can I put this image to my background image url?

Body:
or in your CSS directly as background-image: url("https://i.imgur.com/QdMWFHZ.jpg")

since you need background of webpage it would be part of the body attribute like (CSS):

body  {
    background-image: url("https://i.imgur.com/QdMWFHZ.jpg")
}

You can test it here


问:
Select Price value only from td in python
I am trying to capture just price value from html td tag but the problem is there are other td with same class name: please see the picture below. enter image description here

here is the code i have written

```<code>from  builtins import any as b_any
from urllib.parse import urlparse
from urllib.parse import urljoin
from collections import Counter
import urllib.request
import csv
import schedule
import time
import re
from bs4 import BeautifulSoup

url="http://offer.ebay.es/ws/eBayISAPI.dll?ViewBidsLogin&item=122713288532&rt=nc&_trksid=p2047675.l2564"

req = urllib.request.Request(url, headers={'User-agent': 'Mozilla/5.0'})

htmlpage = urllib.request.urlopen(req)

html = htmlpage.read().decode('utf-8')

soup = BeautifulSoup(html,"html.parser")

table = soup.find_all('td',{'class':'onheadNav'})

'''for txt in table:
    nametxt = txt.text
    result = ''.join([i for i in nametxt if not i.isdigit()])
    cleantxt = result.replace('(','')
    print(cleantxt.replace(')',''))

    rank = txt.a.text
    print(rank)'''
price = soup.select('td.contentValueFont')
for pr in price:
    print(pr.text)
</code>```

If i slice price in for loop it will get only first price but i want to have all prices at once.

Edited description:
I want to capture all prices but problem is there are three td with same class name one td is for price one for Cantidad(quantity) and the one which is for date these all have same class. and when i try to get only price section my code returns all three td's. I hope you get it now

答:
lazy way:</p>

```<code>soup = BeautifulSoup(html,"html.parser")

table = soup.find_all('table')

trs = table[9].select('tr') # You should select the table first (use your way)

for tr in trs: # loop the tr in the table
    if len(tr.select('td')) > 2: # check length
        print(tr.select('td')[2].text) # select third td
</code>```

Body:
I am trying to capture just price value from html td tag but the problem is there are other td with same class name: please see the picture below. enter image description here

here is the code i have written

from  builtins import any as b_any
from urllib.parse import urlparse
from urllib.parse import urljoin
from collections import Counter
import urllib.request
import csv
import schedule
import time
import re
from bs4 import BeautifulSoup

url="http://offer.ebay.es/ws/eBayISAPI.dll?ViewBidsLogin&item=122713288532&rt=nc&_trksid=p2047675.l2564"

req = urllib.request.Request(url, headers={'User-agent': 'Mozilla/5.0'})

htmlpage = urllib.request.urlopen(req)

html = htmlpage.read().decode('utf-8')

soup = BeautifulSoup(html,"html.parser")

table = soup.find_all('td',{'class':'onheadNav'})

'''for txt in table:
    nametxt = txt.text
    result = ''.join([i for i in nametxt if not i.isdigit()])
    cleantxt = result.replace('(','')
    print(cleantxt.replace(')',''))

    rank = txt.a.text
    print(rank)'''
price = soup.select('td.contentValueFont')
for pr in price:
    print(pr.text)

If i slice price in for loop it will get only first price but i want to have all prices at once.

Edited description:
I want to capture all prices but problem is there are three td with same class name one td is for price one for Cantidad(quantity) and the one which is for date these all have same class. and when i try to get only price section my code returns all three td's. I hope you get it now

Body:
lazy way:

soup = BeautifulSoup(html,"html.parser")

table = soup.find_all('table')

trs = table[9].select('tr') # You should select the table first (use your way)

for tr in trs: # loop the tr in the table
    if len(tr.select('td')) > 2: # check length
        print(tr.select('td')[2].text) # select third td


问:
SQL Merge Join two tables from two separate databases
I'm trying to execute a simple merge join query on Microsoft SQL Server, using python SQL Alchemy core.

First let me explain how it's done using the server management studio:

```<code>MERGE [Database1].[Schema1].[Table1] table1
USING [Database2].[Schema2].[Table2] table2
ON table1.[Key] = table2.[Key]
WHEN MATCHED THEN
UPDATE
SET table1.[Column] = table2.[Column];
</code>```

This works fine and the Column is set successfully.

But when I do this using python:

```<code>DB_TARGET = {
'drivername': 'mssql+pyodbc',
'servername': 'localhost',
'port': '1443',
'username': 'user1',
'password': 'pass',
'driver': 'ODBC Driver 13 for SQL Server',
'trusted_connection': 'yes',
'legacy_schema_aliasing': False
}

params = urllib.parse.quote_plus("DRIVER={" + DB_TARGET['driver'] + "}" +
                              ";SERVER=" + DB_TARGET['servername'] +
                              ";UID=" + DB_TARGET['username']+
                              ";PWD=" + DB_TARGET['password'])

engine1 = create_engine( DB_TARGET['drivername'] + ":///?odbc_connect=%s" % params)
metadata = MetaData(bind=engine1)
conn = engine1.connect()

q="MERGE [Database1].[Schema1].[Table1] table1 \
USING [Database2].[Schema2].[Table2] table2 \
ON table1.[Key] = table2.[Key] \
WHEN MATCHED THEN \
UPDATE \
SET table1.[Column] = table2.[Column];"

conn.execute(q)
conn.close()
</code>```

Nothing happens, no exception thrown, and the Column values are not affected.

I have checked SQL Server profiler and made sure that the query is being submitted.

I tried executing more simple queries, like:

```<code>q="SELECT * FROM TABLE1"
</code>```

Works just fine.

What seems to be the problem here ?

答:
SQLAlchemy does not by default recognize the MERGE statement as a data changing operation, and so does not issue a commit when you're using a connection without using a Transaction. You should read "Understanding Autocommit". So either use an explicit transaction:

```<code>with conn.begin() as trans:
    conn.execute(q)
</code>```

or inform SQLAlchemy that this statement should autocommit:

```<code>conn.execute(text(q).execution_options(autocommit=True))
</code>```

As an aside, Python supports multiline strings with triple quotes without backslashes, unless you specifically want to avoid the newlines:

```<code>q = """MERGE [Database1].[Schema1].[Table1] table1
USING [Database2].[Schema2].[Table2] table2
ON table1.[Key] = table2.[Key]
WHEN MATCHED THEN
UPDATE
SET table1.[Column] = table2.[Column];"""
</code>```

Body:
I'm trying to execute a simple merge join query on Microsoft SQL Server, using python SQL Alchemy core.

First let me explain how it's done using the server management studio:

MERGE [Database1].[Schema1].[Table1] table1
USING [Database2].[Schema2].[Table2] table2
ON table1.[Key] = table2.[Key]
WHEN MATCHED THEN
UPDATE
SET table1.[Column] = table2.[Column];

This works fine and the Column is set successfully.

But when I do this using python:

DB_TARGET = {
'drivername': 'mssql+pyodbc',
'servername': 'localhost',
'port': '1443',
'username': 'user1',
'password': 'pass',
'driver': 'ODBC Driver 13 for SQL Server',
'trusted_connection': 'yes',
'legacy_schema_aliasing': False
}

params = urllib.parse.quote_plus("DRIVER={" + DB_TARGET['driver'] + "}" +
                              ";SERVER=" + DB_TARGET['servername'] +
                              ";UID=" + DB_TARGET['username']+
                              ";PWD=" + DB_TARGET['password'])

engine1 = create_engine( DB_TARGET['drivername'] + ":///?odbc_connect=%s" % params)
metadata = MetaData(bind=engine1)
conn = engine1.connect()

q="MERGE [Database1].[Schema1].[Table1] table1 \
USING [Database2].[Schema2].[Table2] table2 \
ON table1.[Key] = table2.[Key] \
WHEN MATCHED THEN \
UPDATE \
SET table1.[Column] = table2.[Column];"

conn.execute(q)
conn.close()

Nothing happens, no exception thrown, and the Column values are not affected.

I have checked SQL Server profiler and made sure that the query is being submitted.

I tried executing more simple queries, like:

q="SELECT * FROM TABLE1"

Works just fine.

What seems to be the problem here ?

Body:
SQLAlchemy does not by default recognize the MERGE statement as a data changing operation, and so does not issue a commit when you're using a connection without using a Transaction. You should read "Understanding Autocommit". So either use an explicit transaction:

with conn.begin() as trans:
    conn.execute(q)

or inform SQLAlchemy that this statement should autocommit:

conn.execute(text(q).execution_options(autocommit=True))

As an aside, Python supports multiline strings with triple quotes without backslashes, unless you specifically want to avoid the newlines:

q = """MERGE [Database1].[Schema1].[Table1] table1
USING [Database2].[Schema2].[Table2] table2
ON table1.[Key] = table2.[Key]
WHEN MATCHED THEN
UPDATE
SET table1.[Column] = table2.[Column];"""


问:
VeriFIX test automation in Jenkins
We are working with a client that uses VeriFIX to test their FIX message flow.  Whilst they have built up lots of tests in many suites, it is a manual process to run them and to collate the results.

On the VeriFIX website it says

Incorporate tests into nightly builds using VeriFIX’s command-line script player.

but I cannot find any details on how to to it.  Does anyone have any experience in running VeriFIX tests in a continuous integration server (ideally a Jenkins pipeline).

Many thanks.

答:
You can run VeriFIX playlists in batch mode from the command line:

"%VERIFIX_HOME%\verifixbatch\verifixbatch.exe" -version "FIX (x.y)" -playlist "myplaylist" -disablelogging "false"

Title: VeriFIX test automation in Jenkins

ContentLicense: CC BY-SA 4.0


问:
Ansible jinja block
How to comment a particular line only by using jinja template.
I have my line
/var/log/maillog
I have tried

```<code>{% comment %}{{ var }} {% endcomment %}
</code>```

also

```<code>{% if var is defined %}
{{ var }}
{% endif %}
</code>```

答:
Can you try this:</p>

```<code>{# {{ var }} #}
</code>```

Title: Ansible jinja block

Body:
How to comment a particular line only by using jinja template.
I have my line
/var/log/maillog
I have tried

{% comment %}{{ var }} {% endcomment %}

also

{% if var is defined %}
{{ var }}
{% endif %}

Body:
Can you try this:

{# {{ var }} #}


问:
How to set up Mockito for Kotlin and Android
I want to use Mockito for unit testing, so I added the Mockito library into my gradle dependencies.

```<code>testImplementation 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:2.12.0'
</code>```

But still, I can not use any Mockito annotations.

/androidTest/ExampleTest.kt

```<code>@RunWith(MockitoJUnitRunner::class) // Unresolved reference MockitoJUnitRunner
@Mock // Unresolved reference Mock
</code>```

What I'm missing it?

答:
You may need another dependency:

```<code>androidTestCompile 'org.mockito:mockito-android:2.12.0'
</code>```

Alternatively, you can try manually importing the annotations:

```<code>import static org.mockito.Mockito.*;
</code>```

It could be that it didn't import properly and that's why it showed as an unresolved reference. Auto-import has its flaws

Body:
I want to use Mockito for unit testing, so I added the Mockito library into my gradle dependencies.

testImplementation 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:2.12.0'

But still, I can not use any Mockito annotations.

/androidTest/ExampleTest.kt

@RunWith(MockitoJUnitRunner::class) // Unresolved reference MockitoJUnitRunner
@Mock // Unresolved reference Mock

What I'm missing it?

Body:
You may need another dependency:

androidTestCompile 'org.mockito:mockito-android:2.12.0'

Alternatively, you can try manually importing the annotations:

import static org.mockito.Mockito.*;

It could be that it didn't import properly and that's why it showed as an unresolved reference. Auto-import has its flaws


问:
Xamarin UiTest make some tests only executable on android or iOS?
I implemented UITest for the android version of an app and i am now trying to adapt the UI Tests code so it would work for both iOS and Android.

The thing is that there are really specific functions i've created for Android testing and they can't be used for iOS since the views are not concieved the same way at all.

Here are my questions:

-Is it possible to make certain test function executable only on iOS or Android (only one, not both) but within the same test.cs file ?

-What is the most conventional and clean way of organizing Ui Tests for Android or iOS?

Same Project and same files for both platform("mySolution.UiTests" project and "Testfile.cs")

Same Project different files for each platform ("mySolution.UiTests" project and "TestfileAndroid.cs" + "TestfileiOS.cs" )

Different Projects for each platform ("mySolution.iOS.UiTests" and "mySolution.Droid.Uitests")

答:
I can give you an answer to the first question:

You can mark test fixtures with a platform attributle like this:
[TestFixture(Platform.Android)] to be executed on android and     [TestFixture(Platform.iOS)] to be executed on ios.

Provide both attributes above the class to make a test class executable on both platforms.
I do not know if it is possbile for single tests too as I currently only needed it for whole classes.

So the useage could be like this

```<code>[TestFixture(Platform.Android)]
[TestFixture(Platform.iOS)]
public class FooTests
{ ... }
</code>```

BR
Hubertus

Body:
I can give you an answer to the first question:

You can mark test fixtures with a platform attributle like this:
[TestFixture(Platform.Android)] to be executed on android and     [TestFixture(Platform.iOS)] to be executed on ios.

Provide both attributes above the class to make a test class executable on both platforms.
I do not know if it is possbile for single tests too as I currently only needed it for whole classes.

So the useage could be like this

[TestFixture(Platform.Android)]
[TestFixture(Platform.iOS)]
public class FooTests
{ ... }

BR
Hubertus


问:
Print DBMS_OUTPUT.put_line with Hibernate or Spring
I would like to know if Hibernate or Spring or any 3rd party lib provide the ability of printing DBMS_OUTPUT.put_line messages directly to system.out or a file of log.

The purpose is to have both PLSQL log messages and java log messages in the console.

I know there is a similar question of which the answer is to turn PLSQL procedure to function in returning the log message, but this doesn't suite my situation. In fact my log message is too complex that returning it in a function is impossible.

I have read this https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:45027262935845 and got inspiration but I'm wondering if there is an out of box solution to avoid whales reproducing.

答:
Since nobody answerred this question, I suppose there isn't any out-of-box solution. So I built it myself and post my codes here for whom it may interests.

Anyone who want to improve this solution is welcome! Just don't be shame to share yours!

Solution based on Spring AOP. An annotation @DbmsOutput is created for adding DBMS_OUTPUT aware ability on relating methods.

Env : Maven + Spring 4.2.6 + Hibernate 5.1.0

Step 1: adding Spring AOP dependencies

```<code><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>4.2.6.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.8.4</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.4</version>
</dependency>
</code>```

Step 2: creating @DbmsOutput

```<code>import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface DbmsOutput {
}
</code>```

Step 3: creating interceptor for all methods declared with @DbmsOutput.

```<code>import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.jdbc.Work;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

@Aspect
@Order(Ordered.LOWEST_PRECEDENCE)
public class DbmsOutputAspect {

    private static final Logger LOGGER = Logger.getLogger(DbmsOutputAspect.class);

    @Autowired
    protected SessionFactory sessionFactory;
    /**
     * make Dbms output aware enable/disable configurable in spring bean declaration
     */
    private boolean enable = true;
    private int size = 1000000;

    public boolean isEnable() {
        return enable;
    }

    public void setEnable(final boolean enable) {
        this.enable = enable;
    }

    public int getSize() {
        return size;
    }

    public void setSize(final int size) {
        this.size = size;
    }

    @Pointcut("execution(@DbmsOutput * *(..))")
    public void DbmsOutputInterceptMethod() {
    }

    @Around("DbmsOutputInterceptMethod()")
    public Object around(final ProceedingJoinPoint point)
            throws Throwable {

        if (isEnable()) {
            LOGGER.debug("before DBMS_OUTPUT point cut");
            Query queryEnable = sessionFactory.getCurrentSession().createSQLQuery("call dbms_output.enable(:size)");
            queryEnable.setParameter("size", getSize());
            queryEnable.executeUpdate();
        }
        try {
            return point.proceed(point.getArgs());
        } finally {
            if (isEnable()) {
                sessionFactory.getCurrentSession().doWork(new Work() {

                    @Override
                    public void execute(final Connection connection)
                            throws SQLException {

                        CallableStatement show_stmt = connection.prepareCall(
                                "declare " +
                                        " l_line varchar2(255); " +
                                        " l_done number; " +
                                        " l_buffer long; " +
                                        "begin " +
                                        " loop " +
                                        " exit when length(l_buffer)+255 > :maxbytes OR l_done = 1; " +
                                        " dbms_output.get_line( l_line, l_done ); " +
                                        " l_buffer := l_buffer || l_line || chr(10); " +
                                        " end loop; " +
                                        " :done := l_done; " +
                                        " :buffer := l_buffer; " +
                                        "end;");
                        int done = 0;

                        show_stmt.registerOutParameter(2, java.sql.Types.INTEGER);
                        show_stmt.registerOutParameter(3, java.sql.Types.VARCHAR);

                        for (;;) {
                            show_stmt.setInt(1, 32000);
                            show_stmt.executeUpdate();
                            LOGGER.info(show_stmt.getString(3));
                            done = show_stmt.getInt(2);
                            if (done == 1) {
                                break;
                            }
                        }
                    }
                });
                Query queryDisable = sessionFactory.getCurrentSession().createSQLQuery("call dbms_output.disable()");
                queryDisable.executeUpdate();
                LOGGER.debug("after DBMS_OUTPUT point cut");
            }
        }
    }
}
</code>```

Step 4: Configuring DbmsOutputAspect and TransactionManager in Spring

```<code><!-- aspectj -->
<aop:aspectj-autoproxy proxy-target-class="true" />
<bean class="DbmsOutputAspect" />

<!-- transaction -->
<tx:annotation-driven transaction-manager="transactionManager" order="0" />
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory">
        <ref bean="sessionFactory" />
    </property>
</bean>
</code>```

Body:
Since nobody answerred this question, I suppose there isn't any out-of-box solution. So I built it myself and post my codes here for whom it may interests.

Anyone who want to improve this solution is welcome! Just don't be shame to share yours!

Solution based on Spring AOP. An annotation @DbmsOutput is created for adding DBMS_OUTPUT aware ability on relating methods.

Env : Maven + Spring 4.2.6 + Hibernate 5.1.0

Step 1: adding Spring AOP dependencies

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>4.2.6.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.8.4</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.4</version>
</dependency>

Step 2: creating @DbmsOutput

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface DbmsOutput {
}

Step 3: creating interceptor for all methods declared with @DbmsOutput.

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.jdbc.Work;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

@Aspect
@Order(Ordered.LOWEST_PRECEDENCE)
public class DbmsOutputAspect {

    private static final Logger LOGGER = Logger.getLogger(DbmsOutputAspect.class);

    @Autowired
    protected SessionFactory sessionFactory;
    /**
     * make Dbms output aware enable/disable configurable in spring bean declaration
     */
    private boolean enable = true;
    private int size = 1000000;

    public boolean isEnable() {
        return enable;
    }

    public void setEnable(final boolean enable) {
        this.enable = enable;
    }

    public int getSize() {
        return size;
    }

    public void setSize(final int size) {
        this.size = size;
    }

    @Pointcut("execution(@DbmsOutput * *(..))")
    public void DbmsOutputInterceptMethod() {
    }

    @Around("DbmsOutputInterceptMethod()")
    public Object around(final ProceedingJoinPoint point)
            throws Throwable {

        if (isEnable()) {
            LOGGER.debug("before DBMS_OUTPUT point cut");
            Query queryEnable = sessionFactory.getCurrentSession().createSQLQuery("call dbms_output.enable(:size)");
            queryEnable.setParameter("size", getSize());
            queryEnable.executeUpdate();
        }
        try {
            return point.proceed(point.getArgs());
        } finally {
            if (isEnable()) {
                sessionFactory.getCurrentSession().doWork(new Work() {

                    @Override
                    public void execute(final Connection connection)
                            throws SQLException {

                        CallableStatement show_stmt = connection.prepareCall(
                                "declare " +
                                        " l_line varchar2(255); " +
                                        " l_done number; " +
                                        " l_buffer long; " +
                                        "begin " +
                                        " loop " +
                                        " exit when length(l_buffer)+255 > :maxbytes OR l_done = 1; " +
                                        " dbms_output.get_line( l_line, l_done ); " +
                                        " l_buffer := l_buffer || l_line || chr(10); " +
                                        " end loop; " +
                                        " :done := l_done; " +
                                        " :buffer := l_buffer; " +
                                        "end;");
                        int done = 0;

                        show_stmt.registerOutParameter(2, java.sql.Types.INTEGER);
                        show_stmt.registerOutParameter(3, java.sql.Types.VARCHAR);

                        for (;;) {
                            show_stmt.setInt(1, 32000);
                            show_stmt.executeUpdate();
                            LOGGER.info(show_stmt.getString(3));
                            done = show_stmt.getInt(2);
                            if (done == 1) {
                                break;
                            }
                        }
                    }
                });
                Query queryDisable = sessionFactory.getCurrentSession().createSQLQuery("call dbms_output.disable()");
                queryDisable.executeUpdate();
                LOGGER.debug("after DBMS_OUTPUT point cut");
            }
        }
    }
}

Step 4: Configuring DbmsOutputAspect and TransactionManager in Spring

<!-- aspectj -->
<aop:aspectj-autoproxy proxy-target-class="true" />
<bean class="DbmsOutputAspect" />

<!-- transaction -->
<tx:annotation-driven transaction-manager="transactionManager" order="0" />
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory">
        <ref bean="sessionFactory" />
    </property>
</bean>


问:
Notify email when Azure Storage table gets new entry
Is there an inbuilt way to notify an email when a new entry is added to the Table?

I am asking for anything programatically just within their own UI

答:
The lastest Azure product updates covering event-driven applications suggest to adopt these application patterns to react to events published by Azure Storage. These docs/resources might help to explore the application pattern and current platform/framework support.

Azure Storage

Reacting to Blob storage events (preview)

Did not found anything similar for Azure Tables - what about suggesting this on UserVoice?

CosmosDB

Working with the change feed support in Azure Cosmos DB


问:
How to check the checksum through commandline?
I want to do something like this on commandline on my UNIX variant

```<code>if (shasum httpd-2.4.7.tar.bz2 == 19asdasdasd56462e44d61a093ea57e964cf0af05c0e) echo 'good to go'
</code>```

I dont want to write a separate script text page just to check this.

 This above thing is showing syntax error.
 But there must be a slick way to get around this?

How to do this?

答:
```<code>echo "19asdasdasd56462e44d61a093ea57e964cf0af05c0e  httpd-2.4.7.tar.bz2" \
  | shasum -c
</code>```

Body:
I want to do something like this on commandline on my UNIX variant

if (shasum httpd-2.4.7.tar.bz2 == 19asdasdasd56462e44d61a093ea57e964cf0af05c0e) echo 'good to go'

I dont want to write a separate script text page just to check this.

 This above thing is showing syntax error.
 But there must be a slick way to get around this?

How to do this?


问:
Decompress incoming HTTP SOAP requests in ASMX
I'm trying to get IIS to accept compressed SOAP/XML requests.

It seems that IIS does not support compressed HTTP requests out of the box. Any HTTP request with Content-Encoding: gzip or deflate returns HTTP error 400.

So I tried to add a DelegatingHandler via Global.asax as described in this related question:

Global.asax:

```<code>protected void Application_Start()
{
    GlobalConfiguration.Configuration.MessageHandlers.Add(new DecompressionHandler());
}
</code>```

But in case of ASMX no MessageHandlers seem to be executed (I've checked,  Application_Start is invoked, but the whole WebApi configuration seems to have no effect in ASMX).

So the question is - how to implement SOAP request decompression in an ASMX service?

答:
Was able to get it to work with a SoapExtension:

```<code>using System;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Services.Protocols;

/// <summary>
///   ASPX SOAP request decompression WebMethod annotation
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class CompressedRequestAttribute : SoapExtensionAttribute
{
  public override Type ExtensionType { get { return typeof(CompressedRequestExtension); } }
  public override int Priority { get { return 0; } set { } }
}

/// <summary>
///   ASPX SOAP request decompression implementation
/// </summary>
public class CompressedRequestExtension : SoapExtension
{
  public override object GetInitializer(Type serviceType) { return null; }

  public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute) { return null; }

  public override void Initialize(object initializer) { }

  Stream origStream;
  StreamDelegate wrappedStream = new StreamDelegate();

  public override void ProcessMessage(SoapMessage message) {
    switch (message.Stage) {
      case SoapMessageStage.BeforeDeserialize:
        if (message.ContentEncoding == "gzip") {
          wrappedStream.wrapped = new GZipStream(origStream, CompressionMode.Decompress, true);
          message.ContentEncoding = null;
        }
        else if (message.ContentEncoding == "deflate") {
          wrappedStream.wrapped = new DeflateStream(origStream, CompressionMode.Decompress, true);
          message.ContentEncoding = null;
        }
        else {
          goto default;
        }
        break;
      default:
        wrappedStream.wrapped = origStream;
        break;
    }
  }

  public override Stream ChainStream(Stream stream) {
    origStream = stream;
    return wrappedStream;
  }

}

public class StreamDelegate : Stream
{
  public Stream wrapped;
  public override bool CanRead { get { return wrapped.CanRead; } }
  public override bool CanSeek { get { return wrapped.CanSeek; } }
  public override bool CanWrite { get { return wrapped.CanWrite; } }
  public override long Length { get { return wrapped.Length; } }
  public override long Position { get { return wrapped.Position; } set { wrapped.Position = value; } }
  public override void Flush() { wrapped.Flush(); }
  public override int Read(byte[] buffer, int offset, int count) { return wrapped.Read(buffer, offset, count); }
  public override long Seek(long offset, SeekOrigin origin) { return wrapped.Seek(offset, origin); }
  public override void SetLength(long value) { wrapped.SetLength(value); }
  public override void Write(byte[] buffer, int offset, int count) { wrapped.Write(buffer, offset, count); }
}
</code>```

And then annotate each WebMethod with:

```<code>  [CompressedRequestAttribute]
</code>```

And a proof that it works:

POST /TestService/TestAction1.asmx HTTP/1.1
Host: localhost
Accept-Encoding: deflate, gzip
SOAPAction: http://example.com/TestService:action1
Content-Type: text/xml;charset=UTF-8
Content-Encoding: gzip
Content-Length: 321

<gzipped-request>

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
Content-Encoding: gzip
Content-Length: 10193

<gzipped-response>
```

Body:
I'm trying to get IIS to accept compressed SOAP/XML requests.

It seems that IIS does not support compressed HTTP requests out of the box. Any HTTP request with Content-Encoding: gzip or deflate returns HTTP error 400.

So I tried to add a DelegatingHandler via Global.asax as described in this related question:

Global.asax:

protected void Application_Start()
{
    GlobalConfiguration.Configuration.MessageHandlers.Add(new DecompressionHandler());
}

But in case of ASMX no MessageHandlers seem to be executed (I've checked,  Application_Start is invoked, but the whole WebApi configuration seems to have no effect in ASMX).

So the question is - how to implement SOAP request decompression in an ASMX service?

Body:
Was able to get it to work with a SoapExtension:

using System;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Services.Protocols;

/// <summary>
///   ASPX SOAP request decompression WebMethod annotation
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class CompressedRequestAttribute : SoapExtensionAttribute
{
  public override Type ExtensionType { get { return typeof(CompressedRequestExtension); } }
  public override int Priority { get { return 0; } set { } }
}

/// <summary>
///   ASPX SOAP request decompression implementation
/// </summary>
public class CompressedRequestExtension : SoapExtension
{
  public override object GetInitializer(Type serviceType) { return null; }

  public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute) { return null; }

  public override void Initialize(object initializer) { }

  Stream origStream;
  StreamDelegate wrappedStream = new StreamDelegate();

  public override void ProcessMessage(SoapMessage message) {
    switch (message.Stage) {
      case SoapMessageStage.BeforeDeserialize:
        if (message.ContentEncoding == "gzip") {
          wrappedStream.wrapped = new GZipStream(origStream, CompressionMode.Decompress, true);
          message.ContentEncoding = null;
        }
        else if (message.ContentEncoding == "deflate") {
          wrappedStream.wrapped = new DeflateStream(origStream, CompressionMode.Decompress, true);
          message.ContentEncoding = null;
        }
        else {
          goto default;
        }
        break;
      default:
        wrappedStream.wrapped = origStream;
        break;
    }
  }

  public override Stream ChainStream(Stream stream) {
    origStream = stream;
    return wrappedStream;
  }

}

public class StreamDelegate : Stream
{
  public Stream wrapped;
  public override bool CanRead { get { return wrapped.CanRead; } }
  public override bool CanSeek { get { return wrapped.CanSeek; } }
  public override bool CanWrite { get { return wrapped.CanWrite; } }
  public override long Length { get { return wrapped.Length; } }
  public override long Position { get { return wrapped.Position; } set { wrapped.Position = value; } }
  public override void Flush() { wrapped.Flush(); }
  public override int Read(byte[] buffer, int offset, int count) { return wrapped.Read(buffer, offset, count); }
  public override long Seek(long offset, SeekOrigin origin) { return wrapped.Seek(offset, origin); }
  public override void SetLength(long value) { wrapped.SetLength(value); }
  public override void Write(byte[] buffer, int offset, int count) { wrapped.Write(buffer, offset, count); }
}

And then annotate each WebMethod with:

  [CompressedRequestAttribute]

And a proof that it works:

POST /TestService/TestAction1.asmx HTTP/1.1
Host: localhost
Accept-Encoding: deflate, gzip
SOAPAction: http://example.com/TestService:action1
Content-Type: text/xml;charset=UTF-8
Content-Encoding: gzip
Content-Length: 321

<gzipped-request>

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
Content-Encoding: gzip
Content-Length: 10193

<gzipped-response>


问:
Pytorch How to convert images into tensor
I stored multiple images as below.

```<code>for name in image_names:
    images.append(cv2.imread("./train_mini/"+name))
</code>```

And I’d like to use those images in CNN training later. However, when I stored those data in “torch.utils.data.TensorDataset” like below, it shows error:

```<code>“RuntimeError: can’t convert a given np.ndarray to a tensor - it has an invalid type. The only supported types are: double, float, int64, int32, and uint8.”
</code>```

So I checked the data type of images, and it was “object”.

```<code>train = torch.utils.data.TensorDataset(torch.from_numpy(X_train), torch.from_numpy(Y_train))
</code>```

How can I solve this problem? I am completely stuck…

答: I think Pytorsh doesn't support ndarray of ndarrays, which is why you are seeing this error.</p>

Body:
I stored multiple images as below.

for name in image_names:
    images.append(cv2.imread("./train_mini/"+name))

And I’d like to use those images in CNN training later. However, when I stored those data in “torch.utils.data.TensorDataset” like below, it shows error:

“RuntimeError: can’t convert a given np.ndarray to a tensor - it has an invalid type. The only supported types are: double, float, int64, int32, and uint8.”

So I checked the data type of images, and it was “object”.

train = torch.utils.data.TensorDataset(torch.from_numpy(X_train), torch.from_numpy(Y_train))

How can I solve this problem? I am completely stuck…


问:
How do I check if an object matches certain rules?
I have an array of similar objects. I need a generic template for writing filter rules for this array.
For example, I have an array of movies:

```<code>const movies = [{
    title: 'movie 1',
    type: 'tv',
    genres: ['comedy', 'romantic']
}, {
    title: 'movie 2',
    type: 'serial',
    genres: ['comedy', 'romantic']
}, {
    title: 'movie 3',
    type: 'tv',
    genres: ['romantic', 'horror']
}]
</code>```

And rule

```<code>// Is Comedy movie
const rule = {
    relation: 'AND',
    items: [{
        property: 'type',
        value: 'tv'
    }, {
        property: 'genres',
        value: 'comedy'
    }]
}
</code>```

Result of checking:

```<code>// An improvised example of checking an object by a rule
checkObjByRule(rule, movies[0]) // -> true
checkObjByRule(rule, movies[1]) // -> false
checkObjByRule(rule, movies[2]) // -> false
</code>```

In real work, the object Movie, is much more complicated, has a number of nested properties. I'm trying to find a ready solution, a library, so that I can create complex rules and check them

答:
Try this approach

var movies = [{
  title: 'movie 1',
  type: 'tv',
  genres: ['comedy', 'romantic']
}, {
  title: 'movie 2',
  type: 'serial',
  genres: ['comedy', 'romantic']
}, {
  title: 'movie 3',
  type: 'tv',
  genres: ['romantic', 'horror']
}];
var rule = {
  relation: 'AND',
  items: [{
    property: 'type',
    value: 'tv'
  }, {
    property: 'genres',
    value: 'comedy'
  }]
}

function processRules(obj, rule) {
  return rule.items.reduce(function(a, b) {
    if (typeof a != "boolean") {
      var compareVal = obj[a.property];
      //compare the values here
      a = Array.isArray( compareVal ) ? compareVal.includes( a.value ) : compareVal == a.value;
    }
    compareVal = obj[b.property];
    b = Array.isArray( compareVal ) ? compareVal.includes( b.value ) : compareVal == b.value;
    //based on the relation use the logical operators
    return rule.relation == "AND" ? a && b : a || b;
  });
}
console.log( processRules( movies[0], rule ) );
console.log( processRules( movies[1], rule ) );
console.log( processRules( movies[2], rule ) );```

Body:
I have an array of similar objects. I need a generic template for writing filter rules for this array.
For example, I have an array of movies:

const movies = [{
    title: 'movie 1',
    type: 'tv',
    genres: ['comedy', 'romantic']
}, {
    title: 'movie 2',
    type: 'serial',
    genres: ['comedy', 'romantic']
}, {
    title: 'movie 3',
    type: 'tv',
    genres: ['romantic', 'horror']
}]

And rule

// Is Comedy movie
const rule = {
    relation: 'AND',
    items: [{
        property: 'type',
        value: 'tv'
    }, {
        property: 'genres',
        value: 'comedy'
    }]
}

Result of checking:

// An improvised example of checking an object by a rule
checkObjByRule(rule, movies[0]) // -> true
checkObjByRule(rule, movies[1]) // -> false
checkObjByRule(rule, movies[2]) // -> false

In real work, the object Movie, is much more complicated, has a number of nested properties. I'm trying to find a ready solution, a library, so that I can create complex rules and check them


问:
Assigning a class to the
 parent of an image
ETA - Solution found. Nice work Stack Overflow beauties!! What would I do without you ;) ;)

I'm building a carousel, some items have images, others don't. I need to be able to target the items without images for styling, so I'm trying to add a class to the div that wraps the image if that makes sense?

What I have is this :
For items with images:

      Day 1

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

<p><strong>For items without images :</strong></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-html lang-html prettyprint-override"><code><div class="carousel-item" style="width: 157.4px; margin-right: 2px;">
  <li>

      <span>Day 1</span>

  </li>
</div></code>```

And what I'm trying to do using jquery is add the class 'noImg' to the div 'carousel-item' what I've tried is many variations of this sort of thing :

$("div.carousel-item").addClass("noImg");
if ($(this).hasClass('.img-responsive')) {
  ("div.carousel-item").removeClass("noImg")
};
```

I've tried variations of .children .parent I've tried doing it the other way around and doing .find on image-responsive and adding classes that way.

Any suggestions of the 'you dope, you're missing this obvious thing' would very much be appreciated, Thanks very much in advance.

答:
The issue with your jQuery code in the example is that this has no context. It would related to the window, not the .carousel-item as you seem to be expecting.

Also note that your HTML is invalid. li elements must be contained within a parent ul.

To make this work you can simply use a combination of :not() and :has() to find the containers which do not have an img element, like this:

$('.carousel-item:not(:has(img))').addClass('noImg');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.noImg,
.noImg a {
  color: #C00;
}</code>```

        Day 1

        Day 2

        Day 3

```

Title: Assigning a class to the <div> parent of an image

Body:
ETA - Solution found. Nice work Stack Overflow beauties!! What would I do without you ;) ;)

I'm building a carousel, some items have images, others don't. I need to be able to target the items without images for styling, so I'm trying to add a class to the div that wraps the image if that makes sense?

What I have is this :
For items with images:

      Day 1

For items without images :

      Day 1

And what I'm trying to do using jquery is add the class 'noImg' to the div 'carousel-item' what I've tried is many variations of this sort of thing :

$("div.carousel-item").addClass("noImg");
if ($(this).hasClass('.img-responsive')) {
  ("div.carousel-item").removeClass("noImg")
};

I've tried variations of .children .parent I've tried doing it the other way around and doing .find on image-responsive and adding classes that way.

Any suggestions of the 'you dope, you're missing this obvious thing' would very much be appreciated, Thanks very much in advance.

Body:
The issue with your jQuery code in the example is that this has no context. It would related to the window, not the .carousel-item as you seem to be expecting.

Also note that your HTML is invalid. li elements must be contained within a parent ul.

To make this work you can simply use a combination of :not() and :has() to find the containers which do not have an img element, like this:

$('.carousel-item:not(:has(img))').addClass('noImg');

.noImg,
.noImg a {
  color: #C00;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel-item active" style="width: 157.4px; margin-right: 2px;">
  <ul>
    <li>
      <a href="#" class="innerTabLink" rel="XYZ">
        <span>Day 1</span>
      </a>
    </li>
  </ul>
</div>
<div class="carousel-item active" style="width: 157.4px; margin-right: 2px;">
  <ul>
    <li>
      <a href="#" class="innerTabLink" rel="XYZ">
        <span>Day 2</span>
        <img src="*example image*" class="img-responsive" alt="words here" width="380" height="226" title="words here">
      </a>
    </li>
  </ul>
</div>
<div class="carousel-item active" style="width: 157.4px; margin-right: 2px;">
  <ul>
    <li>
      <a href="#" class="innerTabLink" rel="XYZ">
        <span>Day 3</span>
      </a>
    </li>
  </ul>
</div>


问:
How to make one user login at a time in application
One user should be loggedin to the application at a time. I am maintaining logs if user is logged in or logged out.On logged out (session destroy) i am updating a flag to false.If a flag is false another user can logged in into application. But if for any reason session expires Is there any way i can track it?</p>

答:
A good idea could be this:
Use cookies.
Every time user opens page, send him a unique cookie and save it on server. Next time, if user had that cookie, it would be acceptable. If other one log in, a cookie will be sent to him and value on server will be updated. So the old cookie won't be acceptable. </p>


问:
Compatible DDL (CREATE TABLE) across different SQL databases?
I'm working on a desktop application that must support (currently) MS Access and SQL Server back ends.  The application is under constant development and changes are frequently being made to the database, mostly the addition of tables and views to support new features (but also some DROPs and ALTER TABLEs to add new columns).

I have a system that compiles the DDL into the executable, checks the database to see if the executable has any new DDL that has to be executed, and executes it.  This works fine for a single database.

My immediate problem is that SQL Server and Access support wildly different names for data types so a CREATE TABLE statement that executes against Access will not execute against SQL Server (or worse, will execute but create a table with different datatypes).

Is there a method that can be used to create DDL (especially CREATE TABLE commands) that can be executed through ADO against both of these databases without having to craft separate DDL for each provider?

答:
Did you check

http://db.apache.org/ddlutils/

or

http://publib.boulder.ibm.com/infocenter/wtelecom/v6r1/index.jsp?topic=%2Fcom.ibm.twss.plan.doc%2Fdb_scripts.html

ContentLicense: CC BY-SA 2.5


问:
AnyLogic agent-based modelling: ClassCastException
I am working with an agent-based simulation of an infectious disease epidemic in AnyLogic. I have two agents types in my model- Person and Building. I'm trying to write a function that counts the number of infectious contacts that the agent type 'Person' has at any given point in time. Below is my code for the function:

```<code>int infectedConnections = 0;

if (getConnections() != null)
    for (Agent a : this.getConnections())
        {
        Person p = (Person) a;

        if (p.IsCurrentlyInfected())
            infectedConnections++;
            }

return infectedConnections ;
</code>```

The code compiles without any errors but during runtime, it throws up a java.lang.ClassCastException with the message: model.Building cannot be cast to model.Person.

When I try the same code with just one agent type (i.e. 'Person'), the model runs fine and the function returns the correct value. Could someone tell me how I could rectify my code so that I am able to run the function for 'Person' please?

答:
Although Rob's answer solves your problem, note that having mixed Person and Building connections is really the 'root cause' of your problems: in general, mixing types in a collection of things is a design flaw for the type of reasons you're seeing (and probably your agents' connections to other Person agents or Building agents are two conceptually different relationships).

In AnyLogic you can have multiple networks per agent, not just the default connections one, by adding extra Link to agents elements. So, for example, your Person agent could have one for family relationships (say called family connecting to Person agents) and one for places they live/work in (say called workHomePlaces connecting to Building agents); obviously I'm inventing possible purposes of these networks.

Then you can do things like family.getConnections() and workHomePlaces.getConnections(), avoiding the issues you're encountering and having a more conceptually-correct design.

In the help, see
Agent Based Modeling --> Agent interaction --> Defining custom contact links.

Body:
I am working with an agent-based simulation of an infectious disease epidemic in AnyLogic. I have two agents types in my model- Person and Building. I'm trying to write a function that counts the number of infectious contacts that the agent type 'Person' has at any given point in time. Below is my code for the function:

int infectedConnections = 0;

if (getConnections() != null)
    for (Agent a : this.getConnections())
        {
        Person p = (Person) a;

        if (p.IsCurrentlyInfected())
            infectedConnections++;
            }

return infectedConnections ;

The code compiles without any errors but during runtime, it throws up a java.lang.ClassCastException with the message: model.Building cannot be cast to model.Person.

When I try the same code with just one agent type (i.e. 'Person'), the model runs fine and the function returns the correct value. Could someone tell me how I could rectify my code so that I am able to run the function for 'Person' please?


问:
Create, redirect... calls using AsterNET.ARI
I have installed AsteriskNOW distribution with freePBX. I'm trying to implement autodialer to our existing software. I am monitoring calls wihtout any problems. Only thing that works is to hang up call. When i try to originate, redirect, hold or make similar action i get response from asterisk: Channel not in Stasis application.

var x = client.Channels.Originate("SIP/447", extension: "SIP/446", timeout: 30);
client.Channels.Ring(x.Id);
```

答:
First you have to originate call using Channel.Originate method as

```<code>var newChannel = ActionClient.Channels.Originate(endpoint, extension, context, priority, null, AppName, null, callerId, timeout, variables, channelId, otherChannelId, originator);
</code>```

newChannel.Id is the Channel_id which is created due to the above method.
Now you have to Redirect the call using
public void Redirect(string channelId, string endpoint)
where channelId is your current channel and endpoint is like "endpoint:SIP/703"

Try this.. Good luck!!

Body:
First you have to originate call using Channel.Originate method as

var newChannel = ActionClient.Channels.Originate(endpoint, extension, context, priority, null, AppName, null, callerId, timeout, variables, channelId, otherChannelId, originator);

newChannel.Id is the Channel_id which is created due to the above method.
Now you have to Redirect the call using
public void Redirect(string channelId, string endpoint)
where channelId is your current channel and endpoint is like "endpoint:SIP/703"

Try this.. Good luck!!


问:
Version conflict updating to play-services 9.4.0 Android studio 2.2
I get an error saying

```<code> Error:Execution failed for task ':app:processDebugGoogleServices'.
    > Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 9.0.0.
</code>```

I tried looking at https://bintray.com/android/android-tools/com.google.gms.google-services/ and com.google.gms:google-services:3.0.0 seems to be the latest. This is my project gradle

```<code>dependencies {
            classpath 'com.android.tools.build:gradle:2.1.2'
            classpath 'com.google.gms:google-services:3.0.0'
            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
</code>```

And this is how my app gradle looks like

```<code>buildscript {
        repositories {
            maven { url 'https://maven.fabric.io/public' }
        }

        dependencies {
            classpath 'io.fabric.tools:gradle:1.+'
        }
    }
    apply plugin: 'com.android.application'
    apply plugin: 'io.fabric'
    apply plugin: 'com.google.gms.google-services'

    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    android {
        compileSdkVersion 24
        buildToolsVersion "24.0.1"
        useLibrary 'org.apache.http.legacy'

        defaultConfig {
            applicationId "com.myapp.preburn"
            minSdkVersion 10
            targetSdkVersion 24
            versionCode 14
            versionName "2.0.1"
            renderscriptTargetApi 22
            renderscriptSupportModeEnabled true
        }
        buildTypes {
            release {
                lintOptions {
                    disable 'MissingTranslation'
                }
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    android {
        packagingOptions {
            exclude 'META-INF/DEPENDENCIES'
            exclude 'META-INF/NOTICE'
            exclude 'META-INF/LICENSE'
        }
    }

    repositories {
        mavenCentral()
        jcenter()
    }

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile fileTree(dir: 'libs', include: 'Parse-*.jar')
        compile 'com.parse.bolts:bolts-android:1.2.0'
        compile 'com.android.support:appcompat-v7:24.1.1'
        compile 'com.mcxiaoke.volley:library:1.0.9'
        compile 'com.google.android.gms:play-services-gcm:9.4.0'
        compile 'com.google.android.gms:play-services-location:9.4.0'
        compile 'com.google.android.gms:play-services-maps:9.4.0'
        compile 'com.google.android.gms:play-services-ads:9.4.0'
        compile 'com.google.android.gms:play-services-plus:9.4.0'
        compile 'com.google.android.gms:play-services-analytics:9.4.0'
        compile 'me.leolin:ShortcutBadger:1.1.3@aar'
        compile 'com.squareup.picasso:picasso:2.5.2'
        compile files('libs/jsoup-1.7.3.jar')
        compile('com.crashlytics.sdk.android:crashlytics:2.5.5@aar') {
            transitive = true;
        }
        compile files('libs/InMobi-5.2.2.jar')
        compile files('libs/libadapterinmobi.jar')
        compile files('libs/StartAppAdMobMediation-1.0.1.jar')
        compile files('libs/StartAppInApp-3.3.1.jar')
        compile 'org.adw.library:discrete-seekbar:1.0.1'
        compile 'com.pnikosis:materialish-progress:1.0'
    }
</code>```

If I change the play services to 9.0.0 everything compiles fine. What am I missing here?

答:
I was facing similar problem.At the top when the plugin is added it did not work for me.so Add the plugin at the bottom of the gradle.
this solve my problem of conflict Version

```<code> apply plugin: 'com.google.gms.google-services'
</code>```

and add it dependency these lines

```<code> compile 'com.google.firebase:firebase-core:9.2.0'
 compile 'com.google.firebase:firebase-messaging:9.2.0'
compile 'com.google.android.gms:play-services-location:9.2.0'
compile 'com.google.android.gms:play-services-places:9.2.0'
</code>```

Body:
I get an error saying

 Error:Execution failed for task ':app:processDebugGoogleServices'.
    > Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 9.0.0.

I tried looking at https://bintray.com/android/android-tools/com.google.gms.google-services/ and com.google.gms:google-services:3.0.0 seems to be the latest. This is my project gradle

dependencies {
            classpath 'com.android.tools.build:gradle:2.1.2'
            classpath 'com.google.gms:google-services:3.0.0'
            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }

And this is how my app gradle looks like

buildscript {
        repositories {
            maven { url 'https://maven.fabric.io/public' }
        }

        dependencies {
            classpath 'io.fabric.tools:gradle:1.+'
        }
    }
    apply plugin: 'com.android.application'
    apply plugin: 'io.fabric'
    apply plugin: 'com.google.gms.google-services'

    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    android {
        compileSdkVersion 24
        buildToolsVersion "24.0.1"
        useLibrary 'org.apache.http.legacy'

        defaultConfig {
            applicationId "com.myapp.preburn"
            minSdkVersion 10
            targetSdkVersion 24
            versionCode 14
            versionName "2.0.1"
            renderscriptTargetApi 22
            renderscriptSupportModeEnabled true
        }
        buildTypes {
            release {
                lintOptions {
                    disable 'MissingTranslation'
                }
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    android {
        packagingOptions {
            exclude 'META-INF/DEPENDENCIES'
            exclude 'META-INF/NOTICE'
            exclude 'META-INF/LICENSE'
        }
    }

    repositories {
        mavenCentral()
        jcenter()
    }

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile fileTree(dir: 'libs', include: 'Parse-*.jar')
        compile 'com.parse.bolts:bolts-android:1.2.0'
        compile 'com.android.support:appcompat-v7:24.1.1'
        compile 'com.mcxiaoke.volley:library:1.0.9'
        compile 'com.google.android.gms:play-services-gcm:9.4.0'
        compile 'com.google.android.gms:play-services-location:9.4.0'
        compile 'com.google.android.gms:play-services-maps:9.4.0'
        compile 'com.google.android.gms:play-services-ads:9.4.0'
        compile 'com.google.android.gms:play-services-plus:9.4.0'
        compile 'com.google.android.gms:play-services-analytics:9.4.0'
        compile 'me.leolin:ShortcutBadger:1.1.3@aar'
        compile 'com.squareup.picasso:picasso:2.5.2'
        compile files('libs/jsoup-1.7.3.jar')
        compile('com.crashlytics.sdk.android:crashlytics:2.5.5@aar') {
            transitive = true;
        }
        compile files('libs/InMobi-5.2.2.jar')
        compile files('libs/libadapterinmobi.jar')
        compile files('libs/StartAppAdMobMediation-1.0.1.jar')
        compile files('libs/StartAppInApp-3.3.1.jar')
        compile 'org.adw.library:discrete-seekbar:1.0.1'
        compile 'com.pnikosis:materialish-progress:1.0'
    }

If I change the play services to 9.0.0 everything compiles fine. What am I missing here?

Body:
I was facing similar problem.At the top when the plugin is added it did not work for me.so Add the plugin at the bottom of the gradle.
this solve my problem of conflict Version

 apply plugin: 'com.google.gms.google-services'

and add it dependency these lines

 compile 'com.google.firebase:firebase-core:9.2.0'
 compile 'com.google.firebase:firebase-messaging:9.2.0'
compile 'com.google.android.gms:play-services-location:9.2.0'
compile 'com.google.android.gms:play-services-places:9.2.0'


问:
ContextMenu Fails To Remove Row From ListView With Custom Adapter
The Problem is: My ContextMenu Fails to Remove a Row from ListView with a Custom Adapter and
the app crashes with the error: UnsupportedOperationException, see Logcat output.

I have done Google searches and searched stackoverflow. None of the information I have found solves this problem.

My Question is: What is wrong with my code?
Please provide the correct code to solve this problem.

Java Code:

```<code>        public class TestActivity extends ListActivity {

        private String itemNameArray[];
        private String dateArray[];

        private ListView listview;
        CustomListViewAdapter customListViewAdapter;

                        @Override
                        public void onCreate(Bundle savedInstanceState) {
                            super.onCreate(savedInstanceState);

                            setContentView(R.layout.activity_test);

                            registerForContextMenu(getListView());

                            root = Environment.getExternalStorageDirectory() + File.separator + "/ListTestFiles";
                            getDir(root);

            listview = getListView();

            name=itemNameArray;
            lastmod=dateArray;

            customListViewAdapter = new CustomListViewAdapter(this, name, lastmod);

            listview.setAdapter(customListViewAdapter);

      } // End of onCreate code.

        class CustomListViewAdapter extends ArrayAdapter<String> {
            Context context;
            String[] nameArray;
            String[] modifiedArray;

            CustomListViewAdapter(Context c, String[] name, String[] lastmod)
            {
                super(c, R.layout.layout_item_view, R.id.rowtext, name);
                this.context = c;
                this.nameArray = name;
                this.modifiedArray = lastmod;
            }

            public View getView(int position, View convertView, ViewGroup parent)
            {
                LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View row = inflater.inflate(R.layout.layout_item_view, parent, false);

                TextView myName;
                TextView myLastMod;

                myName=(TextView) row.findViewById(R.id.rowtext);
                myName.setText(nameArray[position]);

                myLastMod=(TextView) row.findViewById(R.id.textView6);
                myLastMod.setText(modifiedArray[position]);

                return row;
            }
        }

         @Override
         public void onCreateContextMenu(ContextMenu menu, View v,
                                         ContextMenu.ContextMenuInfo menuInfo) {
             super.onCreateContextMenu(menu, v, menuInfo);
                 MenuInflater inflater = getMenuInflater();
                 inflater.inflate(R.menu.context_menu, menu);
         }

        @Override
        public boolean onContextItemSelected(MenuItem itemMenu) {

            final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)itemMenu.getMenuInfo();

            switch (itemMenu.getItemId()) {
                case R.id.context_menu_rename:
                    Toast.makeText(this, "Rename", Toast.LENGTH_SHORT).show();
                    return true;
                case R.id.context_menu_delete:
                    // NOTE TESTING the line of code below caused a runtime error: java.lang.UnsupportedOperationException
                    customListViewAdapter.remove(customListViewAdapter.getItem(info.position));
                    customListViewAdapter.notifyDataSetChanged();

                    Toast.makeText(getApplicationContext(), "position = " + info.position, Toast.LENGTH_SHORT).show();
                    Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();

                return true;

                return super.onContextItemSelected(itemMenu);
        }
    }
}
</code>```

Logcat output:

```<code>11-13 10:45:21.229  21432-21432/com.testing.listapp D/AndroidRuntime﹕ Shutting down VM
    --------- beginning of crash
11-13 10:45:21.246  21432-21432/com.testing.listapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.testing.listapp, PID: 21432
    java.lang.UnsupportedOperationException
            at java.util.AbstractList.remove(AbstractList.java:638)
            at java.util.AbstractList$SimpleListIterator.remove(AbstractList.java:75)
            at java.util.AbstractCollection.remove(AbstractCollection.java:229)
            at android.widget.ArrayAdapter.remove(ArrayAdapter.java:244)
            at com.testing.listapp.TestActivity.onContextItemSelected(TestActivity.java:5468)
            at android.app.Activity.onMenuItemSelected(Activity.java:2905)
            at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:4701)
            at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
            at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
            at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
            at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1082)
            at android.widget.AdapterView.performItemClick(AdapterView.java:305)
            at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
            at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
            at android.widget.AbsListView$3.run(AbsListView.java:3860)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code>```

答:
I modified your work:</p>

```<code>public class TestActivity extends ListActivity {
    private ArrayList<String> itemNameArray;
     private ArrayList<String> dateArray;
     private ListView listview;
     CustomListViewAdapter customListViewAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_test);
     registerForContextMenu(getListView());
 String root = Environment.getExternalStorageDirectory() + File.separator + "/ListTestFiles";
     getDir(root);

     listview = getListView();

     CustomListViewAdapter = new CustomListViewAdapter(this, itemNameArray, dateArray);
     listview.setAdapter(customListViewAdapter);
     }
     // End of onCreate code. class

     CustomListViewAdapter extends ArrayAdapter<String> {
    ArrayList<String> nameArray;
     ArrayList<String> modifiedArray; CustomListViewAdapter(Context c, ArrayList<String> name, ArrayList<String> lastmod) {
     super(c, 0, name);
     this.nameArray = name;
     this.modifiedArray = lastmod;
     }
    public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater=LayoutInflater.from(parent.get context());
     convertView = inflater.inflate(R.layout.layout_item_view, parent, false);
    TextView myName;
    TextView myLastMod;
     myName=(TextView) row.findViewById(R.id.rowtext);
     myName.setText(nameArray.get(position));
     myLastMod=(TextView) row.findViewById(R.id.textView6);
     myLastMod.setText(modifiedArray.get(position));
     return convertView;
     }
     }

     @Override
     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    getMenuInflater().inflate(R.menu.context_menu, menu);
    }

     @Override
    public boolean onContextItemSelected(MenuItem itemMenu) {

    switch (itemMenu.getItemId()) {
    case R.id.context_menu_rename:
     Toast.makeText(this, "Rename", Toast.LENGTH_SHORT).show();
     break;
    case R.id.context_menu_delete: itemNameArray.remove(listView.getSelectedItemPosition());
    dateArray.remove(listView.getSelectedItemPosition()); customListViewAdapter.notifyDataSetChanged();
     break;
    }
    return true;
     }
     }
</code>```

Body:
The Problem is: My ContextMenu Fails to Remove a Row from ListView with a Custom Adapter and
the app crashes with the error: UnsupportedOperationException, see Logcat output.

I have done Google searches and searched stackoverflow. None of the information I have found solves this problem.

My Question is: What is wrong with my code?
Please provide the correct code to solve this problem.

Java Code:

        public class TestActivity extends ListActivity {

        private String itemNameArray[];
        private String dateArray[];

        private ListView listview;
        CustomListViewAdapter customListViewAdapter;

                        @Override
                        public void onCreate(Bundle savedInstanceState) {
                            super.onCreate(savedInstanceState);

                            setContentView(R.layout.activity_test);

                            registerForContextMenu(getListView());

                            root = Environment.getExternalStorageDirectory() + File.separator + "/ListTestFiles";
                            getDir(root);

            listview = getListView();

            name=itemNameArray;
            lastmod=dateArray;

            customListViewAdapter = new CustomListViewAdapter(this, name, lastmod);

            listview.setAdapter(customListViewAdapter);

      } // End of onCreate code.

        class CustomListViewAdapter extends ArrayAdapter<String> {
            Context context;
            String[] nameArray;
            String[] modifiedArray;

            CustomListViewAdapter(Context c, String[] name, String[] lastmod)
            {
                super(c, R.layout.layout_item_view, R.id.rowtext, name);
                this.context = c;
                this.nameArray = name;
                this.modifiedArray = lastmod;
            }

            public View getView(int position, View convertView, ViewGroup parent)
            {
                LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View row = inflater.inflate(R.layout.layout_item_view, parent, false);

                TextView myName;
                TextView myLastMod;

                myName=(TextView) row.findViewById(R.id.rowtext);
                myName.setText(nameArray[position]);

                myLastMod=(TextView) row.findViewById(R.id.textView6);
                myLastMod.setText(modifiedArray[position]);

                return row;
            }
        }

         @Override
         public void onCreateContextMenu(ContextMenu menu, View v,
                                         ContextMenu.ContextMenuInfo menuInfo) {
             super.onCreateContextMenu(menu, v, menuInfo);
                 MenuInflater inflater = getMenuInflater();
                 inflater.inflate(R.menu.context_menu, menu);
         }

        @Override
        public boolean onContextItemSelected(MenuItem itemMenu) {

            final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)itemMenu.getMenuInfo();

            switch (itemMenu.getItemId()) {
                case R.id.context_menu_rename:
                    Toast.makeText(this, "Rename", Toast.LENGTH_SHORT).show();
                    return true;
                case R.id.context_menu_delete:
                    // NOTE TESTING the line of code below caused a runtime error: java.lang.UnsupportedOperationException
                    customListViewAdapter.remove(customListViewAdapter.getItem(info.position));
                    customListViewAdapter.notifyDataSetChanged();

                    Toast.makeText(getApplicationContext(), "position = " + info.position, Toast.LENGTH_SHORT).show();
                    Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();

                return true;

                return super.onContextItemSelected(itemMenu);
        }
    }
}

Logcat output:

11-13 10:45:21.229  21432-21432/com.testing.listapp D/AndroidRuntime﹕ Shutting down VM
    --------- beginning of crash
11-13 10:45:21.246  21432-21432/com.testing.listapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.testing.listapp, PID: 21432
    java.lang.UnsupportedOperationException
            at java.util.AbstractList.remove(AbstractList.java:638)
            at java.util.AbstractList$SimpleListIterator.remove(AbstractList.java:75)
            at java.util.AbstractCollection.remove(AbstractCollection.java:229)
            at android.widget.ArrayAdapter.remove(ArrayAdapter.java:244)
            at com.testing.listapp.TestActivity.onContextItemSelected(TestActivity.java:5468)
            at android.app.Activity.onMenuItemSelected(Activity.java:2905)
            at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:4701)
            at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
            at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
            at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
            at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1082)
            at android.widget.AdapterView.performItemClick(AdapterView.java:305)
            at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
            at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
            at android.widget.AbsListView$3.run(AbsListView.java:3860)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Body:
I modified your work:

public class TestActivity extends ListActivity {
    private ArrayList<String> itemNameArray;
     private ArrayList<String> dateArray;
     private ListView listview;
     CustomListViewAdapter customListViewAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_test);
     registerForContextMenu(getListView());
 String root = Environment.getExternalStorageDirectory() + File.separator + "/ListTestFiles";
     getDir(root);

     listview = getListView();

     CustomListViewAdapter = new CustomListViewAdapter(this, itemNameArray, dateArray);
     listview.setAdapter(customListViewAdapter);
     }
     // End of onCreate code. class

     CustomListViewAdapter extends ArrayAdapter<String> {
    ArrayList<String> nameArray;
     ArrayList<String> modifiedArray; CustomListViewAdapter(Context c, ArrayList<String> name, ArrayList<String> lastmod) {
     super(c, 0, name);
     this.nameArray = name;
     this.modifiedArray = lastmod;
     }
    public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater=LayoutInflater.from(parent.get context());
     convertView = inflater.inflate(R.layout.layout_item_view, parent, false);
    TextView myName;
    TextView myLastMod;
     myName=(TextView) row.findViewById(R.id.rowtext);
     myName.setText(nameArray.get(position));
     myLastMod=(TextView) row.findViewById(R.id.textView6);
     myLastMod.setText(modifiedArray.get(position));
     return convertView;
     }
     }

     @Override
     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    getMenuInflater().inflate(R.menu.context_menu, menu);
    }

     @Override
    public boolean onContextItemSelected(MenuItem itemMenu) {

    switch (itemMenu.getItemId()) {
    case R.id.context_menu_rename:
     Toast.makeText(this, "Rename", Toast.LENGTH_SHORT).show();
     break;
    case R.id.context_menu_delete: itemNameArray.remove(listView.getSelectedItemPosition());
    dateArray.remove(listView.getSelectedItemPosition()); customListViewAdapter.notifyDataSetChanged();
     break;
    }
    return true;
     }
     }


问:
Serving static files with restify
I am learning to use Node.js. Currently, I have a folder structure that looks like the following:

```<code>index.html
server.js
client
  index.html
  subs
    index.html
    page.html
res
  css
    style.css
  img
    profile.png
  js
    page.js
    jquery.min.js
</code>```

server.js is my webserver code. I run this from a command-line using node server.js. The contents of that file are:

```<code>var restify = require('restify');

var server = restify.createServer({
    name: 'Test App',
    version: '1.0.0'
});

server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());

server.get('/echo/:name', function (req, res, next) {
    res.send(req.params);
    return next();
});

server.listen(2000, function () {
    console.log('%s running on %s', server.name, server.url);
});
</code>```

As you can see, this server relies on RESTIFY. I've been told I must use RESTIFY. However, I can't figure out how to serve static files. For instance, how do I server the *.html, *.css, *.png, and *.js files in my app?

Thank you!

答:
Try this : Here view is a static resource directory name</p>

```<code>server.get('/\/.*/', restify.plugins.serveStatic({

    directory: __dirname + "/view/",
    default: './home.html'

   })
);
</code>```

Title: Serving static files with restify

Body:
I am learning to use Node.js. Currently, I have a folder structure that looks like the following:

index.html
server.js
client
  index.html
  subs
    index.html
    page.html
res
  css
    style.css
  img
    profile.png
  js
    page.js
    jquery.min.js

server.js is my webserver code. I run this from a command-line using node server.js. The contents of that file are:

var restify = require('restify');

var server = restify.createServer({
    name: 'Test App',
    version: '1.0.0'
});

server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());

server.get('/echo/:name', function (req, res, next) {
    res.send(req.params);
    return next();
});

server.listen(2000, function () {
    console.log('%s running on %s', server.name, server.url);
});

As you can see, this server relies on RESTIFY. I've been told I must use RESTIFY. However, I can't figure out how to serve static files. For instance, how do I server the *.html, *.css, *.png, and *.js files in my app?

Thank you!

Body:
Try this : Here view is a static resource directory name

server.get('/\/.*/', restify.plugins.serveStatic({

    directory: __dirname + "/view/",
    default: './home.html'

   })
);


问:
How to move a pictureBox inside a Panel by Mouse
How to move a pictureBox inside a Panel by Mouse.
Visual Studio 2015 C# Winsows Forms Application.

I've made a primitive slider to control the volume of my WindowsMediaPlayer.
A panel as the background and a pictureBox inside as the slider-knopf.
And it works well.
But purely visually it does not work that good.

I'v searched all around, but can't I find an answer to this little funny problem.

Here is my code:

```<code>    int posY;

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            posY = e.Y; ;
        }
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        PictureBox box = sender as PictureBox;

        if (e.Button == MouseButtons.Left)
        {
            box.Top += e.Y - posY;
        }

        if (box.Top < 0)
        {
            box.Top = 0;
        }

        if (box.Top > 100)
        {
            box.Top = 100;
        }
        int n = box.Top;
        n = n * - 1 + 100;
        label1.Text = n.ToString();
    }
</code>```

When I move the pictureBox out of the edge of the little panel, the pictureBox somehow 'shrinks' in the panel.
But when I release the mouse, the pictureBox restore its size.

Slider.gif

Why is that.?
And how can I avoid it.?

Thanks.

答:
I found a solution.
It's not optimal, but it can be used.
I changed the code to:

```<code>    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            dragging = true;
            startPoint = e.Location;
        }
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (dragging)
        {
            Debug.WriteLine("mousemove X: " + e.X + " Y: " + e.Y);
            pictureBox1.Location = new Point(0, pictureBox1.Top + e.Location.Y - startPoint.Y);

            if (pictureBox1.Location.Y < 0)
            {
                pictureBox1.Location = new Point(0, 0);
                dragging = false;
            }
            if (pictureBox1.Location.Y > 100)
            {
                pictureBox1.Location = new Point(0, 100);
                dragging = false;
            }
            this.Refresh();
        }
        int n = pictureBox1.Location.Y;
        n = n * -1 + 100;
        label1.Text = n.ToString();

        mediaPlayer1.settings.volume = n;
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        dragging = false;
    }
</code>```

gif

I still need to put an 'if' to correct, when the pictureBox1 is pulled out of the panel.
And to avoid flicker, I have had to put a 'dragging = false'.
However, it results in the pictureBox1 is getting frozen to the edge, so I have to release the mouse, and re-click to continue.

But well - it's to live with.

Thanks.

Body:
How to move a pictureBox inside a Panel by Mouse.
Visual Studio 2015 C# Winsows Forms Application.

I've made a primitive slider to control the volume of my WindowsMediaPlayer.
A panel as the background and a pictureBox inside as the slider-knopf.
And it works well.
But purely visually it does not work that good.

I'v searched all around, but can't I find an answer to this little funny problem.

Here is my code:

    int posY;

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            posY = e.Y; ;
        }
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        PictureBox box = sender as PictureBox;

        if (e.Button == MouseButtons.Left)
        {
            box.Top += e.Y - posY;
        }

        if (box.Top < 0)
        {
            box.Top = 0;
        }

        if (box.Top > 100)
        {
            box.Top = 100;
        }
        int n = box.Top;
        n = n * - 1 + 100;
        label1.Text = n.ToString();
    }

When I move the pictureBox out of the edge of the little panel, the pictureBox somehow 'shrinks' in the panel.
But when I release the mouse, the pictureBox restore its size.

Slider.gif

Why is that.?
And how can I avoid it.?

Thanks.

Body:
I found a solution.
It's not optimal, but it can be used.
I changed the code to:

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            dragging = true;
            startPoint = e.Location;
        }
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (dragging)
        {
            Debug.WriteLine("mousemove X: " + e.X + " Y: " + e.Y);
            pictureBox1.Location = new Point(0, pictureBox1.Top + e.Location.Y - startPoint.Y);

            if (pictureBox1.Location.Y < 0)
            {
                pictureBox1.Location = new Point(0, 0);
                dragging = false;
            }
            if (pictureBox1.Location.Y > 100)
            {
                pictureBox1.Location = new Point(0, 100);
                dragging = false;
            }
            this.Refresh();
        }
        int n = pictureBox1.Location.Y;
        n = n * -1 + 100;
        label1.Text = n.ToString();

        mediaPlayer1.settings.volume = n;
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        dragging = false;
    }

gif

I still need to put an 'if' to correct, when the pictureBox1 is pulled out of the panel.
And to avoid flicker, I have had to put a 'dragging = false'.
However, it results in the pictureBox1 is getting frozen to the edge, so I have to release the mouse, and re-click to continue.

But well - it's to live with.

Thanks.


问:
Send sms via aws-sdk-js
What is the way to send sms using aws-sdk-js ?
https://github.com/aws/aws-sdk-js

Is there is proper code available from amazon for this(javascript).
I refered the below docs, but is not enough informative
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SMS.html

This code actually worked for me.

```<code>const AWS = require('aws-sdk');
AWS.config.update({
    region: 'ap-southwest-1',
    accessKeyId: 'XXXXXXXXXXXXXXXXXXXX',
    secretAccessKey: 'xxxxSSSSXXXXXXXXXXXXXXXXXXXXXXXXXX'
});

var sns = new AWS.SNS();

var params = {
    Message: 'Alert! emssage.....',
    MessageStructure: 'string',
    PhoneNumber: 'XXXXXXXXXXXX'
};

sns.publish(params, function (err, data) {
    if (err) console.log(err, err.stack);
    else console.log(data);
});
</code>```

Any better way of doing this with adding Sender ID and all?

答:
You can create a SNS topic and subscribe to a Mobile number. Then you can use SDK to publish the topic. This way you can send SMS.

Visit Send SMS using AWS SDK example given in java.

You can refer this link for Node.js publish sns

```<code>PublishRequest _PublishRequest = null;
    PublishResult _PublishResult = null;
    try{
        _PublishRequest = new PublishRequest("arn:aws:sns:us-east-1:081701745661:sendSMS","MessageBody","Subject");
        _PublishResult = SNSClient.publish(_PublishRequest);
        }catch(Exception e){
            System.out.println("Got an error in method sendSMSNotification: " + e.getMessage());
        }
    return _PublishResult.getMessageId();
</code>```

Title: Send sms via aws-sdk-js

Body:
What is the way to send sms using aws-sdk-js ?
https://github.com/aws/aws-sdk-js

Is there is proper code available from amazon for this(javascript).
I refered the below docs, but is not enough informative
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SMS.html

This code actually worked for me.

const AWS = require('aws-sdk');
AWS.config.update({
    region: 'ap-southwest-1',
    accessKeyId: 'XXXXXXXXXXXXXXXXXXXX',
    secretAccessKey: 'xxxxSSSSXXXXXXXXXXXXXXXXXXXXXXXXXX'
});

var sns = new AWS.SNS();

var params = {
    Message: 'Alert! emssage.....',
    MessageStructure: 'string',
    PhoneNumber: 'XXXXXXXXXXXX'
};

sns.publish(params, function (err, data) {
    if (err) console.log(err, err.stack);
    else console.log(data);
});

Any better way of doing this with adding Sender ID and all?

Body:
You can create a SNS topic and subscribe to a Mobile number. Then you can use SDK to publish the topic. This way you can send SMS.

Visit Send SMS using AWS SDK example given in java.

You can refer this link for Node.js publish sns

PublishRequest _PublishRequest = null;
    PublishResult _PublishResult = null;
    try{
        _PublishRequest = new PublishRequest("arn:aws:sns:us-east-1:081701745661:sendSMS","MessageBody","Subject");
        _PublishResult = SNSClient.publish(_PublishRequest);
        }catch(Exception e){
            System.out.println("Got an error in method sendSMSNotification: " + e.getMessage());
        }
    return _PublishResult.getMessageId();