text:
Q: collapse inline form bootstrap i've added a inline-form to my page, in the main area,
the form is a bit to wide, i would like that it collapse at 991px,
but the rest of the page can collapse at 767px
i understand it can be done with mediaquery but not sure on what to code.
i'm stuck here!
what can i do?
i copied the inline form originally from a navbar of a file, the button is working fine.
it look like this:

       <button
      class="btn btn-default form-toggle"
      type="button"
      data-toggle="collapse"
      data-target="#collapseExample"
      aria-expanded="false"
      aria-controls="collapseExample">  Toggle navigation Reservations
      </button>

     <form class="form-inline navbar-form" name="bookerform" action="---" method="GET" target="_self">

hidden elements

arrivo

partenza

 Numero N

 Numero A

 Numero B

 button check

      </form>

A: thank you for your help,
ok actually i'm almost there.
i like the solution using the bootstrap grid, i've added the media queries but it's not showing as i want, from 992 above it should show only the form, not the button

    <button class="btn btn-default" type="button" data-toggle="collapse" data-target="#myForm"> Reservations
    </button>

<form class="collapse collapse-class" role="form" id="myForm">

            <input type="email" class="form-control">

            <input type="password" class="form-control">

            <input type="text" class="form-control">

            <input type="text" class="form-control">

            <input type="text" class="form-control">

        <button type="submit" class="btn btn-default">Button</button>

</form>

@media (max-width: 992px) {
.collapse-class {
    display: none;
}
}

A: You can do your on custom collapsing with a simple media query and css class. Simply toggle the CSS display from inline-block to block. Here, at 1000px and under, the two selects of the the second td will stack vertically; horizontally above 1000px.
CSS:
.collapse-it {
        display: inline-block;
    }

@media (max-width: 1000px) {
    .collapse-it {
        display:block;
    }

  .mobile-view:after {
    content:"mobile view vertical stacking";
  }
}

HTML:

credit card expiration

    <select>
      <option>a</option>
      <option>b</option>
      <option>c</option>
    </select>

    <select>
      <option>d</option>
      <option>e</option>
      <option>f</option>
    </select>

View Demo on Bootply

A: If you just want it to go away at 992px but keep the button, put a class on what you want to collapse, and leave the button outside it. Then write a media query to display: none at 992px like so:
<form class="form-inline navbar-form collapse-class" name="bookerform" action="---" method="GET" target="_self">

hidden elements

arrivo

partenza

 Numero N

 Numero A

 Numero B

 button check

  </form>

@media (max-width: 992px) {
    .collapse-class {
        display: none;
    }
}

There may be a more elegant way to do this, but I'm having a hard time figuring out exactly what you want, so I'm trying to be general.


text:
Q: keep notification on lock screen after unlock it Am newbie in IOS. I want to create an app in which unread reminder notification OR any local Notification and should not remove from lock screen of iphone. When i slide to unlock and lock it again then my notification remove from lock screen.
i Attached three screenshots in which notification is display and after that it removes. See reference Image here and here

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I get a QLabel to expand to full width? I want a QLabel to expand to full width of the container regardless of the contents. (I want this because I dynamically set the text and add widgets later which cause it to cut off part of the text)
Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    this->setFixedSize(100,100);
    QHBoxLayout *layout = new QHBoxLayout;
    this->setLayout(layout);
    QLabel *label = new QLabel;
    label->setStyleSheet("background-color:blue");
    label->setSizePolicy(QSizePolicy::MinimumExpanding,
                         QSizePolicy::MinimumExpanding);
    label->setText(tr("test"));
    layout->addWidget(label, 0, Qt::AlignTop | Qt::AlignLeft);
}
This code shows that the blue box does not expand to the entire width, why?

A: You must set:
layout->setContentsMargins(0,0,0,0);

By default every QWidget or QFrame add 15 pixels of margin in every direction.
The main problem is with setting the alignment when you add the widget to the layout. Use label->setAlignment instead.
layout->addWidget(label);

I compiled your code, it works with those changes.
Here is the minimal example:
#include <QApplication>
#include <QtGui>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget* w = new QWidget;
    w->setFixedSize(100,100);
    QHBoxLayout* layout = new QHBoxLayout;
    layout->setContentsMargins(0,0,0,0);
    w->setLayout(layout);
    QLabel* label = new QLabel;
    label->setAlignment(Qt::AlignTop | Qt::AlignLeft);
    label->setContentsMargins(0,0,0,0);
    label->setStyleSheet("background-color:blue");
    label->setSizePolicy(QSizePolicy::MinimumExpanding,
                     QSizePolicy::MinimumExpanding);
    label->setText("test");
    layout->addWidget(label);
    w->show();
    return a.exec();
}


text:
Q: java: how to get Timezone abbreviation (from offset)? My code like belows, I am using android. I found different devices may have different result.
Using different phone: I can get : "EST" or "GMT-05:00".
However, I just want to get abbreviation(just like "EST").
How can I get the abbreviation (or change offset to abbreviation)?
   String timezone =Calendar.getInstance().getTimeZone().getDisplayName(false, TimeZone.SHORT);

A: If anyone else need the solution : I just tweak the code and get desired short name, which i needed to display to user.
private static String getTimeZoneShortName() {

    String tz = TimeZone.getDefault().getDisplayName();

    String[] stz = tz.split(" ");

    StringBuilder sName = new StringBuilder();

    for (int i = 0; i < stz.length; i++) {
        sName.append(stz[i].charAt(0));
    }
    return sName.toString();
}


text:
Q: What does a bitwise exclusive OR do in Java? Given:
public class Spock {
    public static void main(String[] args) {
        Long tail = 2000L;
        Long distance = 1999L;
        Long story = 1000L;
        if ((tail > distance) ^ ((story * 2) == tail)) {
            System.out.print("1");
        }
        if ((distance + 1 != tail) ^ ((story * 2) == distance)) {
            System.out.print("2");
        }
    }
}

Why this sample code doesn't output anything?

A: You are using boolean exclusive OR and this is much the same as !=.  In the first case, both conditions are true and in the second, both conditions are false so neither branch is taken. (You can check this with the debugger in your IDE)
The only real difference is that != has higher precedence than & which is higher than ^

A: From http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22.2
For ^, the result value is true if the operand values are different; otherwise, the result is false.

A: In first if you get true ^ true = false
In second if you get false ^ false = false
becouse ^ - is OR exclusive opeartor, it's means
true ^ true = false
true ^ false = true
false ^ true = true
false ^ false = false

A: It doesn't print anything because when the XOR operator is used with boolean arguments (as opposed to integers) will only return true if exactly one of the 2 operands is true.
In your first if both parts evaluate to true and true ^ true == false
In your second if both parts evaluate to false and false ^ false == false


text:
Q: How to update scneraio name from TestRunner class in Karate Is there a way I can update the Scneario names in Scenario outline from the TestRunner class in Karate Framework? As Scenraio outlines have many tests, I want to print the test name with the scenrio name in the karate report. In order to do that I would like to update the scenario name from TestRunner.
I dont want to go to each feature file and do it manually.
Kindly let me know if this can be done.

A: In Karate 1.0 you can use placeholders in the title.
Scenario Outline: some text and ${variable}

And you should be able to set a variable in the feature using multiple options, which you should already be familiar with.
If this is not what you are looking for, consider this as not supported and you are welcome to contribute code. I really don't understand what you mean by "from TestRunner".


text:
Q: Why DataTable().ajax.reload() failed to reload the table automatically with ajax JSON response? I'm new in Jquery I want that once the user deletes an item(row) of table on click on "Supprimer" button I will delete it on data base  the table reloads automatically without this deleted line. To do I used jQuery with DataTables:
What is going on is once I click on "Ajouter" but  it shows me this alert:

DataTables warning: table id=tablebqup - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

I checked my database it was deleted but the table failed to load.
I checked my Console and I found that :
Uncaught TypeError: Cannot set property 'data' of null
at sa (datatables.min.js:48)
at Sb (datatables.min.js:119)
at s.<anonymous> (datatables.min.js:120)
at s.iterator (datatables.min.js:111)
at s.<anonymous> (datatables.min.js:120)
at Object.reload (datatables.min.js:114)
at Object.success (updtbq.js:69)
at i (jquery-3.2.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2)
at A (jquery-3.2.1.min.js:4)
sa @ datatables.min.js:48
Sb @ datatables.min.js:119
(anonymous) @ datatables.min.js:120
iterator @ datatables.min.js:111
(anonymous) @ datatables.min.js:120
(anonymous) @ datatables.min.js:114
(anonymous) @ updtbq.js:69
i @ jquery-3.2.1.min.js:2
fireWith @ jquery-3.2.1.min.js:2
A @ jquery-3.2.1.min.js:4
(anonymous) @ jquery-3.2.1.min.js:4
XMLHttpRequest.send (async)
send @ jquery-3.2.1.min.js:4
ajax @ jquery-3.2.1.min.js:4
r.(anonymous function) @ jquery-3.2.1.min.js:4
(anonymous) @ updtbq.js:58
dispatch @ jquery-3.2.1.min.js:3
q.handle @ jquery-3.2.1.min.js:3

I searched for the error and I found that DataTables by default, expects the data loaded to be valid JSON I have done some modification on my code but I failed to fix the error.
Please can some one help for that.
Here is my php file:
<?php
require_once("C:/wamp/www/Mini_Prj/controllers/mainController.php");
$bnqs=MainController::getBanque();
echo'

      Id Banque
      Nom de la banque
      Abrev
      Siège Sociale
      Tel
      Fax
      Modifier
      Supprimer

  <form method="post">
  ';
  $i=0;
foreach ($bnqs as $bnq) {
if($bnq['supr']!=1)
{
  echo
  "

  ".$bnq['idbc']."
  ".$bnq['nomb']."
  ".$bnq['abrvb']."
  ".$bnq['sigsocial']."
  ".$bnq['tel']."
  ".$bnq['fax']."
   <button id='modif$i' class='btn btn-info modif' name='button'>Modifier</button>
   <button id='supp$i' class='btn btn-info supp' name='button'>Supprimer</button>

";
  $i++;
}
}
echo'
</form>

';

