问:
How to prevent untrusted string parameter in C#
For security reasons, I don't want specific method to receive non-programmer or non-compiler time strings, how could I do this?</p>

```<code>readonly String OK_STR = "some text";
String BAD_STR = "another text";

public void SetSecureStr(String str)
{
    //Use the string for security purpose
}

//Somewhere in the code
SetSecureStr(OK_STR); //Accepted
SetSecureStr(OK_STR + "Programmer passed this staticlly!"); //Accepted (If not possible to implement, forget about it)
SetSecureStr(BAD_STR); //Throw exception, BAD_STR is modifiable
SetSecureStr(OK_STR + untrustedVar); //Throw exception, concatenation with modifiable
SetSecureStr(String.Format("{0}", OK_STR)); //Throw exception, not const
</code>```

答:
I came finally with a solution which is hybrid between the two previously proposed answers:

```<code>public class SqlQuery
{
    private SqlQuery() { }

    private static UInt32 sqlQueriesCount = 0;

    public static UInt32 INBOUND_UPDATE_CALLBACK_NUM = sqlQueriesCount++;
    public static UInt32 INBOUND_UPDATE_DEST_ADDR_SUBUNIT = sqlQueriesCount++;
    public static UInt32 INBOUND_UPDATE_DEST_BEARER_TYPE = sqlQueriesCount++;
    //...etc

    private static readonly Dictionary<UInt32, String> queries = new Dictionary<UInt32, String>
    {
        {SqlQuery.INBOUND_UPDATE_CALLBACK_NUM, "UPDATE inbound SET callbackNum = ? WHERE id = ?"},
        {SqlQuery.INBOUND_UPDATE_DEST_ADDR_SUBUNIT, "UPDATE inbound SET destAddrSubunit = ? WHERE id = ?"},
        {SqlQuery.INBOUND_UPDATE_DEST_BEARER_TYPE, "UPDATE inbound SET destBearerType = ? WHERE id = ?"},
        //...etc
    };

    public static String GetQueryText(UInt32 queryKey)
    {
        String query = null;
        if (SqlQuery.queries.TryGetValue(queryKey, out query) == false)
        {
        throw new ArgumentOutOfRangeException(String.Format("Query must be paramerized query stored within SqlQuery class, provided queryKey: {0}", queryKey));
        }
        return query;
    }
}
</code>```

Usage:

```<code>OdbcCommand cmd = new OdbcCommand(SqlQuery.GetQueryText(SqlQuery.INBOUND_UPDATE_CALLBACK_NUM), con);
</code>```

Body:
For security reasons, I don't want specific method to receive non-programmer or non-compiler time strings, how could I do this?

readonly String OK_STR = "some text";
String BAD_STR = "another text";

public void SetSecureStr(String str)
{
    //Use the string for security purpose
}

//Somewhere in the code
SetSecureStr(OK_STR); //Accepted
SetSecureStr(OK_STR + "Programmer passed this staticlly!"); //Accepted (If not possible to implement, forget about it)
SetSecureStr(BAD_STR); //Throw exception, BAD_STR is modifiable
SetSecureStr(OK_STR + untrustedVar); //Throw exception, concatenation with modifiable
SetSecureStr(String.Format("{0}", OK_STR)); //Throw exception, not const

Body:
I came finally with a solution which is hybrid between the two previously proposed answers:

public class SqlQuery
{
    private SqlQuery() { }

    private static UInt32 sqlQueriesCount = 0;

    public static UInt32 INBOUND_UPDATE_CALLBACK_NUM = sqlQueriesCount++;
    public static UInt32 INBOUND_UPDATE_DEST_ADDR_SUBUNIT = sqlQueriesCount++;
    public static UInt32 INBOUND_UPDATE_DEST_BEARER_TYPE = sqlQueriesCount++;
    //...etc

    private static readonly Dictionary<UInt32, String> queries = new Dictionary<UInt32, String>
    {
        {SqlQuery.INBOUND_UPDATE_CALLBACK_NUM, "UPDATE inbound SET callbackNum = ? WHERE id = ?"},
        {SqlQuery.INBOUND_UPDATE_DEST_ADDR_SUBUNIT, "UPDATE inbound SET destAddrSubunit = ? WHERE id = ?"},
        {SqlQuery.INBOUND_UPDATE_DEST_BEARER_TYPE, "UPDATE inbound SET destBearerType = ? WHERE id = ?"},
        //...etc
    };

    public static String GetQueryText(UInt32 queryKey)
    {
        String query = null;
        if (SqlQuery.queries.TryGetValue(queryKey, out query) == false)
        {
        throw new ArgumentOutOfRangeException(String.Format("Query must be paramerized query stored within SqlQuery class, provided queryKey: {0}", queryKey));
        }
        return query;
    }
}

Usage:

OdbcCommand cmd = new OdbcCommand(SqlQuery.GetQueryText(SqlQuery.INBOUND_UPDATE_CALLBACK_NUM), con);


来源: stackexchange

问:
Is there a way to check debug=true in startup.auth in ASP.NET MVC
I see that we can use HttpContext.Current.IsDebuggingEnabled in controllers to check if debug=true is enabled in web.config. How can I check the same in startup.auth? I need to set different app Ids for my local and production environments for fb authentication using this condition. Please suggest if there is a better way to do this.</p>

答:
I would recommend creating a web.config entry for whatever dynamic data you need to set and then use web.config transforms to change the data depending on environment. This is very commonly used with connection strings to set different source databases depending on what environment youre in (local vs test vs prod).
See the example below:

local Web.config:

```<code><connectionStrings>
     <add name="myConnection" connectionString="Data Source=localhost;Initial Catalog=myDatabase;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
</code>```

Web.Debug.Config:

```<code><connectionStrings>
    <add xdt:Transform="SetAttributes" xdt:Locator="Match(name)" name="myConnection" connectionString="Data Source=myTestSqlServer;Initial Catalog=myTestDb;User Id=myTestUserId;Password=myTestPassword;" providerName="System.Data.SqlClient" />
</connectionStrings>
</code>```

Web.Release.Config:

```<code><connectionStrings>
    <add xdt:Transform="SetAttributes" xdt:Locator="Match(name)" name="myConnection" connectionString="Data Source=myProdSqlServer;Initial Catalog=myProdDb;User Id=myProdUserName;Password=myProdPassword;" providerName="System.Data.SqlClient" />
</connectionStrings>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would recommend creating a web.config entry for whatever dynamic data you need to set and then use web.config transforms to change the data depending on environment. This is very commonly used with connection strings to set different source databases depending on what environment youre in (local vs test vs prod).
See the example below:

local Web.config:

<connectionStrings>
     <add name="myConnection" connectionString="Data Source=localhost;Initial Catalog=myDatabase;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

Web.Debug.Config:

<connectionStrings>
    <add xdt:Transform="SetAttributes" xdt:Locator="Match(name)" name="myConnection" connectionString="Data Source=myTestSqlServer;Initial Catalog=myTestDb;User Id=myTestUserId;Password=myTestPassword;" providerName="System.Data.SqlClient" />
</connectionStrings>

Web.Release.Config:

<connectionStrings>
    <add xdt:Transform="SetAttributes" xdt:Locator="Match(name)" name="myConnection" connectionString="Data Source=myProdSqlServer;Initial Catalog=myProdDb;User Id=myProdUserName;Password=myProdPassword;" providerName="System.Data.SqlClient" />
</connectionStrings>


问:
Support Libraries vs Normal Libraries in Android
How are support libraries different from normal libraries in Android, except the fact that Support libraries can run the app on wider range of devices? Shouldn't one use Support libraries instead of normal libraries, as support libraries can make the app run on a wider range of devices with the same functionality as that of normal libraries?</p>

答: Support libraries are normal libraries.  They're just a set of libraries written by Google that backport features of newer Android devices to older ones.  There's nothing special about them, "Support libraries" is the name.</p>


问:
HTML href links does not work after i added javascript to navigation component
I have a simple main navigation menu created with html and css. When I added some javascript to handle the collapsing and toggling for the button for the mobile menu, every link on the page stops working.

I based the navigation off of this pen: https://codepen.io/anon/pen/YQjzzq

(function() {

  // Definition of caller element
  var getTriggerElement = function(el) {
    var isCollapse = el.getAttribute('data-collapse');
    if (isCollapse !== null) {
      return el;
    } else {
      var isParentCollapse = el.parentNode.getAttribute('data-collapse');
      return (isParentCollapse !== null) ? el.parentNode : undefined;
    }
  };

  // A handler for click on toggle button
  var collapseClickHandler = function(event) {
    var triggerEl = getTriggerElement(event.target);
    // If trigger element does not exist
    if (triggerEl === undefined) {
      event.preventDefault();
      return false;
    }

    // If the target element exists
    var targetEl = document.querySelector(triggerEl.getAttribute('data-target'));
    if (targetEl) {
      triggerEl.classList.toggle('-active');
      targetEl.classList.toggle('-on');
    }
  };

  // Delegated event
  document.addEventListener('click', collapseClickHandler, false);

})(document, window);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav role="navigation" id="navigation" class="list">
          Hem
          Vårt Boende
          Om Kvinnovåld
          Länkar
          Engagera Dig
          English
          Kontakt
        </nav>

        <!-- Button to toggle the display menu  -->
        <button data-collapse data-target="#navigation" class="toggle">
          <!-- Hamburger icon -->
          <span class="icon"></span>
        </button></code>```

答:
event.preventDefault() is the culprit, since following links when the user clicks is the "default" behavior of a link.

Try this on any web page and then try to click a link:

```<code>const f = e => e.preventDefault()
document.addEventListener('click', f, false)
</code>```

You probably want to make sure the element clicked is what you think it is and then and only then preventDefault().

Body:
I have a simple main navigation menu created with html and css. When I added some javascript to handle the collapsing and toggling for the button for the mobile menu, every link on the page stops working.

I based the navigation off of this pen: https://codepen.io/anon/pen/YQjzzq

(function() {

  // Definition of caller element
  var getTriggerElement = function(el) {
    var isCollapse = el.getAttribute('data-collapse');
    if (isCollapse !== null) {
      return el;
    } else {
      var isParentCollapse = el.parentNode.getAttribute('data-collapse');
      return (isParentCollapse !== null) ? el.parentNode : undefined;
    }
  };

  // A handler for click on toggle button
  var collapseClickHandler = function(event) {
    var triggerEl = getTriggerElement(event.target);
    // If trigger element does not exist
    if (triggerEl === undefined) {
      event.preventDefault();
      return false;
    }

    // If the target element exists
    var targetEl = document.querySelector(triggerEl.getAttribute('data-target'));
    if (targetEl) {
      triggerEl.classList.toggle('-active');
      targetEl.classList.toggle('-on');
    }
  };

  // Delegated event
  document.addEventListener('click', collapseClickHandler, false);

})(document, window);

          Hem
          Vårt Boende
          Om Kvinnovåld
          Länkar
          Engagera Dig
          English
          Kontakt

        <button data-collapse data-target="#navigation" class="toggle">

        </button>

