text:
Q: Existe algum método para eu criar traduções de páginas com Javascript ou Typescript? Gostaria de saber se existe algum método para eu criar minhas próprias traduções de páginas estáticas com Javascript.

A: Veja, basta criar um objeto contendo as string.
let TRANSLATIONS = {
  'en': {
    'Homepage': 'Homepage',
    ...
  },
  'pt-br': {
    'Homepage': 'Pagina inicial',
    ...
  }
}

Para os elementos, defina um dataset como data-lang-str exemplo:

...

Para elementos de seleção de idioma, defina um dataset como data-lang, exemplo:
<button class="btn btn-primary" name="btn-translate" data-lang="pt-br">Português</button>
<button class="btn btn-dark" name="btn-translate" data-lang="en">Inglês</button>
...

Método para traduzir:
const translate = (lang = null) => {
  if (lang === null) {
    lang = DEFAULT_LANG;
  }
  let DEFAULT_LANG_LENGTH = Object.keys(TRANSLATIONS[DEFAULT_LANG]).length;
  // Verifica se o idioma selecionado existe.
  if (TRANSLATIONS[lang]) {
    // Existe... Agora verifica se a tradução selecionada está completa
    // Se não estiver exibe a mensagem.
    ALERT_TRANSLATION_UNAVAILABLE.style.display = 'none';
    let LANG_LENGTH = Object.keys(TRANSLATIONS[lang]).length;
    if (LANG_LENGTH < DEFAULT_LANG_LENGTH) {
      ALERT_TRANSLATION_INCOMPLETE.style.display = 'block';
    } else {
      ALERT_TRANSLATION_INCOMPLETE.style.display = 'none';
    }
    DATA_LANG_ELEMENTS.forEach((el) => {
      let STR = el.getAttribute('data-lang-str');
      if (TRANSLATIONS[lang][STR]) {
        el.innerText = (TRANSLATIONS[lang][STR]);
      }
    });
  } else {
    // Não existe, então exibe a mensagem
    ALERT_TRANSLATION_INCOMPLETE.style.display = 'none';
    ALERT_TRANSLATION_UNAVAILABLE.style.display = 'block';
  }
}

Exemplo funcionando

let DEFAULT_LANG = 'en';
let ALERT_TRANSLATION_INCOMPLETE = document.querySelector('#translatoin-incomplete');
let ALERT_TRANSLATION_UNAVAILABLE = document.querySelector('#translatoin-unavailable');
let DATA_LANG_ELEMENTS = document.querySelectorAll('[data-lang-str]');
let TRANSLATIONS = {
  'en': {
    'Homepage': 'Homepage',
    'Features': 'Features',
    'Pricing': 'Pricing',
    'Disabled': 'Disabled',
    'Email': 'Email',
    'Password': 'Password',
    'Address': 'Address',
    'City': 'City',
    'State': 'State',
    'Zip': 'Zip',
    'SendMeNewsletters': 'Send me newsletters'
  },
  'pt-br': {
    'Homepage': 'Pagina inicial',
    'Features': 'Características',
    'Pricing': 'Preços',
    'Disabled': 'Desativado',
    'Email': 'Email',
    'Password': 'Senha',
    'Address': 'Endereço',
    'City': 'Cidade',
    'State': 'Estado',
    'Zip': 'CEP',
    'SendMeNewsletters': 'Envie-me boletins informativos'
  },
  'es': {
    'Homepage': 'Página principal',
    'Features': 'Caracteristicas',
    'Pricing': 'Precio',
    'Disabled': 'Discapacitado',
    'Email': 'Email',
    'Password': 'Contraseña',
    'Address': 'Dirección'
  },
  'ru': {
    'Homepage': 'домашняя страница',
    'Features': 'Особенности',
    'Pricing': 'ценообразование',
    'Disabled': 'Отключено',
    'Email': 'Адрес электронной почты',
    'Password': 'пароль',
    'Address': 'Адрес'
  },
  'ja': {
    'Homepage': 'ホームページ',
    'Features': '特徴',
    'Pricing': '価格設定',
    'Disabled': '無効',
    'Password': 'Password',
    'Address': 'Address'
  }
};

const translate = (lang = null) => {
  if (lang === null) {
    lang = DEFAULT_LANG;
  }
  let DEFAULT_LANG_LENGTH = Object.keys(TRANSLATIONS[DEFAULT_LANG]).length;
  // Verifica se o idioma selecionado existe.
  if (TRANSLATIONS[lang]) {
    // Existe... Agora verifica se a tradução selecionada está completa
    // Se não estiver exibe a mensagem.
    ALERT_TRANSLATION_UNAVAILABLE.style.display = 'none';
    let LANG_LENGTH = Object.keys(TRANSLATIONS[lang]).length;
    if (LANG_LENGTH < DEFAULT_LANG_LENGTH) {
      ALERT_TRANSLATION_INCOMPLETE.style.display = 'block';
    } else {
      ALERT_TRANSLATION_INCOMPLETE.style.display = 'none';
    }
    DATA_LANG_ELEMENTS.forEach((el) => {
      let STR = el.getAttribute('data-lang-str');
      if (TRANSLATIONS[lang][STR]) {
        el.innerText = (TRANSLATIONS[lang][STR]);
      }
    });
  } else {
    // Não existe, então exibe a mensagem
    ALERT_TRANSLATION_INCOMPLETE.style.display = 'none';
    ALERT_TRANSLATION_UNAVAILABLE.style.display = 'block';
  }
}

let BTNS_TRANSLATE = document.querySelectorAll('[name=btn-translate]');
BTNS_TRANSLATE.forEach((btn) => {
  btn.addEventListener('click', (ev) => {
    translate(btn.getAttribute('data-lang'));
  });
});

translate();
* {
  border-radius: 0px !important;
}
body {
  margin-top: 60px !important;
}
.btn {
  cursor: pointer;
  margin-bottom: 14px;
  text-transform: uppercase;
}
#idioma-indisponivel,
#traducao-incompleta {
  display: none;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Disabled

        Incomplete translation

        Language unavailable

      <button class="btn btn-primary" name="btn-translate" data-lang="pt-br">Português</button>
      <button class="btn btn-dark" name="btn-translate" data-lang="en">Inglês</button>
      <button class="btn btn-danger" name="btn-translate" data-lang="es">Espanhol</button>
      <button class="btn btn-info" name="btn-translate" data-lang="ru">Russo</button>
      <button class="btn btn-success" name="btn-translate" data-lang="ja">Japonês</button>
      <button class="btn btn-secondary" name="btn-translate" data-lang="ko">Coreano</button>

    <form>

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

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

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

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

          <select id="inputState" class="form-control">Choose</select>

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

            <input class="form-check-input" type="checkbox">

      <button type="submit" class="btn btn-primary">Sign in</button>
    </form>

A: Se quiser algo automático pode usar o Google Tradutor, exemplo:
<!DOCTYPE html>

Olá, mundo!

Exemplo no jsfiddle

Customizar o Google tradutor
Com CSS é possivel mudar algumas coisas e pra remover aquele menu superior pode usar isto:
#google_translate_element {
    display: none;
}
.goog-te-banner-frame {
    display: none !important;
}
body {
    position: static !important;
    top: 0 !important;
}

Para mais customizações veja isto: https://pt.stackoverflow.com/a/82760/3635


text:
Q: How to convert a hex encoded string to an integer in MS SQL? I want to convert a piece of a hash string returned by the HASHBYTES (SHA2_256) function to an integer in MS SQL Server.
This query returns '6BDA'
SELECT (SUBSTRING(CONVERT(VARCHAR(64), HASHBYTES('SHA2_256', CAST(12.5 AS VARCHAR(64))), 2), 61, 4)) as tmp

But when I try to cast it to an int this results in an error:
--Conversion failed when converting the varchar value '6BDA' to data type int.
SELECT (CONVERT(int, SUBSTRING(CONVERT(VARCHAR(64), HASHBYTES('SHA2_256', CAST(12.5 AS VARCHAR(64))), 2), 61, 4))) as tmp

If I try to convert the substring to varbinary and then to int, the result differs from 27610:
--Returns 910312513
SELECT (CONVERT(int, CONVERT(varbinary, SUBSTRING(CONVERT(VARCHAR(64), HASHBYTES('SHA2_256', CAST(12.5 AS VARCHAR(64))), 2), 61, 4)))) as tmp

In Snowflake I can easily perform the conversion with a to_number function:
The below query converts '6BDA' to 27610. How can I achieve the same result with SQL Server?
SELECT to_number(substr(sha2(TO_VARCHAR(ABS(12.5)), 256), 61), 'xxxx')

A: Try this out
SELECT CAST( CONVERT(VARBINARY,'0x'+RIGHT('00000000'+REPLACE(tmp,'x',''),8),1) AS INT)
from table1

I tested it with the following DDL:
create table table1(tmp varchar(64));

insert into table1
SELECT SUBSTRING(CONVERT(VARCHAR(64), HASHBYTES('SHA2_256', CAST(12.5 AS VARCHAR(64))), 2), 61, 4)

See how it works in this Fiddle.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I emulate 1.7.10's adventure mode in 1.8? Up until Minecraft 1.7.10 I enjoyed playing in adventure mode, which restricts one to use the right tools to destroy or harvest blocks (to have a more realistic experience).
In this version (and before that), it was still possible to place blocks without much restrictions. But now in 1.8, sadly, I discovered that this behaviour was changed, and my favourite gamemode was "gone": I'm unable to place any blocks and cannot break any blocks even when using the proper tool (axe for trees etc.).
How can I emulate 1.7.10's adventure mode while playing the new version (1.8)? Can I define rules for every tool with the command block somehow?
I would prefer a solution without modding the game, staying with pure vanilla MC if possible.

A: Create an entitydata command that will edit your inventory. The only thing it will change is add this tag to all items in the inventory:
CanPlaceOn:["minecraft:stone","minecraft:grass_block","minecraft:dirt"... putting all block IDs on.
Then create an array of command blocks facing upwards. The bottom layer will be repeating command blocks with: clear @p TOOLNAME 0 1
The top layer will be chain conditional command blocks with command:
give @p TOOLNAME 1 1 {CanDestroy:[in this box you put all blocks you want the tool to break]}
This will take a while. But once you are done upload map to the internet and enjoy adventure-loving people wanting to play on it!

A: There are 2 ways to do this, both take HOURS of prep time.
1)
go on survival mode, not adventure
do a command block on a clock saying
/effect @p minecraft:mining_fatigue 10 100 true
place a string of command blocks with this command:
/clear @p wooden_axeBLOCKID0
with a comparator, immediately followed by a repeater
for every tool and BLOCK ID (damage) for tool.
then make it so that if ANY of the repeaters are on do /effect @a clear
2)
You could create a scoreboard objective for crafting every tool, eg:
/scoreboard objectives craftWoodenAxe stat.craftItem.minecraft.stone_axe
create a redstone-block-clock facing +X,
and with command blocks from lowest to highest X value do this:
/clear @a[score_craftWoodenAxe_min=1] wooden_axe 0
/give @a [score_craftWoodenAxe_min=1] wooden_axe 1 {CanBreak:["PUT A BLOCK","PUT A BLOCK","etc"]}
/scoreboard players remove @p[score_craftWoodenAxe_min=1] craftWoodenAxe 1
for every tool...
You would probaly be better off waiting to see if mojang adds this later.