here is my jS file :
var basUrl="http://localhost/Mini_Prj/";
$(document).ready(function(e){
   $('#tablebqup').dataTable();
....

  $(".supp").click(function () {
    $choix=confirm("voulez vous vraiment sauvegarder les modifications");
    if ($choix)
    {
      var id=($(this).parent().parent().find('td:eq(0)').html());// the value in the 1st column.
      var nombc=($(this).parent().parent().find('td:eq(1)').html());
      var abrv= ($(this).parent().parent().find('td:eq(2)').html());
      var sigsoc=($(this).parent().parent().find('td:eq(3)').html());
      var telf=($(this).parent().parent().find('td:eq(4)').html());
      var fx=($(this).parent().parent().find('td:eq(5)').html());
      console.log(id);
      $.post(basUrl+'views/component/updtbq.php',
        {
          action:'sup_bq',
          idbc:id,
          nomb:nombc,
          abrvb:abrv,
          sigsocial:sigsoc,
          tel:telf,
          fax:fx,
        }, function(data) {
     $("#tablebqup").DataTable().ajax.reload();//Here is my problem
       });
     }
  });
...

and here is the generated Html:

  Mise a jours des banques

  <?php  include './component/tbbanqueupd.php';
  ?>

<form  method="post">
  <button type="button" class="btn btn-info" name="button" id="newbq" >Nouvelle banque</button>
</form>

Here is the response:

      Id Banque
      Nom de la banque
      Abrev
      Siège Sociale
      Tel
      Fax
      Modifier
      Supprimer

  <form method="post">

  4
  BANQUE DE DÉVELOPPEMENT LOCAL
  BDL
  5, rue Gaci Amar, Staoueli, Alger
  021 39 34 83– 033 52 15
  021 39 37 53
   <button id='modif0' class='btn btn-info modif' name='button'>Modifier</button>
   <button id='supp0' class='btn btn-info supp' name='button'>Supprimer</button>

  2
  BANQUE DE L'AGRICULTURE ET
DU DÉVELOPPEMENT RURAL
  BADR
  17, Boulevard Colonel Amirouche, Alger
  021 64 24 77– 63 38 78
  021 63 51 46 / 64 34 44
   <button id='modif1' class='btn btn-info modif' name='button'>Modifier</button>
   <button id='supp1' class='btn btn-info supp' name='button'>Supprimer</button>

  1
  BANQUE EXTÉRIEURE D'ALGÉRIE
  BEA
  48, Rue des Frères Bouadou,
Bir Mourad Raïs – Alger
  023 83 54 79
  021 56 30 50 / 056 51 56
   <button id='modif2' class='btn btn-info modif' name='button'>Modifier</button>
   <button id='supp2' class='btn btn-info supp' name='button'>Supprimer</button>

  3
  BANQUE NATIONALE D'ALGÉRIE
  BNA
  Siège Social : 8, Boulevard Ernesto Che Guevara, Alger
   021 43 99 98
   021 43 94 94
   <button id='modif3' class='btn btn-info modif' name='button'>Modifier</button>
   <button id='supp3' class='btn btn-info supp' name='button'>Supprimer</button>

  11
  CAISSE D'ÉPARGNE ET DE PRÉVOYANCE
  CNEP BANQUE
  Lot n°2 Garidi, Kouba – Alger
  0556 64 36 99
  021 91 64 57 et 58
   <button id='modif4' class='btn btn-info modif' name='button'>Modifier</button>
   <button id='supp4' class='btn btn-info supp' name='button'>Supprimer</button>

  5
  CRÉDIT POPULAIRE D'ALGÉRIE
  CPA
  2, Boulevard Colonel Amirouche, Alger
  021 63 57 12
  021 63 56 98 / 63 58 83
   <button id='modif5' class='btn btn-info modif' name='button'>Modifier</button>
   <button id='supp5' class='btn btn-info supp' name='button'>Supprimer</button>

</form>

A: Have you followed the steps in the link provided in the error: http://datatables.net/tn/1?
I would start with that.  What is the JSON that is returned?


text:
Q: Create sequence of time differences based on a condition TLDR: Need to create sequence of distinct rows but having issues with time sequences
I have a list of data frames, each looking similar to this (df1):
sector1 = data.frame(date = rep(seq.POSIXt(as.POSIXct("2001-01-01 00:00:00"),format = "%Y/%m/%d %H:%M:%S",
                                           as.POSIXct("2001-01-01  04:00:00"),format = "%Y/%m/%d  %H:%M:%S","hour"),
                                length.out = 7), order = rep(1,length.out = 7))

sector2 = data.frame(date = rep(seq.POSIXt(as.POSIXct("2001-02-01 04:30:00"),format = "%Y/%m/%d %H:%M:%S",
                                           as.POSIXct("2001-02-01  06:00:00"),format = "%Y/%m/%d  %H:%M:%S","hour"),
                                length.out = 7), order = rep(2,length.out = 7))

sector3 = data.frame(date = rep(seq.POSIXt(as.POSIXct("2001-03-01 06:30:00"),format = "%Y/%m/%d %H:%M:%S",
                                           as.POSIXct("2001-03-01  10:00:00"),format = "%Y/%m/%d  %H:%M:%S","hour"),
                                length.out = 7), order = rep(3,length.out = 7))

# binding sectors
df1 = rbind(sector1,sector2,sector3) %>% distinct(date,order)

Basically they have an "order" and a date (as well as other columns). What I need is to extract a row sequence of the earliest date at which the order changes from one state to another (ultimately only returning unique order; thus in this case I would expect 3 rows) and then calculate how long it took for that state change to occur. For the purposes of this example I'll do things on a single dataframe, but whatever the answer is be aware that it will be applied using lapply to a list.
Setting up a repex dataframe:
#adding spurious row with order 3 but date that precedes order 2
df1[12,] = data.frame(date = as.POSIXct("2001-02-01 03:30:00"), order = 3)

# extracting rows of length(unique(df1$order))
df2 = df1 %>% group_by(order) %>% slice_min(order_by = date, n = 1)

df2 =  df2 %>% arrange(date)

Originally, I achieved this, albeit quite slowly, using:
df2 %>% group_by(order) %>% slice_min(order_by = date, n = 1) %>%
  as.data.frame() %>%  mutate(time_between = as.numeric(date-lag(date), units = 'hours'))

What the above is doing is grouping by order then slicing the first row (mostly this corresponds to the earlies time, as typically this is in time order). Then I'm calculating the time between each order change.
This is the result:
                 date order time_between
1 2001-01-01 00:00:00     1           NA
2 2001-02-01 04:30:00     2        748.5
3 2001-02-01 03:30:00     3         -1.0

Although the above works in the majority of cases (it's quite slow), it has issues when a date from a subsequent order (3 in the above example) is timestamped prior to a preceding order (2 in the above case). This means that I have a negative time value (-1.0) which doesn't make sense.
What I would like to do is instead of merely grouping by order then slicing first row is some sort of logical operation where if the date/time of the row that was going to be extracted precedes the one of the previous order it gets discarded and the first row after the time is chosen, in this case it would be 2001-03-01 06:30:00  3
                 date order time_between
1 2001-01-01 00:00:00     1           NA
2 2001-02-01 04:30:00     2        748.5
3 2001-03-01 06:30:00     3        674.0

As mentioned, I was doing the above across a list of dataframes, so implementing like this:
lapply(list1, function(x) {x %>% group_by(order) %>% slice_min(order_by = date, n = 1) %>% ungroup()})
lapply(list1, function(x) {x %>% mutate(time_between = as.numeric(date-lag(date), units = 'hours'))})

Additional example dataframe:
df1 = data.frame(datetime = as.POSIXct(c("2019-04-11 21:46:55",
                                     "2019-04-13 00:19:23",
                                     "2019-04-15 01:20:41",
                                     "2019-04-15 04:18:12",
                                     "2019-04-23 00:50:45",
                                     "2019-04-22 08:44:41",
                                     "2019-04-24 05:54:17",
                                     "2019-04-23 07:21:36")), order = c(1,3,4,5,6,7,9,7))

A: I am not sure exactly which step is slowing the process but starting from df1 you can do keep one row for each date using distinct and then subtract time using lag and as.numeric.
library(dplyr)

df1 %>%
  mutate(date = lubridate::ymd_hms(date))  %>%
  arrange(order, date) %>%
  distinct(order, .keep_all = TRUE) %>%
  mutate(time_between = as.numeric(date - lag(date), units = 'hours'))

#                 date order  only_date time_between
#1 2001-01-01 00:00:00     1 2001-01-01           NA
#2 2001-02-01 04:30:00     2 2001-02-01        748.5
#3 2001-03-01 06:30:00     3 2001-03-01        674.0

Obviously for list of dataframes use it with lapply/map :
lapply(list1, function(x) {
 x %>%
    mutate(date = lubridate::ymd_hms(date))  %>%
    arrange(order, date) %>%
    distinct(order, .keep_all = TRUE) %>%
    mutate(time_between = as.numeric(date - lag(date), units = 'hours'))
})


text:
Q: Programmatically add source folder from Eclipse plugin I am developing m2e connector for out maven plugin, which actually generates some sources. I need to add generated sources(folder) to workspace as source folder.
I used JavaCore for edit .classpath file:
    IJavaProject javaProject = JavaCore.create(proj);
    IClasspathEntry[] entries = javaProject.getRawClasspath();

    IClasspathEntry[] newEntries = new IClasspathEntry[entries.length + 1];
    System.arraycopy(entries, 0, newEntries, 0, entries.length);

    Path myPath = new Path("target/generated-sources");
    IClasspathEntry myEntry = JavaCore.newSourceEntry(myPath);

    newEntries[entries.length] = JavaCore.newSourceEntry(myEntry.getPath());
    javaProject.setRawClasspath(newEntries, null);

But this code doesn't work it says:
Path for IClasspathEntry must be absolute
If I tried to use absolute path, it has been written to .classpath but in eclipse it wasn't displayed as source folder.
Have anyone any suggestion? It should be easy task but I cannot figure out how to solve it.

A: Problem solved...it was easier then I expected...
IJavaProject javaProject = JavaCore.create(proj);
IClasspathEntry[] entries = javaProject.getRawClasspath();

IClasspathEntry[] newEntries = new IClasspathEntry[entries.length + 1];
System.arraycopy(entries, 0, newEntries, 0, entries.length);

IPath srcPath= javaProject.getPath().append("target/generated-sources");
IClasspathEntry srcEntry= JavaCore.newSourceEntry(srcPath, null);

newEntries[entries.length] = JavaCore.newSourceEntry(srcEntry.getPath());
javaProject.setRawClasspath(newEntries, null);

And this will add source entry to .classpath file:

A: Try one of JavaCore.newSourceEntry(...) methods instead of JavaCore.newProjectEntry(...).


text:
Q: how to load Laravel _variables.scss I have changed some values in the _variables.scss
 $brand-primary: #0040c0;
 $brand-info: #8eb4cb;
 $brand-success: #2ab27b;
 $brand-warning: #cbb956;
 $brand-danger: #bf5329

Unfortunaly my views do not reflect the changes.
How can i display the changes made?
I tried to run dump_autoload and emptied my browsers cache.

A: You need to import those variables in app.scss file before importing bootstrap file like so:
@import "variables";
@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";

Then you need to run:
npm run dev

to compile assets and assuming you use app.css somewhere on your site you should see the changes (obviously assuming simplest scenario - it can be much more complicated if you version your file or compile multiple files into file with other name)


text:
Q: Xamarin iconize font class not found I am implementing the Iconize nuget package for my new project. I want to use this package for displaying icons in my tabbedpage. While following the github repository instructions from Iconize I encountered the following problem:
Visual studio code doesn't seem to find the Fonts class. Did I configure something wrong? Or is it a problem in the overall nuget package? I pasted my app.cs class below.

A: The issue is that the code you used are from different standalone nuget packages, not just a simple Xam.Plugin.Iconize nuget package.
So you should right-click on your App1 project Properties-->Manage Nuget Packages and then make sure that you have installed these nuget packages:
Xam.Plugin.Iconize.EntypoPlus
Xam.Plugin.Iconize.FontAwesome
Xam.Plugin.Iconize.Ionicons
Xam.Plugin.Iconize.JamIcons
Xam.Plugin.Iconize.Material
Xam.Plugin.Iconize.Meteocons
Xam.Plugin.Iconize.SimpleLineIcons
Xam.Plugin.Iconize.Typicons
Xam.Plugin.Iconize.WeatherIcons
You should install them all and then you can get the result well:

Besides, if you still get the error, you could try the following steps:
1) close VS, delete .vs hidden folder under the solution folder, any bin and obj output folders. After that, restart your project to test again.


text:
Q: how to customise the print function for native objects in clojurescript I'm looking to customize how a react element is displayed, this is the code:
(require ["react" :as react])

(defn react-element? [obj]
  (if-let [sym (aget obj "$$typeof")]
    (= js/Symbol
       (type sym))))

(extend-protocol IPrintWithWriter
  object
  (-pr-writer [obj writer _]
    (js/console.log "hello")
    (cond (react-element? obj)
          (write-all writer
                     (-> (js->clj obj)
                         (dissoc "$$typeof")
                         str))

          :else
          (write-all writer (str obj)))))

(react/createElement "h2" nil "Hello, World!")

I'm expecting the output to be
{:type "h2", :key nil, :ref nil, :props {:children "Hello, World!"}}}

but it still prints out the normal #js element:
#js {"$$typeof" Symbol(react.element),
     :type "h2", :key nil, :ref nil,
     :props #js {:children "Hello, World!"}, :_owner nil}

Is there a way to customize this behaviour?

A: The root cause is that in the standard lib printing code, implements? is used and satisfies? is not used. This effectively limits printing overrides to things that are not native types. (implements? doesn't doesn't work on native types).
This may not be intentional and may be fixed with https://dev.clojure.org/jira/browse/CLJS-2812


text: Q: Vue secrets in production How do I secure secrets in the Vue for production environments?  https://cli.vuejs.org/guide/mode-and-env.html is not secure as a solution.  In production I am using NGINX and Node.js serving inside an ECS Docker container.


text:
Q: Check if any object in an array contains a property listed in another array I've tried a few solutions to this and have had a look round on here but can't seem to get this working.
I have 2 arrays, and want to check if any of the items in the array contain any of the strings in the other array.
const stepsShown = ["ref2", "ref7"];
const items = [
{ name: "item1", element: "ref1"},
{ name: "item2", element: "ref2"}
];
const refsExist = items.some((r) =>{stepsShown.indexOf(r.element);});

In this example I would expect refsExist to be true
I think I am a little muddled in my syntax! Can anyone help please? :)