Body:
event.preventDefault() is the culprit, since following links when the user clicks is the "default" behavior of a link.

Try this on any web page and then try to click a link:

const f = e => e.preventDefault()
document.addEventListener('click', f, false)

You probably want to make sure the element clicked is what you think it is and then and only then preventDefault().


问:
MSSQL Query Not Returning Null Columns/Results
I'm kind of new to SQL queries so this is probably something easily fixed, but I can't seem to find any answers.

I've got a bunch of related tables. E.g.
SPClients contains iClientID and sName, SPDocTypes contains iDocTypeID and sName, SPCreditor contains iCreditorID and sName

and then

SPDocIndex contains iIndexID, and then foreign keys to iClientID, iDocTypeID and iCreditorID listed above.

If I do a simple SELECT * FROM SPDocIndex I get all results, with just the IDs being displayed, which isn't much use when bound to a datagrid. So I use an inner join so the actual names appear rather than just their IDs, like so:

```<code>SELECT * FROM SPDocIndex
INNER JOIN SPClients ON SPDocIndex.iClientID=SPClients.iClientID
INNER JOIN SPDocType ON SPDocIndex.iDocTypeID=SPDocType.iDocTypeID
INNER JOIN SPCreditor ON SPDocIndex.iCreditorID=SPCreditor.iCreditorID
</code>```

And the query "works" but it only returns rows that have data in all three columns. If the iCreditorID column of SPDocIndex is null, then that row is NOT returned...but I would like all rows to be returned irrespective of whether the columns are null or not.

答:
```<code>Inner Join will always return the return the matching records within two table. In order  to get the all the records from first table and matching record of second table you must use left join as shown below. Please try below and let me know if you have any further issues.

SELECT * FROM SPDocIndex
LEFT JOIN SPClients ON SPDocIndex.iClientID=SPClients.iClientID
LEFT JOIN SPDocType ON SPDocIndex.iDocTypeID=SPDocType.iDocTypeID
LEFT JOIN SPCreditor ON SPDocIndex.iCreditorID=SPCreditor.iCreditorID
</code>```

Body:
I'm kind of new to SQL queries so this is probably something easily fixed, but I can't seem to find any answers.

I've got a bunch of related tables. E.g.
SPClients contains iClientID and sName, SPDocTypes contains iDocTypeID and sName, SPCreditor contains iCreditorID and sName

and then

SPDocIndex contains iIndexID, and then foreign keys to iClientID, iDocTypeID and iCreditorID listed above.

If I do a simple SELECT * FROM SPDocIndex I get all results, with just the IDs being displayed, which isn't much use when bound to a datagrid. So I use an inner join so the actual names appear rather than just their IDs, like so:

SELECT * FROM SPDocIndex
INNER JOIN SPClients ON SPDocIndex.iClientID=SPClients.iClientID
INNER JOIN SPDocType ON SPDocIndex.iDocTypeID=SPDocType.iDocTypeID
INNER JOIN SPCreditor ON SPDocIndex.iCreditorID=SPCreditor.iCreditorID

And the query "works" but it only returns rows that have data in all three columns. If the iCreditorID column of SPDocIndex is null, then that row is NOT returned...but I would like all rows to be returned irrespective of whether the columns are null or not.


问:
Scrolling just part of the header and rest fixed
I ran into problem I cant solve whole night. Actually what I am looking for.
"Actual look and tool to explain what I am asking for"

I want the red part to scroll up, when I scroll, the blue part go on scroll up too, but on top:0px stop and become fixed, I guess it will be by jQuery and I am really bad at it, best would be just by css, due to mobile users. Can someone help me with that please? Here is my html markup

```<code><header>
        <div ID="Banner">
            <br>
            <h1>RISTORANTE PIZZERIE NA HRADBÁCH</h1>
            <h3>ROZVOZ JÍDEL A PIZZY PO SLANÉM A OKOLÍ</h3>
        </div>
        <div id="Menu">

            <table >
                <tr>
                    <td>
                        <asp:Button ID="homeButton" runat="server" Text="Domů" PostBackUrl="Home.aspx" />
                    </td>
                    <td>
                        <asp:Button ID="dailyMenuButton" runat="server" Text="Denní Nabídka" PostBackUrl="DailyMenu.aspx" />
                    </td>
                    <td>
                        <asp:Button ID="diningMenuButton" runat="server" Text="Jídelní Menu" PostBackUrl="DiningMenu.aspx" />
                    </td>
                    <td>
                        <asp:Button ID="contactsButton" runat="server" Text="Kontakt" PostBackUrl="Contacts.aspx" />
                    </td>
                </tr>
            </table>
        </div>
    </header>
    <div ID="Content">
        <asp:ContentPlaceHolder ID="MainContent" runat="server">
        </asp:ContentPlaceHolder>
    </div>
</code>```

答:
Ok! Got it working.

jQuery

```<code>var distance = $('#Menu').offset().top,
$window = $(window);

$(document).ready(function () {

$(document).scroll(function () {
    if ($window.scrollTop() >= distance) {
        $("#Menu").addClass('MenuOnTop');
        $("#Content").addClass('ContentStep');
    } else {
        $("#Menu").removeClass('MenuOnTop');
        $("#Content").removeClass('ContentStep');
    }

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

CSS

```<code>.MenuOnTop {
position:fixed;
top: 0px;
width:100%;
}

    .ContentStep{
    margin-top:120px;
}

html, body {
    width: 100%;
    font-family: 0;
    margin: 0;
    padding: 0;
    overflow: visible;
}
</code>```

Biggest issue was using windows as variable nad overflow on body, for first didnt have set any, but setting visible did the job. Thanks Junaid Ahmed for kickup.

Body:
I ran into problem I cant solve whole night. Actually what I am looking for.
"Actual look and tool to explain what I am asking for"

I want the red part to scroll up, when I scroll, the blue part go on scroll up too, but on top:0px stop and become fixed, I guess it will be by jQuery and I am really bad at it, best would be just by css, due to mobile users. Can someone help me with that please? Here is my html markup

RISTORANTE PIZZERIE NA HRADBÁCH

ROZVOZ JÍDEL A PIZZY PO SLANÉM A OKOLÍ

                        <asp:Button ID="homeButton" runat="server" Text="Domů" PostBackUrl="Home.aspx" />

                        <asp:Button ID="dailyMenuButton" runat="server" Text="Denní Nabídka" PostBackUrl="DailyMenu.aspx" />

                        <asp:Button ID="diningMenuButton" runat="server" Text="Jídelní Menu" PostBackUrl="DiningMenu.aspx" />

                        <asp:Button ID="contactsButton" runat="server" Text="Kontakt" PostBackUrl="Contacts.aspx" />

        <asp:ContentPlaceHolder ID="MainContent" runat="server">
        </asp:ContentPlaceHolder>

Body:
Ok! Got it working.

jQuery

var distance = $('#Menu').offset().top,
$window = $(window);

$(document).ready(function () {

$(document).scroll(function () {
    if ($window.scrollTop() >= distance) {
        $("#Menu").addClass('MenuOnTop');
        $("#Content").addClass('ContentStep');
    } else {
        $("#Menu").removeClass('MenuOnTop');
        $("#Content").removeClass('ContentStep');
    }

});
});

CSS

.MenuOnTop {
position:fixed;
top: 0px;
width:100%;
}

    .ContentStep{
    margin-top:120px;
}

html, body {
    width: 100%;
    font-family: 0;
    margin: 0;
    padding: 0;
    overflow: visible;
}

Biggest issue was using windows as variable nad overflow on body, for first didnt have set any, but setting visible did the job. Thanks Junaid Ahmed for kickup.


问:
Dynamic breadcrumbs using react router
There is very good example of how to make a breadcrumbs on site in examples folder of react-router repo. But I'm wondering how to make breadcrumbs with dynamic routes.

Assume we have this configuration:

```<code>ReactDOM.render((
<Router history={browserHistory}>
    <Route path="/projects" component={ProjectsApp}>
        <IndexRoute component={ProjectsDashboard} />
        <Route path=":projectId" component={ProjectBoard}>
            <Route path=":taskId" component={ProjectTaskBoard}>
        </Route>
    </Route>
</Router>
), document.getElementById('app'));
</code>```

I want to make something like this:

Projects(link to '/projects') -> MyAwesomeProject (link to '/projects/11'. Title taken from somewhere (from store by id from routeParams or by another way)) -> MyTask (link to '/projects/11/999')

How can I achieve this result? Are there any best practices? Thanks.

答:
We use the package react-breadcrumbs-dynamic which is most

flexible for any router (included react-router v4).

```<code>import {
  BreadcrumbsProvider,
  Breadcrumbs,
  BreadcrumbsItem
} from 'react-breadcrumbs-dynamic'

const theApp = (
  <BreadcrumbsProvider>
    <App />
  </BreadcrumbsProvider>
)

const App = (props) => (
  return (
    <div className="App">
      <Breadcrumbs/>
      {props.children}
    </div>
  )
}

const Page = (props) => (
  <div>
    <BreadcrumbsItem to='/'>Main Page</BreadcrumbsItem>
    {props.children}
    <Route exact path="/user" component={User} />
  </div>
)

const User = (props) => (
  <div>
    <BreadcrumbsItem to='/user'>Home</BreadcrumbsItem>
    <h2>Home</h2>
  </div>
)
</code>```

The repo is here: react-breadcrumbs-dynamic

Title: Dynamic breadcrumbs using react router

Body:
There is very good example of how to make a breadcrumbs on site in examples folder of react-router repo. But I'm wondering how to make breadcrumbs with dynamic routes.

Assume we have this configuration:

ReactDOM.render((
<Router history={browserHistory}>
    <Route path="/projects" component={ProjectsApp}>
        <IndexRoute component={ProjectsDashboard} />
        <Route path=":projectId" component={ProjectBoard}>
            <Route path=":taskId" component={ProjectTaskBoard}>
        </Route>
    </Route>
</Router>
), document.getElementById('app'));

I want to make something like this:

Projects(link to '/projects') -> MyAwesomeProject (link to '/projects/11'. Title taken from somewhere (from store by id from routeParams or by another way)) -> MyTask (link to '/projects/11/999')

How can I achieve this result? Are there any best practices? Thanks.

Body:
We use the package react-breadcrumbs-dynamic which is most

flexible for any router (included react-router v4).

import {
  BreadcrumbsProvider,
  Breadcrumbs,
  BreadcrumbsItem
} from 'react-breadcrumbs-dynamic'

const theApp = (
  <BreadcrumbsProvider>
    <App />
  </BreadcrumbsProvider>
)

const App = (props) => (
  return (
    <div className="App">
      <Breadcrumbs/>
      {props.children}
    </div>
  )
}

const Page = (props) => (
  <div>
    <BreadcrumbsItem to='/'>Main Page</BreadcrumbsItem>
    {props.children}
    <Route exact path="/user" component={User} />
  </div>
)

const User = (props) => (
  <div>
    <BreadcrumbsItem to='/user'>Home</BreadcrumbsItem>
    <h2>Home</h2>
  </div>
)

The repo is here: react-breadcrumbs-dynamic


问:
Python slimit minimizer unwanted warning output
```<code>from slimit import minify

