问:
SQL UPDATE if condition (from other table) is true
SHORT: I want to update a table if the userlevel is 1.

Only certain users (on the website) can update the table in the database.

Those users have a 'userlevel 1'

On the website the users are logged-in.
The log-in information + the userlevel is in table users

The table I want to update is device_data

My query:

```<code>UPDATE table1
SET colum1 = value1
WHERE deviceid = deviceid
INNERJOIN table2 ON table1
IF userlevel = '1'
</code>```

答:
```<code>UPDATE table1  firsttable
INNER JOIN table2 secondtable
ON firsttable.deviceid = secondtable.deviceid
SET firsttable.colum1 = secondtable.value1
where secondtable.userlevel = '1'
</code>```

You can try above code.

Hope this will help.

Body:
SHORT: I want to update a table if the userlevel is 1.

Only certain users (on the website) can update the table in the database.

Those users have a 'userlevel 1'

On the website the users are logged-in.
The log-in information + the userlevel is in table users

The table I want to update is device_data

My query:

UPDATE table1
SET colum1 = value1
WHERE deviceid = deviceid
INNERJOIN table2 ON table1
IF userlevel = '1'

Body:
UPDATE table1  firsttable
INNER JOIN table2 secondtable
ON firsttable.deviceid = secondtable.deviceid
SET firsttable.colum1 = secondtable.value1
where secondtable.userlevel = '1'

You can try above code.

Hope this will help.


来源: stackexchange

问:
intellij fails to push to some of my github repositories
I can easily push code to repositories under organization, but cannot push code to repositories I created.

I get

```<code>Failed with error: fatal: unable to access 'https://github.com/__username__/__project_name__.git/': The requested URL returned error: 403
</code>```

using the git cli, everything is fine.

also tried:

using token instead of username/password

using ssh and https urls for remote origin

how can I resolve this?

答: try change git ssh executable to native.

ContentLicense: CC BY-SA 3.0

Body:
I can easily push code to repositories under organization, but cannot push code to repositories I created.

I get

Failed with error: fatal: unable to access 'https://github.com/__username__/__project_name__.git/': The requested URL returned error: 403

using the git cli, everything is fine.

also tried:

using token instead of username/password

using ssh and https urls for remote origin

how can I resolve this?


问:
Bootstrap grid system with mixed display with different images attached
Bootstrap grid system with mixed display with different images attached.
Please check attached pictures. Everytime if I use different images shown as mobile size, it shows three rows rather than 2 row. How can I solve this issue?

```<code><div id="page-ad">
   <div class="container">
      <hr>
      <div class="row">
        <div class="col-xs-6 col-md-3">
          <a href="#" class="thumbnail">
            <img src="<?php echo $ad_img01[url]; ?>" alt="...">
          </a>
        </div>
      <div class="col-xs-6 col-md-3">
          <a href="#" class="thumbnail">
            <img src="<?php echo $ad_img02[url]; ?>" alt="...">
          </a>
        </div>
      <div class="col-xs-6 col-md-3">
          <a href="#" class="thumbnail">
            <img src="<?php echo $ad_img03[url]; ?>" alt="...">
          </a>
        </div>
      <div class="col-xs-6 col-md-3">
          <a href="#" class="thumbnail">
            <img src="<?php echo $ad_img04[url]; ?>" alt="...">
          </a>
       </div>
    </div>
  </div>
</div>
</code>```

different images,
same images

答:
Try using Bootstrap clearfix after the second col div

http://getbootstrap.com/css/#grid-responsive-resets

```<code><div class="row">
    <div class="col-xs-6 col-md-3">
      <a href="#" class="thumbnail">
        <img src="<?php echo $ad_img01[url]; ?>" alt="...">
      </a>
    </div>
    <div class="col-xs-6 col-md-3">
      <a href="#" class="thumbnail">
        <img src="<?php echo $ad_img02[url]; ?>" alt="...">
      </a>
    </div>

  <!-- here -->
  <div class="clearfix visible-xs-block"></div>
  <!--  -->

    <div class="col-xs-6 col-md-3">
      <a href="#" class="thumbnail">
        <img src="<?php echo $ad_img03[url]; ?>" alt="...">
      </a>
    </div>
    <div class="col-xs-6 col-md-3">
      <a href="#" class="thumbnail">
        <img src="<?php echo $ad_img04[url]; ?>" alt="...">
      </a>
    </div>
</div>
</code>```

Body:
Bootstrap grid system with mixed display with different images attached.
Please check attached pictures. Everytime if I use different images shown as mobile size, it shows three rows rather than 2 row. How can I solve this issue?

            <img src="<?php echo $ad_img01[url]; ?>" alt="...">

            <img src="<?php echo $ad_img02[url]; ?>" alt="...">

            <img src="<?php echo $ad_img03[url]; ?>" alt="...">

            <img src="<?php echo $ad_img04[url]; ?>" alt="...">

different images,
same images

Body:
Try using Bootstrap clearfix after the second col div

http://getbootstrap.com/css/#grid-responsive-resets

<div class="row">
    <div class="col-xs-6 col-md-3">
      <a href="#" class="thumbnail">
        <img src="<?php echo $ad_img01[url]; ?>" alt="...">
      </a>
    </div>
    <div class="col-xs-6 col-md-3">
      <a href="#" class="thumbnail">
        <img src="<?php echo $ad_img02[url]; ?>" alt="...">
      </a>
    </div>

  <!-- here -->
  <div class="clearfix visible-xs-block"></div>
  <!--  -->

    <div class="col-xs-6 col-md-3">
      <a href="#" class="thumbnail">
        <img src="<?php echo $ad_img03[url]; ?>" alt="...">
      </a>
    </div>
    <div class="col-xs-6 col-md-3">
      <a href="#" class="thumbnail">
        <img src="<?php echo $ad_img04[url]; ?>" alt="...">
      </a>
    </div>
</div>


问:
Unmatched deep-link in Ionic 3
I'm apps flow goes like this:

Launch App

Spotify 'Allow App Access' page is opened in the browser (Chrome),

The user give the app permission and is redirect to https://appurl.com/spotify-callback/,

That URL is deep-linked so that my app is now opened again,

The deep-link plugin should now match /spotify-callback/ and open the page named SpotifyCallbackPage should be opened but I get the error console.error: Got a deeplink that didn't match

My deep-link code looks like:

deeplinks.route({
                '/spotify-callback/': SpotifyCallbackPage
            }).subscribe((match) => {
                // match.$route - the route we matched, which is the matched entry from the arguments to route()
                // match.$args - the args passed in the link
                // match.$link - the full link data
                console.log('Successfully matched route', match);
            }, (nomatch) => {
                // nomatch.$link - the full link data
                console.error('Got a deeplink that didn\'t match');
                console.log(nomatch);
            });
```

<p>The URL sent to the router is:</p>

```https://appurl.com/spotify-callback/#access_token=random-access-token-here&token_type=Bearer&expires_in=3600
```

<p>The full error message is:</p>

```error opening ws message: {"category":"console","type":"log","data":["On deep
            link",{"url":"https://appurl.com/spotify-callback/#access_token=random-access-token-here&token_type=Bearer&expires_in=3600","path":"/spotify-callback/","scheme":"https","host":"appurl.com","fragment":"access_token=random-access-token-here&token_type=Bearer&expires_in=3600","extra":{"org.chromium.chrome.browser.eenp":["io.ionic.starter"],"org.chromium.chrome.browser.referrer_id":21,"com.android.browser.application_id":"com.android.chrome"}}]}
[16:28:02]  console.error: Got a deeplink that didn't match
```

I've tried different URLs and endpoints in the router but none of them will match. Does anybody know what I should be trying to match?

答:
I'm not sure if you already have found a way to fix this problem. Perhaps you could try changing the route url (spotify-callback) to something like:

spotify-callback + window.location.hash

Title: Unmatched deep-link in Ionic 3

Body:
I'm apps flow goes like this:

Launch App

Spotify 'Allow App Access' page is opened in the browser (Chrome),

The user give the app permission and is redirect to https://appurl.com/spotify-callback/,

That URL is deep-linked so that my app is now opened again,

The deep-link plugin should now match /spotify-callback/ and open the page named SpotifyCallbackPage should be opened but I get the error console.error: Got a deeplink that didn't match

My deep-link code looks like:

deeplinks.route({
                '/spotify-callback/': SpotifyCallbackPage
            }).subscribe((match) => {
                // match.$route - the route we matched, which is the matched entry from the arguments to route()
                // match.$args - the args passed in the link
                // match.$link - the full link data
                console.log('Successfully matched route', match);
            }, (nomatch) => {
                // nomatch.$link - the full link data
                console.error('Got a deeplink that didn\'t match');
                console.log(nomatch);
            });

The URL sent to the router is:

https://appurl.com/spotify-callback/#access_token=random-access-token-here&token_type=Bearer&expires_in=3600

The full error message is:

error opening ws message: {"category":"console","type":"log","data":["On deep
            link",{"url":"https://appurl.com/spotify-callback/#access_token=random-access-token-here&token_type=Bearer&expires_in=3600","path":"/spotify-callback/","scheme":"https","host":"appurl.com","fragment":"access_token=random-access-token-here&token_type=Bearer&expires_in=3600","extra":{"org.chromium.chrome.browser.eenp":["io.ionic.starter"],"org.chromium.chrome.browser.referrer_id":21,"com.android.browser.application_id":"com.android.chrome"}}]}
[16:28:02]  console.error: Got a deeplink that didn't match

I've tried different URLs and endpoints in the router but none of them will match. Does anybody know what I should be trying to match?


问:
How to wait for email intent to finish and get result?
In my Android app, I am able to programmatically open up the default email editor with To, Subject, and Message using the following:

```<code>Intent emailIntent=new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, toemail);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, body);
emailIntent.setType("text/plain");
emailIntent.setClassName("com.android.email", "com.android.email.activity.MessageCompose");
startActivity(emailIntent);
</code>```

This works great, but I need to wait in my app until the user finishes with the email screen and also know whether the email was sent or discarded.

Anyone know how to do this?

答:
This is going to be tricky. There is no standardized return value for email sending, and depending on the user's settings, the mail could be sent with the Email app, the Gmail app, or one of the many 3rd party email apps. They most likely all differ in how they handle ending the emails.

As for your question in general, you can use startActivityForResult() to start an activity and then continue after it finishes, with a return value indicating how things went. However, I'm pretty sure that most email apps won't give you a proper result here.

I'm tempted to say that you may need to handle the sending of the email yourself, i.e. write a simple function that connects to the SMTP and sends the mail out. I'm sure there are lots of libraries out there that handle all the heavy-lifting.

(You can, of course, experiment with startActivityForResult first - MAYBE the most common email apps do give you a return value.)

ContentLicense: CC BY-SA 2.5

Body:
In my Android app, I am able to programmatically open up the default email editor with To, Subject, and Message using the following:

Intent emailIntent=new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, toemail);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, body);
emailIntent.setType("text/plain");
emailIntent.setClassName("com.android.email", "com.android.email.activity.MessageCompose");
startActivity(emailIntent);

This works great, but I need to wait in my app until the user finishes with the email screen and also know whether the email was sent or discarded.

Anyone know how to do this?


问:
Skype chat bot framework - node.js
I'm new to the bot framework and working on the skype chat bot by using node SDK.

I have JSON tree array which provide me the id and names for tree data.

```<code>treeName = tree.parse({
    "id": 1,
    "title": "menu",
    "children": [
        {
            "id": 11,
            "title": "company _ data",
            "children": [{"id": 111}]
        },
        {
            "id": 12,
            "title": "adhoc data test ",
            "children": [{"id": 121}, {"id": 122}]
        },
        {
            "id": 13,
            "title": "quit",
            "children": [{"id": 131}, {"id": 132}]
        }
    ]
});
</code>```

Code for get the title from tree.

```<code>var node1 = treeName.first(function (node) {
    return node.model.id === 1;
});
</code>```

Array

```<code>var firstChild = [];
        for (var i = 0; i < node1.model.children.length; i++) {
            firstChild.push(node1.model.children[i].title);
        }
        builder.Prompts.choice(session, "What scenario would you like to run? ",firstChild );