A: You have it almost right, except that you need to test for a non -1 value, and your arrow function shouldn't have brackets.
If your arrow function consists of a single expression, you don't need brackets:
items.some(r=>stepsShown.indexOf(r.element)!=-1);

If your arrow function includes statements or multiple expressions, you need curly brackets. When you use curly brackets, you must include an explicit return statement.
items.some(r=>{
    for(some;thing;) { ... }
    return otherThing;
});

Instead of relying on the less-readable .indexOf(..)!=-1 test, you can simply use includes:
items.some(r=>stepsShown.includes(r.element));

A: You can find an element and later check if it is undefined or not

const stepsShown = ["ref2", "ref7"];
const items = [
{ name: "item1", element: "ref1"},
{ name: "item2", element: "ref2"}
];
const refsExist = items.find((r) =>{
    return stepsShown.indexOf(r.element)>-1;
});

console.log(refsExist !== undefined);


text:
Q: Cannot read property 'large' of null I have a graphql request. It works fine, but if the poster is missing I got errors.
I tried to fix like this:
<div className="movie__hero">
    <img
       src={ movie.poster.large == null ? "poster" : movie.poster.large }
       alt="Poster"
       className="movie__img"
     />
 </div>

enter image description here
Any ideas to fix the issue?

A: The error isn't telling you that large is null, it's telling you that poster is null:
src={ movie.poster == null ? "poster" : movie.poster.large }


text:
Q: Volume of the solid generated by revolving the region R enclosed by the curve - Disk and Shell method Find the volume of the solid generated by revolving the region $R$ enclosed by the curve $y=x^3$, the $x$-axis and the line $x=1$.
(About the line $y=1$ using the disk and shell method.)

A: Using the Disk Method, $$V=\int_{0}^1\pi[1^2-(1-y)^2]dx=\pi\int_{0}^1[2y-y^2]dx=\pi\int_{0}^1[2x^3-x^6]dx=\dots=\frac{5\pi}{14}$$ and by using the Shell Method,
$$V=\int_{0}^1\big[2\pi(1-y)\cdot (1-x)dy\big]=\int_{0}^1\big[2\pi(1-y)\cdot (1-\sqrt[3]y)dy\big]=\dots=\frac{5\pi}{14}$$
Edit: Note that $2\pi(1-y)$ is the circumference of the circle obtained by rotating the point $(x,y)$ from the curve $y=x^3$ about the line $y=1$. Also, $(1-\sqrt[3]y)dy$ is the area of the sliced element of the region.

A: It seems like you have the disk method down fine, so let's look at the shell method. When describing our shells, we want to find the radius and height of each shell. Notice that we will be integrating along the $y$ values.
When $y = y_0$, for $0 \leq y_0 \leq 1$, the radius of the shell will be $1-y_0$ (the vertical distance from the line $y=1$ to $y_0$). The height of the shell will be $1-y_0^{1/3}$, which is the difference in the $x$ values for the curves $x=1$ and $x^3 = y$ at $y=y_0$.
Then each shell has the volume $2\pi rh \, dy$, or in this case, $2 \pi (1-y_0)(1-y_0^{1/3}) \, dy$.
This gives us the integral $\int\limits_0^1 2 \pi (1-y_0)(1-y_0^{1/3}) \, dy = \frac{5\pi}{14}$.


text:
Q: how to insert the ≠ sign into a string What I want as an end result is this
System.out.println("This is the not equal to sign\n≠");

to appear (when run) as
This is the not equal to sign
≠

not to appear as
This is the not equal to sign
?

Is there any way to do this? I tried using windows character map, copied the symbol here, and in my code, but after changing encoding to UTF-8 and inserting it, it comes up as ? when run...
What can be done? Thanks in advance for answers to this utterly simple question

A: Set character encoding to UTF-8, pass this vm argument, if your text editor already uses UTF-8 or supports this character
-Dfile.encoding=UTF-8

A: As @Tobias Brandt says, you could use: \u2260
And btw also @Crozin is right about your console configuration
Like this
System.out.println("This is the not equal to sign \n\u2260");

A: There are five potential issues here:
1) In which charset encoding are you saving (from your editor) you Java source?
2) Which charset encoding the java compiler assumes?
3) Which charset is your console?
4) Are you using some terminal with translation?
5) Does your console font include that particular character?
For getting issues 1-2 right, you should use UTF-8 for both (editor and javac settings), or more robust, specifify the Unicode char with escaped pure ascii text (Frakcool answer).
For issue 3, try -Dfile.encoding=UTF-8 or see this answer. Issues 4-5 are outside your Java program scope. If you are unsure, just redirect the ouput to a file, and look at it with a Hex editor.

A: When you save the java file, make sure it is saved in the same Charset as the one it is open.
In my Eclipse, when I save a file with special chars (such as \u2260) it asks me what charset I want to use.
Open your file in the terminal and inspect the content of the file.
Make sure it is the same char as the one in the editor you are using.

A: It seems that after Eclipse asked me if I want to change to UTF-8, it worked, only after I posted this.
Sorry for wasting your time


text:
Q: EF Core Set FK to NULL for child entity with soft delete parent entity record I am trying to set CustomerID to NULL for the Orders when setting Isdeleted = true (soft delete) for Customer (parent entity).
It is updating both 'archivedBy' and 'ArchivDate',
but not updating the CustomerID to NULL.
Is there any option other than fetching the Orders separately and setting the CustomerID to NULL?
Below is the code I am using to update the data.
var customer = dbContext.Customers.Find(1);

customer.IsDeleted = true;
customer.Orders.ForEach(r =>
   r.CustomerId = NULL;
   r.ArchivedBy = user;
   r.ArchivedDate = DateTime.Today()
);

dbContext.Customers.Update(customer);
dbContext.SaveChanges();

A: you don't need to call update customer, it brakes the code
and don't use Find, you have to include Orders to your db set. And it is better to use For loop, it doesn' t create a copy
var customerId=1;
var customer = dbContext.Customers.
         .Include(i=>i.Orders).First( c=> c.Id == customerId );

customer.IsDeleted = true;
for(var i==0; i< customer.Orders.Count; i++)
{
   customer.Orders[i].CustomerId = null;
   customer.Orders[i].ArchivedBy = user;
   customer.Orders[i].ArchivedDate = DateTime.Today()
);