if __name__ == "__main__":
    print("start")

    # Normally, I pass real JavaScript. For this issue, an empty string reproduces problem.
    minify("", mangle=True)

    print("exit")
</code>```

This triggers the following console output.

```<code>start
WARNING: Couldn't write lextab module <module 'slimit.lextab' from '/Users/kurtostfeld/samba/wrapad/venv/lib/python2.7/site-packages/slimit/lextab.pyc'>. Won't overwrite existing lextab module
WARNING: yacc table file version is out of date
WARNING: Token 'IMPORT' defined, but not used
WARNING: Token 'BLOCK_COMMENT' defined, but not used
WARNING: Token 'ENUM' defined, but not used
WARNING: Token 'EXTENDS' defined, but not used
WARNING: Token 'LINE_COMMENT' defined, but not used
WARNING: Token 'LINE_TERMINATOR' defined, but not used
WARNING: Token 'CONST' defined, but not used
WARNING: Token 'EXPORT' defined, but not used
WARNING: Token 'CLASS' defined, but not used
WARNING: Token 'SUPER' defined, but not used
WARNING: There are 10 unused tokens
WARNING: Couldn't create <module 'slimit.yacctab' from '/Users/kurtostfeld/samba/wrapad/venv/lib/python2.7/site-packages/slimit/yacctab.pyc'>. Won't overwrite existing tabmodule
exit
</code>```

These warnings are flooding my application console output. How can I use minify without generating warnings?

I'm using Python 2.7.12, and what is currently the latest library versions: slimit 0.8.1, ply 3.10.

答:
Here was the solution that I went with. I made a custom variant of two slimit functions that pass an extra errorlog=ply.yacc.NullLogger() call to the ply.yacc.yacc function.

```<code>class SlimitNoLoggingParser(Parser):
    """
    This is a simple customized variant to slimit.parser.Parser.

    The only difference is that this passes a errorlog=ply.yacc.NullLogger() to ply.yacc.yacc to suppress unwanted
    stderr logging output.
    """

    def __init__(self, lex_optimize=True, lextab=lextab,
                 yacc_optimize=True, yacctab=yacctab, yacc_debug=False):
        self.lex_optimize = lex_optimize
        self.lextab = lextab
        self.yacc_optimize = yacc_optimize
        self.yacctab = yacctab
        self.yacc_debug = yacc_debug

        self.lexer = Lexer()
        self.lexer.build(optimize=lex_optimize, lextab=lextab)
        self.tokens = self.lexer.tokens

        self.parser = ply.yacc.yacc(
            module=self, optimize=yacc_optimize,
            errorlog=ply.yacc.NullLogger(),
            debug=yacc_debug, tabmodule=yacctab, start='program')

        # https://github.com/rspivak/slimit/issues/29
        # lexer.auto_semi can cause a loop in a parser
        # when a parser error happens on a token right after
        # a newline.
        # We keep record of the tokens that caused p_error
        # and if the token has already been seen - we raise
        # a SyntaxError exception to avoid looping over and
        # over again.
        self._error_tokens = {}

# This is a simply variant of slimit.minify that suppresses unwanted noisy stderr logging output.
def warning_free_minify(text, mangle=False, mangle_toplevel=False):
    parser = SlimitNoLoggingParser(lex_optimize=False)
    tree = parser.parse(text)
    if mangle:
        mangler.mangle(tree, toplevel=mangle_toplevel)
    minified = ECMAMinifier().visit(tree)
    return minified
</code>```

Body:
from slimit import minify

if __name__ == "__main__":
    print("start")

    # Normally, I pass real JavaScript. For this issue, an empty string reproduces problem.
    minify("", mangle=True)

    print("exit")

This triggers the following console output.

start
WARNING: Couldn't write lextab module <module 'slimit.lextab' from '/Users/kurtostfeld/samba/wrapad/venv/lib/python2.7/site-packages/slimit/lextab.pyc'>. Won't overwrite existing lextab module
WARNING: yacc table file version is out of date
WARNING: Token 'IMPORT' defined, but not used
WARNING: Token 'BLOCK_COMMENT' defined, but not used
WARNING: Token 'ENUM' defined, but not used
WARNING: Token 'EXTENDS' defined, but not used
WARNING: Token 'LINE_COMMENT' defined, but not used
WARNING: Token 'LINE_TERMINATOR' defined, but not used
WARNING: Token 'CONST' defined, but not used
WARNING: Token 'EXPORT' defined, but not used
WARNING: Token 'CLASS' defined, but not used
WARNING: Token 'SUPER' defined, but not used
WARNING: There are 10 unused tokens
WARNING: Couldn't create <module 'slimit.yacctab' from '/Users/kurtostfeld/samba/wrapad/venv/lib/python2.7/site-packages/slimit/yacctab.pyc'>. Won't overwrite existing tabmodule
exit

These warnings are flooding my application console output. How can I use minify without generating warnings?

I'm using Python 2.7.12, and what is currently the latest library versions: slimit 0.8.1, ply 3.10.

Body:
Here was the solution that I went with. I made a custom variant of two slimit functions that pass an extra errorlog=ply.yacc.NullLogger() call to the ply.yacc.yacc function.

class SlimitNoLoggingParser(Parser):
    """
    This is a simple customized variant to slimit.parser.Parser.

    The only difference is that this passes a errorlog=ply.yacc.NullLogger() to ply.yacc.yacc to suppress unwanted
    stderr logging output.
    """

    def __init__(self, lex_optimize=True, lextab=lextab,
                 yacc_optimize=True, yacctab=yacctab, yacc_debug=False):
        self.lex_optimize = lex_optimize
        self.lextab = lextab
        self.yacc_optimize = yacc_optimize
        self.yacctab = yacctab
        self.yacc_debug = yacc_debug

        self.lexer = Lexer()
        self.lexer.build(optimize=lex_optimize, lextab=lextab)
        self.tokens = self.lexer.tokens

        self.parser = ply.yacc.yacc(
            module=self, optimize=yacc_optimize,
            errorlog=ply.yacc.NullLogger(),
            debug=yacc_debug, tabmodule=yacctab, start='program')

        # https://github.com/rspivak/slimit/issues/29
        # lexer.auto_semi can cause a loop in a parser
        # when a parser error happens on a token right after
        # a newline.
        # We keep record of the tokens that caused p_error
        # and if the token has already been seen - we raise
        # a SyntaxError exception to avoid looping over and
        # over again.
        self._error_tokens = {}

# This is a simply variant of slimit.minify that suppresses unwanted noisy stderr logging output.
def warning_free_minify(text, mangle=False, mangle_toplevel=False):
    parser = SlimitNoLoggingParser(lex_optimize=False)
    tree = parser.parse(text)
    if mangle:
        mangler.mangle(tree, toplevel=mangle_toplevel)
    minified = ECMAMinifier().visit(tree)
    return minified


问:
Lightweight workflow engine for Java
Is it better to write a new workflow engine or to use an existing BPM engine: jBPM 5, Activiti 5?

My application is a web based application and performance is important. My doubt is whether using jBPM/Activiti will be a performance overhead compared to writing a simple workflow engine.

If I go with self implementation, I will miss visualization of workflow. For performance it can be traded.

答: I recently open sourced Piper (https://github.com/creactiviti/piper) a distributed and very light weight, Spring-based, workflow engine. </p>

ContentLicense: CC BY-SA 4.0

Title: Lightweight workflow engine for Java


问:
Turn SELECT into DELETE mysql php
I am having a heck of a time turn this SELECT statement into a DELETE.

```<code>$query  = "
SELECT n.thread_id
     , n.status
     , n.status_tooltip_text
  FROM newmessages n
     , oldmessages o
 WHERE n.thread_id = o.thread_id
   AND n.status_tooltip_text = o.status_tooltip_text
";
</code>```

The end result I am trying to achieve is to delete from newmessages where the status tooltip text is the same as the status tooltip in oldmessages.

The select I have above works, but when I turn the select into a delete it says database query failed.  The columns in the two tables have identical column definitions.

答:
Replacing SELECT with DELETE is not going to work DELETE statement doest not have the column

```<code>$query  = "DELETE n FROM
newmessages n, oldmessages o ";
$query .= "WHERE n.thread_id=o.thread_id ";
$query .= "AND n.status_tooltip_text=o.status_tooltip_text";
</code>```

I hope this helps

Title: Turn SELECT into DELETE mysql php

Body:
I am having a heck of a time turn this SELECT statement into a DELETE.

$query  = "
SELECT n.thread_id
     , n.status
     , n.status_tooltip_text
  FROM newmessages n
     , oldmessages o
 WHERE n.thread_id = o.thread_id
   AND n.status_tooltip_text = o.status_tooltip_text
";

The end result I am trying to achieve is to delete from newmessages where the status tooltip text is the same as the status tooltip in oldmessages.

The select I have above works, but when I turn the select into a delete it says database query failed.  The columns in the two tables have identical column definitions.

Body:
Replacing SELECT with DELETE is not going to work DELETE statement doest not have the column

$query  = "DELETE n FROM
newmessages n, oldmessages o ";
$query .= "WHERE n.thread_id=o.thread_id ";
$query .= "AND n.status_tooltip_text=o.status_tooltip_text";

I hope this helps


问:
Fetch Table Column values into varchar in SQL Sever
I have

```<code>tableA (strX varchar(10), strY varchar(10))
Values ('Me', 'Today')
       ('You', 'Yesterday')

tableB (strP varchar(10), strQ varchar(10))
Values ('He', 'Rejected')
       ('Me', 'Accepted')
       ('You', 'Rejected')
       ('Her', 'Accepted')
</code>```

and my Query in stored procedure goes like below and is being called more than 10 times in my procedure.

```<code>Select * from tableB  Where strp in (Select strX from tableA);
</code>```

Is there a way I can store Select strX from tableA into a variable and make use of it like below ?

```<code>Declare @strValues = (Select strX from tableA);

Select * from tableB  Where strp in @strValues;
</code>```

no of entries for strX is dynamic in tableA.

答:
Not to detract from what the rest are saying here, but I think a table variable like below is technically what you're asking for:

```<code>declare @strValues table (value varchar(10))
insert into @strValues
    select strx from tableA