A: Add the CanBreak or CanPlaceOn tag to items.
Example:
/give @p minecraft:stone 1 0 {CanPlaceOn:["minecraft:dirt"]}
This would give the closest player a stone block that you can place on dirt.
/give @p minecraft:stone_sword 1 0 {CanDestroy:["minecraft:web"]}
And this would give a stone sword that can destroy webs.

A: You could solve half the problem by switching between survival and adventure mode based on the item you are holding. However, you would still need CanBreak tags on all your tools.
(Also you could break blocks when holding another block or nothing)
This is only a partwise solution, as this allows you to place blocks only when you are not holding a tool.


text:
Q: ARKit and RealityKit – Collaborative Session I can't find any examples of RealityKit collaborative session.
I set up Multipeer Connectivity bu I have no idea if I'm doing it wrong:
configuration.isCollaborationEnabled = true

but when I try to load in a Reality Composer box file on two devices, only the boxes created by each device are shown on the screens.
I have seen Apple's WWDC Building Collaborative AR Experiences, but it doesn't help.

A: There is a great tutorial and post on Medium "Getting Started with RealityKit: Collaborative Augmented Reality" That does a great job of explaining the details of the McSession, how the SynchronizationService works, how Ownership is designated and shared, and in general a great place to start.

A: @andy-jazz, I have multipeer session established, the data is being shared.
Problem is the Box created on horizontal surface does not display on the second device. only display in the device it self.
Let me know if the following understanding is correct:
First Device:
Touch the screen ->
arView.session.add(anchor: anchor) ->
didOutputCollaborationData ->
NSKeyArchiver -> Data -> Send MCSession ->
Second Device:
Received Session ->
NSKeyUnarchiver ->
arView.session.update(with: data)->
session(_ session: ARSession, didAdd anchors: [ARAnchor])
Is there any steps that is missing or understood it wrong?
I went through the article but no luck.


text:
Q: Why is all my content disappearing when I turn on client validation in ASP.NET MVC 2 RC2? I am using the following partial to render the editor for the Create and Edit pages:
PersonEditor.ascx
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyProj.ViewModels.PersonEditorViewModel>" %>

<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript" />
<script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript" />

<%  Html.EnableClientValidation(); %>
<%  using (Html.BeginForm())
    {
%>
        <%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>
        <%= Html.EditorForModel()%>
        <p>
            <input type="submit" value="Save" />
        </p>
<%
    }
%>

I believe I have followed the instructions correctly on Scott Gu's blog post (see "Enabling Client-Side Validation"), but when I load this page in a browser, the entire editor form vanishes. If I remove the two scripts and Html.EnableClientValidation(), everything is back to normal again (except, of course, there is no client-side validation).
I have tried putting the script tags in the master page, but that made no difference.
Any ideas how I might be able to fix this?
Update
If I put the two script tags in Site.Master instead of the partial, everything disappears. It basically makes my app completely invisible. No errors, though. It just loads a blank page.

A: Your script tags are:

*

*Different than what is in the blog post you reference, and

*Incorrect.

They should be:
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>


text:
Q: How to get current controller name with jquery? I want to active menu item in MVC with jquery.

     Reports

    User Groups

    Projects

I created this menu with @Html.Navigation().
I want to get current controller in jquery for add active class to selected menu.
highlightActiveMenuItem = function () {
var currentAction = ???;
var currentController = ???;

};

A: I use this
$(document).ready(function () {
 highlightActiveMenuItem();
});

highlightActiveMenuItem = function () {
  var url = window.location.pathname;
   $('.menu a[href="' + url + '"]').addClass('active_menu_item');
};

A: highlightActiveMenuItem = function () {
    var currentAction = '@ViewContext.RouteData.Values["action"].ToString()';
    var currentController = '@ViewContext.RouteData.Values["controller"].ToString()';
};

A: try this

    <button onclick="currntcontrol()"></button>


text:
Q: Xamarin.Android how to override style from nuget library? I'm using for example BottomNavigationBarXF library in my Xamarin.Android project and I would like to change font which it uses. I found in source code styles responsible for that, but I don't know how to override them without adding library source code to my project.
Style are here: source code.
Is it possible? I would like to change font for this one: BB_BottomBarItem_Fixed.TitleAppearance

A:
Is it possible? I would like to change font for this one:BB_BottomBarItem_Fixed.TitleAppearance

According to README of BottomNavigationBar. You can set the Text Appearance of Bottom Navigationbar using BottomBar.SetTextAppearance(resId).
So first step, define a style for text appearance in styles.xml:
 <style name="MyTextAppearance">
    <item name="android:textSize">12sp</item>
 </style>

Then use this style after you create the bottom bar:
var _bottomBar = BottomBar.Attach(this, savedInstanceState);
...
_bottomBar.setTextAppearance(Resource.Style.MyTextAppearance)


text:
Q: I want to loop through an item to create an array then store it in array field in the DB. How do I do it? I am receiving some values from body and I want to create an array using the values and then store the array in a db
exports.creatVerification = catchAsync(async (req, res, next) => {
  const date = req.body.dateVerified;
  const [duration] = req.body;
  const dueDates = [];
  const generateDates = (dates, period) => {
    for (let i = 1; i <= period; i + 1) {
      dueDates.push(
        moment(dates).add(i, 'months').add(1, 'days').toISOString()
      );
    }
  };
  generateDates(date, duration);

  const data = {
    investment: req.body.investment,
    topUp: req.body.topUp,
    verified: req.body.verified,
    verifiedBy: req.body.verifiedBy,
    dateVerified: req.body.dateVerified,
    dueDates,
    note: req.body.note,
  };
  console.log(data);
  const newVerify = await Verify.create(data);

  res.status(201).json(newVerify);
});

Here is the Schema
const mongoose = require('mongoose');

const verifySchema = new mongoose.Schema(
  {
    investment: {
      type: mongoose.Schema.ObjectId,
      ref: 'Investment',
    },
    topup: {
      type: mongoose.Schema.ObjectId,
      ref: 'TopUp',
    },
    verified: {
      type: Boolean,
      required: true,
    },
    verifiedBy: {
      type: mongoose.Schema.ObjectId,
      ref: 'Auth',
    },
    dateVerified: {
      type: Date,
      default: Date.now(),
      required: true,
    },
    createdAt: { type: Date, default: Date.now() },
    dueDates: [Date],
  },
  {
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
);

const Verify = mongoose.model('Verify', verifySchema);

module.exports = Verify;

This is the verify schema which contains all the data. Also, when I try to data using react, it doesnt store on the database but when I use postman, it stores.

A: You've defined dueDates to be an array of Dates, but you pass strings, since in your loop you do moment(dates).add(i, 'months').add(1, 'days').toISOString(). Removing .toISOString() should fix the issue:
dueDates.push(moment(dates).add(i, 'months').add(1, 'days'));

EDIT:
Just tested it on my local machine, and it seems it works either way, so .toISOString() is not the issue here. i + 1 (it should be i=i+1 or i++) in the for loop might be the issue, as your loop will run forever. Also you're not extracting the duration correctly, it should be:
const { duration } = req.body;

instead of
const [duration] = req.body;


text:
Q: Flutter/Firebase - Create future function for gathering firebase images I am trying to display some images downloaded from firestore but when I load this screen it takes a while to download the images. To make this a bit more seamless I am thinking of creating a Future function that will allow me to download the images first, and then display them all at once. I have created a future function to get the data from Firebase but I now need to create a new function to download the images. Here are my two future functions:
     Future getCardData() async {
    return await Firestore.instance.collection('cards')
    .where('Event', isEqualTo: widget.documentid).getDocuments();
  }

  Future getCardImage(int index) async {
    final _data = getCardData();
    return await FirebaseImage(_data.data.documents[index].data['img_url'], maxSizeBytes: 15 * 1024 * 1024);
  }

And then I would implement like so:
  body: FutureBuilder(
    future: getCardData(),
    builder: (context, snapshot)  {
      if (!snapshot.hasData) {
        return Center(child: const Text('Loading...'));
      }
      return GridView.builder(
        shrinkWrap: true,
        gridDelegate:
        SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
        itemCount: snapshot.data.documents.length,
        itemBuilder:
        // ignore: missing_return
            (BuildContext context, int index) {
          print(snapshot.data.documents[index].data['img_url']);
          return Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              color: Colors.blue,
              height: MediaQuery.of(context).size.height / 6,
              child: Center(
                  child: Card(
                    elevation: 8.0,
                    child: getCardImage(index);
                    ),
                  )
              ),
            ),
          );
        },
      );
    },
  ),

But i'm just not sure the best way to create the future function to download the images because when I run the above, i get the following error:
The argument type 'Future<dynamic>' can't be assigned to the parameter type 'ImageProvider<dynamic>'

Any suggestions?
Thanks

A: Would this get you there?
     Future<FirebaseImage> getCardImage(int index) async {
final _data = getCardData();
return await FirebaseImage(_data.data.documents[index].data['img_url'], maxSizeBytes: 15 * 1024 * 1024);

}


text:
Q: "younger face" or "younger looks" (1) I haven't met Jack for at least twenty years. Yesterday, I received his photo in my email. I don't remember how he looked when he was youngers. (my original example)
(2) I haven't met Jack for at least twenty years. Yesterday, I received his photo in my email. I don't remember his younger face.
(3) I haven't met Jack for at least twenty years. Yesterday, I received his photo in my email. I don't remember his younger looks.
I want to replace the highlighted words in (1) with a shorter phrase. Do "younger face" and "younger looks" work?

A: First of all, not directly addressing the question, but about "met":
"I haven't met Jack for ..." is a bit awkward putting "met" in present perfect tense like that and specifying a duration.
Plain "met" sort of implies the initial meeting/introduction, as in "I haven't met Jack yet" (but I hope to one day, etc.). But applying a duration as you are, it would be more natural to use "I haven't seen Jack for at least twenty years".
On the other hand, if you add "with" as in "I haven't met with Jack for at least twenty years", it's closer to what you are intending, but "met with" is more appropriate for appointments/meetings such as in a professional context, whereas with friends it might be "met up with" (informally, bordering on slang?).
On to your question of shortening "I don't remember how he looked when he was youngers"
1 ("how he looked when he was youngers") is OK, though it would be "younger" and not "youngers". You are trying to make this shorter, so you just saved one character :)
2 ("remember his younger face") is bit awkward.
3 ("remember his younger looks") is most awkward. "Younger looks" doesn't sound right in this possessive context.
You can try more creative phrasing like "I don't remember his youthful visage", though this feels like trying too hard.
About "I don't remember..."
Another tweak to the phrasing to make it fit more naturally in your paragraph: "I didn't even remember ..."
The past tense of "didn't" is wrapping around the previous sentence's "yesterday", the point at which you received the photo. This flows more naturally.
Summary
Possibly not the best writing, but definitely natural:
I haven't seen Jack for at least twenty years. Yesterday, I received his photo in my email. I didn't even remember how he looked when he was younger.


text:
Q: Beta regression (proportions) with phylogenetic comparative analysis? Is there a package in R that allows phylogenetic comparative analysis of proportion data (i.e. a beta distribution)?

A: You can do GLMMs including phylogeny as an error term in the package brms. See here for an example. The package also allows for beta distribution. The new version of glmmTMB also allows you to include several types of covariance structures and includes the beta distribution.