dbContext.Entry(customer).State = EntityState.Modified; //optional

dbContext.SaveChanges();

if it still not working, try to modify Orders, instead of customer.Orders.
var customerOrders= dbContext.Orders.Where(o=> o.CustomerId==customerId).ToList();

for(var i==0; i< customerOrders.Count; i++)
{
   customerOrders[i].CustomerId = null;
   customerOrders[i].ArchivedBy = user;
   customerOrders[i].ArchivedDate = DateTime.Today()
);


text:
Q: Rearrange a 36 bit number? I am an amateur to Python, I have made a program that will encode a long string of characters and output 6 characters.
def token (n):
    if n < 10:
        return chr( ord( '0' ) + (n) )
    if n in range (10, 36):
        return chr( ord( 'A' ) - 10 + (n))
    if n in range (37, 62):
        return chr( ord( 'a' ) - 36 + (n))
    if n is 62:
        return '-'
    if n is 63:
        return '+'

The token turns a number(n) into a character. Upper and lower case letters including the characters "-" and "+".
def encode (n):
    a = n // 1 % 64
    b = n // 64 % 64
    c = n // 64 ** 2 % 64
    d = n // 64 ** 3 % 64
    e = n // 64 ** 4 % 64
    f = n // 64 ** 5 % 64
    return (token(a) + token(b) + token(c) + token(d) + token(e) + token(f))

This is the rest of the encode.
print(encode(1234567890))
'IBWb91'

Again, is there a way to create an order for the six characters for the output?
This is what I have so far. I got this from an existing question.
How can I reorder a list in python?
mylist = ['a','b','c','d','e','f',]
myorder = [6,5,4,3,2,1]
mylist = [ mylist[i] for i in myorder]

But...it gives me this:
IndexError: list index out of range

What I want to happen:
>>> print(mylist)
['f','e','d','c','b','a']

I am totally new to this. Please help :)

A: If you just want to reverse the list, just call the reverse method or reversed function:
>>> mylist = ['a','b','c','d','e','f']
>>> list(reversed(mylist))
['f', 'e', 'd', 'c', 'b', 'a']

If you want to do it the hard way, you can, but you have to use indices that are actually in the list:
>>> [i for i, e in enumerate(mylist)]
[0, 1, 2, 3, 4, 5]

Those are the indices in the list. 6 is not one of them. So if you try to use mylist[6] you're going to get an IndexError. What you probably wanted was [5, 4, 3, 2, 1, 0].

A: Lists in python are indexed starting from 0, not from 1. If you want to reorder an n-element list with the method you show, you therefore need to have a list containing the numbers 0,1,...,n - 1, as trying to access element n of an n-element list will give an
error, as the index will be outside of the expected range.
For example, with what you gave,
mylist = ['a','b','c','d','e','f']
myorder = [5,4,3,2,1,0]
mylist = [mylist[i] for i in myorder]

A: The order has to be zero-indexed. That's how python lists work - the first element is mylist[0], the second element is mylist[1], etc. Therefore, it should be [5,4,3,2,1,0].


text:
Q: How to implement a process regulator in C/C++? The question is quite simple and I don't know where and how to implement the transfer functions.
Let's say that I have a classic system

where P has a transfer function of the second order with zita=0.7, F=1 and C is the process regulator.
I would like to implement this regulator on a controller like ATMega128P in C or C++.
The transfer function of the process is identified by experimental methods and the regulator may vary depending on the process transfer function.
Where should I start?

A: If you have your transfer function it in continuous time (Laplace), you will need to transform it in discrete time (Z-Transform), using one of the discretization methods (forward difference, backward difference, trapezoidal).
Once you have the discrete transfer function, you will need to apply inverse Z transform to obtain the system's equation in the time domain. Next, you will need to detrmine the discretization step.
When if you have this data, you can implement this system on the microcontroller quite easily, since practically you will only implement a simple equation which will probably read a sensor periodically through an ADC input and according to that and previous input (y[k], y[k-1], ...) values will generate the control value (u[k]) according to its reference (r[k]).
The ADC (y[k]) can be read using in a timer interrupt, set to fire according to your discretization step. Once the value is read, you can compute u[k] and set the execution element accordingly.
For implementation, I would recommend C, since C++ would probably be a little bit of an overkill in this case (most embedded systems which implement a system such as this one are programmed using ANSI C or MISRA C - especially in automotive).
Before jumping to C, I would first try to see if I got the calculations correctly and I would simulate the system in Simulink (MATLAB), or Scilab.
For tuning the real embedded system, I would recommend reading about the Ziegler-Nichols method.
http://en.wikipedia.org/wiki/Ziegler%E2%80%93Nichols_method
Info on discretization:
http://www-verimag.imag.fr/~tdang/DocumentsCours/Discretization.pdf


text:
Q: How do you drop an unnamed check constraint in a PostgresQL table? I created a PostgresQL table but I added an unnamed check constraint on one of the columns:
CREATE TABLE FOO
(
id serial primary key,
price_range smallint CHECK (price_range > 0),
url varchar(255)
);

Now I want to remove this constraint but I can't figure out how. The typical ALTER TABLE...DROP CONSTRAINT... needs a constraint_name but I don't have one.
I know there is an answer here but when I tried to determine the name of my check constraint by following the answer there:
SELECT *
FROM information_schema.constraint_table_usage
WHERE table_name = 'your_table'

All I got back was a single constraint whose constraint_name entry was foo pkey which refers to the primary key constraint and not my check on the price column. So that answer did not help me, unless I am missing something.
How can I drop this constraint without losing any data?
Thanks!

A: The constraint has a name, whether you specified it or not.
From psql, \d foo will list all table constraints, along with their automatically assigned names.
You can also find these by querying the catalog tables directly:
SELECT conname
FROM pg_constraint
WHERE
  conrelid = 'foo'::regclass AND
  contype = 'c'

The table name can be schema-qualified if necessary (e.g. 'public.foo'::regclass).
contype = 'c' filters it down to CHECK constraints; the contype values for other constraint types are documented here.

A: It doesn't matter if you specified a name or not, the constraint has a name. To figure out the "Constraint name" in Postgre SQL using pgAdmin4. The easiest way is to open the database first, then click "Schemas", then click "Tables" and select the table in which we have to make the change. Now a drop-down menu will open where you will see "Constraints". Double-click over the "Constraints" column and you will see a new drop-down menu with all the "Constraints" we created for the respective table. Now you can "right click" on the respective column name and then click "Properties". A new pop-up window will open in which we can see the name of the constraint under "General". The name we see there is the name of the constraint. Now you can copy that name and execute the code by pasting it. I hope this helps.
E.g: Alter TABLE foo DROP CONSTRAINT foo_price_range_check;


text:
Q: Open application with single instance When I minimize my app and do any other operation on the mobile device and click back on my app icon (to relaunch), the app is switch back to where it was previously. But it opens with new instance of it. That means if I press Back button the new launch app is closed but previously opened app is not closed.
So what I want is if my app is already running and then minimized and click on the launch icon, I just want to only one app instance to.

A: You should get familiar with Activity launch modes.
In your case you could set in AndroidManifest.xml:
android:launchMode="singleTop"

in case your Activity is the one that was visible last when app went to the background
or set:
android:launchMode="singleTask"

A: You can override onBackPressed in your activity
@Override
public void onBackPressed() {

        super.onBackPressed();

     this.moveTaskToBack(true);
    }

A: I suggest you to recall that application from system tray, instead of relaunching, whenever you press your application icon it creates a new instance from your system tray. So it is common practice to recall application from system tray instead of relaunch.

A: if you reqire just single instance of your activity set activity as below in your manifeast file...
<activity
        android:name="com.example.activity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:launchMode="singleInstance" />


text:
Q: firebase: How to get a reference key for an object node // Creates local "temporary" object for holding employee data
    var newTrain = {
       tname: trainName,
       dest: destination,
       firstTime: firstTrainTime,
       freq: frequency
     };

    // Uploads train data to the database
    trainDataBase.ref().push(newTrain);

THIS IS THE PART I CAN"T figure out how do I get a key for the object I just created on the server? I tired the below but it comes back undefined, also also tired var = newKey = trainDatabase.ref.push(newTrain).key but then it creates to object versus one but I do get a key
    // newKey = trainDataBase.ref(newTrain).key
    // console.log("nodeKey" , newKey)
    // Alert
    console.log("train successfully added");

     // Clears all of the text-boxes
    $("#trainName").val("");
    $("#destination").val("");
    $("#firstTrainTime").val("");
    $("#frequency").val("");

     // Prevents moving to new page
    return false;
    });

A: Perhaps there's a better way, but I've used this to make it work:
var trainDataBaseRef = trainDataBase.ref().push();
trainDataBaseRef.set({
  id: trainDataBaseRef.key,
  // rest of object data
});

Take a look at their docs for an additional way to do this (Updating or deleting data section):
function writeNewPost(...) {
  var postData = {
    // data
  };

  // Get a key for a new Post.
  var newPostKey = firebase.database().ref().child('posts').push().key;

  // Write the new post's data simultaneously in the posts list and the user's post list.
  var updates = {};
  updates['/posts/' + newPostKey] = postData;
  updates['/user-posts/' + uid + '/' + newPostKey] = postData;

  return firebase.database().ref().update(updates);
}


text:
Q: what is the return type of an SQL SELECT query in php, is it array, object, or what? I'm documenting functions in a REST API in php but I couldn't figure out the return type of a get all query, is it array, object, or what

A: This returns an object or a boolean.
In case you have an error in your SQL statement then the return value will be a boolean. In general, if no errors in your SQL your query will return a mysqli_result object.
That's an output example of a SQL query:
class mysqli_result#2 (5) {
  public $current_field =>
  int(0)
  public $field_count =>
  int(79)
  public $lengths =>
  NULL
  public $num_rows =>
  int(1457)
  public $type =>
  int(0)
}


text:
Q: Django celery CPU uses and SIGNKLILL error Hello All i am reciving below error. i have checked status of rabbitmqctl and its working good. but find below issue when run task in periodic. Also CPU consumption increase to 100%. please help me out of this issue.
[2015-04-27 15:03:56,927: ERROR/MainProcess] Task tarjeta.tasks.demon_2[4d6cb246-cf34-4f70-a5a5-d56677287041] raised unexpected: WorkerLostError('Worker exited prematurely: signal 9 (SIGKILL).',)
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/billiard/pool.py", line 1169, in mark_as_worker_lost
    human_status(exitcode)),