select * from tableB where strP in (select * from @strValues)
</code>```

I doubt this would be an improvement but present it for what it's worth.

Body:
I have

tableA (strX varchar(10), strY varchar(10))
Values ('Me', 'Today')
       ('You', 'Yesterday')

tableB (strP varchar(10), strQ varchar(10))
Values ('He', 'Rejected')
       ('Me', 'Accepted')
       ('You', 'Rejected')
       ('Her', 'Accepted')

and my Query in stored procedure goes like below and is being called more than 10 times in my procedure.

Select * from tableB  Where strp in (Select strX from tableA);

Is there a way I can store Select strX from tableA into a variable and make use of it like below ?

Declare @strValues = (Select strX from tableA);

Select * from tableB  Where strp in @strValues;

no of entries for strX is dynamic in tableA.

Body:
Not to detract from what the rest are saying here, but I think a table variable like below is technically what you're asking for:

declare @strValues table (value varchar(10))
insert into @strValues
    select strx from tableA

select * from tableB where strP in (select * from @strValues)

I doubt this would be an improvement but present it for what it's worth.


问:
Deleting rows in BigQuery fails with "Invalid schema update"
I'm trying to delete some rows from a BigQuery table (using standard SQL dialect):

```<code>DELETE FROM ocds.releases
WHERE
  ocid LIKE 'ocds-b5fd17-%'
</code>```

However, I get the following error:

```<code>Query Failed
Error: Invalid schema update. Field packageInfo has changed mode from REQUIRED to NULLABLE
Job ID: ocds-172716:bquijob_2f60927_15d13c97149
</code>```

It seems as though BigQuery doesn't like deleting rows with a REQUIRED column. Is there any way around this?

答:
It has been a known limitation that BigQuery DML doesn't work with tables with required fields (see https://cloud.google.com/bigquery/docs/reference/standard-sql/data-manipulation-language#known_issues).

We are in the process of removing this limitation. We whitelisted your project today. Please try running your query again in the same project. Let us know if the problem is still there, or if you want to have more projects whitelisted.

Body:
I'm trying to delete some rows from a BigQuery table (using standard SQL dialect):

DELETE FROM ocds.releases
WHERE
  ocid LIKE 'ocds-b5fd17-%'

However, I get the following error:

Query Failed
Error: Invalid schema update. Field packageInfo has changed mode from REQUIRED to NULLABLE
Job ID: ocds-172716:bquijob_2f60927_15d13c97149

It seems as though BigQuery doesn't like deleting rows with a REQUIRED column. Is there any way around this?


问:
vis.js Network Manipulation: Split Node label onto different lines
I am using vis.4.18.1.

I have an interactive chart and nodes can be added or edited by clicking on the map using addNode() and editNode().

How can I set the Node label on multiple lines?

I am collecting the label data using a pop-up form.

I know this can be done when importing initial chart data when the map is created by using newline but this does not work interactively and the node label looks like:

'John Smith\nDate of birth'.

I have also tried setting node font to multi and using html br but this also doesn't work.

答:
Have you tried something along the lines of:

```<code>node.username = "John Smith";
node.dateOfBirth = "Jun 18th 1978";
node.label = node.username + "\n" + node.dateOfBirth;
</code>```

You may extend your node object by properties not inherent to visJS nodes/dataSet. Maybe that way you can work around your issue.

Edit: I just tested this example where node.label = node.title on the initial render and gets expanded when the node is selected.

```<code>function expandNode(selectedNode){
  selectedNode.label = selectedNode.title + '\n' + 'a' + '\n' + 'b' + '\n' + selectedNode.problem;
  nodesObj.update(selectedNode);
}