A: There is an (as yet unpublished) extension to glmmTMB that fits phylogenetic models by creating a specially structured Z matrix: see here, here, here.


text:
Q: IOS - How to draw a border and a shadow that rotates with view but doesn't scale with it I am developing an ios app.
In my app I have got a view, the view is has got a border and a shadow.
The view can be scaled and rotated.
When a user scaled my view it causes my border and shadow to scale as well.
I don't want my shadow or border to scale at all.
On the other hand I do want my shadow and border to rotate when I rotate the view.
Is there any built in mechanism to prevent border \ shadow scale?
Thank you

A: As far as I know there isn't such a built in mechanism.
The only way I see for you to solve your problem is to simply use two different views, with different management in case of rotation.
Have one view as a sort of background and add your border and shadow to it, and then place the content on top of it (or in it, depends on your case).


text:
Q: wait file to create before send mail Im having some problems with a function with nodemailer, i need to create a pdf from body req, then attach it to a mail and send it, the problem here is i dont know how to wait to the file to finish saving before send the mail, and im having errors because the mails goes before the system can create the file or even attach the pdf file...
the idea will be: send post req -> get the req.body -> create pdf -> create mail options (nodemailer) -> send the mail.
but the code now is going like: send post req -> get the req.body -> create pdf -> create mail options (nodemailer) -> send the mail -> system
still making the pdf -> error
my current code is:

 app.post('/send', function(req, res) {
        if (req.body.email == "" || req.body.subject == "") {
            res.send("Error: Email & Subject should not blank");
            return false;
        }

        // Sending Emails with SMTP, Configuring SMTP settings

        var smtpTransport = nodemailer.createTransport({
            host: "mail.vyg.cl", // hostname
            secureConnection: true, // use SSL
            port: 465, // port for secure SMTP
            auth: {
                user: 'crm@vyg.cl',
                pass: '******'
            }
        });
        const pdfArchive = './server/' + req.body.subject + '.pdf';

        if (fs.existsSync(pdfArchive)) {
            fs.unlinkSync(pdfArchive);
        }
        pdf.create(req.body.description).toFile('./server/' + req.body.subject + '.pdf', function(err, res) {
            if (err) {
                console.log(err);
            } else {
                console.log(res)

            }
        });

        const mailOptions = {
            from: req.body.from, // sender address
            to: req.body.to, // list of receivers
            cc: req.body.cc,
            subject: req.body.subject, // Subject line
            //text: "Hello world ✔", // plaintext body
            // html: req.body.description, // html body,
            attachments: [{ // file on disk as an attachment
                filename: req.body.subject + '.pdf',
                path: './server/' + req.body.subject + '.pdf' // stream this file
            }]
        }
        smtpTransport.sendMail(mailOptions, function(error, response) {
            if (error) {
                res.status(400).json({ message: "Email could not sent due to error: " + error });
            } else {
                res.status(200).json({ message: "Email has been sent successfully" });
            }
        });
        if (fs.existsSync(pdfArchive)) {
            fs.unlinkSync(pdfArchive);
        }
    });

i tryed to send the mail in the conditional when the pdf was created but i dont get the smtpTransport response....
any help will be appreciated

A:

app.post('/send', async function(req, res) {
        if (req.body.email == "" || req.body.subject == "") {
            res.send("Error: Email & Subject should not blank");
            return false;
        }

        // Sending Emails with SMTP, Configuring SMTP settings

        var smtpTransport = nodemailer.createTransport({
            host: "mail.vyg.cl", // hostname
            secureConnection: true, // use SSL
            port: 465, // port for secure SMTP
            auth: {
                user: 'crm@vyg.cl',
                pass: '*******'
            }
        });

        const mailOptions = {
            from: req.body.from, // sender address
            to: req.body.to, // list of receivers
            cc: req.body.cc,
            subject: req.body.subject, // Subject line
            //text: "Hello world ✔", // plaintext body
            // html: req.body.description, // html body,
            attachments: [{ // file on disk as an attachment
                filename: req.body.subject + '.pdf',
                path: './server/' + req.body.subject + '.pdf' // stream this file
            }]
        }

        const pdfArchive = './server/' + req.body.subject + '.pdf';

        if (fs.existsSync(pdfArchive)) {
            await fs.unlinkSync(pdfArchive);// Add wait here
        }
        try{

   var result = await pdf.create(req.body.description).toFile('./server/' + req.body.subject + '.pdf') // capture result if you need to
   try{
   await smtpTransport.sendMail(mailOptions) // wrap this in a try catch if you want to capture email sending specific erorrs else outer try catch will work
   res.status(200).json({ message: "Email has been sent successfully" });

   }
   catch(error)
   {
    res.status(400).json({ message: "Email could not sent due to error: " + error });
   }
  }
  catch(error)
  {
   console.log(err);
   res.send(error)
  }
    });


text:
Q: get apache total cpu usage in (linux) I want to write a script (in bash or Perl on linux) which monitors the Apache and restarts the Apache in case it exceeds X% CPU.
I understand that I need to get the total CPU usage of Apache since it opens child process.
How can I get the total CPU usage of Apache?

A: Try the following, but make sure to update the Apache-process name with your actual one (mine is httpd):
ps u -C httpd | awk '{sum += $3} END {print sum}'

This will get a list of all apache processes running and sum the %CPU column of ps's output using awk.

A: this will return sum load of parent apache process and all child processes, in percents, without any additional info, so that you can easily use this script in any way:
ps --no-heading -o pcpu -C httpd | awk '{s+=$1} END {print s}'

A: This will list you the total CPU usage of each apache2 process:
ps u -C apache2 | awk '{print $3}' | grep -v "%CPU"

Note, however, that the total (=average) CPU usage might be rather low even if the current CPU usage is high, especially for long running processes.


text:
Q: Convert datetime in python How do i convert this datetime using python?
2017-10-16T08:27:16+0000

I tried to use strptime but getting ValueError: time data '2017-10-16T08:27:16+0000' does not match format 'The %d %B %Y at. %H:%M'
import datetime
datetime.datetime.strptime("2017-10-16T08:27:16+0000", "The %d %B %Y at. %H:%M")

'''
I want my output to look like this
The 16 october 2017 at. 08:27
'''

A: First parse the string correctly, then print it in the desired format:
import datetime
date = datetime.datetime.strptime("2017-10-16T08:27:16+0000", "%Y-%m-%dT%H:%M:%S%z")
print(date.strftime("The %d %B %Y at. %H:%M"))

A: https://blogs.harvard.edu/rprasad/2011/09/21/python-string-to-a-datetime-object/
You have to first strip your date using strptime() and then rebuild it using strftime()
import datetime
time = "2017-10-16T08:27:16+0000"
stripedTime = datetime.datetime.strptime(time, '%Y-%m-%dT%I:%M:%S%z')

rebuildTime = stripedTime.strftime('The %d %B %Y at. %H:%M')
print(rebuildTime)


text:
Q: OpenShift superuser permissions I am trying to install Client tools on RHEL/OpenShift free server. However following https://developers.openshift.com/en/getting-started-rhel-centos.html#client-tools I am supposed to execute some super user commands which gives a permission error. Do I need to do something to enable super user access on my virtual machine?

sudo su

bash: /usr/bin/sudo: Permission denied

A: OpenShift Online does not allow you to gain super user access, so I don't think you will be able to install the client tools on your OpenShift servers. The OpenShift client tools (rhc) aren't meant to be installed on your OpenShift servers, they are meant to be installed on your local computer.


text:
Q: How to load two versions of the same php extension? The web application I am working on needs to be able to handle two different versions of the same PHP extension. (Specifically MapScript for Mapserver 5.6 and MapScript for Mapserver 6.2.)
The script won't know which of the two versions needs to be loaded until after php execution has started. (But only one extension is needed for each request.)
My original plan was to use php built-in dl function, but I discovered that dl has been disabled because of security issues. (http://php.net/manual/en/function.dl.php)
Is there any way secure way to load an extension during execution? Or perhaps always load both, but put them in different namespaces so they can be accessed separately?

A: I've given the question a +1 because it's a good question, well asked.
However, I can't imagine that there will be an answer that will do what you're looking for. If the extension is not backward compatible between versions then it's clearly not well designed, and it's hard to see how PHP can be responsible for that.
The best solution I can think of involves using two separate php.ini or .htaccess files, specifying the two separate versions of the extension. PHP programs run from your web server would pick up different versions of the extension depending on which directory they're in.
eg http://myserver/newmaps/program.php would run the new version of the extension and http://myserver/oldmaps/program.php would run the old version of the extension.
Then you just need to have the same program in two directories. If it detects that it's not got the extension version it needs, it could just issue a http redirect to load the other version.


text:
Q: Cannot Create Window-based Application in Non-main Thread In one of my projects, I need to create a window in a non-main thread. I have never done that so I don't much experience on that.
According to the MSDN documentation and the SO question, I should be able to create a window in other thread, but I cannot succeed. Even though, in thread start routine, I register a window class, create a window and provide a message loop, the thread starts and exits immediately. In addition, I cannot debug the thread start routine so I cannot hit the break points inside it.
Is there something I am missing? I hope I don't miss anything silly.
Please consider the following demo. Thank you for taking your time.
#include <Windows.h>
#include <tchar.h>

HANDLE hThread;
DWORD WINAPI OtherUIThreadFunc(LPVOID args);

LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

HWND m_hwnd;
MSG msg;
WNDCLASSEX m_wcx;
const int MESSAGE_PROCESSED = 0;
const TCHAR* m_szClassName = _T("DemoWndCls");
const TCHAR* m_szWindowTitle = _T("Demo Window");

int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int nCmdShow)
{
    hThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)OtherUIThreadFunc, hInstance, 0, NULL);
    /*MSG msg;

    ZeroMemory(&m_wcx, sizeof(m_wcx));
    m_wcx.cbSize = sizeof(m_wcx);
    m_wcx.style = CS_VREDRAW | CS_HREDRAW;
    m_wcx.hInstance = hInstance;
    m_wcx.lpszClassName = m_szClassName;
    m_wcx.lpfnWndProc = WndProc;
    m_wcx.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    m_wcx.hCursor = LoadCursor(NULL, IDC_ARROW);
    m_wcx.hbrBackground = (HBRUSH)COLOR_WINDOW;

    if (!RegisterClassEx(&m_wcx))
        return false;

    m_hwnd = CreateWindowEx(0, m_wcx.lpszClassName, m_szWindowTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 480, 360, NULL, NULL, hInstance, NULL);

    if (!m_hwnd)
        return false;
    ShowWindow(m_hwnd, SW_NORMAL);
    UpdateWindow(m_hwnd);
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;*/
}

DWORD WINAPI OtherUIThreadFunc(LPVOID args)
{
    HINSTANCE hInstance = (HINSTANCE)args;

    ZeroMemory(&m_wcx, sizeof(m_wcx));
    m_wcx.cbSize = sizeof(m_wcx);
    m_wcx.style = CS_VREDRAW | CS_HREDRAW;
    m_wcx.hInstance = hInstance;
    m_wcx.lpszClassName = m_szClassName;
    m_wcx.lpfnWndProc = WndProc;
    m_wcx.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    m_wcx.hCursor = LoadCursor(NULL, IDC_ARROW);
    m_wcx.hbrBackground = (HBRUSH)COLOR_WINDOW;

    if (!RegisterClassEx(&m_wcx))
        return false;
    m_hwnd = CreateWindowEx(0, m_wcx.lpszClassName, m_szWindowTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 480, 360, NULL, NULL, hInstance, NULL);
    if (!m_hwnd)
        return false;
    ShowWindow(m_hwnd, SW_NORMAL);
    UpdateWindow(m_hwnd);
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
}
LRESULT WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_CLOSE:
        DestroyWindow(hwnd);
        return MESSAGE_PROCESSED;
    case WM_DESTROY:
        PostQuitMessage(0);
        return MESSAGE_PROCESSED;
    default:
        return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }

}