Also can you please let me kow "are there both issue related with each other ??"
Thanks for any help.


text:
Q: Rotate a 3D object (OSG & vc++) I'm developing a 3D environment using VC++ and OSG and I need some help
I'm using this code below to charge the 3D models for the scene
    mueble00Node = osgDB::readNodeFile("Model/mueble_desk.3ds");
    mueble00Transform = new osg::MatrixTransform;
    mueble00Transform->setName("mueble00");
    mueble00Transform->setDataVariance(osg::Object::STATIC);
    mueble00Transform->addChild(mueble00Node);
    sceneRoot->addChild(mueble00Transform);

I've tried with some lines to rotate the 3D models, but with no result
Could anybody explain to me how to rotate the models on its own axis?

A: Use MatrixTransform::setMatrix() to change the orientation of the child node.
MatrixTransform* transform = new osg::MatrixTransform;
const double angle = 0.8;
const Vec3d axis(0, 0, 1);
transform->setMatrix(Matrix::rotate(angle, axis));

Below is a complete program that loads and displays a 3D object with and without the transformation added.
#include <string>
#include <osg/Object>
#include <osg/Node>
#include <osg/Transform>
#include <osg/Matrix>
#include <osg/MatrixTransform>
#include <osgDB/ReadFile>
#include <osgViewer/Viewer>
#include <osgGA/TrackballManipulator>

using namespace osg;

int main(int argc, char** argv)
{
    if (argc != 2) {
        std::cerr << "Usage: " << argv[0] << "<file>\n";
        exit(1);
    }
    const std::string file = argv[1];

    // Load a node.
    Node* node = osgDB::readNodeFile(file);
    if (!node) {
        std::cerr << "Can't load node from file '" << file << "'\n";
        exit(1);
    }

    // Set a transform for the node.
    MatrixTransform* transform = new osg::MatrixTransform;
    const double angle = 0.8;
    const Vec3d axis(0, 0, 1);
    transform->setMatrix(Matrix::rotate(angle, axis));
    transform->setName(file);
    transform->addChild(node);

    // Add the node with and without the transform.
    Group* scene = new Group();
    scene->addChild(transform);
    scene->addChild(node);

    // Start a scene graph viewer.
    osgViewer::Viewer viewer;
    viewer.setSceneData(scene);
    viewer.setCameraManipulator(new osgGA::TrackballManipulator());
    viewer.realize();
    while (!viewer.done()) viewer.frame();
}

A: You'll want to use a quat
http://www.openscenegraph.org/documentation/OpenSceneGraphReferenceDocs/a00568.html
It has a number of functions you can use for rotation.


text:
Q: Flicker when custom drawing on a double buffered TTreeView When listening to the AdvancedCustomDraw event of a TTreeView event this way:
if Stage = cdPrePaint then begin
    // modify some Sender.Canvas properties and let it draw itself
end else if Stage = cdPostPaint then begin
    // draw 'something extra' using a separate TControlCanvas
    TControlCanvas.TextOut(SomeRect, 'Hello');
end;

... it seems that when I enable DoubleBuffered the control decides not to copy the 'something extra' to the offscreen buffer. This means that as long as I don't disturb the window in question, all is fine. When I do, the 'something extra' is only visible in random parts of the window.
What am I missing here?

A: Since your comment gave me carte blanche to suggest an alternative solution, here's what I would do:

*

*Stop using DoubleBuffered. It leads to lots of visual oddities in lots of controls. I personally avoid it like the plague.

*Solve your flickering problem by adding the WS_EX_COMPOSITED extended window style to your control. This window style can be a bit of a performance drag and I'd recommend that you only add this during the sizing loop, which is when you need it. I describe how to do that in my answer here: TLabel and TGroupbox Captions Flicker on Resize.


text:
Q: How to get email to show in color when typed in text? In LaTeX's article documentclass, how do I (using hyperref, if I understood right) get email links to show in color (say, red) when I type them in the middle of a paragraph?

A: You can use the options colorlinks=true and urlcolor=<color>:
\documentclass{article}
\usepackage{xcolor}
\usepackage[colorlinks=true,urlcolor=olive]{hyperref}

\begin{document}

\url{gmedina@tex.stackexchange}

\href{gmedina@tex.stackexchange}{gm-email}

\end{document}

A: Depending on your preference, you could do any one of the following:

*

*If you just want to typeset it in colour, without any linking capabilities, you could use
\usepackage{xcolor}% http://ctan.org/pkg/xcolor
...
My email address is {\color{red} who@cares.com}.

Note the scoping of the \color{...} by putting it within { }, otherwise all the text following the command will be typeset in red. Compiling this may cause some unwanted linking of @cares.com, while leaving who unlinked.

*The hyperref package does allow linking through a number of commands. You're probably interested in using the \url{...} command, since it takes care of the tricky @ that has to be escaped in order to be typeset. It will also take care of breaking the email address (or url) across lines, if needed.
\usepackage[%
  colorlinks=true,%
  urlcolor=red%
]{hyperref}% http://ctan.org/pkg/hyperref
...
My email address is \url{who@cares.com}.

This is also not entire accurate if you want to hyperlink to an email (via a mailto protocol).

*Using hyperref's \href{<url>}{<text>} provides the correct action:
\usepackage[%
  colorlinks=true,%
  urlcolor=red%
]{hyperref}% http://ctan.org/pkg/hyperref
...
My email address is \href{mailto:who@cares.com}{who@cares.com}.

You can also typeset the email address in a different shape using, say, \texttt{who@cares.com}. Then it will be typeset similarly to that of option 2.


text:
Q: Visual Studio Code GitHub account I have a Visual Studio Code project for an Angular2 app created using AngularCli (webpack version).  Out of the box, AngularCli will generate a new project for you and check it into Git.  How do you know which GitHub account it's using?  I cannot find any information in Visual Studio as to what GitHub account is controlling the code history.  I can make changes to the code and check it in using Visual Studio Code's embedded Git functionality.  I've logged into GitHub using my account, but I do not see this new project.  Where do you find information on what GitHub account either AngualrCli and/or Visual Studio Code is using?

A:
How do you know which GitHub account it's using?

It doesn't need to use any github account to create a git repo. It's just calling git init, followed by some git add/git commit commands. You can do those without github credentials. After the tool does its job, you have a fully-functional local git repo.
You only need github account when you try to push code to github, which you did not yet do, I assume. You don't need github credentials to work with local repository (view history, add new commits, branch, merge, etc.)


text:
Q: Javascript - how to redirect users from old URL to new one so SSL cert matches We have 2 DNS entries for our corporate site; our old domain still works and our new domain is used in all of our ads, but many users have our old site bookmarked.
We installed an SSL cert for 4 pages that require users to enter personal info. I have a redirect for http to https like so:
    <script> if(location.protocol.indexOf("https") === -1) {     location.href = location.href.replace("http", "https"); }</script>

and it works perfectly unless someone enters the page from our old domain, then the domain name in the URL doesn't match the cert and users get a nasty warning from their browsers.
I copied the following code which I thought would redirect if they came to this page using the previous domain but it doesn't seem to work.
    <script>if (document.referrer == 'olddomain.co.jp' || document.referrer == 'www.olddomain.co.jp') == 1)
           { top.location="https://newdomain.com/english/engform.aspx";

}

but it doesn't redirect; it still gives me the warning. Any recommendations?

A: Then you just need to check if it's old domain and send them to new domain using same method as you described on your question
if (location.href.indexOf("oldsite.domain") > -1) location.href = location.href.replace("oldsite.domain", "newsite.domain");

A: You need to get certificates for both your old domain and your new domain.   Without a certificate for the old domain, the browser shows a security warning before your JavaScript runs.
The typical way to do this is to get a subject alternative name (SAN) certificate that covers both your old domain and your new domain.  Then you can use the same certificate, server configuration, and document root for both domains and redirect from one to the other either using .htaccess (preferred) or JavaScript like you have been trying.

A: function RedirectUrl() {
var expression = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/
var regex = new RegExp(expression);
var current_url = window.location.href;
var redirect_url = "/news"; /* where news is like news.html same news-inspiration is a news-inspiration.html like www.abc.com/news-inspiration */
if (current_url.indexOf('/news-inspiration') > -1) {
    if (!current_url.match(redirect_url) && current_url.match(regex)) {
        window.location.replace(redirect_url);
    }
}

}
after making it function call it during any javascript event.
//calling function----
RedirectUrl();


text:
Q: Show soft upgrade or share review again after user declines upgrade I am beginner in Native Java for android.
I would like to know how I can ask the user to update the app again only after the days I choose?
Currently when the user clicks cancel a soft update, the app asks for the update again after the user enters the App, and this is annoying. Please, can someone help me?
How can I do this for IN-APP-REVIEW as well?
When the user declines an evaluation within flow(), I ask for an evaluation again after X days..
Review Code Flow:
  void activateReviewInfo()
  {
    final Handler handler = new Handler(Looper.getMainLooper());
    handler.postDelayed(() -> {
      manager = ReviewManagerFactory.create(this);

      Task<ReviewInfo> request = manager.requestReviewFlow();
      request.addOnCompleteListener(task -> {
        if (task.isSuccessful()) {
          reviewInfo = task.getResult();
          Task<Void> flow = manager.launchReviewFlow(this, reviewInfo);

          flow.addOnCompleteListener(result -> {
          });
        }
      });

      request.addOnFailureListener(e -> System.out.println(e.getMessage()));
    }, 15000);
  }