network.on('select', function(selection){
  let selectedNodes = nodesObj.get(selection.nodes); // nodesObj is a visjs dataSet
  if(selection.nodes.length === 1){
    expandNode(selectedNodes[0]);
  }
}
</code>```

Collapsed & expanded node

Body:
Have you tried something along the lines of:

node.username = "John Smith";
node.dateOfBirth = "Jun 18th 1978";
node.label = node.username + "\n" + node.dateOfBirth;

You may extend your node object by properties not inherent to visJS nodes/dataSet. Maybe that way you can work around your issue.

Edit: I just tested this example where node.label = node.title on the initial render and gets expanded when the node is selected.

function expandNode(selectedNode){
  selectedNode.label = selectedNode.title + '\n' + 'a' + '\n' + 'b' + '\n' + selectedNode.problem;
  nodesObj.update(selectedNode);
}

network.on('select', function(selection){
  let selectedNodes = nodesObj.get(selection.nodes); // nodesObj is a visjs dataSet
  if(selection.nodes.length === 1){
    expandNode(selectedNodes[0]);
  }
}

Collapsed & expanded node


问:
fatal error: numpy/arrayobject.h: No such file or directory
I am limited on what I can share as this is part of a huge stack of code that I am porting from Ubuntu 14.04 to 16.04.

It should be trivial, but somehow I am struggling with this. It doesn't find numpy/arrayobject.h that I am referencing in my source file with #include <numpy/arrayobject.h>

I will try to share as much as I can, see if someone can guide me through a resolution.

Ubuntu

```<code>$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.2 LTS
Release:    16.04
Codename:   xenial
</code>```

make

```<code>$ make --version
GNU Make 4.1
Built for x86_64-pc-linux-gnu
</code>```

g++

```<code>$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
</code>```

upgraded to

```<code># g++ --version
g++ (Ubuntu 5.4.1-2ubuntu1~16.04) 5.4.1 20160904
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

python

```<code>$ python --version
Python 2.7.12
</code>```

Some environment variables

```<code>PYTHON       /usr/bin/python2.7
ARCH         x86_64
OS           Linux
VERSION      4.4.071generic
PLATFORM     linux2
HOSTNAME     deploy
USER         myUser
WUSS_BUILD   NO
CCVER        gcc
PYLIBDIR     build.x86_64-linux2
LIBDIR       build.x86_64-linux2
BINDIR       build.x86_64-linux2
ODIR         build.x86_64-linux2-gcc
STATICLIBDIR build-static.x86_64-linux2
</code>```

Error

The make command leads to

```<code>+++ Compile mycore/boost_numpy.cc to build.x86_64-linux2-gcc
anycore/boost_numpy.cc:2:31: fatal error: numpy/arrayobject.h: No such file or directory
</code>```

My source file

```<code>user@deploy:~/my-linux$ vim mycore/boost_numpy.cc

#include "anycore/boost_python_headers.h"
#include <numpy/arrayobject.h>           <====== DECLARATION
#include <numpy/ufuncobject.h>
#include "mycore/boost_numpy.h"
#include "mycore/numerical.h"
#include "mycore/vec3.h"

using namespace boost::python;

PyObject *
read_numeric_file_ficii(FILE *fp, int ncols, char arrtype, int headlines, int taillines)
{
  if (!(arrtype=='d' || arrtype=='f' || arrtype=='i')) {
    PyErr_SetString(PyExc_ValueError, "Unknown array type for read_numeric_file");
    return NULL;
  }
...FILTERED...
</code>```

Declaration file numpy/arrayobject.h on disk

```<code>root@deploy:/home#  find / -name arrayobject.h
/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h
</code>```

Please let me know how I can improve the question. Directions or pointers are most welcome

UPDATE

```<code>$ ls -l /usr/include/numpy
ls: cannot access '/usr/include/numpy': No such file or directory
</code>```

RESOLVED WITH

```<code>sudo ln -s  /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy /usr/include/numpy
</code>```

答:
I have experienced the same behavior on a partly broken Debian installation.

I fixed the error by reestablishing a symbolic link

sudo ln -s /usr/lib/python2.7/dist-packages/numpy/core/include/numpy /usr/include/numpy

Body:
I am limited on what I can share as this is part of a huge stack of code that I am porting from Ubuntu 14.04 to 16.04.

It should be trivial, but somehow I am struggling with this. It doesn't find numpy/arrayobject.h that I am referencing in my source file with #include <numpy/arrayobject.h>

I will try to share as much as I can, see if someone can guide me through a resolution.

Ubuntu

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.2 LTS
Release:    16.04
Codename:   xenial

make

$ make --version
GNU Make 4.1
Built for x86_64-pc-linux-gnu

g++

$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609

upgraded to

# g++ --version
g++ (Ubuntu 5.4.1-2ubuntu1~16.04) 5.4.1 20160904
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

python

$ python --version
Python 2.7.12

Some environment variables

PYTHON       /usr/bin/python2.7
ARCH         x86_64
OS           Linux
VERSION      4.4.071generic
PLATFORM     linux2
HOSTNAME     deploy
USER         myUser
WUSS_BUILD   NO
CCVER        gcc
PYLIBDIR     build.x86_64-linux2
LIBDIR       build.x86_64-linux2
BINDIR       build.x86_64-linux2
ODIR         build.x86_64-linux2-gcc
STATICLIBDIR build-static.x86_64-linux2

Error

The make command leads to

+++ Compile mycore/boost_numpy.cc to build.x86_64-linux2-gcc
anycore/boost_numpy.cc:2:31: fatal error: numpy/arrayobject.h: No such file or directory

My source file

user@deploy:~/my-linux$ vim mycore/boost_numpy.cc

#include "anycore/boost_python_headers.h"
#include <numpy/arrayobject.h>           <====== DECLARATION
#include <numpy/ufuncobject.h>
#include "mycore/boost_numpy.h"
#include "mycore/numerical.h"
#include "mycore/vec3.h"

using namespace boost::python;

PyObject *
read_numeric_file_ficii(FILE *fp, int ncols, char arrtype, int headlines, int taillines)
{
  if (!(arrtype=='d' || arrtype=='f' || arrtype=='i')) {
    PyErr_SetString(PyExc_ValueError, "Unknown array type for read_numeric_file");
    return NULL;
  }
...FILTERED...

Declaration file numpy/arrayobject.h on disk

root@deploy:/home#  find / -name arrayobject.h
/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h

Please let me know how I can improve the question. Directions or pointers are most welcome

UPDATE

$ ls -l /usr/include/numpy
ls: cannot access '/usr/include/numpy': No such file or directory

RESOLVED WITH

sudo ln -s  /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy /usr/include/numpy


问:
Space between SVG stroke and fill
Filling and stroking a circle with the same color and a stroke-width exceeding a certain size, produces a strange transparent region “between” the two paint regions. What is going on?

This is happening in both Chrome and Firefox, so it may be to spec, but I couldn’t find any language in the spec about this behavior.

Fiddle

```<code><svg viewBox="0 0 300 300">
  <circle cx="100" cy="100" r="8"
    stroke="#000" stroke-width="40"
    fill="#000"/>
</svg>
</code>```

Produces this rendering:

答:
As Robert Longson noted, the issue shows up when a stroke overlaps itself in such a way that it creates a donut-hole when you convert the stroke outline to a separate path (depending on the winding-order / fill-rule calculations).

The gap between the fill and stroke in your particular example is caused by the "inside" edge of the stroke extending across the entire fill region and out the other side.

It gets really weird when you have dashed strokes, as shown in the examples from Tavmjong Bah's discussion article.

This is, unfortunately, neither according to the SVG spec nor against the spec. Instead, the spec at this point of time has left the matter undefined.

SVG working group discussion is here.

At this point, WebKit, Blink, and Firefox on Mac/Android draw strokes with cut-outs, using the Skia graphics library or Apple's CoreGraphics.

IE/Edge and Firefox on Windows/Linux just draw the total stroke, without cut-outs, as do Inkscape and Illustrator and most PDF-rendering software (the PDF spec itself is non-committal).

Everyone I've discussed this with agrees that the cut-outs are a sub-optimal result.  But with so many browsers using rendering engines that do it this way, the SVG working group wasn't willing to make the more-intuitive stroke behavior a strict requirement.  So instead, the SVG 2 spec has a warning-to-authors with a sample figure:

At this point, the best prospect for making a change would be to file issues (or contribute code) on the Skia library.  If it was changed, that puts pressure on Apple to update to match, and the SVG spec would be able to make it official.

Title: Space between SVG stroke and fill

Body:
Filling and stroking a circle with the same color and a stroke-width exceeding a certain size, produces a strange transparent region “between” the two paint regions. What is going on?

This is happening in both Chrome and Firefox, so it may be to spec, but I couldn’t find any language in the spec about this behavior.

Fiddle

<svg viewBox="0 0 300 300">
  <circle cx="100" cy="100" r="8"
    stroke="#000" stroke-width="40"
    fill="#000"/>
</svg>

Produces this rendering:


问:
Default field values in nested objects
I am attempting to create an object from JSON.

Part of my object looks like

```<code>a: {
   name: "A name",
   b: {
      c: {
         d: []
         }
      }
   }
</code>```

To save bandwidth, empty arrays and empty objects are stripped from the JSON, so the JSON that I receive is

```<code>{ "a": { "name": "A name" }}
</code>```

If I just convert the JSON to an object, this leads to errors when I try to do things like a.b.c.d.length, as undefined does not have a length.

At the moment, I am populating the missing fields by something like

```<code>const json = getJson();
const obj = {
    ...json,
    a: {
       ...json.a,
       b: {
          ...json.a.b,
          c: {
             ...json.a.b.c,
             d: json.a.b.c.d || []
             }
           }
        }
     };
</code>```

This is pretty verbose, and is going to get even uglier when there are several fields that need default values.

One obvious solution is to not strip out the empty arrays from the transmitted JSON.  Assuming that that is not possible, is there a better way to handle this case?

In the real case, there are multiple fields at each level, so all of the spread operators are necessary.  (Even if they were not, I would want to include them as the structure is likely to grow in the future.)

Edit: I am not using JQuery.  I am using whatwg-fetch to retrieve data.

答:
For best practice, I think you should not employ sophisticated approach or syntax.
Just use a common default value set of Javascript:

```<code>var _d = a.b.c.d || [].
// does something with _d.length
</code>```

While you are trying to do something, you can achieve that but code quality is worse. Think different and do different it may be better.

Moreover, I think declare the original a object explicitly with all properties is better than remove empty property like you do.

Title: Default field values in nested objects

Body:
I am attempting to create an object from JSON.

Part of my object looks like

a: {
   name: "A name",
   b: {
      c: {
         d: []
         }
      }
   }

To save bandwidth, empty arrays and empty objects are stripped from the JSON, so the JSON that I receive is

{ "a": { "name": "A name" }}

If I just convert the JSON to an object, this leads to errors when I try to do things like a.b.c.d.length, as undefined does not have a length.

At the moment, I am populating the missing fields by something like

const json = getJson();
const obj = {
    ...json,
    a: {
       ...json.a,
       b: {
          ...json.a.b,
          c: {
             ...json.a.b.c,
             d: json.a.b.c.d || []
             }
           }
        }
     };

This is pretty verbose, and is going to get even uglier when there are several fields that need default values.

One obvious solution is to not strip out the empty arrays from the transmitted JSON.  Assuming that that is not possible, is there a better way to handle this case?

In the real case, there are multiple fields at each level, so all of the spread operators are necessary.  (Even if they were not, I would want to include them as the structure is likely to grow in the future.)

Edit: I am not using JQuery.  I am using whatwg-fetch to retrieve data.

Body:
For best practice, I think you should not employ sophisticated approach or syntax.
Just use a common default value set of Javascript:

var _d = a.b.c.d || [].
// does something with _d.length

While you are trying to do something, you can achieve that but code quality is worse. Think different and do different it may be better.

Moreover, I think declare the original a object explicitly with all properties is better than remove empty property like you do.


答:
I would suggest some sort of solution in which you establish a pre-determined schema, and continue to omit empty arrays/values. You can then do something like

```<code>_.get(object, 'property.path.here', defaultValue)
</code>```

with lodash.get(), where defaultValue is determined by your schema as an empty string "", 0, null, etc.

Title: Default field values in nested objects

Body:
I would suggest some sort of solution in which you establish a pre-determined schema, and continue to omit empty arrays/values. You can then do something like

_.get(object, 'property.path.here', defaultValue)

with lodash.get(), where defaultValue is determined by your schema as an empty string "", 0, null, etc.


问:
Sequelize: join two times the same table

Background:

I have a table Users with a one-to-many relationship to Userlang. For instance:

```<code> userlang.id userlang.userid userlang.lang
+-----------+---------------+-------------+
 1            1              EN
 2            1              FR
 3            1              IT
 4            2              EN
 5            2              DE
 6            3              IT
</code>```

I want to select all users and their userlangs that have at least one userlang.lang=EN.

So, I cannot use the following query:

```<code>Select USERS.id from USERS inner join USERLANG on USERS.ID=USERLANG.USERID where USERLANG.LANG="EN"
</code>```

because it will select only the Userlangs row with a lang="EN", while I want to select all userlang rows of each user, where at least one has lang="EN"

I am already able to write such a query in two ways with SQL:

using sub queries:

```<code>Select *
from USERS inner join USERLANG on USERS.ID=USERLANG.USERID
where USERS.ID in (
    Select USERS.id
    from USERS inner join USERLANG on USERS.ID=USERLANG.USERID
    where USERLANG.LANG="EN"
)
</code>```

While the inner query will select only userlang rows with lang="EN", the outer one will select all userlangs for such users.

using two inner joins of the same table:

```<code>Select *
from USERS innerjoin USERLANG as FILTER on FILTER.userid=USERS.userid
inner join USERLANG on USERLANG.userid=FILTER.userid
where FILTER.lang="EN"
</code>```

The problem: porting them on sequelize

I am completely unable to write a subquery on sequelize: I want to avoid to write pure SQL as it would be open possible injections attack.

This is my failed attempt that gives error becasue of no relation of 'FILTER' with USer:

```<code>models.User.findAll({
    include:[models.Userlang,{model:models.Userlang,as:'FILTER'}]
})
</code>```

答:
Try to define your associations with some alias:

```<code>            List.belongsTo(Task, {
              as: 'dailyTask',
              foreignKey: 'dailyTask'
            });

            List.belongsTo(Task, {
               as: 'weeklyTask',
               foreignKey: 'weeklyTask'
            });
</code>```

The example from the creator is in this link:
https://github.com/sequelize/sequelize/issues/3678

Body:
Background:

I have a table Users with a one-to-many relationship to Userlang. For instance:

 userlang.id userlang.userid userlang.lang
+-----------+---------------+-------------+
 1            1              EN
 2            1              FR
 3            1              IT
 4            2              EN
 5            2              DE
 6            3              IT

I want to select all users and their userlangs that have at least one userlang.lang=EN.

So, I cannot use the following query:

Select USERS.id from USERS inner join USERLANG on USERS.ID=USERLANG.USERID where USERLANG.LANG="EN"

because it will select only the Userlangs row with a lang="EN", while I want to select all userlang rows of each user, where at least one has lang="EN"

I am already able to write such a query in two ways with SQL:

using sub queries:

Select *
from USERS inner join USERLANG on USERS.ID=USERLANG.USERID
where USERS.ID in (
    Select USERS.id
    from USERS inner join USERLANG on USERS.ID=USERLANG.USERID
    where USERLANG.LANG="EN"
)

While the inner query will select only userlang rows with lang="EN", the outer one will select all userlangs for such users.

using two inner joins of the same table:

Select *
from USERS innerjoin USERLANG as FILTER on FILTER.userid=USERS.userid
inner join USERLANG on USERLANG.userid=FILTER.userid
where FILTER.lang="EN"

The problem: porting them on sequelize

I am completely unable to write a subquery on sequelize: I want to avoid to write pure SQL as it would be open possible injections attack.

This is my failed attempt that gives error becasue of no relation of 'FILTER' with USer:

models.User.findAll({
    include:[models.Userlang,{model:models.Userlang,as:'FILTER'}]
})

Body:
Try to define your associations with some alias:

            List.belongsTo(Task, {
              as: 'dailyTask',
              foreignKey: 'dailyTask'
            });

            List.belongsTo(Task, {
               as: 'weeklyTask',
               foreignKey: 'weeklyTask'
            });

The example from the creator is in this link:
https://github.com/sequelize/sequelize/issues/3678


问:
how to compare word letters using if statements?
I'm trying to write a program that reads a word and prints if:

it ends with the letter y.

has the same first and last character, ignoring case.

This is what I have so far, but I'm having trouble thinking of a line of code that will check individual letters or compare the first and last letters.

```<code>  if (. . .)
  {
     System.out.println(word + " ends in a y");
  }

  if (. . .)
  {
     System.out.println(word + " starts and ends with the same letter");
  }
</code>```

答:
You can use String.endsWith for both:</p>
```<code>// To ignore case, just lower all
word = word.toLowerCase();
// Check if it ends with 'y'
if (word.endsWith("y"))
// Check if it starts and ends with same letter
if (word.endsWith(word.substring(0,1)))
</code>```

Body:
I'm trying to write a program that reads a word and prints if:

it ends with the letter y.

has the same first and last character, ignoring case.

This is what I have so far, but I'm having trouble thinking of a line of code that will check individual letters or compare the first and last letters.

  if (. . .)
  {
     System.out.println(word + " ends in a y");
  }

  if (. . .)
  {
     System.out.println(word + " starts and ends with the same letter");
  }

Body:
You can use String.endsWith for both:

// To ignore case, just lower all
word = word.toLowerCase();
// Check if it ends with 'y'
if (word.endsWith("y"))
// Check if it starts and ends with same letter
if (word.endsWith(word.substring(0,1)))


问:
Fading in/out GameObject
I'm fairly new to coding, I'm still trying to develop that logic of thinking to help me create the solutions I'm wanting for games. Currently, I'm in Unity trying to create a 2D GameObject that's a wall hiding a secret door. I want that GameObject to fade out (about 90%) when the player GameObject triggers it, revealing the space behind and the hidden door.

So far, I've managed to figure out how to render the "secret wall" GO inactive on the trigger, so it disappears, but this doesn't produce the visual that I'm going for. As I said, I'm still working on developing that coder's way of thinking, so while I've done a lot of research to solve this problem, many of the results I don't readily understand.

Here's my code:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SecretDoor1 : MonoBehaviour {

    void OnTriggerEnter2D (Collider2D SecretDoorTrig) {
         if (SecretDoorTrig.gameObject.tag == "Player") {
             GetComponent<SpriteRenderer> ().enabled = false;
         }
         else {
             GetComponent<SpriteRenderer> ().enabled = true;
         }
    }

    void OnTriggerExit2D (Collider2D SecretDoorTrig) {

         if (SecretDoorTrig.gameObject.tag == "Player") {

             GetComponent<SpriteRenderer> ().enabled = true;
         }
         else {
             GetComponent<SpriteRenderer> ().enabled = false;
         }
    }
}
</code>```

答:
Fading a Sprite is almost the-same as moving GameObject over time except that you modify its alpha instead of it's position.

The three most important stuff about fading an Object are Time.deltaTime, Mathf.Lerp/Color.Lerp and coroutine. You need to understand how these work together.

Start coroutine, use Time.deltaTime to increment a variable. That variable is used to use to determine how much that function has ran. In a for/while loop, use that variable that is incremented every-frame and the duration you want the fade to happen to generate the alpha with the help of the Mathf.Lerp function. Create new color with that alpha and and assign it to the Sprite.

This is done every frame until that variable that is incremented with  Time.deltaTime reaches the duration you want to the fade to happen within.

Here is a simple SpriteRenderer fade function:

```<code>public SpriteRenderer spriteToFade;

IEnumerator fadeOut(SpriteRenderer MyRenderer, float duration)
{
    float counter = 0;
    //Get current color
    Color spriteColor = MyRenderer.material.color;

    while (counter < duration)
    {
        counter += Time.deltaTime;
        //Fade from 1 to 0
        float alpha = Mathf.Lerp(1, 0, counter / duration);
        Debug.Log(alpha);

        //Change alpha only
        MyRenderer.color = new Color(spriteColor.r, spriteColor.g, spriteColor.b, alpha);
        //Wait for a frame
        yield return null;
    }
}
</code>```

If you want it to fade in, change Mathf.Lerp(1, 0, counter / duration); to Mathf.Lerp(0, 1, counter / duration); which will make the alpha go from 0 to 1 over-time instead of 1 to 0.

From the example above, writing a fade-out and fade-in functions only requires a way to tell the function to change the alpha from 1 to 0 or from 0 to 1. You can make the function use a boolean or enum variable to determine which type of fade to perform. Of-course, you can separate the fade-in/fade-out functions but it's good to have it in one function.

Here is the extended version of that function that supports fade-in and fade-out. It also supports almost all GameObjects like MeshRenderer(3D), SpriteRenderer(2D), Image, RawImage....You can extend it to support more components that's missing.

```<code>IEnumerator fadeInAndOut(GameObject objectToFade, bool fadeIn, float duration)
{
    float counter = 0f;

    //Set Values depending on if fadeIn or fadeOut
    float a, b;
    if (fadeIn)
    {
        a = 0;
        b = 1;
    }
    else
    {
        a = 1;
        b = 0;
    }

    int mode = 0;
    Color currentColor = Color.clear;

    SpriteRenderer tempSPRenderer = objectToFade.GetComponent<SpriteRenderer>();
    Image tempImage = objectToFade.GetComponent<Image>();
    RawImage tempRawImage = objectToFade.GetComponent<RawImage>();
    MeshRenderer tempRenderer = objectToFade.GetComponent<MeshRenderer>();
    Text tempText = objectToFade.GetComponent<Text>();

    //Check if this is a Sprite
    if (tempSPRenderer != null)
    {
        currentColor = tempSPRenderer.color;
        mode = 0;
    }
    //Check if Image
    else if (tempImage != null)
    {
        currentColor = tempImage.color;
        mode = 1;
    }
    //Check if RawImage
    else if (tempRawImage != null)
    {
        currentColor = tempRawImage.color;
        mode = 2;
    }
    //Check if Text
    else if (tempText != null)
    {
        currentColor = tempText.color;
        mode = 3;
    }

    //Check if 3D Object
    else if (tempRenderer != null)
    {
        currentColor = tempRenderer.material.color;
        mode = 4;

        //ENABLE FADE Mode on the material if not done already
        tempRenderer.material.SetFloat("_Mode", 2);
        tempRenderer.material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
        tempRenderer.material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
        tempRenderer.material.SetInt("_ZWrite", 0);
        tempRenderer.material.DisableKeyword("_ALPHATEST_ON");
        tempRenderer.material.EnableKeyword("_ALPHABLEND_ON");
        tempRenderer.material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
        tempRenderer.material.renderQueue = 3000;
    }
    else
    {
        yield break;
    }

    while (counter < duration)
    {
        counter += Time.deltaTime;
        float alpha = Mathf.Lerp(a, b, counter / duration);

        switch (mode)
        {
            case 0:
                tempSPRenderer.color = new Color(currentColor.r, currentColor.g, currentColor.b, alpha);
                break;
            case 1:
                tempImage.color = new Color(currentColor.r, currentColor.g, currentColor.b, alpha);
                break;
            case 2:
                tempRawImage.color = new Color(currentColor.r, currentColor.g, currentColor.b, alpha);
                break;
            case 3:
                tempText.color = new Color(currentColor.r, currentColor.g, currentColor.b, alpha);
                break;
            case 4:
                tempRenderer.material.color = new Color(currentColor.r, currentColor.g, currentColor.b, alpha);
                break;
        }
        yield return null;
    }
}
</code>```

Usage:

GameObject to fade:

```<code>public GameObject SpriteRend;
</code>```

Fade-out in 3 seconds

```<code>StartCoroutine(fadeInAndOut(SpriteRend, false, 3f));
</code>```

Fade-in in 3 seconds

```<code>StartCoroutine(fadeInAndOut(SpriteRend, true, 3f));
</code>```

Title: Fading in/out GameObject

Body:
I'm fairly new to coding, I'm still trying to develop that logic of thinking to help me create the solutions I'm wanting for games. Currently, I'm in Unity trying to create a 2D GameObject that's a wall hiding a secret door. I want that GameObject to fade out (about 90%) when the player GameObject triggers it, revealing the space behind and the hidden door.

So far, I've managed to figure out how to render the "secret wall" GO inactive on the trigger, so it disappears, but this doesn't produce the visual that I'm going for. As I said, I'm still working on developing that coder's way of thinking, so while I've done a lot of research to solve this problem, many of the results I don't readily understand.

Here's my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SecretDoor1 : MonoBehaviour {

    void OnTriggerEnter2D (Collider2D SecretDoorTrig) {
         if (SecretDoorTrig.gameObject.tag == "Player") {
             GetComponent<SpriteRenderer> ().enabled = false;
         }
         else {
             GetComponent<SpriteRenderer> ().enabled = true;
         }
    }

    void OnTriggerExit2D (Collider2D SecretDoorTrig) {

         if (SecretDoorTrig.gameObject.tag == "Player") {

             GetComponent<SpriteRenderer> ().enabled = true;
         }
         else {
             GetComponent<SpriteRenderer> ().enabled = false;
         }
    }
}

Body:
Fading a Sprite is almost the-same as moving GameObject over time except that you modify its alpha instead of it's position.

The three most important stuff about fading an Object are Time.deltaTime, Mathf.Lerp/Color.Lerp and coroutine. You need to understand how these work together.

Start coroutine, use Time.deltaTime to increment a variable. That variable is used to use to determine how much that function has ran. In a for/while loop, use that variable that is incremented every-frame and the duration you want the fade to happen to generate the alpha with the help of the Mathf.Lerp function. Create new color with that alpha and and assign it to the Sprite.

This is done every frame until that variable that is incremented with  Time.deltaTime reaches the duration you want to the fade to happen within.

Here is a simple SpriteRenderer fade function:

public SpriteRenderer spriteToFade;

IEnumerator fadeOut(SpriteRenderer MyRenderer, float duration)
{
    float counter = 0;
    //Get current color
    Color spriteColor = MyRenderer.material.color;

    while (counter < duration)
    {
        counter += Time.deltaTime;
        //Fade from 1 to 0
        float alpha = Mathf.Lerp(1, 0, counter / duration);
        Debug.Log(alpha);

        //Change alpha only
        MyRenderer.color = new Color(spriteColor.r, spriteColor.g, spriteColor.b, alpha);
        //Wait for a frame
        yield return null;
    }
}

If you want it to fade in, change Mathf.Lerp(1, 0, counter / duration); to Mathf.Lerp(0, 1, counter / duration); which will make the alpha go from 0 to 1 over-time instead of 1 to 0.

From the example above, writing a fade-out and fade-in functions only requires a way to tell the function to change the alpha from 1 to 0 or from 0 to 1. You can make the function use a boolean or enum variable to determine which type of fade to perform. Of-course, you can separate the fade-in/fade-out functions but it's good to have it in one function.

Here is the extended version of that function that supports fade-in and fade-out. It also supports almost all GameObjects like MeshRenderer(3D), SpriteRenderer(2D), Image, RawImage....You can extend it to support more components that's missing.

IEnumerator fadeInAndOut(GameObject objectToFade, bool fadeIn, float duration)
{
    float counter = 0f;

    //Set Values depending on if fadeIn or fadeOut
    float a, b;
    if (fadeIn)
    {
        a = 0;
        b = 1;
    }
    else
    {
        a = 1;
        b = 0;
    }

    int mode = 0;
    Color currentColor = Color.clear;

    SpriteRenderer tempSPRenderer = objectToFade.GetComponent<SpriteRenderer>();
    Image tempImage = objectToFade.GetComponent<Image>();
    RawImage tempRawImage = objectToFade.GetComponent<RawImage>();
    MeshRenderer tempRenderer = objectToFade.GetComponent<MeshRenderer>();
    Text tempText = objectToFade.GetComponent<Text>();

    //Check if this is a Sprite
    if (tempSPRenderer != null)
    {
        currentColor = tempSPRenderer.color;
        mode = 0;
    }
    //Check if Image
    else if (tempImage != null)
    {
        currentColor = tempImage.color;
        mode = 1;
    }
    //Check if RawImage
    else if (tempRawImage != null)
    {
        currentColor = tempRawImage.color;
        mode = 2;
    }
    //Check if Text
    else if (tempText != null)
    {
        currentColor = tempText.color;
        mode = 3;
    }

    //Check if 3D Object
    else if (tempRenderer != null)
    {
        currentColor = tempRenderer.material.color;
        mode = 4;

        //ENABLE FADE Mode on the material if not done already
        tempRenderer.material.SetFloat("_Mode", 2);
        tempRenderer.material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
        tempRenderer.material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
        tempRenderer.material.SetInt("_ZWrite", 0);
        tempRenderer.material.DisableKeyword("_ALPHATEST_ON");
        tempRenderer.material.EnableKeyword("_ALPHABLEND_ON");
        tempRenderer.material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
        tempRenderer.material.renderQueue = 3000;
    }
    else
    {
        yield break;
    }

    while (counter < duration)
    {
        counter += Time.deltaTime;
        float alpha = Mathf.Lerp(a, b, counter / duration);

        switch (mode)
        {
            case 0:
                tempSPRenderer.color = new Color(currentColor.r, currentColor.g, currentColor.b, alpha);
                break;
            case 1:
                tempImage.color = new Color(currentColor.r, currentColor.g, currentColor.b, alpha);
                break;
            case 2:
                tempRawImage.color = new Color(currentColor.r, currentColor.g, currentColor.b, alpha);
                break;
            case 3:
                tempText.color = new Color(currentColor.r, currentColor.g, currentColor.b, alpha);
                break;
            case 4:
                tempRenderer.material.color = new Color(currentColor.r, currentColor.g, currentColor.b, alpha);
                break;
        }
        yield return null;
    }
}

Usage:

GameObject to fade:

public GameObject SpriteRend;

Fade-out in 3 seconds

StartCoroutine(fadeInAndOut(SpriteRend, false, 3f));

Fade-in in 3 seconds

StartCoroutine(fadeInAndOut(SpriteRend, true, 3f));


问:
Npm package has too many dependencies
Im new to this all npm thing and I have a question about dependencies.
I started the React tutorial and I have been asked to run the following command:

```<code>npm install -g create-react-app
</code>```

also, for a side project I also rn this following command in the same directory:

```<code>npm install react-chartjs-2 chart.js
</code>```

And suddenly, my node_modules contains 800+ folders of packages.

So I found this site that tells you how many packages your package depends on and it showed me that I depend on only 100+ packages.
I know the meaning of npm install.

I find it really unexplainedable, I will appreaciate any help from your side.

Thank you very much.

答:
install npm-remote-ls globally and check the dependencies of any package you want

```<code>npm install npm-remote-ls -g
</code>```

checking react dependencies: npm-remote-ls react

Title: Npm package has too many dependencies

Body:
Im new to this all npm thing and I have a question about dependencies.
I started the React tutorial and I have been asked to run the following command:

npm install -g create-react-app

also, for a side project I also rn this following command in the same directory:

npm install react-chartjs-2 chart.js

And suddenly, my node_modules contains 800+ folders of packages.

So I found this site that tells you how many packages your package depends on and it showed me that I depend on only 100+ packages.
I know the meaning of npm install.

I find it really unexplainedable, I will appreaciate any help from your side.

Thank you very much.

Body:
install npm-remote-ls globally and check the dependencies of any package you want

npm install npm-remote-ls -g

checking react dependencies: npm-remote-ls react


问:
Counting multiple instances of an object in an image using machine learning
I am a beginner and have just started studying machine learning and neural networks and have just understood the very basics of this vast and interesting domain.

  From my basic knowledge, I know that a model/classifier can be used to Classify an image as something. But I was curious if there is a way to detect multiple instances of the same object and count the same.

  Basically I wanted to calculate the density of traffic at a red light to dynamically control the flow of traffic, so I was curious if there was a way to detect multiple cars and count the number of cars at a red light by training the ConvNet on Images of Cars (and if there is a way to implement the same using tensor-flow)

答: You might consider using an off the shelf object detector, e.g., the Tensorflow Object Detection API (github.com/tensorflow/models/tree/master/object_detection) to first detect cars, and then count them.</p>


问:
VirtualBox Localhost connection
i have problem with connect to my ubuntu localhost on virtualbox. Host os is windows. On ubuntu i had installed Perforce Swarm Dashboard - in firefox i open it using "localhost" address. I can't reach it from host os.
Of course i run 2 NIC's on virtualbox:
1 - NAT,
2 - Host-only
When i try to connect via host web browser with external ip address on ubuntu it show Apache2 ubuntu default page. The most strange is that when i try to open 127.0.0.1 (localhost ip) on webrowser on ubuntu - it show me Apache2 page again... How to resolve it?</p>

答:
I didn't quite understand the problem. You cant connect from windows to virtualbox machine(cant access apace webpage)?
Did you try to ping the ip of the virtual machine?
Also try editing virtual machine network adapter settings to bridge mode. If you are able to ping the virtual device then you need to edit apache.conf file and replace deny all to allow all or require local.</p>

Title: VirtualBox Localhost connection


问:
jQuery not doing what I want it to do
I'm having trouble with a little jQuery, and thought someone in the community could help me out? So, my markup is as follows:

```<code><div class="left">
    <ul id="editing-nav">
        <li><a class="active testforso" href="#TestForSO">Test For SO</a></li>
        <li><a class="testforso2" href="#TestForSO2">Test For SO2</a></li>
        ...and so on.
    </ul>
</div>

<div class="scroll">
    <div class="scrollContainer">
        <div id="testforso">
            ...some content
        </div>
        <div id="testforso2">
            ...some content
        </div>
        ...and so on.
    </div>
</div>
</code>```

So, basically - .left is floated left, and .scroll is on the right side. I am looking for a way so the active nav element (by default, the first one, and then when the user would click another one, it'd assign that element a class of ".active" and remove the previous one's active class)'s co-insiding div has a display:block, while all others hide. I'm doing this inside of fancybox, which makes it a little bit more complicated, but here's what I have now -

```<code>$('#editing-nav li > a').click(function() {
        $('#editing-nav li > a').removeClass('active');
        $(this).addClass('active');
        activeClassID = $(this).attr('class');  // grabs the nav class for the id to show in .scroll
        var divIDToShow = ('.scroll .scrollContainer #') + activeClassID;       // grabs the DOM path & ID of the coinciding div to show
            divIDToShow = divIDToShow.replace(' active', ''); // removes " active" from the class (because before it would have a class of "testforso2 active"; now it just has "testforso".
        $('.scrollContainer div:not(#' + divIDToShow + ')').hide();
        $('.scrollContainer #' + divIDToShow ).show();
    });
</code>```

This works for the first link someone clicks, but not after that. I don't know if I was clear earlier, but the class for the #editing-nav li a co-incides with what div to show inside of .scroll.

Any ideas? I'm not sure why it's doing this... Thank you!

答:
The reason why it's doing this is probably because it ran into an error during the first click. 'active testforso'.replace(' active') evaluates to 'active testforso' because there is no ' active' in the string. Even if you fix that, you don't know whether 'active' is in front or at the back of the class string. You could instead do .replace(/\s*active\s*/, '') , but my example below just removes all spaces.

I think you could probably change your code to something like:

```<code>$('#editing-nav li > a').click(function() {
    $('#editing-nav li > a:active').removeClass('active');
    $(this).addClass('active');
    activeClassID = $(this).attr('class');  // grabs the nav class for the id to show in .scroll
    var divIDToShow = activeClassID;       // grabs the DOM path & ID of the coinciding div to show
    divIDToShow = divIDToShow.replace('active', '').replace(/\s+/g,''); // removes "active" from the class then remove all spaces in what's left - "testforso2 active"; now it just has "testforso".
    $('.scrollContainer div:not(#' + divIDToShow + ')').hide();
    $('#' + divIDToShow ).show();
});
</code>```

BUT:

Instead of doing all these, you might want to use the jQuery-BBQ plugin which allows you to track states through the hash. So you can just detect changes in the hash like, for example, using the hash as the id itself.

ContentLicense: CC BY-SA 2.5

Title: jQuery not doing what I want it to do

Body:
I'm having trouble with a little jQuery, and thought someone in the community could help me out? So, my markup is as follows:

Test For SO

Test For SO2

        ...and so on.

            ...some content

            ...some content

        ...and so on.

So, basically - .left is floated left, and .scroll is on the right side. I am looking for a way so the active nav element (by default, the first one, and then when the user would click another one, it'd assign that element a class of ".active" and remove the previous one's active class)'s co-insiding div has a display:block, while all others hide. I'm doing this inside of fancybox, which makes it a little bit more complicated, but here's what I have now -

$('#editing-nav li > a').click(function() {
        $('#editing-nav li > a').removeClass('active');
        $(this).addClass('active');
        activeClassID = $(this).attr('class');  // grabs the nav class for the id to show in .scroll
        var divIDToShow = ('.scroll .scrollContainer #') + activeClassID;       // grabs the DOM path & ID of the coinciding div to show
            divIDToShow = divIDToShow.replace(' active', ''); // removes " active" from the class (because before it would have a class of "testforso2 active"; now it just has "testforso".
        $('.scrollContainer div:not(#' + divIDToShow + ')').hide();
        $('.scrollContainer #' + divIDToShow ).show();
    });

This works for the first link someone clicks, but not after that. I don't know if I was clear earlier, but the class for the #editing-nav li a co-incides with what div to show inside of .scroll.

Any ideas? I'm not sure why it's doing this... Thank you!

Body:
The reason why it's doing this is probably because it ran into an error during the first click. 'active testforso'.replace(' active') evaluates to 'active testforso' because there is no ' active' in the string. Even if you fix that, you don't know whether 'active' is in front or at the back of the class string. You could instead do .replace(/\s*active\s*/, '') , but my example below just removes all spaces.

I think you could probably change your code to something like:

$('#editing-nav li > a').click(function() {
    $('#editing-nav li > a:active').removeClass('active');
    $(this).addClass('active');
    activeClassID = $(this).attr('class');  // grabs the nav class for the id to show in .scroll
    var divIDToShow = activeClassID;       // grabs the DOM path & ID of the coinciding div to show
    divIDToShow = divIDToShow.replace('active', '').replace(/\s+/g,''); // removes "active" from the class then remove all spaces in what's left - "testforso2 active"; now it just has "testforso".
    $('.scrollContainer div:not(#' + divIDToShow + ')').hide();
    $('#' + divIDToShow ).show();
});

BUT:

Instead of doing all these, you might want to use the jQuery-BBQ plugin which allows you to track states through the hash. So you can just detect changes in the hash like, for example, using the hash as the id itself.


问:
How to access the cardboard trigger on google Gvr( in code)? 1.6 version SDK
How to access the cardboard trigger on google Gvr( in code) ? In the earlier version it was GvrViewer.Instance.Triggered</p>

答:
I use Input.GetButtonDown("Fire 1") and it works for me on the latest SDK version (1.6) and latest Unity version (5.6)

EDIT:
Use Input.GetButtonDown("Fire1") if you follow the default naming conventions for input events supported by unity. Please note that there is no space character between "Fire" and "1".

Otherwise, you might the error - "ArgumentException: Input Button Fire 1 is not setup."


问:
Trouble using GSoap and SSL
I'm writing a gSoap client application against a service that has both standard http and https versions.  Everything I've written so far works fine with the http service, but when I switch over to the https service, suddenly I'm getting errors.

The only change I made to the code for https support was to add the following on startup:

```<code> soap_ssl_init();
 if(soap_ssl_client_context(&_tradeService, SOAP_SSL_SKIP_HOST_CHECK, NULL, NULL, NULL, NULL, NULL)) {
     handleError("Failed to set up SSL connection");
     return;
 }
</code>```

If I have the -DDEBUG flag on, I get an error about certificates: "SSL verify error or warning with certificate at depth 2: self signed certificate in certificate chain" which doesn't cause soap_ssl_client_context to return an error, and I don't think is a huge deal since while I'm testing I don't really care to authenticate the host.

The real issue is this error:

SOAP 1.2 fault: SOAP-ENV:Sender [no
  subcode] "Unable to handle request
  without a valid action parameter.
  Please supply a valid soap action."

which I get when I try and make a request to the service.  If I look in the send log that gsoap generates, I see the SoapAction parameter set in the outgoing header.  In fact, if I compare the send logs for the http/https services, the only differences is that the urls for the secure service are prefixed by https.

I then thought maybe something is messed up with the server, so I used curl to send the exact same XML data that gsoap logged it sent, with the exact same headers.  This works fine, I see a normal response with the data I expect.  This leads me to believe maybe I am setting up SSL incorrectly?

The other issue I had that was not in the docs, was that when I built with the -DWITH_OPENSSL -lgsoapssl++ -lssl -lcrypto flags I was still getting linker errors about gsoap's ssl methods.  I had to include stdsoap2_ssl_cpp.cpp in my build in order to get these resolved, which I thought was odd.

Anybody tried doing this before that can give me some pointers?

答:
If I have the -DDEBUG flag on, I get an error about certificates: "SSL verify error or warning with certificate at depth 2: self signed certificate in certificate chain" which doesn't cause soap_ssl_client_context to return an error, and I don't think is a huge deal since while I'm testing I don't really care to authenticate the host.

This error may not go away when you remove -DDEBUG for production use.  You can accept self-signed certificates by adding a verify callback:

```<code>soap->fsslverify = verify_callback;

int ssl_verify_callback(int ok, X509_STORE_CTX *store)
{
  if (!ok)
  {
    int err = X509_STORE_CTX_get_error(store);
    switch (err)
    {
      case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
        X509_STORE_CTX_set_error(store, X509_V_OK);
        ok = 1;
        break;
    }
  }
  return ok;
}
</code>```

SOAP 1.2 fault: SOAP-ENV:Sender [no subcode] "Unable to handle request without a valid action parameter. Please supply a valid soap action."

The SOAP Action may be missing from the HTTP/S header or is incorrect for some reason.  This SOAP Action should be defined in the WSDL and is specific for each service operation invoked.

To set the SOAP Action parameter in the HTTP/S header, make sure to pass either NULL or a SOAP Action string as the third argument when making a call:

```<code>soap_call_SomeMethod(soap, "endpoint URL", "SOAP Action string", ...);
</code>```

When you pass NULL, the SOAP Action string defined in the WSDL will be used.  Check the wsdl2h-generated code on what it says for the service operation to use as a SOAP Action.  The SOAP Action isn't really needed with gSOAP services, but other services e.g. WCF will throw errors at you.

When using a C++ proxy object, the call above is replaced by a simple method invocation:

```<code>proxy.SomeMethod("endpoint URL", "SOAP Action string", ...);
</code>```

If you want to use the WSDL-defined endpoint and SOAP action then omit these parameters:

```<code>proxy.SomeMethod(...);
</code>```

That's all.

Title: Trouble using GSoap and SSL

Body:
I'm writing a gSoap client application against a service that has both standard http and https versions.  Everything I've written so far works fine with the http service, but when I switch over to the https service, suddenly I'm getting errors.

The only change I made to the code for https support was to add the following on startup:

 soap_ssl_init();
 if(soap_ssl_client_context(&_tradeService, SOAP_SSL_SKIP_HOST_CHECK, NULL, NULL, NULL, NULL, NULL)) {
     handleError("Failed to set up SSL connection");
     return;
 }

If I have the -DDEBUG flag on, I get an error about certificates: "SSL verify error or warning with certificate at depth 2: self signed certificate in certificate chain" which doesn't cause soap_ssl_client_context to return an error, and I don't think is a huge deal since while I'm testing I don't really care to authenticate the host.

The real issue is this error:

SOAP 1.2 fault: SOAP-ENV:Sender [no
  subcode] "Unable to handle request
  without a valid action parameter.
  Please supply a valid soap action."

which I get when I try and make a request to the service.  If I look in the send log that gsoap generates, I see the SoapAction parameter set in the outgoing header.  In fact, if I compare the send logs for the http/https services, the only differences is that the urls for the secure service are prefixed by https.

I then thought maybe something is messed up with the server, so I used curl to send the exact same XML data that gsoap logged it sent, with the exact same headers.  This works fine, I see a normal response with the data I expect.  This leads me to believe maybe I am setting up SSL incorrectly?

The other issue I had that was not in the docs, was that when I built with the -DWITH_OPENSSL -lgsoapssl++ -lssl -lcrypto flags I was still getting linker errors about gsoap's ssl methods.  I had to include stdsoap2_ssl_cpp.cpp in my build in order to get these resolved, which I thought was odd.

Anybody tried doing this before that can give me some pointers?

Body:
If I have the -DDEBUG flag on, I get an error about certificates: "SSL verify error or warning with certificate at depth 2: self signed certificate in certificate chain" which doesn't cause soap_ssl_client_context to return an error, and I don't think is a huge deal since while I'm testing I don't really care to authenticate the host.

This error may not go away when you remove -DDEBUG for production use.  You can accept self-signed certificates by adding a verify callback:

soap->fsslverify = verify_callback;

int ssl_verify_callback(int ok, X509_STORE_CTX *store)
{
  if (!ok)
  {
    int err = X509_STORE_CTX_get_error(store);
    switch (err)
    {
      case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
        X509_STORE_CTX_set_error(store, X509_V_OK);
        ok = 1;
        break;
    }
  }
  return ok;
}

SOAP 1.2 fault: SOAP-ENV:Sender [no subcode] "Unable to handle request without a valid action parameter. Please supply a valid soap action."

The SOAP Action may be missing from the HTTP/S header or is incorrect for some reason.  This SOAP Action should be defined in the WSDL and is specific for each service operation invoked.

To set the SOAP Action parameter in the HTTP/S header, make sure to pass either NULL or a SOAP Action string as the third argument when making a call:

soap_call_SomeMethod(soap, "endpoint URL", "SOAP Action string", ...);

When you pass NULL, the SOAP Action string defined in the WSDL will be used.  Check the wsdl2h-generated code on what it says for the service operation to use as a SOAP Action.  The SOAP Action isn't really needed with gSOAP services, but other services e.g. WCF will throw errors at you.

When using a C++ proxy object, the call above is replaced by a simple method invocation:

proxy.SomeMethod("endpoint URL", "SOAP Action string", ...);

If you want to use the WSDL-defined endpoint and SOAP action then omit these parameters:

proxy.SomeMethod(...);

That's all.


问:
Select a Date Difference inside a LINQ statement
below is part of a LINQ statement i have where i'm trying to cast a property in my DTO to a new date,  that Date being the number of Days (if any), hours and minutes from a start date of right now (DateTime.Now or something similar) to a date pulled from SQL Server.

```<code>select new ATSRequestDto
                    {
                        ATSRequestID = atsr.ATSRequestID,
                        CreatedDate = atsr.CreatedDt,
                        Desciption = atsr.Description,
                        Priority = c.Description,
                        DepartmentName = laststatus.Department.Name,
                        DepartmentID = laststatus.Department.DepartmentID,
                        Status = laststatus.Code.Description,
                        IsClosed = atsr.IsClosed,

                        LastStatusDateDiff = laststatus.CreatedDt - DateTime.Now    // right here

                    };
</code>```

i could probably figure out how to do this without this being in the cast,  just don't know how to do it inside the cast..    Thanks for your help

答:
Not clear on your question.

Can you do
LastStatusDateDiff = laststatus.CreatedDt.Date - DateTime.Now

or
LastStatusDateDiff = DateTime.ParseExact(laststatus.CreatedDt, "yyyyMMDD") - DateTime.Now

Body:
below is part of a LINQ statement i have where i'm trying to cast a property in my DTO to a new date,  that Date being the number of Days (if any), hours and minutes from a start date of right now (DateTime.Now or something similar) to a date pulled from SQL Server.

select new ATSRequestDto
                    {
                        ATSRequestID = atsr.ATSRequestID,
                        CreatedDate = atsr.CreatedDt,
                        Desciption = atsr.Description,
                        Priority = c.Description,
                        DepartmentName = laststatus.Department.Name,
                        DepartmentID = laststatus.Department.DepartmentID,
                        Status = laststatus.Code.Description,
                        IsClosed = atsr.IsClosed,

                        LastStatusDateDiff = laststatus.CreatedDt - DateTime.Now    // right here

                    };

i could probably figure out how to do this without this being in the cast,  just don't know how to do it inside the cast..    Thanks for your help


问:
Should I use NI Measurement Studio or niDAQms for my VB.NET windows GUI app?
I need to create a VB.NET GUI to manage a National Instruments (NI) USB-6343 instrument.

Should I use the NI Measurement Studio or niDAQms API?

My GUI requirements are:
- command the 6343 to input analog values
- command it to control output analog value
- chart the input analog value over time.

I'm using Visual Studio VB.NET 2017 PRO on Windows-7 desktop and Windows-10 laptop.

答:
This highly depends on the functionality you need to add later on. Both the options are possible, directly calling the ni-DAQmx API or create the VB.net code via the measurement studio.

From practical point of view I would suggest that you create the VB.net code from the measurement studio via the solution explorer with the basic measurements you want. Than copy that code to visual studio and use the API for the rest of the work where needed.

This should give you the efficiency benefits of using the measurement studio and latter the flexibility of using the API and visual studio.