A: Window creation succeeds (in theory, anyway). The issue is that the primary thread moves one to return, which causes the runtime to terminate the process.
To solve the issue you will have to keep the primary thread alive. A call to WaitForSingleObject, or a message loop are possible options.

This is mostly a result of following the conventions of C and C++. In either case returning from the main function is equivalent to calling the exit() function. This explains why returning from the primary thread tears down the entire process.
Bonus reading: If you return from the main thread, does the process exit?


text:
Q: Android Source Code Project build failing Trying to build AOSP
I have followed this guide exactly on a clean Ubuntu 16.04 virtual machine.
All commands leading up-to make -j4 have been successful, however when I build it fails at 11% with the following error:
[ 11% 9531/83760] target thumb C: nfc_nci.bullhea..._32 <= system/nfc/halimpl/pn54x/hal/phNxpNciHal.c
FAILED: out/target/product/bullhead/obj_arm/SHARED_LIBRARIES/nfc_nci.bullhead_intermediates/hal/phNxpNciHal.o
/bin/bash -c "PWD=/proc/self/cwd prebuilts/misc/linux-x86/ccache/ccache prebuilts/clang/host/linux-x86/clang-4053586/bin/clang  -I system/nfc/halimpl/pn54x/utils -I system/nfc/halimpl/pn54x/inc -I system/nfc/halimpl/pn54x/common -I system/nfc/halimpl/pn54x/dnld -I system/nfc/halimpl/pn54x/hal -I system/nfc/halimpl/pn54x/log -I system/nfc/halimpl/pn54x/tml -I system/nfc/halimpl/pn54x/self-test -I system/nfc/halimpl/pn54x -I out/target/product/bullhead/obj_arm/SHARED_LIBRARIES/nfc_nci.bullhead_intermediates -I out/target/product/bullhead/gen/SHARED_LIBRARIES/nfc_nci.bullhead_intermediates -I libnativehelper/include/nativehelper \$(cat out/target/product/bullhead/obj_arm/SHARED_LIBRARIES/nfc_nci.bullhead_intermediates/import_includes)  -I system/core/include -I system/media/audio/include -I hardware/libhardware/include -I hardware/libhardware_legacy/include -I hardware/ril/include -I libnativehelper/include -I frameworks/native/include -I frameworks/native/opengl/include -I frameworks/av/include -isystem out/target/product/bullhead/obj/include -isystem device/lge/bullhead/kernel-headers -isystem hardware/qcom/msm8994/kernel-headers -isystem bionic/libc/arch-arm/include -isystem bionic/libc/include -isystem bionic/libc/kernel/uapi -isystem bionic/libc/kernel/uapi/asm-arm -isystem bionic/libc/kernel/android/scsi -isystem bionic/libc/kernel/android/uapi -c  -fno-exceptions -Wno-multichar -ffunction-sections -fdata-sections -funwind-tables -fstack-protector-strong -Wa,--noexecstack -Werror=format-security -D_FORTIFY_SOURCE=2 -fno-short-enums -no-canonical-prefixes -DNDEBUG -g -Wstrict-aliasing=2 -DANDROID -fmessage-length=0 -W -Wall -Wno-unused -Winit-self -Wpointer-arith -DNDEBUG -UDEBUG -fdebug-prefix-map=/proc/self/cwd= -D__compiler_offsetof=__builtin_offsetof -Werror=int-conversion -Wno-reserved-id-macro -Wno-format-pedantic -Wno-unused-command-line-argument -fcolor-diagnostics -Wno-expansion-to-defined -fdebug-prefix-map=\$PWD/= -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Werror=date-time -nostdlibinc -msoft-float -mfloat-abi=softfp -mfpu=neon -mcpu=cortex-a53 -mfpu=neon-fp-armv8 -D__ARM_FEATURE_LPAE=1 -target arm-linux-androideabi -Bprebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.9/arm-linux-androideabi/bin   -std=gnu99 -mthumb -Os -fomit-frame-pointer -fno-strict-aliasing   -DPN547C2=1 -DPN548C2=2 -DPN551=3 -DPN553=4 -DNFC_NXP_CHIP_TYPE=PN548C2 -DANDROID -DNXP_UICC_ENABLE -DNXP_HW_SELF_TEST -DNFC_NXP_HFO_SETTINGS=FALSE -fPIC -D_USING_LIBCXX -DANDROID_STRICT   -Werror=int-to-pointer-cast -Werror=pointer-to-int-cast -Werror=address-of-temporary -Werror=return-type -MD -MF out/target/product/bullhead/obj_arm/SHARED_LIBRARIES/nfc_nci.bullhead_intermediates/hal/phNxpNciHal.d -o out/target/product/bullhead/obj_arm/SHARED_LIBRARIES/nfc_nci.bullhead_intermediates/hal/phNxpNciHal.o system/nfc/halimpl/pn54x/hal/phNxpNciHal.c"
system/nfc/halimpl/pn54x/hal/phNxpNciHal.c:2637:22: error: no member named 'nci_data' in 'struct phNxpNciHal_Control'

  if (nxpncihal_ctrl.nci_data.nci_version == NCI_VERSION_2_0) {
      ~~~~~~~~~~~~~~ ^
1 error generated.
ninja: build stopped: subcommand failed.
10:02:33 ninja failed with: exit status 1
build/core/main.mk:21: recipe for target 'run_soong_ui' failed
make: *** [run_soong_ui] Error 1

#### make failed to build some targets (06:37 (mm:ss)) ####

What am I missing here? I have executed a repo sync in-case some files are missing, and a make clean.
Virtual machine stats:
    CPUs- 4-cores (Host: Intel Xeon E3-1575M : 8-cores)
    RAM - 20GB (Host: 32GB)
    HDD - 100GB

Build settings:
repo init -u https://android.googlesource.com/platform/manifest -b android-8.0.0_r33 --depth=1
...
lunch aosp_bullhead-userdebug

A: https://android.googlesource.com/platform/system/nfc/+/android-8.0.0_r33/halimpl/pn54x/hal/phNxpNciHal.c
File location: path_to_aosp_oreo/system/nfc/halimpl/pn54x/hal/phNxpNciHal.c
Line: 2637
https://android.googlesource.com/platform/system/nfc/+/android-8.0.0_r33/halimpl/pn54x/hal/phNxpNciHal.h
line: 66-101
There is not nci_data in typedef struct phNxpNciHal_Control only nci_info
I think that you must edit line 2637 from
  if (nxpncihal_ctrl.nci_data.nci_version == NCI_VERSION_2_0)

to
  if (nxpncihal_ctrl.nci_info.nci_version == NCI_VERSION_2_0)

Or change version to 8.1.0_r18 or higher
https://android.googlesource.com/platform/system/nfc/+/android-8.1.0_r18/halimpl/pn54x/hal/phNxpNciHal.c
in line: 2623
https://android.googlesource.com/platform/system/nfc/+/android-8.1.0_r18/halimpl/pn54x/hal/phNxpNciHal.h
in line: 66-101


text:
Q: Xamarin Navigation.PushAsync crashing within ItemSelected Im new to Xamarin , so please excuse my if this is an obvious one.
I created a navigation page , where the main page has a list. When an item is selected I was going to go to that page. Then able to return with the standard navigation way. The below is my main page . When the item is clicked the page is called with PushAsync(..). I see a blank screen with the return indicator in the top left. If I press on it, nothing happens  and doesnt go back to the main page. It just freezes, then a message indicating it inst responding. If I place the PushAsync() in the main body, then works fine (see in the below).
Thanks For your help
Scott.
One of the pages is simply as follows:
public partial class Page3:ContentPage
{
    public Page3()
    {
        InitializeComponent();
    }
}

xamal page:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="MultiList.Page3">
<Label Text="{Binding MainText}" VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage>

Main Page:
public partial class MainPage : ContentPage
{

   public MainPage()
    {
        InitializeComponent();

        var listView = new ListView
        {
            RowHeight = 40
        };

        listView.ItemsSource = new MainItem[] {
            new MainItem { Name = "Page 1" ,ID= Constants.FIRST_PAGE},
            new MainItem { Name = "Page 2" ,ID= Constants.SECOND_PAGE},
            new MainItem { Name = "Page 3" ,ID= Constants.THIRD_PAGE},
        };

        listView.ItemTemplate = new DataTemplate(typeof(TextCell));
        listView.ItemTemplate.SetBinding(TextCell.TextProperty, "Name");

        Content = new StackLayout
        {
            VerticalOptions = LayoutOptions.FillAndExpand,
            Children = { listView }
        };

         //Navigation.PushAsync(new Page2()); this works here as expected

        listView.ItemSelected += async (sender, e) => {
            var MainItem = (MainItem)e.SelectedItem;
            switch(MainItem.ID)
            {
                case Constants.FIRST_PAGE:
                                            await Navigation.PushAsync(new Page1());
                                            break;

                case Constants.SECOND_PAGE:
                                             await Navigation.PushAsync(new Page2());
                                            break;

                case Constants.THIRD_PAGE:  await Navigation.PushAsync(new Page3());
                                            break;
            }
            this.ClearValue(ListView.SelectedItemProperty);
            listView.SelectedItem = null;

        };

    }
}

}


text:
Q: Client validate in MVC 2 I'm very new in MVC 2,
Let say, I have a page with 1 text box and 2 input typed submit, "back" and "next".
I'm using client validation like this:
<script src="<%=Url.Content("~/Scripts/MicrosoftAjax.js")%>" type="text/javascript"/>
<script src="<%=Url.Content("~/Scripts/MicrosoftMvcAjax.js")%>" type="text/javascript"/>
<script src="<%=Url.Content("~/Scripts/MicrosoftMvcValidation.js")%>" type="text/javascript"/>
.
.
<% Html.EnableClientValidation(); %>
.
.
<input type="submit" name="btnBack" id="btnBack"/>
<input type="submit" name="btnNext" id="btnNext"/>

and validation rule used for that text box is
[StringLength(100, ErrorMessage="This field should be no longer than 100")]

My wish is that validation rules will be applied only when I click on Next button. And when I click on Back button, no validation error message will be displayed and form will be posted to server. Is it possible to do that? could you please tell me how?
My problem now is that when I click Back, validation rules are applied and prevent me from posting back to server.
Many thanks!


text:
Q: How can I use Gulp to show test coverage using gulp-mocha Please house, I have transpile my code from es6 to es5 using gulp as a task runner. I have done my coverage report with istanbul. It is not showing test coverage after setting it up. below is my code
import gulp from 'gulp';
import loadPlugins from 'gulp-load-plugins';
import path from 'path';
import mocha from 'gulp-mocha';
import exit from 'gulp-exit';
import coveralls from 'gulp-coveralls';
import cover from 'gulp-coverage';

Load the gulp plugins into the plugins variable
const plugins = loadPlugins();