In-App-Update
  private ReviewInfo reviewInfo;
  private ReviewManager manager;

  private static final int RC_APP_UPDATE = 100;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(null);
    if (new ReviewsManager().getDaysAppInstaled(this) >= 7) {
      activateReviewInfo();
    }
    activateUpdate();
  }

  void activateUpdate(){
    final Handler handler = new Handler(Looper.getMainLooper());
    handler.postDelayed(() -> {
      AppUpdateManager mAppUpdateManager = AppUpdateManagerFactory.create(this);
      Task<AppUpdateInfo> appUpdateInfoTask = mAppUpdateManager.getAppUpdateInfo();

      appUpdateInfoTask.addOnSuccessListener(result -> {
        if (result.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
                && result.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)) {
          try {
            mAppUpdateManager.startUpdateFlowForResult(result, AppUpdateType.FLEXIBLE, MainActivity.this, RC_APP_UPDATE);
          } catch (IntentSender.SendIntentException e) {
            System.out.println(e.getMessage());
          }

        }
      });
      mAppUpdateManager.registerListener(installStateUpdatedListener);
    }, 9000);
  }

  private final InstallStateUpdatedListener installStateUpdatedListener = installState -> {
    if (installState.installStatus() == InstallStatus.DOWNLOADED) {
      showCompleteUpdate();
    }
  };

  private void showCompleteUpdate() {
    AppUpdateManager mAppUpdateManager = AppUpdateManagerFactory.create(this);
    Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Atualização pronta para ser Instalada...",
            Snackbar.LENGTH_INDEFINITE);

    snackbar.setAction("Instalar", view -> mAppUpdateManager.completeUpdate());

    snackbar.show();
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_APP_UPDATE && resultCode != RESULT_OK) {
      Toast.makeText(this, "Cancelado", Toast.LENGTH_SHORT).show();
    }
  }

  private void installAppIfHaveDownload () {
    AppUpdateManager mAppUpdateManager = AppUpdateManagerFactory.create(this);
    mAppUpdateManager.getAppUpdateInfo().addOnSuccessListener(appUpdateInfo -> {
      if(appUpdateInfo.installStatus() == InstallStatus.DOWNLOADED) {
        showCompleteUpdate();
      }
    });
  }

  private void unregisterListenerIfAppIsInstalled () {
    AppUpdateManager mAppUpdateManager = AppUpdateManagerFactory.create(this);
    mAppUpdateManager.getAppUpdateInfo().addOnSuccessListener(appUpdateInfo -> {
      if(appUpdateInfo.installStatus() == InstallStatus.INSTALLED) {
        mAppUpdateManager.unregisterListener(installStateUpdatedListener);
      }
    });
  }

@Override
  protected void onStop() {
    super.onStop();
    unregisterListenerIfAppIsInstalled();
  }

  @Override
  protected void onResume() {
    super.onResume();
    installAppIfHaveDownload();
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    reviewInfo = null;
    manager = null;
  }

A: My sugestion is call:
if(task.isCanceled()) {
 /// code
}

OR

if(appUpdateInfo.installStatus() === InstallStatus.CANCELED){
 /// code..
/// if ok call showCompleteUpdate();
}

But i do know how to do here :/ i'm beginner in java.
do i just need to call the function to activate the evaluation flow or refresh again after x days? How can I do this calculation and what do I need to do?


text:
Q: Firebase Security Rules -- using attribute from User document I'm struggling to make my Firebase security rules work.
I only want to allow write access to documents in the collection Nouns to users with the attribute 'admin' == true (boolean) in their user document (stored in collection Users).
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    match /Users/{userId}/{documents=**} {
      allow read, write: if request.auth != null
                && request.auth.uid == userId
    }

    match /Nouns/{documents=**} {
      allow read: if request.auth != null
    }

    match /Nouns/{documents=**} {
      allow read, write: if request.auth != null
                && resource.data.admin == true
    }

  }
}

The rules playground gives the following error when I try a write on a document in the Nouns collection:

Error: simulator.rules line [17], column [13]. Property admin is undefined on object.

Can anyone please let me know what I'm doing wrong?

A: resource.data will contain data of the document being accessed in Nouns collection. If you want to read data from user's document, use get() instead:
match /Nouns/{documents=**} {
  allow read, write: if request.auth != null
                && get(/databases/$(database)/documents/Users/$(request.auth.uid)).data.admin == true
}

Collection names are case-sensitive so make sure you enter it correctly.


text:
Q: Two inputs to one model in Keras Is it possible in Keras to feed both an image and a vector of values as inputs to one model? If yes, how?
What I want is to create a CNN with an image and a vector of 6 values on the input.
The output is the vector of 3 values.

A: Yes, please have a look at Keras' Functional API for many examples on how to build models with multiple inputs.
Your code will look something like this, where you will probably want to pass the image through a convolutional layer, flatten the output and concatenate it with your vector input:
from keras.layers import Input, Concatenate, Conv2D, Flatten, Dense
from keras.models import Model

# Define two input layers
image_input = Input((32, 32, 3))
vector_input = Input((6,))

# Convolution + Flatten for the image
conv_layer = Conv2D(32, (3,3))(image_input)
flat_layer = Flatten()(conv_layer)

# Concatenate the convolutional features and the vector input
concat_layer= Concatenate()([vector_input, flat_layer])
output = Dense(3)(concat_layer)

# define a model with a list of two inputs
model = Model(inputs=[image_input, vector_input], outputs=output)

This will give you a model with the following specs:
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_8 (InputLayer)            (None, 32, 32, 3)    0
__________________________________________________________________________________________________
conv2d_4 (Conv2D)               (None, 30, 30, 32)   896         input_8[0][0]
__________________________________________________________________________________________________
input_9 (InputLayer)            (None, 6)            0
__________________________________________________________________________________________________
flatten_3 (Flatten)             (None, 28800)        0           conv2d_4[0][0]
__________________________________________________________________________________________________
concatenate_3 (Concatenate)     (None, 28806)        0           input_9[0][0]
                                                                 flatten_3[0][0]
__________________________________________________________________________________________________
dense_3 (Dense)                 (None, 3)            86421       concatenate_3[0][0]
==================================================================================================
Total params: 87,317
Trainable params: 87,317
Non-trainable params: 0

Another way to visualize it is through Keras' visualization utilities:


text:
Q: Stop sprite from leaving screen using physics bodies I have a sprite that the user is able to move side to side by pressing on the left or right side of the screen. If you hold down on either side, the player sprite will leave the screen. I want to stop that from happening using physic bodies, but I can't seem to make it work.
To start, here are my categories.
//Categories for physics bodies
let sceneCategory:UInt32   = 0x1 << 0 // Equal to 1
let playerCategory:UInt32 = 0x1 << 1 // Equal to 2

Here is where I set the physics body of the scene itself.
self.physicsWorld.contactDelegate = self
self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame)
self.physicsBody?.categoryBitMask = sceneCategory
self.physicsBody?.contactTestBitMask = playerCategory
self.physicsBody?.collisionBitMask = 0
self.physicsBody?.isDynamic = false

This is how I have the physics set for the player itself. I'm trying to set the physics body around the car itself. Is the way I have it setup the same as setting an alpha mask physics body?
let texture = SKTexture(imageNamed: "PorscheBlue")
player.physicsBody = SKPhysicsBody(texture: texture, size: player.size)
player.physicsBody?.isDynamic = false
player.physicsBody?.categoryBitMask = playerCategory
player.physicsBody?.contactTestBitMask = sceneCategory
player.physicsBody?.collisionBitMask = 0

Then, in the didBegin method, I just wanted it to print showing that the method was called. This isn't happening though for some reason.
func didBegin(_ contact: SKPhysicsContact)
{
    print("called")
}

Why isn't the didBegin method being called? Do I have the physics set up properly? How can I make it so the player isn't allowed to leave the screen when moving?
Thank you
EDIT: So when having the physics boundaries visible, it looks like the boundaries for the scene are only being drawn on the top and bottom. I can't see any lines being drawn on the sides. That may be the issue, but I can't get it to show on the sides.

A: I resolved my issue by changing the dynamic value. I had both set to false, which causes the didBegin function to not be called. At least one of the nodes needs to be dynamic.


text:
Q: Displaying list contenst on JSP The list contents are not displayed in the JSF page.
The table is not displayed on the jsf page. It is always blank. The list contains a list of recommended items. There are getter and setter methods and a function which returns a list of recommended items.
here is my code:
package org.recommender;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.TanimotoCoefficientSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;

@ManagedBean(name="similarvaluerecommender")
@ViewScoped

public class SimilarValueRecommender implements Serializable {
public List<RecommendedItem> recommendedItems;
@PostConstruct
public List<RecommendedItem> loadRec(){
this.recommendedItems = new ArrayList<>();
       DataModel dm;
        try {
        dm = new FileDataModel(new File("Dataset/userdata.csv"));

    //ItemSimilarity sim = new LogLikelihoodSimilarity(dm);
        TanimotoCoefficientSimilarity sim = new TanimotoCoefficientSimilarity(dm);
        GenericItemBasedRecommender recommender = new GenericItemBasedRecommender(dm, sim);
        int x=1;

        for(LongPrimitiveIterator items = dm.getItemIDs(); items.hasNext();) {
            long itemId = items.nextLong();
          List<RecommendedItem>recommendations = recommender.mostSimilarItems(itemId, 10);

            this.recommendedItems.addAll(recommendations);
            setList(recommendations);

            x++;

        }
    } catch (TasteException ex) {
        Logger.getLogger(SimilarValueRecommender.class.getName()).log(Level.SEVERE, null, ex);
    }
    catch (IOException ex) {
        Logger.getLogger(SimilarValueRecommender.class.getName()).log(Level.SEVERE, null, ex);
    }
return recommendedItems;

}

//getter and setter...
 public List<RecommendedItem> getRecommendedItems(){
    return recommendedItems;
     }
 public void setList(List<RecommendedItem> recommendedItems) {
 this.recommendedItems=recommendedItems;
 }

  }

JSF Page:
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
  xmlns:f="http://xmlns.jcp.org/jsf/core"
  xmlns:c="http://xmlns.jcp.org/jsp/jstl/core">
   <h:body>

  <ui:composition template="WEB-INF/commonlayout.xhtml">
    <ui:define name="content">
        <h:form>
            hi
            <h:dataTable id="similarvaluestable" value="# {similarvaluerecommender.recommendedItems}" var="recommendedItems">
            <h:column>
            #{recommendedItems.itemID}
       </h:column>

            </h:form>
         </ui:define>
         </ui:composition>

         </h:body>
          </html>