</code>```

When I'm trying to get the id it will work well but if I want to get title in one array then I get this error:

```<code>/node_modules/promise/lib/done.js:10
      throw err;
      ^

TypeError: choice.trim is not a function
</code>```

答:
You don't appear to have defined the variable 'choice' anywhere.

```<code>treeName.title
</code>```

or

```<code>treename.children[X].title
</code>```

The first one would, in this case, return 'menu', whereas the second one returns "company_data", or "adhoc data test", etc.

You cannot use .trim() on arrays or objects.

Title: Skype chat bot framework - node.js

Body:
I'm new to the bot framework and working on the skype chat bot by using node SDK.

I have JSON tree array which provide me the id and names for tree data.

treeName = tree.parse({
    "id": 1,
    "title": "menu",
    "children": [
        {
            "id": 11,
            "title": "company _ data",
            "children": [{"id": 111}]
        },
        {
            "id": 12,
            "title": "adhoc data test ",
            "children": [{"id": 121}, {"id": 122}]
        },
        {
            "id": 13,
            "title": "quit",
            "children": [{"id": 131}, {"id": 132}]
        }
    ]
});

Code for get the title from tree.

var node1 = treeName.first(function (node) {
    return node.model.id === 1;
});

Array

var firstChild = [];
        for (var i = 0; i < node1.model.children.length; i++) {
            firstChild.push(node1.model.children[i].title);
        }
        builder.Prompts.choice(session, "What scenario would you like to run? ",firstChild );

When I'm trying to get the id it will work well but if I want to get title in one array then I get this error:

/node_modules/promise/lib/done.js:10
      throw err;
      ^

TypeError: choice.trim is not a function

Body:
You don't appear to have defined the variable 'choice' anywhere.

treeName.title

or

treename.children[X].title

The first one would, in this case, return 'menu', whereas the second one returns "company_data", or "adhoc data test", etc.

You cannot use .trim() on arrays or objects.

ContentLicense: CC BY-SA 4.0


问:
Hide SQLite Database in Android from Other Applications
I am Working on an Android Application which will be launched with a huge Pre loaded SQLite database. Problem is that database is visible to Applications like HACKDataApp etc. And Can also be viewed and copied in Android Device Monitor.
Question is, Is there any way to protect\hide my database from other applications?? </p>

答:
you got to make your contentProvider not exported. SImply as that :

from official documentation :
android:exported: Flag allowing other applications to use this provider.

put this in your manifest declaration for each contentProvider.


问:
Production compilation with ejected Angular 4 application produces large files
ng build --prod Angular CLI command produces highly compressed javascript files in Angular4 application.

When the application is ejected using ng eject command, Angular CLI commands are gone and we are left with npm scripts( npm run build command to build the app), but unfortunately that command outputs a non-production build.

I tried running webpack -p command directly but the output result files are slightly larger compared to the output of ng build --prod command.

How to get a compression equivalent of ng build --prod command but on an ejected application? What command/arguments can produce such results?

答:
You can eject the production version of the webpack config by using the following command:

```<code>ng eject --prod
</code>```

EDIT

If you want to use both the development & production versions of the ejected webpack config, do the following:

Backup your existing package.json

Execute ng eject --prod (this will eject the production version of webpack config)

Rename the ejected webpack.config.json to webpack.config-prod.json

Restore your backed up package.json (the actual changes are pretty much the scripts and few new packages). You might also want to edit your .angular-cli.json and change the ejected property to false.

Execute ng eject (this will eject the development version).

You're now left with a production & development version of your webpack configs. Now, to compile your Angular project for production, execute webpack --config webpack.config-prod.js and you can also add this to your package.json scripts for ease.

However, this may not be the perfect method for this but this is what I did in the. If there's a better version, feel free to edit.

Body:
You can eject the production version of the webpack config by using the following command:

ng eject --prod

EDIT

If you want to use both the development & production versions of the ejected webpack config, do the following:

Backup your existing package.json

Execute ng eject --prod (this will eject the production version of webpack config)

Rename the ejected webpack.config.json to webpack.config-prod.json

Restore your backed up package.json (the actual changes are pretty much the scripts and few new packages). You might also want to edit your .angular-cli.json and change the ejected property to false.

Execute ng eject (this will eject the development version).

You're now left with a production & development version of your webpack configs. Now, to compile your Angular project for production, execute webpack --config webpack.config-prod.js and you can also add this to your package.json scripts for ease.

However, this may not be the perfect method for this but this is what I did in the. If there's a better version, feel free to edit.


问:
perforce backup question
for safety purpose, is it enough to backup all the files under perforce server directory?</p>

答:
Short answer: No

Long answer: All you need to know about backup and recovery of Perforce data is detailed in the Manual. In a nutshell for the impatient:

p4 verify //...

(Verify the integrity of your server)

p4 admin checkpoint

(Make a checkpoint; make sure that this step is successful)

back up the checkpoint file and the old journal file

(if you run Perforce with Journal files, which you should)

back up your versioned files

(that's the actual data, not to be confused with the db.* files in the Perforce server directory.)

But please do read the manual, especially about the various restore scenarios. Remember:
Backups usually work fine, it's the restore that fails.

Title: perforce backup question


问:
Proper toolbar styling
I would like to avoid applying a style to the toolbars in all layouts, so I have a style I created for it:

```<code><style name="DarkToolbar" >
        <item name="android:textColorPrimary">@color/white</item>
        <item name="android:textColorSecondary">@color/white</item>
        <item name="android:background">@color/blue</item>
        <item name="android:elevation">4dp</item>
</style>
</code>```

And I added it to my theme as follows:

```<code><style name="Theme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/blue</item>
        <item name="colorPrimaryDark">@color/blue</item>
        <item name="colorAccent">@color/blue</item>
        <item name="android:toolbarStyle">@style/DarkToolbar</item>
</style>
</code>```

This is the resulting toolbar:

As you can see, the title and subtitle have the wrong formatting. If I remove the style from the theme and apply it directly to the toolbar in the layout, I get the following result instead:

Both images use the same style. One is applied through the app theme with

```<code><item name="android:toolbarStyle">@style/DarkToolbar</item>
</code>```

and the second one is applied directly to the toolbar with

```<code>style="@style/DarkToolbar"
</code>```

Does anyone know the reason for the difference?
Also, does anyone know why the

```<code><item name="android:textColorPrimary">@color/white</item>
<item name="android:textColorSecondary">@color/white</item>
</code>```

Are not being applied?

Thanks

答:
I think this has to do with

< item name="android:theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar< /item>

in your style

I personally find styling toolbar text quite complicated, so mostly end up with my own TextView. How about using your own TextView inside toolbar. It would be easy, though a bit lengthy.

Title: Proper toolbar styling

Body:
I would like to avoid applying a style to the toolbars in all layouts, so I have a style I created for it:

And I added it to my theme as follows:

This is the resulting toolbar:

As you can see, the title and subtitle have the wrong formatting. If I remove the style from the theme and apply it directly to the toolbar in the layout, I get the following result instead:

Both images use the same style. One is applied through the app theme with

<item name="android:toolbarStyle">@style/DarkToolbar</item>

and the second one is applied directly to the toolbar with

style="@style/DarkToolbar"

Does anyone know the reason for the difference?
Also, does anyone know why the

<item name="android:textColorPrimary">@color/white</item>
<item name="android:textColorSecondary">@color/white</item>

Are not being applied?

Thanks


问:
Loops and Collatz Conjecture
I have a problem with loops and declaring variables. currently I am making a program about Collatz Conjecture, the program should check what is the biggest steps to reach one from certain amount of Collatz Sequence. here's my code :

```<code>start_num = int(input("insert a starting Number > "))
how_many = int(input("how many times you want to check? >"))

def even_or_odd(number):
    if number % 2 == 0:
        return 'isEven'
    else:
        return 'notEven'

def collatz(n):
    z = n
    counter = 0
    while True:
        if n != 1:
            if even_or_odd(n) == 'isEven':
                n = n/2
                counter += 1
                continue
            if even_or_odd(n) == 'notEven':
                n = (n*3)+1
                counter += 1
                continue
        else:
            print('number ' + str(z) + ' reached 1 with : ' + str(counter) + ' steps')
            return counter
            break

def check_biggest_steps(steps_before, steps_after):
    if steps_before > steps_after:
        return steps_before
    if steps_after > steps_before:
        return steps_after
    if steps_after == steps_before:
        return steps_after

def compute_collatz(n_times, collatz_number):
    for _ in range(n_times):
        before = collatz(collatz_number)
        collatz_number += 1
        after = collatz(collatz_number)
        collatz_number += 1
        biggest_steps = check_biggest_steps(before, after)

    print('Biggest Steps is :' + str(biggest_steps))

compute_collatz(how_many, start_num)
</code>```

this biggest_steps variable always return the last 2 steps. I know what causing this problem is that biggest_step variable located inside the loop but I can't get it working anywhere don't know what to do. Thanks

答:
you didn't save your biggest_steps and compared always the last 2 only.

I would suggest following change.

```<code>def compute_collatz(n_times, collatz_number):
    biggest_steps = 0
    for _ in range(n_times):
        steps = collatz(collatz_number)
        if steps > biggest_steps:
            biggest_steps = steps
        collatz_number += 1

    print('Biggest Steps is :' + str(biggest_steps))