gulp.task('tests', () => {
  gulp.src('./server/tests/*.js')
    .pipe(plugins.babel())
    .pipe(mocha())
    .pipe(exit());
 });

Compile all Babel Javascript into ES5 and place in dist folder
const paths = {
  js: ['./**/*.js', '!dist/**', '!node_modules/**']
};

Compile all Babel Javascript into ES5 and put it into the dist dir
gulp.task('babel', () =>
  gulp.src(paths.js, { base: '.' })
    .pipe(plugins.babel())
    .pipe(gulp.dest('dist'))
);

gulp.task('coverage', () => {
  gulp.src('server/test/**/*.js', { read: false })
    .pipe(cover.instrument({
     pattern: ['server/controllers/**/*.js'],
      debugDirectory: 'debug'
    }))
    .pipe(mocha())
    .pipe(cover.gather())
    .pipe(cover.format())
    .pipe(gulp.dest('reports'));
 });

gulp.task('coveralls', () => gulp.src('./coverage/lcov')
    .pipe(coveralls()));

Restart server with on every changes made to file
  gulp.task('nodemon', ['babel'], () =>
    plugins.nodemon({
    script: path.join('dist', 'index.js'),
    ignore: ['README.md', 'node_modules/**/*.js', 'dist/**/*.js'],
    ext: 'js',
    tasks: ['babel']
  })
);

gulp.task('test', ['tests']);
gulp.task('default', ['nodemon']);
gulp.task('production', ['babel']);

A: The following snippets walk through how I solved this issue with a little modification.
put the following code in you gulpfile
import gulp from 'gulp';
import loadPlugins from 'gulp-load-plugins';
import path from 'path';
import shell from 'gulp-shell';

// Load the gulp plugins into the `plugins` variable
const plugins = loadPlugins();

// Compile all Babel Javascript into ES5 and place in dist folder
const paths = {
  js: ['./**/*.js', '!dist/**', '!node_modules/**',
  '!./server/tests/**']
};

// Compile all Babel Javascript into ES5 and put it into the dist dir
gulp.task('babel', () =>
  gulp.src(paths.js, { base: '.' })
    .pipe(plugins.babel())
    .pipe(gulp.dest('dist'))
);

gulp.task('migrate', shell.task([
  'cross-env NODE_ENV=test sequelize db:migrate',
]));

gulp.task('coverage', shell.task([
  'cross-env NODE_ENV=test nyc mocha ./server/test/**/*.js',
]));

// Restart server with on every changes made to file
gulp.task('nodemon', ['babel'], () =>
  plugins.nodemon({
    script: path.join('dist', 'index.js'),
    ignore: ['README.md', 'node_modules/**/*.js', 'dist/**/*.js'],
    ext: 'js',
    tasks: ['babel']
  })
);

gulp.task('test', ['migrate', 'coverage']);
gulp.task('default', ['nodemon']);
gulp.task('production', ['babel']);

then go over to your package.json then add the following
"nyc": {
    "require": [
      "babel-register"
    ],
    "reporter": [
      "lcov",
      "text",
      "html"
    ],
    "sourceMap": false,
    "instrument": false,
    "exclude": [
      "the test file you want to exclude from coverage"
    ]
  }

absolutely done


text:
Q: Extract substring between two tokens. Second token could be missing Good day,
I need to extract portion of string which can looks like this:
"some_text MarkerA some_text_to_extract MarkerB some_text"
"some_text MarkerA some_text_to_extract"

I need to extract some_text_to_extract in both cases.
MarkerA, MarkerB - predefined text strings.
I tried this regexps, but with no luck:
".*\sMarkerA(.*)MarkerB.*" - does not work in case 2
".*\sMarkerA(.*)(?=MarkerB)?.*" - wrong result "some_text_to_extract MarkerB some_text"
".*\sMarkerA(.*)(?:MarkerB)?.*" - does not work at all

Could you please help me with this issue?

A: First, get rid of the .* at the beginning and the end; you don't need to match the whole string.  Then use alternation to match either the ending delimiter or the end of the string.
"MarkerA(.*?)(?:MarkerB|$)"

A: Try:
".*\sMarkerA(.*?)(?=$|MarkerB)"

Test code:
#!/usr/bin/env python

tests = [
        ("some_text MarkerA some_text_to_extract MarkerB some_text"," some_text_to_extract "),
        ("some_text MarkerA some_text_to_extract"," some_text_to_extract")
        ]

import re
reg = re.compile(r".*\sMarkerA(.*?)(?=$|MarkerB)")

for (input,expected) in tests:
    mo = reg.match(input)
    assert mo is not None
    print mo.group(1),expected
    assert mo.group(1) == expected

A: The
".*\sMarkerA(.*)"

Part of the regex will match everything after MarkerA not giving a change for MarkerB or anything else to match to match. The .* is being greedy, you can use the non greedy form of * , *? to give:
".*\sMarkerA(.*)(?=MarkerB)?.*"

You probably want not to capture the space before MarkerB so in that case use:
".*\sMarkerA(.*)(?=\sMarkerB)?.*"


text:
Q: Basic rule for diffraction I'm a high school student. I still don't understand the reflection, diffraction and refraction of light. It seems to me that in concept of quantum physics, reflection is just a process of object absorbing and reemiting light at a particular angle. What really is diffraction? Is it the behavior of light propagating over an obstacle? How big is the obstacle? I remember in the double slit experiment that if the slit is too big, the light will just go through it. The width of the slit must be smaller than the wavelength? Why wavelength? It seems to me that, in a simple model of wave propagating forward, the amplitude will affect whether it can go through the slit or not.

A: You should read this page :http://en.wikipedia.org/wiki/Huygens%E2%80%93Fresnel_principle
The Huygens principle explain intuitively why the wave will spread after being "cutoff" by an obstacle, as the spherical sources at the edge will not interfere anymore with the adjacent ones (those being stopped by the obstacle) to form a plane wave.
As shown in the figure in the link, this principle also explain refraction.
The diffraction by a slit can also be explained as an effect of the uncertainty principle (velocity-position): when the photon passes through the slit, its position in along the slit direction (vertical if you look at the figure in Rnr1410 answer) is known more precisely (the uncertainty on its position is reduced). So, in virtue of the uncertainty principle the velocity along the same direction will be increased. Before the slit, the velocity along the slit dimension was zero (assuming perpendicular incidence), after the slit it could be 0 plus or minus some vertical component : the photon will thus appear on the screen at a position higher or lower thatn the slit's "shadow".
If this is done with many individual photons (one by one) the overall distribution of the photon on the screen will reproduced the interference pattern, see http://en.wikipedia.org/wiki/Double-slit_experiment#Variations_of_the_experiment

A: diffraction only occurs when the width of the slit is less then wavelength λ  of the source. we can prove this in lay-man terms also.explainationeach photon ( light-particle ) will be assumed as a wave too.so imagine you cut the slits into infinitely many slits, which were placed side-by-side. then each slit acts as a souce of light. each slit makes amplitude waves on the screen. if the width of all the slits is more than λ , then the sumation of all the waves on the screen is made analogous to what is guessed by classical physics. but if the slit width is small, then the quantum mechanics comes into dominance.Note: if the width is big, light is approximated as falling only on center, but not exactly.
see superposition of waves - wikipedia