text:
Q: Python using Google YouTube Data API (v3) gives an Oauth2 KeyError: 'client_secret' I am trying to do a personal project related to gathering data from YouTube, and I am having a heck of a time using the API methods that require one to authenticate with OAuth2. The ones you can use an API key with, I'm all set on, and that part of my little app is working great. But downloading the transcript of a video requires OAuth2.
As a starting point to figuring OAuth2 out, I got example Python code generated from the Try It sidebar on the Youtube API Reference page for the Captions Download method. I modified it to include the caption ID for one of the videos I am interested in, the JSON secrets file for the project's OAuth 2.0 Client ID of type desktop that I downloaded from the Google Cloud Console, and the file path where I wanted it to put the transcript.
Unfortunately, it does not work! I've included below (with possibly-secret info replaced with placeholders) the code I was using, the contents of the secrets JSON file, and the contents of the console with the error message.
The code includes a call to flow.run_console() which is marked in PyCharm as deprecated. When I hover my mouse over it for a couple seconds, this pops up above the documentation about the function:
New clients will be unable to use `InstalledAppFlow.run_console` starting on Feb 28, 2022. All clients will be unable to use this method starting on Oct 3, 2022. Use `InstalledAppFlow.run_local_server` instead. For details on the OOB flow deprecation, see https://developers.googleblog.com/2022/02/making-oauth-flows-safer.html?m=1#disallowed-oob

At that site, I read about the security risks that made them deprecate this. Unfortunately, I could not figure out from that site how to replace it. Using credentials = flow.run_local_server() instead of credentials = flow.run_console() produced the exact same KeyError. It seems like the other options are all intended to be hosted on a website or used for mobile apps. I only ever want to use this app on my computer specifically.
It does seem to work as far as that line, or at least, it gives me a URL that lets me click, authorize my project to use my Youtube account, and paste the code back in. It's after I paste in the code that it fails. The error it gives me is actually about the credentials file not having a key with the name client_secret -- which, indeed, is missing from my credentials file. Maybe they stopped including that in general and never updated the example-code-generator on the API reference? When searching for other answers, I see a lot of references to creating an OAuth2 ClientID with the type of "Installed / other" but that is no longer an option in the type dropdown, as far as I can see.
Or, maybe it's related to the fact that my app is still listed with Google as in "testing" mode? I don't intend to release it to the world, I'm the only one who will ever use this app. It's staying on my computer, so I don't have a website to give Google so that they can check out my privacy policy or whatever other requirements they need for a released app.
Error message when running code:
C:\Users\myUserName\PycharmProjects\MyProjectName\venv\Scripts\python.exe C:/Users/acrai/PycharmProjects/MyProjectName/example_download_captions.py
flow_before
Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=xxxxxxxxxxxxxxx.apps.googleusercontent.com&redirect_uri=urnxxxxxxoauth%3A2.0%3Aoob&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.force-ssl&state=xxxxxxxxxx&prompt=consent&access_type=offline
Enter the authorization code: 4/1AX4blahblahblah-I clicked the link above, authorized with my Youtube account, and pasted in the code it gave me here!
Traceback (most recent call last):
  File "C:\Users\myUserName\PycharmProjects\MyProjectName\example_download_captions.py", line 54, in <module>
    main()
  File "C:\Users\myUserName\PycharmProjects\MyProjectName\example_download_captions.py", line 36, in main
    credentials = flow.run_console()
  File "C:\Users\myUserName\PycharmProjects\MyProjectName\venv\lib\site-packages\google_auth_oauthlib\flow.py", line 439, in run_console
    self.fetch_token(code=code)
  File "C:\Users\myUserName\PycharmProjects\MyProjectName\venv\lib\site-packages\google_auth_oauthlib\flow.py", line 298, in fetch_token
    kwargs.setdefault("client_secret", self.client_config["client_secret"])
KeyError: 'client_secret'

My code, very much based on the example code generated from the Try It sidebar on the Youtube API Reference page for the Captions Download method:
# https://developers.google.com/youtube/v3/docs/captions/download
# -*- coding: utf-8 -*-

# Sample Python code for youtube.captions.download
# NOTE: This sample code downloads a file and can't be executed via this
#       interface. To test this sample, you must run it locally using your
#       own API credentials.

# See instructions for running these code samples locally:
# https://developers.google.com/explorer-help/code-samples#python

import io
import os

import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors

from googleapiclient.http import MediaIoBaseDownload

scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = "C:\\Users\\myUserName\\Documents\\MyProjectDirectoryName\\client_secret_xxxxxxxx.apps.googleusercontent.com.json"
    result_file = 'C:\\Users\\myUserName\\Documents\\MyProjectDirectoryName\\Video Transcripts\\vid_example_transcript.txt'
    test_caption_id = 'VxPQ0cBI7BNjG-6Kpo8Wi1H6VXAziegGD0Be0NlMJCg='

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    print("flow_before")
    credentials = flow.run_console()
    print("flow_after")
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

    request = youtube.captions().download(
        id=test_caption_id
    )

    fh = io.FileIO(result_file, "wb")

    download = MediaIoBaseDownload(fh, request)
    complete = False
    while not complete:
      status, complete = download.next_chunk()

if __name__ == "__main__":
    main()

What is in the JSON secrets file:
{"installed": {
        "client_id": "abcd-1234.apps.googleusercontent.com",
        "project_id": "MyProjectName",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "redirect_uris": [
            "http://localhost"
        ]
    }}

Here's how I obtained this file:
I went to https://console.cloud.google.com/apis/api/youtube.googleapis.com/credentials?project=MyProjectName
Under "OAuth 2.0 Client IDs" on that page is the credential I made with the same name as the project name, the type is Desktop.
At the far right of that line with the credential is an Actions column, I hit the Download icon, and then in the box that pops up, I hit the Download JSON button.
So, does anyone know how I can change my code to make it work?


text:
Q: How to use map and find together in Typescript? I am trying to create an array of all string which has length more than zero.
let sampleArray2:string[] = ["hello","world","angular","typescript"];
let subArray:string[] = sampleArray2
    .map(() => sampleArray2
        .find(val => val.length > 5)
    );
console.log(subArray);

As expected, it is returning [ 'angular', 'angular', 'angular', 'angular' ]
I wanted it to print [ 'angular', 'typescript' ]
I am specifically looking for a solution which uses both map and find together to accomplish this. How can I fix this?
Note: Though filter is a straightforward solution, I am trying to see if map and find can be used together to get the desired output.

A: let subArray:string[] = sampleArray2.filter(i => i.length > 5);
see MDN web docs - Array.prototype.filter

A: .find is not what you want - you want .filter.

A: The problem is that your map() returns 'angular' 5 times.
A correct syntax using filter (and therefore preserving your types) should be :
let subArray:string[]= sampleArray2.filter(val=>val.length>5)

A: You don't need the function map nor the function find.
Use the function filter.

let sampleArray2 = ["hello", "world", "angular", "typescript"];
let subArray = sampleArray2.filter(val => val.length > 5);

console.log(subArray);


text:
Q: Grails Spring Security Plugin - Username escaping problem I'm currently working with Grails and the Spring Security plugin and trying to implement a password expiration workflow. I've configured the plugin as expected:
grails.plugins.springsecurity.failureHandler.exceptionMappings = [
    'org.springframework.security.authentication.CredentialsExpiredException': '/login/passwordExpired'
]

and in my passwordExpired action if I call:
def username = session['SPRING_SECURITY_LAST_USERNAME']

then in the username the HTML special characters are going to be escaped like
my_user => my_user
my-user => my-user

Is it possible to turn this escaping off?
Ritesh mentioned here spring_security_last_username that the SPRING_SECURITY_LAST_USERNAME is deprecated, so what else can I use?
For any help, thanks in advance!

A: The String 'SPRING_SECURITY_LAST_USERNAME' isn't deprecated - the old constant with that value is and has been moved with a new name but the same value. So your code will continue to be valid.
Rather than changing things to not escape, you can un-escape easily:
import org.apache.commons.lang.StringEscapeUtils
...
String username = StringEscapeUtils.unescapeHtml(session['SPRING_SECURITY_LAST_USERNAME'])

A: You don't need to use a tool. Use Grails HTML codec:
username = session['SPRING_SECURITY_LAST_USERNAME']?.decodeHTML()


text:
Q: How can I resize QTableView row according to specific cell value? I want to resize the row height according to a specific column value. For example, the table I want to change is here:

At row 10, row height is resized by the third column value. But at row 11 it is resized by the second column value. I want to resize row height by only the third column value. Is there a way to do this?
Thank you.
This is my code for this QTableView
ui->tableView->setModel(modal);
ui->tableView->hideColumn(0);
ui->tableView->resizeColumnsToContents();
ui->tableView->resizeRowsToContents();
ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->tableView->horizontalHeader()->setStyleSheet("QHeaderView { font-size: 18pt; color:#002B5B; font-weight: bold; }");

A: I haven't actually tried it myself, but from looking at the Qt source code (in particular the source code for QTableView::rowHeight(int) const and QHeaderView::sectionSizeFromContents(int) const), it looks like you could do something like:
const int addressColumnLogicalIndex = 1;  // i.e. 2nd column in the table
const int fixedRowHeight = 18;  // or whatever fixed height you want the address-column to use
model()->setHeaderData(addressColumnLogicalIndex, Qt::Vertical, QSize(0, fixedRowHeight), Qt::SizeHintRole);


text:
Q: User deletes questions as soon as they get answer This has happened twice to me now and I'm sure it was the same user. I submitted an answer that was time consuming to prepare and the user immediately deletes the question once they have got what they want!
It seems to me they are abusing the system. I don't have the URL of the first occasion but the most recent question was this one.

A: Interesting -- haven't seen this particular pathology before, but definitely flag it and we will take action. This is extremely community hostile behavior and will not be tolerated.


text:
Q: Forcing a Route to my API I have these 2 apis in my API Controller (MVC5):
    [HttpGet]
    [HttpPost]
    public RestErrorHandler Add([FromBody]Models.Customer customer)
    {
        try
        {
          //do something...
            return new RestErrorHandler { Error = res.ErrorMessage, Location = MethodBase.GetCurrentMethod().Name };
        }
        catch (Exception ex)
        {
            return new RestErrorHandler { Error = ex.ToString(), Location = MethodBase.GetCurrentMethod().Name };
        }
    }

    [HttpGet]
    [HttpPost]
    public RestErrorHandler Delete([FromBody]Models.Customer customer)
    {
        try
        {
          //do something
            return new RestErrorHandler { Error = res.ErrorMessage, Location = MethodBase.GetCurrentMethod().Name };
        }
        catch (Exception ex)
        {
            return new RestErrorHandler { Error = ex.ToString(), Location = MethodBase.GetCurrentMethod().Name };
        }
    }