</code>```

Title: Loops and Collatz Conjecture

Body:
I have a problem with loops and declaring variables. currently I am making a program about Collatz Conjecture, the program should check what is the biggest steps to reach one from certain amount of Collatz Sequence. here's my code :

start_num = int(input("insert a starting Number > "))
how_many = int(input("how many times you want to check? >"))

def even_or_odd(number):
    if number % 2 == 0:
        return 'isEven'
    else:
        return 'notEven'

def collatz(n):
    z = n
    counter = 0
    while True:
        if n != 1:
            if even_or_odd(n) == 'isEven':
                n = n/2
                counter += 1
                continue
            if even_or_odd(n) == 'notEven':
                n = (n*3)+1
                counter += 1
                continue
        else:
            print('number ' + str(z) + ' reached 1 with : ' + str(counter) + ' steps')
            return counter
            break

def check_biggest_steps(steps_before, steps_after):
    if steps_before > steps_after:
        return steps_before
    if steps_after > steps_before:
        return steps_after
    if steps_after == steps_before:
        return steps_after

def compute_collatz(n_times, collatz_number):
    for _ in range(n_times):
        before = collatz(collatz_number)
        collatz_number += 1
        after = collatz(collatz_number)
        collatz_number += 1
        biggest_steps = check_biggest_steps(before, after)

    print('Biggest Steps is :' + str(biggest_steps))

compute_collatz(how_many, start_num)

this biggest_steps variable always return the last 2 steps. I know what causing this problem is that biggest_step variable located inside the loop but I can't get it working anywhere don't know what to do. Thanks

Body:
you didn't save your biggest_steps and compared always the last 2 only.

I would suggest following change.

def compute_collatz(n_times, collatz_number):
    biggest_steps = 0
    for _ in range(n_times):
        steps = collatz(collatz_number)
        if steps > biggest_steps:
            biggest_steps = steps
        collatz_number += 1

    print('Biggest Steps is :' + str(biggest_steps))


问:
Hide any tabpanel in shiny
I have a tabsetPanel() and I try to hide one tabPanel() if choice is two and checkbox is on. I tried the following code to do that, however it does not work.

ui

```<code>shinyUI(
  fluidPage(
    titlePanel("Hello Shiny!"),
  sidebarLayout(
    sidebarPanel(
      fluidRow(
        column(5,
               radioButtons("radio", label = h5("Data uploaded"),
                            choices = list("Aff" = 1, "Cod" = 2,
                                           "Ill" = 3),selected = 1)
        )),
      checkboxInput("checkbox", "cheb", value = F)
  ),
    mainPanel(
      tabsetPanel(
        tabPanel("Plot", "plot1"),
        conditionalPanel(
          condition = "input.radio !=2 && input.checkbox == false",
        tabPanel("Summary", "summary1")
        ),
        tabPanel("Table", "table1")
      )
    )
  )

)
)
</code>```

server

```<code>shinyServer(function(input,output,session){

})
</code>```

How can I hide a tabPanel()?

答:
You could do it with renderUI():
Create the tabpanels() in a list within the renderUI()
and conditionally add the third one:
if(input$radio == 2 & !input$checkbox)
and then return the whole tabsetPanel() with do.call(tabsetPanel, panels).

```<code>ui <- shinyUI(
  fluidPage(
    titlePanel("Hello Shiny!"),
    sidebarLayout(
      sidebarPanel(
        fluidRow(
          column(5,
                 radioButtons("radio", label = h5("Data uploaded"),
                              choices = list("Aff" = 1, "Cod" = 2,
                                             "Ill" = 3),selected = 1)
          )),
        checkboxInput("checkbox", "cheb", value = F)
      ),
      mainPanel(
          uiOutput("summary")
        )
      )
  )
)

server <- shinyServer(function(input,output,session){

  output$summary <- renderUI({
      panels <- list(
        tabPanel("Plot", "plot1"),
        tabPanel("Table", "table1")
      )
      if(input$radio == 2 & !input$checkbox) panels[[3]] <- tabPanel("Summary", "summary1")
      do.call(tabsetPanel, panels)
  })

})

shinyApp(ui, server)
</code>```

Title: Hide any tabpanel in shiny

Body:
I have a tabsetPanel() and I try to hide one tabPanel() if choice is two and checkbox is on. I tried the following code to do that, however it does not work.

ui

shinyUI(
  fluidPage(
    titlePanel("Hello Shiny!"),
  sidebarLayout(
    sidebarPanel(
      fluidRow(
        column(5,
               radioButtons("radio", label = h5("Data uploaded"),
                            choices = list("Aff" = 1, "Cod" = 2,
                                           "Ill" = 3),selected = 1)
        )),
      checkboxInput("checkbox", "cheb", value = F)
  ),
    mainPanel(
      tabsetPanel(
        tabPanel("Plot", "plot1"),
        conditionalPanel(
          condition = "input.radio !=2 && input.checkbox == false",
        tabPanel("Summary", "summary1")
        ),
        tabPanel("Table", "table1")
      )
    )
  )

)
)

server

shinyServer(function(input,output,session){

})

How can I hide a tabPanel()?

Body:
You could do it with renderUI():
Create the tabpanels() in a list within the renderUI()
and conditionally add the third one:
if(input$radio == 2 & !input$checkbox)
and then return the whole tabsetPanel() with do.call(tabsetPanel, panels).

ui <- shinyUI(
  fluidPage(
    titlePanel("Hello Shiny!"),
    sidebarLayout(
      sidebarPanel(
        fluidRow(
          column(5,
                 radioButtons("radio", label = h5("Data uploaded"),
                              choices = list("Aff" = 1, "Cod" = 2,
                                             "Ill" = 3),selected = 1)
          )),
        checkboxInput("checkbox", "cheb", value = F)
      ),
      mainPanel(
          uiOutput("summary")
        )
      )
  )
)

server <- shinyServer(function(input,output,session){

  output$summary <- renderUI({
      panels <- list(
        tabPanel("Plot", "plot1"),
        tabPanel("Table", "table1")
      )
      if(input$radio == 2 & !input$checkbox) panels[[3]] <- tabPanel("Summary", "summary1")
      do.call(tabsetPanel, panels)
  })

})

shinyApp(ui, server)


问:
Storing time zone offset in Oracle DB as separate field
I am working on air flight Java app and need to store local time with time zone information in Oracle DB.

DATE/TIMESTAMP types have less problems then WITH TIME ZONE analogs.

If I store local date in DATE field what type should I assign for offset as separate field in Oracle DB and Java/Hibernate mapping? I hope that date arithmetic would be easy both in Java and Oracle native SQL queries.

I can imaging only INT(6) to store offsets as seconds. Native Oracle SQL queries can use arithmetic operations:

```<code>departure_date + departure_off/(24*60*60)
</code>```

In Java:

```<code>departureDate.atOffset(ZoneOffset.ofTotalSeconds(departureOff))
</code>```

UPDATE I have no information for TZ region, like 'US/Pacific', only numeric offset.

答:
I would first recommend to use TIMESTAMP WITH TIME ZONE, resp. TIMESTAMP WITH LOCAL TIME ZONE, I think this would be the easiest way.

Otherwise I would store time zone offset as according ISO-8601, i.e. as VARCHAR(6) value like +05:00

Then you can make a very simple conversion to TIMESTAMP WITH TIME ZONE like

```<code>SELECT FROM_TZ(departure_date, departure_off)
FROM ...
</code>```

Body:
I am working on air flight Java app and need to store local time with time zone information in Oracle DB.

DATE/TIMESTAMP types have less problems then WITH TIME ZONE analogs.

If I store local date in DATE field what type should I assign for offset as separate field in Oracle DB and Java/Hibernate mapping? I hope that date arithmetic would be easy both in Java and Oracle native SQL queries.

I can imaging only INT(6) to store offsets as seconds. Native Oracle SQL queries can use arithmetic operations:

departure_date + departure_off/(24*60*60)

In Java:

departureDate.atOffset(ZoneOffset.ofTotalSeconds(departureOff))

UPDATE I have no information for TZ region, like 'US/Pacific', only numeric offset.

Body:
I would first recommend to use TIMESTAMP WITH TIME ZONE, resp. TIMESTAMP WITH LOCAL TIME ZONE, I think this would be the easiest way.

Otherwise I would store time zone offset as according ISO-8601, i.e. as VARCHAR(6) value like +05:00

Then you can make a very simple conversion to TIMESTAMP WITH TIME ZONE like

SELECT FROM_TZ(departure_date, departure_off)
FROM ...


问:
How to merge css or How to use class in JS instead of id
In One of My application for input field I am geeting this design.

Pic
My code

```<code><input class="myCombo-combobox" name="language" style="width:30%;">
</code>```

My CSS

```<code>.textbox {
  position: relative;
  border: 1px solid #95B8E7;
  background-color: #fff;
  vertical-align: middle;
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  margin: 0;
  padding: 0;
  -moz-border-radius: 5px 5px 5px 5px;
  -webkit-border-radius: 5px 5px 5px 5px;
  border-radius: 5px 5px 5px 5px;
}
.textbox .textbox-text {
  font-size: 12px;
  border: 0;
  margin: 0;
  padding: 4px;
  white-space: normal;
  vertical-align: top;
  outline-style: none;
  resize: none;
  -moz-border-radius: 5px 5px 5px 5px;
  -webkit-border-radius: 5px 5px 5px 5px;
  border-radius: 5px 5px 5px 5px;
}
.textbox .textbox-text::-ms-clear,
.textbox .textbox-text::-ms-reveal {
  display: none;
}
.textbox textarea.textbox-text {
  white-space: pre-wrap;
}
.textbox .textbox-prompt {
  font-size: 12px;
  color: #aaa;
}
.textbox .textbox-bgicon {
  background-position: 3px center;
  padding-left: 21px;
}

.textbox-addon {
  position: absolute;
  top: 0;
}

.textbox-label-after {
  padding-left: 5px;
  padding-right: 0;
}
.textbox-label-top {
  display: block;
  width: auto;
  padding: 0;
}
.textbox-disabled,
.textbox-label-disabled {
  opacity: 0.6;
  filter: alpha(opacity=60);
}

.combo-arrow {
  width: 18px;
  height: 20px;
  overflow: hidden;
  display: inline-block;
  vertical-align: top;
  cursor: pointer;
  opacity: 0.6;
  filter: alpha(opacity=60);
}
.combo-arrow-hover {
  opacity: 1.0;
  filter: alpha(opacity=100);
}
.combo-panel {
  overflow: auto;
}
.combo-arrow {
  background: url('images/combo_arrow.png') no-repeat center center;
}
.combo-panel {
  background-color: #ffffff;
}
.combo-arrow {
  background-color: #E0ECFF;
}
.combo-arrow-hover {
  background-color: #eaf2ff;
}
.combo-arrow:hover {
  background-color: #eaf2ff;
}
.combo .textbox-icon-disabled:hover {
  cursor: default;
}
.combobox-item,
.combobox-group,
.combobox-stick {
  font-size: 12px;
  padding: 3px;
}
.combobox-item-disabled {
  opacity: 0.5;
  filter: alpha(opacity=50);
}
.combobox-gitem {
  padding-left: 10px;
}
.combobox-group,
.combobox-stick {
  font-weight: bold;
}
.combobox-stick {
  position: absolute;
  top: 1px;
  left: 1px;
  right: 1px;
  background: inherit;
}
.combobox-item-hover {
  background-color: #eaf2ff;
  color: #000000;
}
.combobox-item-selected {
  background-color: #ffe48d;
  color: #000000;
}
.combobox-icon {
  display: inline-block;
  width: 16px;
  height: 16px;
  vertical-align: middle;
  margin-right: 2px;
}
</code>```

The other places I am creating my input field like this way

Pic

```<code>var myTable = '<input type="text" class="combobox"; style="width:30%;" id="myInput" onkeyup="myFunction()" title="Type in a name">' +
    '<table id="myTable">' + '<tr class="header"></tr>' + '<tr><td></td></tr>' + '</table>';
</code>```

My CSS

```<code>* {
  box-sizing: border-box;
}
#myInput {
  background-image: url('Drop.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 30%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}
#tdiv{
    height : 30%;
    overflow-y:auto;

}

tbody {
  display: block;
}

tbody {
  max-height: 150px;
  overflow: auto;
}
#myTable {
  border-collapse: collapse;
  width: 30%;
  border: 1px solid #ddd;
  font-size: 18px;
  display: none;
  margin-top:-12px;
}

#myTable th, #myTable td {
  text-align: left;
  padding: 12px;
  width : 10%;
}

#myTable tr {
  border-bottom: 1px solid #ddd;
  order-top: 1px solid #ddd;
}

#myTable tr.header, #myTable tr:hover {
  background-color: #f1f1f1;
}

#myInput:focus + #myTable{
  display: block;
}