text:
Q: Posting data from webpage using JavaScript PHP jQuery to Google Sheet Before you say this is a duplicate, hear me out. I followed this answer (jQuery Ajax POST example with PHP), but I am trying to send the data to a Google Sheet. I have already got the code working on the Google Sheet, as I can add data to it by running my code directly from the sheet.
However, getting it to work with my webpage is apparently the problem. Even though I have followed the answer to the question I posted above, I think there is something more at play here that has to do with my lack of experience working in this area.
The code below is to a floating footer and is contained within the code of the whole webpage (where jquery-1.11.0.min.js and jquery-migrate-1.2.1.min.js have already been called). When I click on the submit button, the page looks like it processes the request, but nothing ever appears on the Google Sheet, Sheet1 (https://docs.google.com/spreadsheets/d/19l2kSHdBKEWtIFX44FxLBdvCoKjy7VqPF4IW6C1xAZc/edit?usp=sharing).
#document

Newsletter

      <form id="floater_footer" class="validate subscribe_form">

          <input type="text" class="form-control subscribe_mail" id="bar" name="bar" value="" placeholder="email address" required />

          <input type="submit" value="Subscribe" class="subscr_btn subscribe_btn" />

      </form>

Any suggestions on what could be going wrong? I am quite inexperienced when it comes to web development, as compared to most on this site. So I'm sure it's something simple I am missing!

A: I don't completely understand why it worked, but taking out the script and putting it in the head of the page HTML seemed to work! Perhaps this was because having the script come after the elements was an issue, or perhaps having a $(document).ready() inside of an HTML that was inside the page's main HTML caused issue, or perhaps it was something else! No matter which one it is, the following solved the problem.
Up at the top of the code in the head of the page's HTML (but after the jQuery.js files were declared), I placed the script you saw already, but with some cosmetic changes. I'll put it here in the event I did indeed change something important that I didn't realize. I will also show the two jQuery files I included before the script:

Further down into the body of the HTML was this code where my footer was to be placed:
    #document

Newsletter

      <form id="floater_footer" class="validate subscribe_form">

          <input type="text" class="form-control subscribe_mail" id="email1" name="emailSignup" value="" placeholder="email address" required />

          <input type="submit" value="Subscribe" class="subscr_btn subscribe_btn" />

      </form>

Hopefully that will help somebody that has this problem in the future. You may see a reason this worked that I do not.
Big thanks to Jay Blanchard for making me question if my script was even triggering at all, which inspired me to pull the script out and put it somewhere else! The script almost certainly wasn't firing at all, and was the root of the problem. But WHY that was, I don't know. But I hope this helps someone else!


text:
Q: Format a date from itemStyle.xml file I want to print date like
Tuesday,17 February,2015

I tried somethings that print dates like
Tuesday,17 February 2015
Tuesday, February 17, 2015

What I tried is:

How can I print date like Tuesday,5 April,2016?

A: I resolved this issue by making changes in date format as below
<xsl:value-of select="ddwrt:FormatDateTime(string(@EventDate),3081,'dddd,d MMMM,yyyy')"/>

A: You can use below mentioned line to get your desired output.
<xsl:value-of select="ddwrt:FormatDateTime(string(@EventDate), 1033, 'dddd, mmmm d, yyyy')" />


text:
Q: Overlay sidepanel inside div, not fixed On the page there is a container (header above it, nav to the left). It contains a grid.
On grid selection i want to show a sidepanel (on the right side, that shows up).
I cannot use fixed position - it should be inside that container AND scroll when body is scrolled.
It cannot be absolute position because it would ignore flexbox height and would not grow to fit the page and would break responsive height.
The sidepanel should overlay on top of the grid not push it to the side whe nit appears.
The panel would have roughly similar layout (flexbox):

No jQuery. It is a purely Angular 4 project.

A: By using a combination of relative and absolute with flex, i managed to add the sidebar inside the container and to the right plus allowing it to overlay the content when visible.
html:

    <ng-sidebar-container>
        <ng-sidebar>
        </ng-sidebar>
    </ng-sidebar-container>

css:
.main-wrapper {
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    -webkit-flex-direction: row;
    flex-direction: row;
    height: 100%;
    position: relative;
}
ng-sidebar-container {
    height: 100%;
    right: 0;
    display: block;
    position: relative;
}
.ng-sidebar {
    position: absolute;
}


text:
Q: Sharing data between two independent Windows applications in C# I have two applications that use my clients database(s), but have no mutual dependency. The problem is that I need to make an application for configuration in which the administrator could set the parameters. For instance which database to which the two applications connect and some other parameters, mostly string and numerical. These parameters must affect both applications.
The first solution that I thought of is to make a configuration file in which I could store the data and the applications would read that file on startup. The problem with this approach is that it is not very safe (even if I encrypt the data in the file).
Is there a way to send data from one application to the other, assuming that each application is created as an individual project?

A: You can use Memory-Mapped Files
You can use it as a file, and access from different executables.
Build your own class for interfacing with it.
Tutorials:
Programming Memory-Mapped Files with the .NET Framework
Working with memory mapped files in .NET 4

A: or you can even use named pipe :
http://www.eggheadcafe.com/articles/20060404.asp
Or make communication with socket.
You have a plenty of solution.
If you need more details, feel free to ask.
Best regards,
Sylvain.


text:
Q: How to remove duplicate br tag that exceeds a number of occurences? I want to keep no more than 2
 for each paragraph
string html = @"paragraph 1 a dkahdk ahkdhadk.

paragraph 2  adshkad hkasdhkasdh.

paragraph 3 akdash dkjahiewry iwery.

paragraph 4 ljsdlfjsldfj.

";

HtmlAgilityPack.HtmlDocument doc = new HtmlDocument();

doc.LoadHtml(html);
var xpath = "//text()[not(normalize-space())]";
var emptyNodes = doc.DocumentNode.SelectNodes(xpath);
foreach (HtmlNode emptyNode in emptyNodes)
{
    emptyNode.Remove(); // remove  \r\n
}
var nodes = doc.DocumentNode.SelectNodes("//br[following-sibling::br[3]]").ToList();
foreach (var node in nodes)
{
    node.Remove();
}

The output is somehow it removes all br.  The right output should be
paragraph 1 a dkahdk ahkdhadk.

paragraph 2  adshkad hkasdhkasdh.

paragraph 3 akdash dkjahiewry iwery.

paragraph 4 ljsdlfjsldfj.

A: A simple regex replace would suffice, as opposed to using HtmlAgilityPack. For example, using a multi-step process:
//use regex to find
,
 or
 tags:
//var toNewLines = new Regex( @"
" );
//var onlyNewLines = toNewLines.Replace(html, Environment.NewLine);
//or, since all br tags are
:
var onlyNewLines = html.Replace("
", Environment.NewLine);

var regex = new Regex( @"([" + Environment.NewLine + "\t])+" );

var result = regex.Replace(onlyNewLines, Environment.NewLine);

var finalResult = result.Replace(Environment.NewLine, "

" + Environment.NewLine);


text:
Q: Fastest way to do PCA in MATLAB for very high dimensional data (princomp too slow) I am trying to find the principal components of very high dimensional data (~20,000). The princomp function that comes with MATLAB takes way too long (~10 seconds) to compute. I was wondering if there are faster ways to do this. I have been looking for mex implementations of this algorithm with no luck so far.
Thanks

A: Try to use just the instructions that you want to calculate PCA, for example:
[V E] = eig(cov(X));
[E S] = sort(diag(E),'descend');
V = V(:,S);


text:
Q: Tensorflow gradient of loss with respect to model output gives None I'm trying to differentiate my loss function with respect to the model output in the training_step function of a tf.keras.Model. This is my attempt:
    def train_step(self, data):
        x, y = data
        with tf.GradientTape(persistent=True) as tape1:
            y_pred, dense_out = self(x, training=True)
            with tf.GradientTape() as tape2:
                tape2.watch(y_pred)
                loss = self.compiled_loss(y, y_pred)
        dy = tape2.gradient(loss, y_pred)

I would use tape1 for gradients I need later. First of all, dy gives None, how can I fix this? Secondly, is it allowed to return two output values when training=True in the  call-method of my model and only one when training=False? Even if I don't do this dy is None?
Edit: If I do the following outside the train_step function, It does give a result different from None:
    with tf.GradientTape() as tape:
        y_pred, dense_out = model(x_train, training=True)
        loss = loss_fn(y_train, y_pred)
    print(tape.gradient(loss, y_pred))


text:
Q: Android своя клавиатура в альбомной ориентации сдвигает экран, как исправить При долгом нажатии на выделенный текст ограничители-курсоры всплывают в нежелательном месте. В чем может быть проблема?

Добавлю разметку
<EditText
        android:id="@+id/et_uname"
        android:layout_width="775dp"
        android:layout_height="50dp"
        android:background="@drawable/box_shadow"
        android:ems="23"
        android:inputType="text"
        android:paddingLeft="6dp"
        android:textColor="@color/label"
        android:textSize="23sp"
        android:cursorVisible="true"
        android:textCursorDrawable="@null"
        android:imeOptions="flagNoExtractUi"
        >

Выяснила интересный факт - на андроиде 4.2.2 планшета Ирбис реагирует, как описано выше. Тестирую на своих ЛыЖах (5.0.2) ту же кастомную клавиатуру - все пучком, реагирует адекватно.Теперь я в тупике :(
UPD: выяснила, что этот баг появляется в ландшафтной ориентации. В портретной все как надо - выплывает копи паст бар, выделение никуда не смещается.
UPD: вывод: моя клавиатура сдвигает в альбомной ориентации эту панельку, получается, некорректно видит размеры экрана. Какие мысли на этот счет?

A: Итак. Проблема в полноэкранном режиме клавиатуры, который стоит по умолчанию в альбомной ориентации. В классе extends InpetMethodService переписала метод
 @Override
public boolean onEvaluateFullscreenMode() {
    DisplayMetrics dm = getResources().getDisplayMetrics();
    float displayHeight = dm.heightPixels;
    // If the display is more than X inches high, don't go to fullscreen
    // mode
    float dimen = getResources().getDimension(
            R.dimen.max_height_for_fullscreen);
    if (displayHeight > dimen) {
        return false;
    } else {
        return super.onEvaluateFullscreenMode();
    }
}

В @Override onStartInputView() на всякий случай вызвала updateFullscreenMode(); При таком раскладе на планшете свои клавиатура работает аналогично стандартной - является панель копирования-вставки, адекватно выделяется слово, без сдвигов, как на скрине.


text:
Q: Emacs24 won't download marmalade-repo.org archive Installed emacs-snapshot from this debian repo. Added in my init.el:
(add-to-list 'package-archives
             '("marmalade" . "http://marmalade-repo.org/packages/"))
(package-initialize)

When I M-x package-refresh-contents it hangs for about 2 minutes with the message:
Contacting host: marmalade-repo.org:80

Then times-out with the message:
Failed to download `marmalade' archive.

As I can see with tcpdump, package lists are actually fetched. Unsure why the error occurs. Tried installing the package.el provided at the Marmalade page, no luck.

A: The Marmalade archive is back up now.


text:
Q: RecyclerView make endless scrolling with JSON I'm trying to make my Android App (I'm only experienced in iOS).
I created a RecyclerView that gets the data from a web. I tried everything to implement endless scrolling to load more items, but when I call the function to get the items, the entire RecyclerView loads again and no attach the new results on the bottom.
This is my code:
ConversationUser.kt
 data class ConversationUser(
     val message_nickname: String,
     val message_image_thumb: String,
     val message_large_thumb: String,
     val message_modified: String,
     val message_status: String,
     val message_unread: Int,
     val conv_id: String,
     val message_dest: String) {
 }

ConversacionesActivity.kt
class ConversacionesActivity : AppCompatActivity() {

// MARK: Variables

var user_token = ""
var user_id = ""

override fun onCreate(savedInstanceState: Bundle?) {

    // User Defaults

    val sharedPreferences = getSharedPreferences("Preferences", Context.MODE_PRIVATE)
    user_token = sharedPreferences.getString("user_token", "")!!
    user_id = sharedPreferences.getString("user_id", "")!!

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_conversaciones)

    recyclerConv.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL))

    getConversationsData()

    recyclerConv.setLoadingListener(object : LoadingListener {
        override fun onRefresh() {
            //refresh data here

        }

        override fun onLoadMore() {
            // load more data here
            getConversationsData()

        }
    })
}

fun getConversationsData() {

    val httpAsync = "https://mywebsite.com/conversations/${user_token}"
        .httpPost()
        .responseString { request, response, result ->
            when (result) {
                is Result.Failure -> {
                    val ex = result.getException()
                    println(ex)
                }
                is Result.Success -> {
                    val data = result.get()
                    runOnUiThread {
                        val conversaciones = processJson(data)
                        show(conversaciones)

                        return@runOnUiThread
                    }
                }
            }
        }

    httpAsync.join()

}

fun processJson(json: String): List<ConversationUser> {
    val gson: Gson = GsonBuilder().create()
    val conversaciones: List<ConversationUser> = gson.fromJson(
        json,
        Array<ConversationUser>::class.java
    ).toList()

    return conversaciones
}

fun show(conversaciones: List<ConversationUser>) {
    recyclerConv.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
    recyclerConv.adapter = AdaptadorConv(conversaciones, this, user_token, user_id)

}

AdaptadorConv.kt
class AdaptadorConv(
val conversaciones: List<ConversationUser> = ArrayList(),
val context: Context,
val user_token: String,
val user_id: String) : RecyclerView.Adapter<AdaptadorConv.ConvViewHolder>() {

override fun onBindViewHolder(holder: ConvViewHolder, position: Int) {

    holder.convName.text = conversaciones[position].message_nickname

    holder.convTime.text = conversaciones[position].message_modified

}

override fun getItemCount(): Int {
    return conversaciones.size - 1
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ConvViewHolder {
    val view: View = LayoutInflater.from(parent.context).inflate(
        R.layout.conversaciones,
        parent,
        false
    )
    return ConvViewHolder(view)
}

class ConvViewHolder(vista: View): RecyclerView.ViewHolder(vista) {

    val convImg: ImageView = itemView.findViewById(R.id.convImg)
    val convStatus: ImageView = itemView.findViewById(R.id.convStatus)
    val convName: TextView = itemView.findViewById(R.id.convName)
    val convUnread: TextView = itemView.findViewById(R.id.convUnread)
    val convTime: TextView = itemView.findViewById(R.id.convTime)

}

Thanks for any help or hint.

A: Please check your show () method, you are creating new Adapter every time with the new dataset. You have to append the new items to the adapter's list and adapter should be set to list once. Helpful tutorial can be found at here.


text:
Q: Can Oracle SQL*Loader check for extra delimiters? From tests done, it seems that loading does not fail if the file contains extra delimiters.
Let say I have a control file with 3 columns a,b,c as follows
LOAD DATA
TRUNCATE INTO TABLE test
FIELDS TERMINATED BY "|"  trailing nullcols
(
a,
b,
c
)

But the file contains extra delimiters in some of the rows. As example:
1|2|3
4|5|6
7|8|9|10
11|12|13

In the above example, row 3 contains an extra delimiter but loading is successful and the last value (10) is not loaded.
Can you specify some option in the control file to treat row 3 as bad or discard?
Validations of the input file can be done prior to loading but wanted to check if the loader itself supports such feature.


text:
Q: Python from matrix to simple text file I would like to ask you how to change file looks like this:
 123 111 1
 146 204 2
 178 398 1
 ...
 ...

First column is x, second is y and the third mean the number in each square.
My matrix is 400x400 dimension. I would like to change it to the simple file
M file doesn't posses every square (for example 0 0 doesn't exist which mean that in output file i would like to have 0 in first row in first place.
My output file should look like this
 0 0 1 0 0 0 1 0 7 9 3 0 2 0 ...
 8 0 0 1 0 0 0 0 0 0 0 0 0 0 ...
 7 8 9 0 7 5 0 0 3 2 4 5 5 7 ...
 ...
 ...

How can I change my file?
From first file i would like to reah second file. Like text file with 400lines each 400 characters splited by " " (blankspace).

A: Just initialize your matrix as as a list of list of zeros, and then iterate the lines in the file and set the values in the matrix accordingly. Cells that are not in the file will remain unchanged.
matrix = [[0 for i in range(400)] for k in range(400)]
with open("filename") as data:
    for row in data:
        (x, y, n) = map(int, row.split())
        matrix[x][y] = n

Finally, write that matrix to another file:
with open("outfile", "w") as outfile:
    for row in matrix:
        outfile.write(" ".join(map(str, row)) + "\n")

You could also use numpy:
matrix = numpy.zeros((4,4), dtype=numpy.int8)


text:
Q: consequences of the periodicity of a function $f(t, x)$ for the accompanying differential equation $\dot{x} = f(t, x)$ Consider a (continuous) function $f: \mathbb{R}^2 \to \mathbb{R}$ that is $p$-periodic in the first variable, meaning that $f(t + p, x) = f(t, x)$ for all $t, x \in \mathbb{R}$, with p > 0.
First, I want to find out what consequences this does have for the slope field of the differential equation $\dot{x} = f(t, x)$. Based on that, I want to make an educated assumption about what this indicates about the solution of the differential equation $\dot{x}(t) = f(t, x(t))$, and want to verify (or discard) this assumption.
To the first part: the slope field consists of vectors of the shape $\pmatrix{1 \\ f(t, x)}$ being placed at the point $(t, x) \in \mathbb{R}^2$. Therefore, in case that $f(t + p, x) = f(t, x)$, we have that $\pmatrix{1 \\ f(t + p, x)} = \pmatrix{1 \\ f(t, x)}$ for all $x, t \in \mathbb{R}$. Hence, the slope field is $p$-periodic along the $t$-axis. So far, so good.
But with the second part, I've had trouble so far. My first guess was that the solutions would have to be $p$-periodic, but I've quickly come to the conclusion that this assumption doesn't hold: if we consider the function $f(t, x) = x - sin(t)$, altogether with the differential equation $\dot{x}(t) = x(t) - sin(t)$, then the solutions of this equation have the shape $x(t) = c e^t + \frac{sin(t)}{2} + \frac{cos(t)}{2}, c \in \mathbb{R}$ (according to WolframAlpha), which aren't periodic (unless $c = 0$). Therefore, this guess about the periodicity is apparently wrong.
My second guess would be that if there's a solution $x_1: (a, b) \to \mathbb{R}$, that we could conclude the existence of another solution $x_2: (a + p, b + p) \to \mathbb{R}, t \mapsto x_1(t - p)$ or something along that lines. But this guess seems to be wrong aswell, if we again consider the counterexample $f(t, x) = x - sin(t)$.
Therefore, I'm rather confused on what exactly I am to "guess" and to verify about the solution. What exactly can we deduce about the solution of the differential equation, based on the periodicity of the slope field or of $f$? Is there something totally obvious that I'm missing? Or is there anything wrong about my counterexamples?

A: There is something you can say: if $x(t)$ is a solution, so is $x(t+p)$. I do not think that anything more can be said in the general case. For particular cases you might be able to say something. For example consider the case $f(t,x)=P(t)\,g(x)$, where $P$ is periodic and $\int_0^pP(t)\,dt=0$.


text:
Q: OpenCV || matchShapes findContours assertion failed I am trying to match two contours with the matchShapes method but I always get assertion failed.
I know this must have something to do with the wrong Mat format but I can't seem to be able to solve it.
The findContours is working very well:
vector<vector<cv::Point> > contours;
cv::findContours(incomingimage,
                 contours,
                 CV_RETR_EXTERNAL,
                 CV_CHAIN_APPROX_SIMPLE);

vector<vector<cv::Point> > contourstwo;
cv::findContours(incomingimagetwo,
                 contourstwo,
                 CV_RETR_EXTERNAL,
                 CV_CHAIN_APPROX_SIMPLE);

I get good output from these methods but then
matchShapes(Mat(contours), Mat(contourstwo), CV_CONTOURS_MATCH_I3, 0);

returns
OpenCV Error: Assertion failed
I am a bit in the dark here.
Any help would be highly appreciated.
Thank you very much.

A: I'm also beginner at openCV, but I just figure out how to solve this today
(after many trial and error).
Please try this one
matchShapes(contours[0], contourstwo[0], CV_CONTOURS_MATCH_I3, 0);

A: The input to matchShapes according to the documentation should be of the type vector<Point> and not vector<vector<Point> >, as is the output of findContours, just iterate over each contour and pass it to matchShapes.


text:
Q: How do I simulate the Salesforce Mobile App in Chrome's Dev Console? It used to be that we could open up the Chrome Developer Console, then hit refresh, and it would essentially pull up the Salesforce1 app.
However, we think with the Summer 20 release, we aren't able to get it to flip to the mobile app when we refresh. It instead flips to the Classic version. Does anyone know if this was changed and if there's a workaround?

A: Yes, you're right. Salesforce retired the mobile web experience with the Summer '20 release. You can read the Knowledge Article here.
As per now I do not think that you are able to test your developments emulating the mobile app on Chrome, even though they said that simulator builds of the Salesforce mobile app would be available to download.
Best regards!


text:
Q: ng-click function inside controller does not work I'm trying to make a three tab app using routeProvider ng-view and 3 controllers. I've made one main HTML page and 3 tab HTML pages. Switching tabs works OK and I can access variables inside tab one; however, I cant access the functions declared inside the controller. Where is the problem?
<!doctype html>

    <meta charset="utf-8">
    <title>Tabs</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="css/bootstrap-responsive.css" rel="stylesheet">
    <link href="css/app.css" rel="stylesheet">

            Tab1

            Tab2

            Tab3

This is the JavaScript code:
angular.module('project',[]).
    config(function($routeProvider) {
        $routeProvider.
            when('/', {controller:Ctrl1, templateUrl:'tbb_1.html'}).
            when('/tab1', {controller:Ctrl1, templateUrl:'tbb_1.html'}).
            when('/tab2', {controller:Ctrl2, templateUrl:'tbb_2.html'}).
            when('/tab3', {controller:Ctrl3, templateUrl:'tbb_3.html'}).
            otherwise({redirectTo:'/'});
    })
    .run( function($rootScope, $location) {

        $rootScope.var1=1;
        //alert($rootScope.var1);
        // register listener to watch route changes
        $rootScope.$on( "$routeChangeStart", function(event, next, current) {
                //alert('change');

        });
    });

function Ctrl1($scope,$rootScope) {

$scope.var2=$rootScope.var1;

function dodo1(){
    alert('23');
}

$rootScope.$on('$routeChangeStart', function(event, next, current) {
        //alert('change inside ctrl');
    //alert(form.supervisor.$dirty);
    });

}

function Ctrl2($scope,$rootScope) {
}

function Ctrl3($scope,$rootScope) {
}

tbb_1.html

tab1

{{2+2}}

|{{var1}}|

|{{form.var1.$dirty}}|
property
dodo
<button class="btn btn-mini" ng-click="dodo1()">buu</button>
<form class="form-horizontal" novalidate name="form" ng-submit="submit()">
    <fieldset>
    <input id="var1" name="var1" placeholder="" class="input"
               type="text" ng-model="var1">
    </fieldset>
</form>

Why does clicking dodo and the button do nothing?

A: Just attach your dodo1 method to the $scope , like this:
$scope.dodo1 = function(){
    alert('23');
}

Working plnkr: http://plnkr.co/edit/glyGT6?p=preview
Otherwise it will be scope' "private" function.


text:
Q: Why does one code produce a memory leak and the other doesn't? Why does this code produce a memory leak? I'm a newbie and don't understand it. The object gets assigned to the shared_ptr so it's still accessible or not? I need to create the new instance in another function so I can't think of another way to do that. Is there anything I need to fix?
std::shared_ptr<MyClass>newItem(getNewMyClassInstance());

MyClass* MyClass::getNewMyClassInstance()
{
    return new MyClass();
}

Also what is the difference between the above mentioned code and
std::shared_ptr<MyClass>newItem(new MyClass());

regarding memory leaks?

A: There is a subtle difference.
Whenever the constructor of MyClass throws, new MyClass(); does not produce any memory leak since the storage allocated for MyClass is automatically freed by new when an exception is thrown. In the snippets displayed in your question, none of the forms lead to memory leak.
But, if one would expand the definition of getNewMyClassInstance() in such a way than an exception is thrown at scope exit, your first form does lead to memory leak:
MyClass* MyClass::getNewMyClassInstance()
{
    ThrowsWhenDestructed t;
    return new MyClass();
}

std::shared_ptr<MyClass>newItem(getNewMyClassInstance());
// MyClass pointer is not acquired, and lost to oblivion.

With this form (a raw pointer returned by a function and then acquired by a smart pointer), there is a small gap where memory could be lost. Almost always this is not an issue, but it might be for you.
As an alternative, why won't you define:
std::shared_ptr<MyClass> MyClass::getNewMyClassInstance()
{
    return std::make_shared<MyClass>();
}

A: The point I suspect that someone is making is that by returning the shared pointer, you ensure that the pointer is always wrapped by a smart pointer.  By returning a naked pointer; this guarantee is lost; and thus leaves it more open to accidental leaks; ie
 { getNewMyClassInstance()->doStuff() }

will leak in one case; but not in the other.
However; the example usage you posted will not leak.

A: Actually your code does not produce any memory leak. But to answer your second question:

*

*in the first form, it can produce a memory leak if you don't pay attention on the returned value of getNewMyClassInstance(). I mean you return a raw pointer then the caller may forget to free it correctly. You can return a shared pointer to have a better code.

*the first form is more like using a factory, which leads to more degree of freedom in the way instances are created.

A: Neither of these pieces of code creates a memory leak.
You have nothing to "fix".


text:
Q: Cygwin bash calls adb with awk does not see dollar sign $ I am running a bash script under windows cygwin.
Important note:
I run the bash script from a command.exe window like:
bash.exe myscript.sh
The script will do an adb shell and ps/awk/kill a process.  The android is rooted.  The script below works except for the awk part.  It seems that something about running this under window makes the dollar sign in $2 invalid.  So the last awk part does not work.  Help!
#!/bin/bash     -x
C:/scripts/adb.exe shell << EOF
su
ls
ps  | grep "myapp" | echo  awk '{print $2}'
EOF

The output I get from this script:
# awk {print }

A: You will have to do something like this
ps  | grep "myapp" | awk '{print $2}'

awk utility takes input from a pipe or from a file. When you do echo followed by command, shell interprets it as plain text.

A: When using a here-file, all $var are evalutated by the shell as part of processing.
I think you can fix this, just by escaping any '$'s (that are for variables or shell parms, et), with the '\' char, i.e. '\$2', and for your case it would be
Edit: Your code has an extra word in it, 'echo', I've removed that from the solutions below.
#!/bin/bash     -x
C:/scripts/adb.exe shell << EOF
su
ls
ps  | grep "myapp" | awk '{print \$2}'
EOF

Or you can 'quote' the whole here-file by quoting the EOF, i.e.
#!/bin/bash     -x
C:/scripts/adb.exe shell <<'EOF'
su
ls
ps  | grep "myapp" | awk '{print $2}'
EOF

Note that the closing EOF should not be quoted.
I hope this helps.
P.S. Welcome to StackOverflow (S.O.) Please remeber to read the FAQs, http://tinyurl.com/2vycnvr , vote for good Q/A  by using the gray triangles,  http://i.imgur.com/kygEP.png , and to accept the answer that bes solves your problem, if any, by pressing the checkmark sign , http://i.imgur.com/uqJeW.png


text:
Q: Recognising that $\sum_{n=0}^\infty \frac{a^2-b^2(2n+1)^2}{(a^2+b^2(2n+1)^2)^2}=-\frac{\pi^2\mathrm{sech}^2\left(\frac{a\pi}{2b}\right)}{8b^2}$ So I know from Mathematica that:
$$\sum_{n=0}^\infty \frac{a^2-b^2(2n+1)^2}{(a^2+b^2(2n+1)^2)^2}=-\frac{\pi^2\mathrm{sech}^2\left(\frac{a\pi}{2b}\right)}{8b^2}$$
I am wondering how someone could come up with this answer logically without having to plug it into a computer. What kind of thought processes could you follow, upon seeing the sum on the left, to try and get a closed form expression?

A: As Semiclassical noted, you look at
$$ \sum_{n=0}^\infty \dfrac{r^2 - (2n+1)^2}{(r^2 + (2n+1)^2)^2} $$
Expand the summand in partial fractions:
$$ \dfrac{r^2 - (2n+1)^2}{(r^2 + (2n+1)^2)^2} ={\frac {2 {r}^{2}}{ \left( r^2 + (2n+1)^2 \right) ^{2}}} - \dfrac{1}{ r^2 + (2n+1)^2 }$$
First deal with the term on the right:
$$ F(r) = \sum_{n=0}^\infty \dfrac{1}{r^2 + (2n+1)^2}$$
Let $$G(r) = \sum_{k=1}^\infty \dfrac{1}{r^2 + k^2} $$
so that $F(r)$ consists of the terms of $G(r)$ for odd $k$.  But since
$$\dfrac{1}{r^2 + (2n)^2} = \dfrac{1}{4} \dfrac{1}{(r/2)^2 + n^2}$$
we have
$$G(r) = F(r) + \dfrac{1}{4} G(r/2)$$
Now it is a ``well-known'' identity that
$$ \pi \cot(\pi z) = \dfrac{1}{z} + \sum_{n=1}^\infty \dfrac{2z}{z^2 - n^2}
=  \dfrac{1}{z} - 2 z G(iz) $$
and this leads to
$$ F(r) = \dfrac{\pi \coth(\pi r)}{2r} - \dfrac{\pi \coth(\pi r/2)}{4r} $$
which can be simplified to
$$ F(r) = \dfrac{\pi \tanh(\pi r/2)}{4r}$$
Now note that $$\dfrac{d}{dr} \dfrac{1}{r^2 + (2n+1)^2} = \dfrac{-2r}{\left(r^2+(2n+1)^2\right)^2}$$
so your sum is
$$ - \dfrac{\pi \tanh(\pi r/2)}{4r} - r \dfrac{d}{dr} \dfrac{\pi \tanh(\pi r/2)}{4r}$$
which should simplify to
$$ - \dfrac{\pi^2 \text{sech}^2(\pi r/2)}{8} $$


text:
Q: Website images recently disappeared I have a php file, and I am fairly novice at website development, but I've been helping a friend out.  On the site we had some images that have been there for months, and recently they disappeared.  I know the path to the images is still correct, and nothing with the coding has changed.  Any ideas on why this could be broken? The pictures were in the div class = "graphicbuttons_cont"
$poli_more = do_shortcode('[pl_modal title="Buy & Sell" type="tab_links" label="
Buy & Sell"]{27}[/pl_modal]');
        $feed_back = do_shortcode('[pl_modal title="Feedback" type="tab_links" label="
Feedback"][gravityform id=4 title=false ajax=true field_values=\'store_page_id={28}\'][/pl_modal]');
        $email_list = do_shortcode('[pl_modal title="email list" label="
email list"][gravityform id=1 title=false][/pl_modal]');
        $desc_template = '
' .
                            '
' .
                                'Game on {0}' .
                            '
' .
                        '
' .

                        '
' .
                            '' .
                        '
' .

                        '
' .
                            '
' .
                                $poli_more.
                            '
' .
                            '
' .
                                '

Directions
                                ' .
                            '
' .
                            '
' .
                                '

Follow
                                ' .
                            '
' .
                            '
' .
                                $email_list.
                            '
' .
                            '
' .
                                '

Review
                                ' .
                            '
' .
                            '
' .
                                $feed_back.
                            '
' .
                        '
' .

Here's the style.css page,
#main_container {
padding: 30px;
background: #f1f1ef;
margin-top: -15px;
margin-bottom: 20px;
}
#store_image_container {
float: left;
width: 33%;
}
#gen_info_container {
float: left;
width: 61%;
margin-left: 60px;
}

#header_container h1 {
text-transform: uppercase;
float: left;
line-height: 32px;
font-size: 24px;
color: #ffffff;
padding-left: 10px;
}

#header_container {
background-color: #474647;
padding: 5px;
height: 32px;
margin-top: 20px;
}
#store_image_container img {
margin-bottom: 20px;

}
#data_gen_info {
margin-bottom: 22px;
clear: both;
}
#label_gen_info,  .social-icon a {
font-size: 12px;
color: #37a8ab;
}
#label_notefrmowner {
font-size: 22px;
color: #B98BBF;
}
#data_notefrmowner {
    margin-bottom: 30px;
}
#data_gen_info div table, #data_notefrmowner div table {
border: 0px;
}
#data_gen_info div table tr td, #data_notefrmowner div table tr td {
border: 0px;
}
#map_slideout {
display: none;
height: 410px;
}
#menu_cont {
float: right;
margin-right: 20px;
line-height: 32px;
}
#slider_button {
z-index: 1035;
height: 20px;
}
 #click_btn {
background: url("viewstorelocator.png") no-repeat scroll 0 0 transparent;
padding: 0 196px 30px 0;
position: absolute;
right: 15px;
top: 0;
}
.tab_links, .tab_links:hover {
color: #ffffff;
margin: 0 10px 0 10px;
font-size: 12px;
text-transform: uppercase;
background-color: transparent;
text-shadow: 0 0 0 transparent;     display: inline-block;
}
#sl_div img {
max-width: none;
}
#directionurl {
background: #37A8AB;
color: #ffffff;
box-shadow: none;
text-shadow: none;
border: 0px;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
padding: 4px 10px;
font-size: 12px;
}

.social-icon {
float: left;
    margin-right: 10px;
width: 31%;
}
.social-icon a {
color: #37A8AB;
}
.social-icon span {
display: inline-block;
width: 100%;
text-transform: uppercase;
}
.social-icon .social-icon-inner {
height: 130px;
}

.store_banner_class{
width: 100%;
overflow: hidden;
}

.banner_img{
height: 330px;
width: 100%;
}

.graphicbuttons_area{
background: none repeat scroll 0 0 #F1F1EF;
padding: 20px 0px;
text-align: center;
}

.graphicbuttons_cont{
display: inline-block;
margin: 0 15px;
}

.graphicbuttons_cont span{
color: #37A8AB;
font-family: "Montserrat";
font-size: 14px;
text-transform: uppercase;

A: This has nothing to do with your CSS and everything to do with your image locations...your urls in your php code are /wp-content/uploads/2013/02/fblikeus_icon.png and the url being printed in your live site are /portugal/wp-content/uploads/2013/02/fblikeus_icon.png
I would suggest figuring out why there is a discrepancy there.  When I take /portugal/ out of your paths in Chrome's dev tools...your images show up fine.


text:
Q: Sql Server OPENJSON returns unicode string I have issue with SQL Server and JSON :/
There are a lot of JSON strings coming from a remote database (which I only have read permission). The problem is that all of them are parsed into unicodes and I don't know how to turn them into UTF-8 !
Take a look at this JSON for example:
{
   "0":{
      "id":1,
      "name":"\\u062a\\u0646"
   },
   "1":{
      "id":2,
      "name":"\\u0628\\u0633\\u062a\\u0647 10\\u062a\\u0627\\u06cc\\u06cc"
   },
   "2":{
      "id":3,
      "name":"\\u0639\\u062f\\u062f 10\\u062a\\u0627\\u06cc\\u06cc"
   },
   "5":{
      "id":6,
      "name":"\\u0639\\u062f\\u062f 1000\\u062a\\u0627\\u06cc\\u06cc"
   },
   "6":{
      "id":7,
      "name":"\\u06a9\\u06cc\\u0644\\u0648\\u06af\\u0631\\u0645"
   }
}

As you can see field name is parsed into unicode. I did this to extract data into a table:
SELECT Units.*
FROM OPENJSON(@Json) AS i
CROSS APPLY OPENJSON(i.[value]) WITH (
   [Id] INT '$.id',
   [Name] NVARCHAR(MAX) '$.name'
) AS Units

It will then show something like this as result:

*

*Id: 1, Name: \u062a\u0646

*Id: 2, Name: \u0628\u0633\u062a\u0647 10\u062a\u0627\u06cc\u06cc

*...

But I need something like this as result:

*

*Id: 1, Name: تن

*Id: 2, Name: عدد 10تایی

*...

A: Some explanations from ECMA-404 standard: A JSON string is a sequence of Unicode code points wrapped with quotation marks (U+0022). ... If the code point is in the Basic Multilingual Plane (U+0000 through
U+FFFF), then it may be represented as a six-character sequence: a reverse solidus, followed by the lowercase letter u, followed by four hexadecimal digits that encode the code point.
It seems, that the names are escaped, so a possible option is to replace the escaped \:
JSON:
DECLARE @json nvarchar(max) = N'{
   "0":{
      "id":1,
      "name":"\\u062a\\u0646"
   },
   "1":{
      "id":2,
      "name":"\\u0628\\u0633\\u062a\\u0647 10\\u062a\\u0627\\u06cc\\u06cc"
   },
   "2":{
      "id":3,
      "name":"\\u0639\\u062f\\u062f 10\\u062a\\u0627\\u06cc\\u06cc"
   },
   "5":{
      "id":6,
      "name":"\\u0639\\u062f\\u062f 1000\\u062a\\u0627\\u06cc\\u06cc"
   },
   "6":{
      "id":7,
      "name":"\\u06a9\\u06cc\\u0644\\u0648\\u06af\\u0631\\u0645"
   }
}'

Statement:
SELECT Units.*
FROM OPENJSON(REPLACE(@Json, N'\\u', N'\u')) AS i
CROSS APPLY OPENJSON(i.[value]) WITH (
   [Id] INT '$.id',
   [Name] NVARCHAR(MAX) '$.name'
) AS Units

Result:
Id  Name
1   تن
2   بسته 10تایی
3   عدد 10تایی
6   عدد 1000تایی
7   کیلوگرم