My client call is this:
var response = client.PostAsync(string.Format("http://my_uri/api/Customer/" + action), contentPost).Result;

Where 'action' can be 'Add' or 'Delete'.
Testing the delete it tells me this error:
Multiple actions were found that match the request:

To try and 'force' it to go to the correct way I added a Route tag to my method in my API:
    [HttpGet]
    [HttpPost]
    [Route("Customer/Delete/Customer")]
    public RestErrorHandler Delete([FromBody]Models.Customer customer)
    {
        try
        {
            //do something
            return new RestErrorHandler { Error = res.ErrorMessage, Location = MethodBase.GetCurrentMethod().Name };
        }
        catch (Exception ex)
        {
            return new RestErrorHandler { Error = ex.ToString(), Location = MethodBase.GetCurrentMethod().Name };
        }
    }

But it calls my 'Add' api..?
What am I missing please?

A: Both of these methods are POST's, remove GET.
[RoutePrefix("api")]
public class YourController: ApiController
{
    [HttpPost, Route("customers/add")]
    public RestErrorHandler Add([FromBody]Models.Customer customer)
    {
            try
            {
              //do something...
                return new RestErrorHandler { Error = res.ErrorMessage, Location = MethodBase.GetCurrentMethod().Name };
            }
            catch (Exception ex)
            {
                return new RestErrorHandler { Error = ex.ToString(), Location = MethodBase.GetCurrentMethod().Name };
            }
    }

    [HttpPost, Route("customers/remove")]
    public RestErrorHandler Delete([FromBody]Models.Customer customer)
    {
            try
            {
                //do something
                return new RestErrorHandler { Error = res.ErrorMessage, Location = MethodBase.GetCurrentMethod().Name };
            }
            catch (Exception ex)
            {
                return new RestErrorHandler { Error = ex.ToString(), Location = MethodBase.GetCurrentMethod().Name };
            }
    }
}

public void Configuration(IAppBuilder app)
{
     var configuration = new HttpConfiguration();

     //for route attributes on controllers
     configuration.MapHttpAttributeRoutes();
}

var response = await client.PostAsync("http://my_uri/api/customers/add", contentPost);

Postman


text:
Q: Unexpected inner join behavior I've a query :
select  TABLE.NAME,
  max(case when TABLE_ADDITION.CODE= 1 then TABLE_ADDITION.VALUE end) Mach1,
  max(case when TABLE_ADDITION.CODE= 4 then TABLE_ADDITION.VALUE end) Source,
  max(case when TABLE_ADDITION.CODE= 6 then TABLE_ADDITION.VALUE end) Dest,
  max(case when TABLE_ADDITION.CODE= 16 then TABLE_ADDITION.VALUE end) Mach2
 FROM TABLE

This is working, the result is :
NAME     Mach1      Source       Dest      Mach2
test     11         testS        testD     12

I need another information from another table (MACH). Columns Mach1 and mach2 are IDs. I want to use this ID to take the name from the correct table MACH (see data below - end of the post).
I want to have :
NAME     Mach1          Source       Dest      Mach2
test     machName11     testS        testD     machName12

For that, I did :
   select  TABLE.NAME,
      max(case when TABLE_ADDITION.CODE= 1 then MACH.MACHNAME end) Mach1,
      max(case when TABLE_ADDITION.CODE= 4 then TABLE_ADDITION.VALUE end) Source,
      max(case when TABLE_ADDITION.CODE= 6 then TABLE_ADDITION.VALUE end) Dest,
      max(case when TABLE_ADDITION.CODE= 16 then MACH.MACHNAME end) Mach2
     FROM TABLE
     INNER JOIN TABLE_ADDITION ON TABLE.TABLEID = TABLE_ADDITION.TABLEID AND TABLE.NAME = TABLE_ADDITION.NAME
     INNER JOIN MACH ON TABLE_ADDITION.CODE IN (1, 16) AND TABLE_ADDITION .VALUE = MACH.MACHID

However, I didn't receive my expected behavior :
NAME     Mach1          Source       Dest      Mach2
test     machName11     NULL         NULL      machName12

I tried for LEFT JOIN and INNER JOIN.
Data for TABLE_ADDITION :
TABLEID       NAME    CODE     VALUE
1             test    1        11
1             test    4        testS
1             test    6        testD
1             test    16       12
1             test    20       value11
1             test    25       45
1             test    ... [continue with a lot of ID and VALUE are int or varchar]
2             test2    1        45
2             test2    4        testSource\test
2             test2    6        testDest\test
2             test2    16       1
2             test2    20       value
2             test2    25       76
[continue for other ID]

For MACH
MACHID    MACHNAME    MACHTYPE
0         test        0
3         test1       1
10        test3       2
11        machName11  2
12        machName12  2
[continue with other ID]

For TABLE
TABLEID    NAME   TABLETYPE
1          test   12
1          test3  12
2          name   5
[continue with other ID]

I need the TABLE because it's my main table (with other column), I select some of them without issue.
EDIT, I edit my post, it was wrong and missing too much data to understand my issue.
For now it's working because I added one join :
   select  TABLE.NAME,
      max(case when t2.CODE= 1 then MACH.MACHNAME end) Mach1,
      max(case when TABLE_ADDITION.CODE= 4 then TABLE_ADDITION.VALUE end) Source,
      max(case when TABLE_ADDITION.CODE= 6 then TABLE_ADDITION.VALUE end) Dest,
      max(case when t2.CODE= 16 then MACH.MACHNAME end) Mach2
     FROM TABLE
     INNER JOIN TABLE_ADDITION ON TABLE.TABLEID = TABLE_ADDITION.TABLEID AND TABLE.NAME = TABLE_ADDITION.NAME
     INNER JOIN TABLE_ADDITION t2 ON TABLE.TABLEID = t2 .TABLEID AND TABLE.NAME = t2 .NAME
     INNER JOIN MACH ON t2 .CODE IN (1, 16) AND t2 .VALUE = MACH.MACHID

Thanks


text:
Q: Microsoft Stream SSO with Azure AD programmatically I know that is possible to configure the Azure AD SSO between Office 365 portals, but how can I do it programmatically?
Are there any ways in local ASP.NET web application to authenticate a user in Azure AD programmatically using username/password without prompt Azure AD logon screen, get a token and then redirect to Microsoft Stream page with the user authenticated?
I cannot find this functionality in Microsoft Graph API and the Microsoft Stream API are in development.

A: You can use this (resource owner password credential) flow to log in with specific user/pass https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc however, this will get you a token for azure ad app, I don't think it will work on the office 365 portals / stream portal though you can try it. It's mainly for accessing apis and aad applications. but feel free to give it a try, its the only way to authenticate with user/pass without interaction that I'm aware of.

A: You can use ROPC Flow to get the token  which helps in authenticate to Microsoft Stream without login popup.
Here is the request for your reference:
POST {tenant}/oauth2/v2.0/token
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&scope=user.read%20openid%20profile%20offline_access
&username=MyUsername@myTenant.com
&password=SuperS3cret
&grant_type=password

Note: Microsoft recommends you do not use the ROPC flow. In most
  scenarios, more secure alternatives are available and recommended.
  This flow requires a very high degree of trust in the application, and
  carries risks which are not present in other flows. You should only
  use this flow when other more secure flows can't be used.

Based on the above note it advises using client credential flow. Please refer similar question with client credential flow that may help you


text:
Q: C# Databound ComboBox Automatic Update I have a combobox bound to a database table.
When the user inserts a new piece of data into the table, I want the combobox to be automatically updated to display this data, however I am unsure of how I would go about doing this.
Help would be greatly appreciated.

A: I have something similar to this in a program of mine.
Whenever my datagridview is updated, I empty the combobox and refill it.
Something along the lines of (I don't have my code available right now, but this is the general idea):
if (!combobox.isempty())
{
    combobox.clear()
}

// Fill combobox here

A: i think, in the moment you know you add some data to this table, you should call:
yourcombobox.Databind();

also you must define yourcombobox.DataSource property again, before calling Databind()


text:
Q: Cannot Read Property 'getSheetId' of null; Not sure why this happens I have a the following snippet of code
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheets()[0];
 var driverArray = sheet.getRange("H2:H33").getValues().flat().filter(r=>r!="");

 var ssname = ss.getName();
 var length = ssname.length;
 var shName = sheet.getName();
 var date = ssname.substring(0,length-15);
 var scheduleDate = ss.getSheets()[7].getRange("G27").getValue(); //this contains a formula, but it evaluates to a date coinciding with the title of a sheet
 const body = "Hello,

Attached is the pay stub for the week ending "+ date+"."+"

 Thank you,
 Elizabeth";
 var arrayLength = driverArray.length;

  var scheduleSheet = SpreadsheetApp.openById("SpreadsheetURL");
  var scheduleSS = scheduleSheet.getId();
  var nextSchedule = scheduleSheet.getSheetByName(scheduleDate);
  var scheduleID  = nextSchedule.getSheetId(); // I believe the error is coming here

I am trying to get the ID of a sheet on a different spreadsheet. I believe that I am navigating to that sheet correctly, but I get the error "cannot read property of 'getSheetId' of null". Does this mean that it did not find a sheet with the name?
G27 contains the formula
=(Leftb(Summary!$A$2,2)&"-"&Midb(Summary!$A$2,3,2)&"-"&rightb(Summary!$A$2,2))+7

but it evaluates to a date. And the format of the date matches correctly with the title of the sheet.

A: Instead of
var scheduleDate = ss.getSheets()[7].getRange("G27").getValue()

use
var scheduleDate = ss.getSheets()[7].getRange("G27").getDisplayValue()

The above because getValue() returns a Date object for cells holding a date value and usually the Date object is parsed as string in a long format rather than the usual date formats.


text:
Q: Copying a working chart from a spreadsheet to a document results with "All series on a given axis must be of the same data type" I have a Google spreadsheet that contains charts which are properly displayed. When I am using a GAS to copy these charts to a Google document some of the charts are properly displayed in the document while others (which are displayed properly in the spreadsheet) are displaying the message "All series on a given axis must be of the same data type".
Since these are working charts I am not sure why I get this message. Is there a workaround to this problem or a known issue?
Any advise will help.
Thx!

A: Based on KRR answer. Even though the chart might be working in Google spreadsheet it appears that the getBlob of the chart rechecks the source values of the chart. You need to make sure that the source values (in my case above from a spreadsheet) all have the same data type.