#myTable:hover{
 display: block;
}
</code>```

For My second application also I want the first kind of design. How to make with css because I am using id insted of class.
2. Is it possible that input data from table should be underlined and ";" seperated.

答:
CSS classes allow reuse, i.e. applying the same style to several elements.

You can use both id and class together in the HTML element, and CSS rules selecting by id and/or class too.

If different CSS rules apply to the same element, in case of conflict, the "closest" one takes precedence. For id vs class selectors, the id is more specific, thus the id CSS rule would have higher priority than the one related to the class. If there is no conflict, they are both applied.

Body:
In One of My application for input field I am geeting this design.

Pic
My code

<input class="myCombo-combobox" name="language" style="width:30%;">

My CSS

.textbox {
  position: relative;
  border: 1px solid #95B8E7;
  background-color: #fff;
  vertical-align: middle;
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  margin: 0;
  padding: 0;
  -moz-border-radius: 5px 5px 5px 5px;
  -webkit-border-radius: 5px 5px 5px 5px;
  border-radius: 5px 5px 5px 5px;
}
.textbox .textbox-text {
  font-size: 12px;
  border: 0;
  margin: 0;
  padding: 4px;
  white-space: normal;
  vertical-align: top;
  outline-style: none;
  resize: none;
  -moz-border-radius: 5px 5px 5px 5px;
  -webkit-border-radius: 5px 5px 5px 5px;
  border-radius: 5px 5px 5px 5px;
}
.textbox .textbox-text::-ms-clear,
.textbox .textbox-text::-ms-reveal {
  display: none;
}
.textbox textarea.textbox-text {
  white-space: pre-wrap;
}
.textbox .textbox-prompt {
  font-size: 12px;
  color: #aaa;
}
.textbox .textbox-bgicon {
  background-position: 3px center;
  padding-left: 21px;
}

.textbox-addon {
  position: absolute;
  top: 0;
}

.textbox-label-after {
  padding-left: 5px;
  padding-right: 0;
}
.textbox-label-top {
  display: block;
  width: auto;
  padding: 0;
}
.textbox-disabled,
.textbox-label-disabled {
  opacity: 0.6;
  filter: alpha(opacity=60);
}

.combo-arrow {
  width: 18px;
  height: 20px;
  overflow: hidden;
  display: inline-block;
  vertical-align: top;
  cursor: pointer;
  opacity: 0.6;
  filter: alpha(opacity=60);
}
.combo-arrow-hover {
  opacity: 1.0;
  filter: alpha(opacity=100);
}
.combo-panel {
  overflow: auto;
}
.combo-arrow {
  background: url('images/combo_arrow.png') no-repeat center center;
}
.combo-panel {
  background-color: #ffffff;
}
.combo-arrow {
  background-color: #E0ECFF;
}
.combo-arrow-hover {
  background-color: #eaf2ff;
}
.combo-arrow:hover {
  background-color: #eaf2ff;
}
.combo .textbox-icon-disabled:hover {
  cursor: default;
}
.combobox-item,
.combobox-group,
.combobox-stick {
  font-size: 12px;
  padding: 3px;
}
.combobox-item-disabled {
  opacity: 0.5;
  filter: alpha(opacity=50);
}
.combobox-gitem {
  padding-left: 10px;
}
.combobox-group,
.combobox-stick {
  font-weight: bold;
}
.combobox-stick {
  position: absolute;
  top: 1px;
  left: 1px;
  right: 1px;
  background: inherit;
}
.combobox-item-hover {
  background-color: #eaf2ff;
  color: #000000;
}
.combobox-item-selected {
  background-color: #ffe48d;
  color: #000000;
}
.combobox-icon {
  display: inline-block;
  width: 16px;
  height: 16px;
  vertical-align: middle;
  margin-right: 2px;
}

The other places I am creating my input field like this way

Pic

var myTable = '<input type="text" class="combobox"; style="width:30%;" id="myInput" onkeyup="myFunction()" title="Type in a name">' +
    '
' + '

' + '

' + '
';

My CSS

* {
  box-sizing: border-box;
}
#myInput {
  background-image: url('Drop.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 30%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}
#tdiv{
    height : 30%;
    overflow-y:auto;

}

tbody {
  display: block;
}

tbody {
  max-height: 150px;
  overflow: auto;
}
#myTable {
  border-collapse: collapse;
  width: 30%;
  border: 1px solid #ddd;
  font-size: 18px;
  display: none;
  margin-top:-12px;
}

#myTable th, #myTable td {
  text-align: left;
  padding: 12px;
  width : 10%;
}

#myTable tr {
  border-bottom: 1px solid #ddd;
  order-top: 1px solid #ddd;
}

#myTable tr.header, #myTable tr:hover {
  background-color: #f1f1f1;
}

#myInput:focus + #myTable{
  display: block;
}

#myTable:hover{
 display: block;
}

For My second application also I want the first kind of design. How to make with css because I am using id insted of class.
2. Is it possible that input data from table should be underlined and ";" seperated.


问:
Dynamically Creating Resource Name from Values
My end goal is to create a policy document from a cloudformation script. I want to have one script where the parameter is selected and that value is used to in the name of the resource.

"arn:aws:dynamodb:us-east-1:12345678:table/monit-${dev}/stream/*"

where ${dev} is a parameter value

Parameters:
  Environment:
    Default: dev
    Description: Leveraged for environment tagging.
    Type: String
    AllowedValues:
    - dev
    - tst
    - qa
    - stg
    - prd

I want to try something like the following but don't know how to add the Ref Environment from the parameter or is there some other method?

'Fn::Sub': 'arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}'

So I don't end up have to create a bunch of different scripts

```<code>    PolicyDocument:
      Statement:
      - Effect: Allow
        Action:
        - dynamodb:DescribeStream
        - dynamodb:GetRecords
        - dynamodb:GetShardIterator
        - dynamodb:ListStreams
        - dynamodb:Scan
        #This will need to changed for other tables
      Resource:
         - "arn:aws:dynamodb:us-east-1:12345678:table/monit-dev/stream/*"
         - "arn:aws:dynamodb:us-east-1:12345678:table/monit-dev"
</code>```

答:
If i understood you correctly, You can use Fn::Join to add the "Environment" value. You dont use Ref of the value it self.

The intrinsic function Ref returns the value of the specified parameter or resource.

When you specify a parameter's logical name, it returns the value of the parameter.
When you specify a resource's logical name, it returns a value that you can typically use to refer to that resource, such as a physical ID.

json example:

```<code>    "CustomInstanceProfileArn": {
      "Fn::Join": [
        "", ["arn:aws:iam::", {
            "Ref": "AWS::AccountId"
          },
          ":instance-profile/", {
            "Ref": "InstanceProfile"
          }
        ]
      ]
    },
</code>```

http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html

Body:
My end goal is to create a policy document from a cloudformation script. I want to have one script where the parameter is selected and that value is used to in the name of the resource.

"arn:aws:dynamodb:us-east-1:12345678:table/monit-${dev}/stream/*"

where ${dev} is a parameter value

Parameters:
  Environment:
    Default: dev
    Description: Leveraged for environment tagging.
    Type: String
    AllowedValues:
    - dev
    - tst
    - qa
    - stg
    - prd

I want to try something like the following but don't know how to add the Ref Environment from the parameter or is there some other method?

'Fn::Sub': 'arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}'

So I don't end up have to create a bunch of different scripts

    PolicyDocument:
      Statement:
      - Effect: Allow
        Action:
        - dynamodb:DescribeStream
        - dynamodb:GetRecords
        - dynamodb:GetShardIterator
        - dynamodb:ListStreams
        - dynamodb:Scan
        #This will need to changed for other tables
      Resource:
         - "arn:aws:dynamodb:us-east-1:12345678:table/monit-dev/stream/*"
         - "arn:aws:dynamodb:us-east-1:12345678:table/monit-dev"

Body:
If i understood you correctly, You can use Fn::Join to add the "Environment" value. You dont use Ref of the value it self.

The intrinsic function Ref returns the value of the specified parameter or resource.

When you specify a parameter's logical name, it returns the value of the parameter.
When you specify a resource's logical name, it returns a value that you can typically use to refer to that resource, such as a physical ID.

json example:

    "CustomInstanceProfileArn": {
      "Fn::Join": [
        "", ["arn:aws:iam::", {
            "Ref": "AWS::AccountId"
          },
          ":instance-profile/", {
            "Ref": "InstanceProfile"
          }
        ]
      ]
    },

http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html


答:
Use below query :</p>

```<code>  UPDATE table1  SET colum1 = value1
  FROM table2 T2
  WHERE T2.deviceid = table1.deviceid AND userlevel = '1'
</code>```

Title: SQL UPDATE if condition (from other table) is true

Body:
SHORT: I want to update a table if the userlevel is 1.

Only certain users (on the website) can update the table in the database.

Those users have a 'userlevel 1'

On the website the users are logged-in.
The log-in information + the userlevel is in table users

The table I want to update is device_data

My query:

UPDATE table1
SET colum1 = value1
WHERE deviceid = deviceid
INNERJOIN table2 ON table1
IF userlevel = '1'

Body:
Use below query :

  UPDATE table1  SET colum1 = value1
  FROM table2 T2
  WHERE T2.deviceid = table1.deviceid AND userlevel = '1'


问:
how to combine 2 array values into single one by common value
1.fetching the values from a same table with different date

```<code> <?php
    $date= date("Y-m-d");;
    $prev_date = date('Y-m-d', strtotime($date .' -1 day'));
    $result_yest=mysql_query("SELECT isp,sum(sent) AS `sent_yest` FROM red_global WHERE status_date='$prev_date' and sent > 0 group by 1",$link1);
    $data_yest = array(); // create a variable to hold the information
    while (($row_yest = mysql_fetch_array($result_yest, MYSQL_ASSOC)) !== false){
      $data_yest[] = $row_yest; // add the row in to the results (data) array
    }
    print_r($data_yest);
    $result_today=mysql_query("SELECT isp,sum(sent) AS `sent_today` FROM red_global WHERE status_date='$date' and sent > 0 group by 1",$link1);
    $data_today = array(); // create a variable to hold the information
    while (($row_today = mysql_fetch_array($result_today, MYSQL_ASSOC)) !== false){
      $data_today[] = $row_today; // add the row in to the results (data) array
    }
    print_r($data_today);
    exit;
?>
</code>```

2.Array results in which one array contains yesterday's sent count and another one aray contains today's sent count both array having the common isp

```<code>Array (
  [0] => Array ( [isp] => aol [sent_yest] => 46838 )
  [1] => Array ( [isp] => gmail [sent_yest] => 33015 )
  [2] => Array ( [isp] => juno [sent_yest] => 93544 )
  [3] => Array ( [isp] => roadrunner [sent_yest] => 6181 )
  [4] => Array ( [isp] => yahoo [sent_yest] => 71444 )
)

Array (
  [0] => Array ( [isp] => aol [sent_today] => 14135 )
  [1] => Array ( [isp] => att [sent_today] => 624 )
  [2] => Array ( [isp] => gmail [sent_today] => 21263 )
  [3] => Array ( [isp] => juno [sent_today] => 74934 )
  [4] => Array ( [isp] => roadrunner [sent_today] => 939 )
  [5] => Array ( [isp] => yahoo [sent_today] => 22059 )
)
</code>```

Now i need a result like this isp name, yesterday's sent count, today's sent count

```<code>[isp, sent_yest, sent_today],
[aol, 46838,  14135],
[att, 0,  624],
[gmail, 33015,  21263],
</code>```

Anyone help me to solve this.. Thanks in advance

答:
I would avoid foreach if it's possible, since it leads to code that's much harder to understand. With array operation it can look like this:

```<code>// First we merge the two arrays
$merged = array_merge($data_yest, $data_today);

// Then format it
$final = array_reduce($merged, function($final, $item) {

    // Initialize for each isp if it's not present
    // This way we avoid overwriting previous data and have a default value 0
    if (! isset($final[ $item['isp'] ])) {
        $final[ $item['isp'] ] = [
            'sent_yest' => 0,
            'sent_today' => 0,
        ];
    }

    // And if one of the days is present, we add it
    if (isset($item['sent_yest'])) {
        $final[ $item['isp'] ][ 'sent_yest' ] = $item['sent_yest'];
    }
    if (isset($item['sent_today'])) {
        $final[ $item['isp'] ][ 'sent_today' ] = $item['sent_today'];
    }

    // Then return the modified array
    return $final;
}, []);

print_r($final);
exit;
</code>```

Result looks like this:

```<code>Array
(
    [aol] => Array
        (
            [sent_yest] => 46838
            [sent_today] => 14135
        )

    [gmail] => Array
        (
            [sent_yest] => 33015
            [sent_today] => 21263
        )

    [juno] => Array
        (
            [sent_yest] => 93544
            [sent_today] => 74934
        )

    [roadrunner] => Array
        (
            [sent_yest] => 6181
            [sent_today] => 939
        )

    [yahoo] => Array
        (
            [sent_yest] => 71444
            [sent_today] => 22059
        )

    [att] => Array
        (
            [sent_yest] => 0
            [sent_today] => 624
        )

)
</code>```

Body:
1.fetching the values from a same table with different date

 <?php
    $date= date("Y-m-d");;
    $prev_date = date('Y-m-d', strtotime($date .' -1 day'));
    $result_yest=mysql_query("SELECT isp,sum(sent) AS `sent_yest` FROM red_global WHERE status_date='$prev_date' and sent > 0 group by 1",$link1);
    $data_yest = array(); // create a variable to hold the information
    while (($row_yest = mysql_fetch_array($result_yest, MYSQL_ASSOC)) !== false){
      $data_yest[] = $row_yest; // add the row in to the results (data) array
    }
    print_r($data_yest);
    $result_today=mysql_query("SELECT isp,sum(sent) AS `sent_today` FROM red_global WHERE status_date='$date' and sent > 0 group by 1",$link1);
    $data_today = array(); // create a variable to hold the information
    while (($row_today = mysql_fetch_array($result_today, MYSQL_ASSOC)) !== false){
      $data_today[] = $row_today; // add the row in to the results (data) array
    }
    print_r($data_today);
    exit;
?>

2.Array results in which one array contains yesterday's sent count and another one aray contains today's sent count both array having the common isp

Array (
  [0] => Array ( [isp] => aol [sent_yest] => 46838 )
  [1] => Array ( [isp] => gmail [sent_yest] => 33015 )
  [2] => Array ( [isp] => juno [sent_yest] => 93544 )
  [3] => Array ( [isp] => roadrunner [sent_yest] => 6181 )
  [4] => Array ( [isp] => yahoo [sent_yest] => 71444 )
)

Array (
  [0] => Array ( [isp] => aol [sent_today] => 14135 )
  [1] => Array ( [isp] => att [sent_today] => 624 )
  [2] => Array ( [isp] => gmail [sent_today] => 21263 )
  [3] => Array ( [isp] => juno [sent_today] => 74934 )
  [4] => Array ( [isp] => roadrunner [sent_today] => 939 )
  [5] => Array ( [isp] => yahoo [sent_today] => 22059 )
)

Now i need a result like this isp name, yesterday's sent count, today's sent count

[isp, sent_yest, sent_today],
[aol, 46838,  14135],
[att, 0,  624],
[gmail, 33015,  21263],

Anyone help me to solve this.. Thanks in advance

Body:
I would avoid foreach if it's possible, since it leads to code that's much harder to understand. With array operation it can look like this:

// First we merge the two arrays
$merged = array_merge($data_yest, $data_today);

// Then format it
$final = array_reduce($merged, function($final, $item) {

    // Initialize for each isp if it's not present
    // This way we avoid overwriting previous data and have a default value 0
    if (! isset($final[ $item['isp'] ])) {
        $final[ $item['isp'] ] = [
            'sent_yest' => 0,
            'sent_today' => 0,
        ];
    }

    // And if one of the days is present, we add it
    if (isset($item['sent_yest'])) {
        $final[ $item['isp'] ][ 'sent_yest' ] = $item['sent_yest'];
    }
    if (isset($item['sent_today'])) {
        $final[ $item['isp'] ][ 'sent_today' ] = $item['sent_today'];
    }

    // Then return the modified array
    return $final;
}, []);

print_r($final);
exit;

Result looks like this:

Array
(
    [aol] => Array
        (
            [sent_yest] => 46838
            [sent_today] => 14135
        )

    [gmail] => Array
        (
            [sent_yest] => 33015
            [sent_today] => 21263
        )

    [juno] => Array
        (
            [sent_yest] => 93544
            [sent_today] => 74934
        )

    [roadrunner] => Array
        (
            [sent_yest] => 6181
            [sent_today] => 939
        )

    [yahoo] => Array
        (
            [sent_yest] => 71444
            [sent_today] => 22059
        )

    [att] => Array
        (
            [sent_yest] => 0
            [sent_today] => 624
        )

)


问:
Find angularjs version
I tried in browser console:

```<code>angular.version
</code>```

And I got below

codeName : "foam-acceleration" dot : 3 full : "1.4.3" major : 1 minor
  : 4

So what angular version is used? Is it angular2 or 4 or any other?

Thanks

答: Neither. It is not angular 2 or 4. It is AngularJS 1.4.3, which is what we commonly refer to as AngularJS 1.x</p>

Title: Find angularjs version

Body:
I tried in browser console:

angular.version

And I got below

codeName : "foam-acceleration" dot : 3 full : "1.4.3" major : 1 minor
  : 4

So what angular version is used? Is it angular2 or 4 or any other?

Thanks


问:
jQuery ajax call fires error event on a 200 success call
I have an ASP.NET Core WebAPI project with the following GET in my controller:

```<code>[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}
</code>```

I'm trying to call this method from jQuery ajax call:

```<code>$.ajax({
    type: "GET",
    url: url,
    async: true,
    dataType: "json",
    success: function (data) {
        setJsonResult(data);
        showResultPane("API request result");
    },
    error: function (obj, textStatus, errorThrown) {
        setHtmlResult("Error returned by API: " + errorThrown);
        showResultPane("Unauthorized request result");
    },
    beforeSend: function (request) {
        if (currentToken) {
            request.setRequestHeader("Authorization", "Bearer " + currentToken);
        }
    }
});
</code>```

I monitor the web traffic with Fiddler and I see that the server returns a 200 Ok response with the following:

```<code>HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Kestrel
Access-Control-Allow-Origin: *
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type,     Accept, Authorization
Date: Thu, 08 Jun 2017 09:13:18 GMT

13
["value1","value2"]
0
</code>```

The problem is that while the response from the web server is successful, the jQuery ajax error method is still being fired instead of the success method. I've tried playing with the dataType parameter (changing it, removing it) - no effect.

I even tried returning a different value from the API that is just a string and even change dataType to text - still firing error.

What's going on here?

答:
The response does not look like valid JSON to me. Change the return for the Get()-method to string and try to serialize the response from with JavaScriptSerializer().Serialize() before returning it.

Also try setting dataType to 'application/json' and add crossDomain: true in the ajax-call.

I have only experience with self-hosted wcf application, but there I'm using [WebGet(ResponseFormat = WebMessageFormat.Json] attributes for my REST-methods.

Body:
I have an ASP.NET Core WebAPI project with the following GET in my controller:

[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

I'm trying to call this method from jQuery ajax call:

$.ajax({
    type: "GET",
    url: url,
    async: true,
    dataType: "json",
    success: function (data) {
        setJsonResult(data);
        showResultPane("API request result");
    },
    error: function (obj, textStatus, errorThrown) {
        setHtmlResult("Error returned by API: " + errorThrown);
        showResultPane("Unauthorized request result");
    },
    beforeSend: function (request) {
        if (currentToken) {
            request.setRequestHeader("Authorization", "Bearer " + currentToken);
        }
    }
});

I monitor the web traffic with Fiddler and I see that the server returns a 200 Ok response with the following:

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Kestrel
Access-Control-Allow-Origin: *
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type,     Accept, Authorization
Date: Thu, 08 Jun 2017 09:13:18 GMT

13
["value1","value2"]
0

The problem is that while the response from the web server is successful, the jQuery ajax error method is still being fired instead of the success method. I've tried playing with the dataType parameter (changing it, removing it) - no effect.

I even tried returning a different value from the API that is just a string and even change dataType to text - still firing error.

What's going on here?


答:
```<code>IF OBJECT_ID('Tempdb..#Temp') IS NOT NULL
Drop table #Temp

Declare @Tab1 TABLE ( ID INT, ChecklistItemID INT , Attachment INT)
Insert into @Tab1
SELECT 327 , 912, 611 UNION ALL
SELECT 328 , 912, 612

Declare @Tab2 TABLE (ID INT,FileName Varchar(10))
INSERT INTO @Tab2
SELECT  611 , '2.jpg' Union all
SELECT  612 , '3.jpg'

SELECT ChecklistItemID,[FileName] INTO #Temp FROM @Tab1 t1
INNER JOIN @Tab2 t2
ON t1.Attachment=t2.ID

DECLARE @COulmn nvarchar(max),
        @query nvarchar(max)
SELECT @COulmn= STUFF((SELECT ', '+'File'+CAST( ROW_NUMBER()OVER(PARTITION BY ChecklistItemID ORDER BY ChecklistItemID) AS Varchar(5))
FROM #Temp For XML PATH ('')),1,1,'')

SET @query = N'SELECT ChecklistItemID,' + @COulmn + N' from
             (
                SELECT *,''File''+ CAST(ROW_NUMBER()OVER(PARTITION BY ChecklistItemID ORDER BY ChecklistItemID) AS Varchar(5)) As FileColumn
                FROM #Temp
            ) Src
            PIVOT
            (
                MAX([FileName])
                FOR FileColumn in (' + @COulmn + N')
            ) pvt '

EXEC sp_executesql @query;
</code>```

OutPut

```<code>ChecklistItemID File1   File2
-----------------------------
912             2.jpg   3.jpg
</code>```

Title: I'm trying to implement Pivot SQL

Body:
this is my first time trying to do a pivot but even with all the information online, i'm still useless :(

I have this table.

+-----+-----------------+------------+
| ID  | ChecklistItemID | Attachment |
| 327 | 912             | 611        |
| 328 | 912             | 612        |
+-----+-----------------+------------+

and this table

+-----+----------+
| ID  | FileName |
| 611 | 2.jpg    |
| 612 | 3.jpg    |
+-----+----------+

I want my output to be like this

+-----------------+-------+-------+
| ChecklistItemID | File1 | File2 |
| 912             | 2.jpg | 3.jpg |
+-----------------+-------+-------+

Can anyone help please?

Body:
IF OBJECT_ID('Tempdb..#Temp') IS NOT NULL
Drop table #Temp

Declare @Tab1 TABLE ( ID INT, ChecklistItemID INT , Attachment INT)
Insert into @Tab1
SELECT 327 , 912, 611 UNION ALL
SELECT 328 , 912, 612

Declare @Tab2 TABLE (ID INT,FileName Varchar(10))
INSERT INTO @Tab2
SELECT  611 , '2.jpg' Union all
SELECT  612 , '3.jpg'

SELECT ChecklistItemID,[FileName] INTO #Temp FROM @Tab1 t1
INNER JOIN @Tab2 t2
ON t1.Attachment=t2.ID

DECLARE @COulmn nvarchar(max),
        @query nvarchar(max)
SELECT @COulmn= STUFF((SELECT ', '+'File'+CAST( ROW_NUMBER()OVER(PARTITION BY ChecklistItemID ORDER BY ChecklistItemID) AS Varchar(5))
FROM #Temp For XML PATH ('')),1,1,'')

SET @query = N'SELECT ChecklistItemID,' + @COulmn + N' from
             (
                SELECT *,''File''+ CAST(ROW_NUMBER()OVER(PARTITION BY ChecklistItemID ORDER BY ChecklistItemID) AS Varchar(5)) As FileColumn
                FROM #Temp
            ) Src
            PIVOT
            (
                MAX([FileName])
                FOR FileColumn in (' + @COulmn + N')
            ) pvt '

EXEC sp_executesql @query;

OutPut

ChecklistItemID File1   File2
-----------------------------
912             2.jpg   3.jpg


问:
Multi-command shell AS detached child process WITH spawn() IN Node.js
For reference: https://nodejs.org/api/child_process.html#child_process_options_detached

Hey guys,

So I need to spawn a child child-process, spawn because exec doesn't allow a options.detached & child.unref();, meaning it can be decoupled with the parent allowing the child to run and finish on it's own, vice-versa also the parent (in our particular case, the parent process can die before a long-running child, update in that case, is finished without needing to wait for the child like with exec).

We have a long connected ("… ; … ; …") command that is built by the node (parent) app, but as like spawn("echo stuff >>stderr.log") doesn't work, only spawn('ls', [-l]), I obviously can't chain commands (as it's also referenced in he docu and multiple times on SO.

TLDR;

We need to use spawn, but spawn can't process chained shell commands.
Do I really now need to write my command in a bash and execute that then, is this REALLY the ONLY option??

THX

答:
Notice the shell option for spawn:

If true, runs command inside of a shell. Uses '/bin/sh' on UNIX, and 'cmd.exe' on Windows. A different shell can be specified as a string. The shell should understand the -c switch on UNIX, or /d /s /c on Windows. Defaults to false (no shell).

So:

```<code>let child = child_process.spawn('foo; bar; blah', { shell : true });
</code>```

EDIT: if you're using a Node version that doesn't support this option, here's an alternative:

```<code>let child = child_process.spawn('/bin/sh', [ '-c', 'foo; bar; blah' ]);
</code>```

Body:
Notice the shell option for spawn:

If true, runs command inside of a shell. Uses '/bin/sh' on UNIX, and 'cmd.exe' on Windows. A different shell can be specified as a string. The shell should understand the -c switch on UNIX, or /d /s /c on Windows. Defaults to false (no shell).

So:

let child = child_process.spawn('foo; bar; blah', { shell : true });

EDIT: if you're using a Node version that doesn't support this option, here's an alternative:

let child = child_process.spawn('/bin/sh', [ '-c', 'foo; bar; blah' ]);


问:
Eigen library --> initialize matrix with data from file or existing std::vector<string> content (c++)
My question is how to initialize an eigen Matrix, but NOT this way:

```<code>matrix << 1,0,1,0,
          1,0,1,0,
          1,0,1,0,
</code>```

I have a Matrix that looks like the above one ( commas or no commas doesnt matter)
stored in a txt file.

I already wrote a function to read in each line and put it into a vector
now I want to create a matrix with this data

But it doesn' work and I cant find any page that explains how to assign data to a matrix without writing just the values.(like the example above)

All I need is the data from my file in an eigen Matrix

What I tried so far: (PS: had the idea with the iterators but i guess it will take too long with really big matrices, I just tried this example with a 1-2 dimensional matrix)

```<code>int readFromFile (const char * path, vector <string> & mv)
{
    fstream file;
    string line;
    file.open(path);

    while (getline(file,line))
    {
        mv.push_back(line);
    }
    file.close();
    return 0;
}

typedef Matrix <int, 1, 2> MyMatrix;

int fromVectoEigen (vector<string> & source, MyMatrix & target)
{   //for (int i = source.size(); i<0 ; i--)
    //{

        string valuerow = source.back();
        string::iterator it = valuerow.begin();
        target.row(0)<< *it;
        target.row(0)<<*it+1;
        //source.pop_back();
    //}

    return 0;
}
</code>```

Unfortunately cant just say Matrix.row(i) = vector.back() that doesnt work.

答:
A variation using only Eigen::Map for mapping data from std::vector, based on examples from https://eigen.tuxfamily.org/dox/group__TutorialMapClass.html</p>

```<code>#include <vector>
#include <Eigen/Dense>

std::vector<double> myStdVector;

// Insert code for filling myStdVector here
// ....

// Detect or set number of rows/columns
size_t numRows = 3;
size_t numCols = 7;

typedef Eigen::Map<Eigen::MatrixXd> Mapper;
Mapper myMatrix(&myStdVector.data()[0], numRows, numCols);
</code>```

Body:
My question is how to initialize an eigen Matrix, but NOT this way:

matrix << 1,0,1,0,
          1,0,1,0,
          1,0,1,0,

I have a Matrix that looks like the above one ( commas or no commas doesnt matter)
stored in a txt file.

I already wrote a function to read in each line and put it into a vector
now I want to create a matrix with this data

But it doesn' work and I cant find any page that explains how to assign data to a matrix without writing just the values.(like the example above)

All I need is the data from my file in an eigen Matrix

What I tried so far: (PS: had the idea with the iterators but i guess it will take too long with really big matrices, I just tried this example with a 1-2 dimensional matrix)

int readFromFile (const char * path, vector <string> & mv)
{
    fstream file;
    string line;
    file.open(path);

    while (getline(file,line))
    {
        mv.push_back(line);
    }
    file.close();
    return 0;
}

typedef Matrix <int, 1, 2> MyMatrix;

int fromVectoEigen (vector<string> & source, MyMatrix & target)
{   //for (int i = source.size(); i<0 ; i--)
    //{

        string valuerow = source.back();
        string::iterator it = valuerow.begin();
        target.row(0)<< *it;
        target.row(0)<<*it+1;
        //source.pop_back();
    //}

    return 0;
}

Unfortunately cant just say Matrix.row(i) = vector.back() that doesnt work.

Body:
A variation using only Eigen::Map for mapping data from std::vector, based on examples from https://eigen.tuxfamily.org/dox/group__TutorialMapClass.html

#include <vector>
#include <Eigen/Dense>

std::vector<double> myStdVector;

// Insert code for filling myStdVector here
// ....

// Detect or set number of rows/columns
size_t numRows = 3;
size_t numCols = 7;

typedef Eigen::Map<Eigen::MatrixXd> Mapper;
Mapper myMatrix(&myStdVector.data()[0], numRows, numCols);


答:
Your current Angular version is 1.4.3.

https://docs.angularjs.org/api/ng/object/angular.version

full is the current fullname version.

major, minor and dot are the 1.4.3 (major.minor.dot)

Title: Find angularjs version


问:
Enumerating ASP.NET MVC RouteTable route URLs
I'm trying to figure out how to enumerate the URLs of Routes in the RouteTable.

In my scenario, I have the following routes defined:

```<code>routes.MapRoute
  ("PadCreateNote", "create", new { controller = "Pad", action = "CreateNote" });
routes.MapRoute
  ("PadDeleteNote", "delete", new { controller = "Pad", action = "DeleteNote" });
routes.MapRoute
   ("PadUserIndex", "{username}", new { controller = "Pad", action = "Index" });
</code>```

In other words, if my site is mysite.com, mysite.com/create invokes PadController.CreateNote(), and mysite.com/foobaris invokes PadController.Index().

I also have a class that strongly types usernames:

```<code>public class Username
{
    public readonly string value;

    public Username(string name)
    {
        if (String.IsNullOrWhiteSpace(name))
        {
            throw new ArgumentException
                ("Is null or contains only whitespace.", "name");
        }

        //... make sure 'name' isn't a route URL off root like 'create', 'delete'

       this.value = name.Trim();
    }

    public override string ToString()
    {
        return this.value;
    }
}
</code>```

In the constructor for Username, I would like to check to make sure that name isn't a defined route. For example, if this is called:

```<code>var username = new Username("create");
</code>```

Then an exception should be thrown. What do I need to replace //... make sure 'name' isn't a route URL off root with?

答:
This doesn't fully answer what you are wanting to do by preventing users from registering  protected words, but there is a way you can constrain your routes.  We had /username url's in our site and we used a constraint like so.

```<code>routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" },   // Parameter defaults
                new
                {
                    controller = new FromValuesListConstraint(true, "Account", "Home", "SignIn"
                        //...etc
                    )
                }
            );

routes.MapRoute(
                 "UserNameRouting",
                  "{id}",
                    new { controller = "Profile", action = "Index", id = "" });
</code>```

You may just have to keep a list of reserved words, or, if you really want it automatic, you could possibly use reflection to get a list of the controllers in the namespace.

You can access the route collection with this.  The issue with this approach is that it requires you to explicitly register all routes you want to be "protected".  I still hold to my statement you'd be better off having a list of reserved keywords stored elsewhere.

```<code>System.Web.Routing.RouteCollection routeCollection = System.Web.Routing.RouteTable.Routes;

var routes = from r in routeCollection
             let t = (System.Web.Routing.Route)r
             where t.Url.Equals(name, StringComparison.OrdinalIgnoreCase)
             select t;

bool isProtected = routes.Count() > 0;
</code>```

Body:
I'm trying to figure out how to enumerate the URLs of Routes in the RouteTable.

In my scenario, I have the following routes defined:

routes.MapRoute
  ("PadCreateNote", "create", new { controller = "Pad", action = "CreateNote" });
routes.MapRoute
  ("PadDeleteNote", "delete", new { controller = "Pad", action = "DeleteNote" });
routes.MapRoute
   ("PadUserIndex", "{username}", new { controller = "Pad", action = "Index" });

In other words, if my site is mysite.com, mysite.com/create invokes PadController.CreateNote(), and mysite.com/foobaris invokes PadController.Index().

I also have a class that strongly types usernames:

public class Username
{
    public readonly string value;

    public Username(string name)
    {
        if (String.IsNullOrWhiteSpace(name))
        {
            throw new ArgumentException
                ("Is null or contains only whitespace.", "name");
        }

        //... make sure 'name' isn't a route URL off root like 'create', 'delete'

       this.value = name.Trim();
    }

    public override string ToString()
    {
        return this.value;
    }
}

In the constructor for Username, I would like to check to make sure that name isn't a defined route. For example, if this is called:

var username = new Username("create");

Then an exception should be thrown. What do I need to replace //... make sure 'name' isn't a route URL off root with?

Body:
This doesn't fully answer what you are wanting to do by preventing users from registering  protected words, but there is a way you can constrain your routes.  We had /username url's in our site and we used a constraint like so.

routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" },   // Parameter defaults
                new
                {
                    controller = new FromValuesListConstraint(true, "Account", "Home", "SignIn"
                        //...etc
                    )
                }
            );

routes.MapRoute(
                 "UserNameRouting",
                  "{id}",
                    new { controller = "Profile", action = "Index", id = "" });

You may just have to keep a list of reserved words, or, if you really want it automatic, you could possibly use reflection to get a list of the controllers in the namespace.

You can access the route collection with this.  The issue with this approach is that it requires you to explicitly register all routes you want to be "protected".  I still hold to my statement you'd be better off having a list of reserved keywords stored elsewhere.

System.Web.Routing.RouteCollection routeCollection = System.Web.Routing.RouteTable.Routes;

var routes = from r in routeCollection
             let t = (System.Web.Routing.Route)r
             where t.Url.Equals(name, StringComparison.OrdinalIgnoreCase)
             select t;

bool isProtected = routes.Count() > 0;


问:
Specify which fields are indexed in ElasticSearch
I have a document with a number of fields that I never query on so I would like to turn indexing on those fields off to save resources. I believe I need to disable the _all field, but how do I specify which fields are indexed then?

答:
Set dynamic index and _all index to false. Specify the required fields in mapping.
https://www.elastic.co/guide/en/elasticsearch/guide/current/dynamic-mapping.html</p>

```<code>{
   "mappings":{
      "candidates":{
         "_all":{
            "enabled":false
         },
          "dynamic": "false",
         "properties":{
            "tags":{
               "type":"text"
            },
            "derivedAttributes":{
               "properties":{
                "city":{
                     "type":"text"
                  },
                  "zip5":{
                     "type":"keyword"
                  }
               }
            }
         }
      }
   }
}
</code>```

Body:
Set dynamic index and _all index to false. Specify the required fields in mapping.
https://www.elastic.co/guide/en/elasticsearch/guide/current/dynamic-mapping.html

{
   "mappings":{
      "candidates":{
         "_all":{
            "enabled":false
         },
          "dynamic": "false",
         "properties":{
            "tags":{
               "type":"text"
            },
            "derivedAttributes":{
               "properties":{
                "city":{
                     "type":"text"
                  },
                  "zip5":{
                     "type":"keyword"
                  }
               }
            }
         }
      }
   }
}


问:
AngularJS: Animate ng-hide / ng-show height of li by using css transitions
I am using Angular to hide/show items of a unordered list. Since the effect is a bit too fast for the user to notice the disappearance/appearance of my lis, I want to add a transition on the height.

```<code>li {
  transition: height 1s linear;
  overflow: hidden;
}

li.ng-hide {
  height: 0;
}
</code>```

This is where my problem is : the transition does not affect the lis, unless I set them a height, which I don't want, since I don't exactly know how big they are.

Here is a plunker to illustrate that. I've made the test on lis and divs and I've also tried without Angular which does not seem to be the responsible.

How can I make the transition work without setting the height of my elements ?

答:
You don't necessarily need to set your transition on height.
You can set it on the ng-hide or ng-show property.

Here is your example with this feature :

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

Simply assign the class to the element you want to animate.

```<code>.animate.ng-hide-add,
.animate.ng-hide-remove {
  transition: all linear 2s;
}
</code>```

You'll find more infos here : https://docs.angularjs.org/api/ng/directive/ngShow

nb: You can seperate the animation for ng-hide-add and ng-hide-remove in your css. of course.

Hope it helps !

Body:
I am using Angular to hide/show items of a unordered list. Since the effect is a bit too fast for the user to notice the disappearance/appearance of my lis, I want to add a transition on the height.

li {
  transition: height 1s linear;
  overflow: hidden;
}

li.ng-hide {
  height: 0;
}

This is where my problem is : the transition does not affect the lis, unless I set them a height, which I don't want, since I don't exactly know how big they are.

Here is a plunker to illustrate that. I've made the test on lis and divs and I've also tried without Angular which does not seem to be the responsible.

How can I make the transition work without setting the height of my elements ?

Body:
You don't necessarily need to set your transition on height.
You can set it on the ng-hide or ng-show property.

Here is your example with this feature :

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

Simply assign the class to the element you want to animate.

.animate.ng-hide-add,
.animate.ng-hide-remove {
  transition: all linear 2s;
}

You'll find more infos here : https://docs.angularjs.org/api/ng/directive/ngShow

nb: You can seperate the animation for ng-hide-add and ng-hide-remove in your css. of course.

Hope it helps !


问:
Bootstrap datatables sorting
I have a small problem, I'm using datatables to display some values, e.g. name, country (hidden) and place.
If I select a country I want that the second filter for the places only displayes Cities that are in the selected country.
Is there and datatables options to do so?

I hope this is the right spot.

```<code>    var dtColumnfilters = {
    init: function() {
        $('#c4s-datatable-trainings_wrapper').children('.row').append('<div class="col-xs-12"><div class="c4s-datatable-filter"><span id="filter-country" class="filter"></span><span id="filter-city" class="filter"></span></div></div>');
        $('#c4s-datatable-trainings.admin').dataTable().columnFilter({
            aoColumns: [
                null,
                {sSelector: '#filter-country', type: 'select'},
                {sSelector: '#filter-city', type: 'select'},
                null
            ]
        });
        $('#c4s-datatable-trainings.account').dataTable().columnFilter({
            aoColumns: [
                null,
                null,
                null,
                {sSelector: '#filter-city', type: 'select'},
                null
            ]
        });
        // STYLE FOR FILTERS
        $('.c4s-datatable-filter select').removeClass('input-sm').addClass('bs-select').attr('data-live-search','true').attr('data-style','btn-default btn-xs');
    }
};
</code>```

答:
In my opinion, this is not something datatables should be responsible for. (or be able to)

You might consider filtering places based on a data attribute country. data-country="COUNTRYCODE or ID" If it takes too lang to load all places, you might also consider loading the places you need with Ajax once a country has been selected.

Title: Bootstrap datatables sorting

Body:
I have a small problem, I'm using datatables to display some values, e.g. name, country (hidden) and place.
If I select a country I want that the second filter for the places only displayes Cities that are in the selected country.
Is there and datatables options to do so?

I hope this is the right spot.

    var dtColumnfilters = {
    init: function() {
        $('#c4s-datatable-trainings_wrapper').children('.row').append('

');
        $('#c4s-datatable-trainings.admin').dataTable().columnFilter({
            aoColumns: [
                null,
                {sSelector: '#filter-country', type: 'select'},
                {sSelector: '#filter-city', type: 'select'},
                null
            ]
        });
        $('#c4s-datatable-trainings.account').dataTable().columnFilter({
            aoColumns: [
                null,
                null,
                null,
                {sSelector: '#filter-city', type: 'select'},
                null
            ]
        });
        // STYLE FOR FILTERS
        $('.c4s-datatable-filter select').removeClass('input-sm').addClass('bs-select').attr('data-live-search','true').attr('data-style','btn-default btn-xs');
    }
};


问:
getting a google analytics access token and how to use it in google sheets script
I am currently pulling data from the API query URI from the query explorer from google. https://ga-dev-tools.appspot.com/query-explorer/ It's possible here to include a 60 minute access token.

Now I want a non expiring access token and gotten as far as the API Project website from google and I have generated a client id and secret.

I tried to add the client_id and client_secret as parameters to the url like so:
url&client_id=xxx&client_secret=yyy

This does not work.

How can I generate a working access token in Google (Sheets) scripts?

Thanks

答:
I think you need to start at the beginning.

To get an Access token you need to use a client id and client secret to request access of a user.   When the user grants your application access then you will be given an access token.  A good place to start Using OAuth 2.0 to Access Google APIs

Usage:

RestRequesturl?access_token=[yourtoken]

When you request access of the user you send scopes with it scopes denote what access your application will need.  There is a large list of scopes for Google here  in your case you will need to request the scope for Google analytics and the scope for google sheets this will allow you to access both the user google analytics account and their Google Sheets.

As you know access tokens expire after an hour for that you need a refresh token a refresh token will allow you to request a new access token of the authentication sever without having to request access for the user again.  I am not a JS developer but i know you can get a refresh token with node.js but i don't think you can with pure js.

I have a tutorial series that may help you get up to speed. Google development for beginners reading the one on Oauth2 would probably help you.  Google Developer console oauth2


问:
AS3: How do I set a value of a class and prevent it from being changed?
Solution found thanks to everyone's answers. Check bottom of this post.

I am using MVC and the problem concerns my model. With my code I am creating a board which in turn creates tiles. Every tile on the board gets an X and a Y value. After this I want to prevent access to the setter to prevent myself from accidentally changing the value ever again.

I was thinking of using a constant instead of a variable, but it seems I have to define the value at the time of creation. In other words: const myConst:uint; myConst = 2; // does not work

Right now I have a work-around which I am not happy with. Surely there's a cleaner way. You can see my work-around below.

```<code>package myboardgame
{
 internal class Tile
 {
  private var _x:uint;
  private var _y:uint;

  private var _xLock:Boolean; // Makes sure that the X and Y values of a tile can only be set once to prevent errors
  private var _yLock:Boolean; //  " "

  internal function set x(x:uint):void
  { if(!_xLock) {_x = x; _xLock = true;} else { throw new Error("Trying to change the one-time write access X tile value")}}
  internal function get x():uint
  { return _x; }
 }
}
</code>```

Edit. The solution I went with:

```<code>package myboardgame
{
    internal class Tile
{
    private var _x:uint;
    private var _y:uint;

    public function Tile(x:uint, y:uint):void
    {
        _x = x;
        _y = y;
    }
    internal function get x():uint
    { return _x; }

    internal function get y():uint
    { return _y; }
}
}
</code>```

答:
If you want to set the value at the creation time you must define an explicit constructor for your class (always suggested even when not needed). </p>

<p>The constructor you define must basically have one parameter by means of which you can provide a value to the inner attribute. This is done only once at the instance initialization. </p>

```<code>public class Tile {

   //these are the attributes: your instance status
   private var x:int;
   private var y:int;

   //this is the class constructor
  public function Tile(_x:int, _y:int){
      //here goes the initialization of your attributes and other stuff you may need
      x = _x;
      y = _y;
   }

   //then the other methods...
}
</code>```

Body:
Solution found thanks to everyone's answers. Check bottom of this post.

I am using MVC and the problem concerns my model. With my code I am creating a board which in turn creates tiles. Every tile on the board gets an X and a Y value. After this I want to prevent access to the setter to prevent myself from accidentally changing the value ever again.

I was thinking of using a constant instead of a variable, but it seems I have to define the value at the time of creation. In other words: const myConst:uint; myConst = 2; // does not work

Right now I have a work-around which I am not happy with. Surely there's a cleaner way. You can see my work-around below.

package myboardgame
{
 internal class Tile
 {
  private var _x:uint;
  private var _y:uint;

  private var _xLock:Boolean; // Makes sure that the X and Y values of a tile can only be set once to prevent errors
  private var _yLock:Boolean; //  " "

  internal function set x(x:uint):void
  { if(!_xLock) {_x = x; _xLock = true;} else { throw new Error("Trying to change the one-time write access X tile value")}}
  internal function get x():uint
  { return _x; }
 }
}

Edit. The solution I went with:

package myboardgame
{
    internal class Tile
{
    private var _x:uint;
    private var _y:uint;

    public function Tile(x:uint, y:uint):void
    {
        _x = x;
        _y = y;
    }
    internal function get x():uint
    { return _x; }

    internal function get y():uint
    { return _y; }
}
}

Body:
If you want to set the value at the creation time you must define an explicit constructor for your class (always suggested even when not needed).

The constructor you define must basically have one parameter by means of which you can provide a value to the inner attribute. This is done only once at the instance initialization.

public class Tile {

   //these are the attributes: your instance status
   private var x:int;
   private var y:int;

   //this is the class constructor
  public function Tile(_x:int, _y:int){
      //here goes the initialization of your attributes and other stuff you may need
      x = _x;
      y = _y;
   }

   //then the other methods...
}


问:
How to click "NEXT" card in the gmail.com webpage using Selenium webdriver 3.4.3?
I want to navigate through gmail.com and log into my account using Selenium.
I'm new to python programming and selenium and hence I don't know how to do that.
In the gmail.com webpage, I can fill in my email account, but then I need to click next card in the bottom. How to do that? Thanks in advance.  </p>

答:
Here is the Answer to your Question:

While working with Selenium 3.4.X and ChromeDriver 2.29 & the latest Google Chrome 58.0 you can use the following code block to open gmail, key in your email-id and click on the NEXT button:

```<code>from selenium import webdriver

driver=webdriver.Chrome("C:\\your_directory\\chromedriver.exe")
driver.maximize_window()
driver.implicitly_wait(20)
driver.get("https://mail.google.com")
driver.find_element_by_xpath("//input[@id='identifierId']").send_keys("alphax")
driver.find_element_by_id("identifierNext").click()
</code>```

Let me know if this Answers your Question.

Body:
Here is the Answer to your Question:

While working with Selenium 3.4.X and ChromeDriver 2.29 & the latest Google Chrome 58.0 you can use the following code block to open gmail, key in your email-id and click on the NEXT button:

from selenium import webdriver

driver=webdriver.Chrome("C:\\your_directory\\chromedriver.exe")
driver.maximize_window()
driver.implicitly_wait(20)
driver.get("https://mail.google.com")
driver.find_element_by_xpath("//input[@id='identifierId']").send_keys("alphax")
driver.find_element_by_id("identifierNext").click()

Let me know if this Answers your Question.


问:
SQL UPDATE if condition (from other table) is true
SHORT: I want to update a table if the userlevel is 1.

Only certain users (on the website) can update the table in the database.

Those users have a 'userlevel 1'

On the website the users are logged-in.
The log-in information + the userlevel is in table users

The table I want to update is device_data

My query:

```<code>UPDATE table1
SET colum1 = value1
WHERE deviceid = deviceid
INNERJOIN table2 ON table1
IF userlevel = '1'
</code>```

答:
try this : </p>

```<code>UPDATE device_data a
inner join users b
on a.deviceid = b.deviceid
SET a.column1 = 'value1'
WHERE b.userlevel = 1
</code>```

Body:
SHORT: I want to update a table if the userlevel is 1.

Only certain users (on the website) can update the table in the database.

Those users have a 'userlevel 1'

On the website the users are logged-in.
The log-in information + the userlevel is in table users

The table I want to update is device_data

My query:

UPDATE table1
SET colum1 = value1
WHERE deviceid = deviceid
INNERJOIN table2 ON table1
IF userlevel = '1'

Body:
try this :

UPDATE device_data a
inner join users b
on a.deviceid = b.deviceid
SET a.column1 = 'value1'
WHERE b.userlevel = 1


问:
how to redirect `command ...` all output into a file in linux?
I'm running command xxx xxx in linux, and I want to redirect all output, including std/warn/err output into one file IN ORDER.

How to deal with this?

For example, if I run command xxx xxx 2>file, the file will only contains error message. If I run command xxx xxx 1>file, the file will only contains std message. But I want all message together, not devided message. How to deal with this?

Thank you!

答:
You could also use this simpler way

```<code>$ command arg1 arg2 >& command.out
</code>```

This is typical C shell way but works well on most advanced shells such as bash.

Body:
You could also use this simpler way

$ command arg1 arg2 >& command.out

This is typical C shell way but works well on most advanced shells such as bash.


问:
Wordpress .Htaccess Usage In Subfolder Site
Could someone help me; where am i doing wrong?

My wordpress site is not in root; i installed it in a directory(newsite/) I mean; there are 2 sites.

My root site(example.com) has default htaccess file.

And this is my sub wordpress site's(example.com/newsite/) .htacces source:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On

RewriteBase /newsite/
RewriteRule ^newsite/news/hello-world /newsite/news/?title=hello-world [L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /newsite/index.php [L]

</IfModule>

# END WordPress
</code>```

I just want:

www.example.com/newsite/news/hello-world

(above url should open the url at below; without url change at address bar)

www.example.com/newsite/news/?title=hello-world

答:
Check with different permalink options.
Note : .htaccess file should be writable or paste the suggested code in .htaccess after permalink saved.</p>

Body:
Could someone help me; where am i doing wrong?

My wordpress site is not in root; i installed it in a directory(newsite/) I mean; there are 2 sites.

My root site(example.com) has default htaccess file.

And this is my sub wordpress site's(example.com/newsite/) .htacces source:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On

RewriteBase /newsite/
RewriteRule ^newsite/news/hello-world /newsite/news/?title=hello-world [L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /newsite/index.php [L]

</IfModule>

# END WordPress

I just want:

www.example.com/newsite/news/hello-world

(above url should open the url at below; without url change at address bar)

www.example.com/newsite/news/?title=hello-world


问:
How to fix bug in mobile chrome about position fixed.And difference between firefox and chrome
In mobile version firefox everything works perfect.In chrome have bug with fixed positioning.When i scroll the header must change absolute to fixed and height 65 to 35 pixels.But its flickering.
Im novice in web development.And its my first static web site.
Im using jquery plugin skrollr.

Heres my jquery code

```<code>$(window).scroll(function(){
      if ($(this).scrollTop() > 20) {
        $('.menu ').addClass("sticky");
      }
      else {
        $('.menu').removeClass("sticky");
      }
    });
</code>```

and my CSS code

```<code>.menu {
    position absolute;
    background: white;
    height: 65px;
}
.menu.sticky {
    position:fixed;
    height: 37px;
    max-width: 480px;
    padding: 0;
    background: white;
}
</code>```

Please help already week cant solve this problem.

答: use transition:all 0.4s ease-in-out in .menu class. You can adjust delay of transition as per needed. One more you don't need to add any plugin for this. You can easily handle this with small jquery code and CSS3 animation.

Body:
In mobile version firefox everything works perfect.In chrome have bug with fixed positioning.When i scroll the header must change absolute to fixed and height 65 to 35 pixels.But its flickering.
Im novice in web development.And its my first static web site.
Im using jquery plugin skrollr.

Heres my jquery code

$(window).scroll(function(){
      if ($(this).scrollTop() > 20) {
        $('.menu ').addClass("sticky");
      }
      else {
        $('.menu').removeClass("sticky");
      }
    });

and my CSS code

.menu {
    position absolute;
    background: white;
    height: 65px;
}
.menu.sticky {
    position:fixed;
    height: 37px;
    max-width: 480px;
    padding: 0;
    background: white;
}

Please help already week cant solve this problem.


问:
How to replace accented characters?
My output looks like 'àéêöhello!'. I need change my output like this  'aeeohello', Just replacing the character à as a like this.

答:
```<code>import unidecode

somestring = "àéêöhello"

#convert plain text to utf-8
u = unicode(somestring, "utf-8")
#convert utf-8 to normal text
print unidecode.unidecode(u)
</code>```

Output:

```<code>aeeohello
</code>```

Title: How to replace accented characters?

Body:
import unidecode

somestring = "àéêöhello"

#convert plain text to utf-8
u = unicode(somestring, "utf-8")
#convert utf-8 to normal text
print unidecode.unidecode(u)

Output:

aeeohello


问:
Storing time zone offset in Oracle DB as separate field
I am working on air flight Java app and need to store local time with time zone information in Oracle DB.

DATE/TIMESTAMP types have less problems then WITH TIME ZONE analogs.

If I store local date in DATE field what type should I assign for offset as separate field in Oracle DB and Java/Hibernate mapping? I hope that date arithmetic would be easy both in Java and Oracle native SQL queries.

I can imaging only INT(6) to store offsets as seconds. Native Oracle SQL queries can use arithmetic operations:

```<code>departure_date + departure_off/(24*60*60)
</code>```

In Java:

```<code>departureDate.atOffset(ZoneOffset.ofTotalSeconds(departureOff))
</code>```

UPDATE I have no information for TZ region, like 'US/Pacific', only numeric offset.

答:
Don't. Convert all the times to a common time zone (i.e. UTC) and then, when the front-end wants to display it in their local time zone it can do the conversion back from UTC.

```<code>INSERT INTO your_table ( departure_date )
VALUES (
  FROM_TZ(
    CAST( :your_date AS TIMESTAMP ),
    TO_CHAR( TRUNC( :your_offset / 60 ), 'FMS00' )
      || ':' || TO_CHAR( MOD( :your_offset, 60 ), 'FM00' )
  ) AT TIME ZONE 'UTC'
);
</code>```

Or you could use TIMESTAMP WITH TIME ZONE.

```<code>CREATE TABLE departures (
  departure_date   TIMESTAMP WITH TIME ZONE
);

INSERT INTO your_table ( departure_date )
VALUES (
  FROM_TZ(
    CAST( :your_date AS TIMESTAMP ),
    TO_CHAR( TRUNC( :your_offset / 60 ), 'FMS00' )
      || ':' || TO_CHAR( MOD( :your_offset, 60 ), 'FM00' )
  )
);
</code>```

However, if you really want to store date and offset separately then use INTERVAL DAY TO SECOND:

```<code>CREATE TABLE departures (
  departure_date   DATE,
  departure_offset INTERVAL DAY TO SECOND
);

INSERT INTO departures VALUES (
  :your_date,
  NUMTODSINTERVAL( :your_offset, 'SECOND' )
);
</code>```

Body:
I am working on air flight Java app and need to store local time with time zone information in Oracle DB.

DATE/TIMESTAMP types have less problems then WITH TIME ZONE analogs.

If I store local date in DATE field what type should I assign for offset as separate field in Oracle DB and Java/Hibernate mapping? I hope that date arithmetic would be easy both in Java and Oracle native SQL queries.

I can imaging only INT(6) to store offsets as seconds. Native Oracle SQL queries can use arithmetic operations:

departure_date + departure_off/(24*60*60)

In Java:

departureDate.atOffset(ZoneOffset.ofTotalSeconds(departureOff))

UPDATE I have no information for TZ region, like 'US/Pacific', only numeric offset.

Body:
Don't. Convert all the times to a common time zone (i.e. UTC) and then, when the front-end wants to display it in their local time zone it can do the conversion back from UTC.

INSERT INTO your_table ( departure_date )
VALUES (
  FROM_TZ(
    CAST( :your_date AS TIMESTAMP ),
    TO_CHAR( TRUNC( :your_offset / 60 ), 'FMS00' )
      || ':' || TO_CHAR( MOD( :your_offset, 60 ), 'FM00' )
  ) AT TIME ZONE 'UTC'
);

Or you could use TIMESTAMP WITH TIME ZONE.

CREATE TABLE departures (
  departure_date   TIMESTAMP WITH TIME ZONE
);

INSERT INTO your_table ( departure_date )
VALUES (
  FROM_TZ(
    CAST( :your_date AS TIMESTAMP ),
    TO_CHAR( TRUNC( :your_offset / 60 ), 'FMS00' )
      || ':' || TO_CHAR( MOD( :your_offset, 60 ), 'FM00' )
  )
);

However, if you really want to store date and offset separately then use INTERVAL DAY TO SECOND:

CREATE TABLE departures (
  departure_date   DATE,
  departure_offset INTERVAL DAY TO SECOND
);

INSERT INTO departures VALUES (
  :your_date,
  NUMTODSINTERVAL( :your_offset, 'SECOND' )
);