text:
Q: Difference between \Sexpr and <<>>= I am new to sweave and learning a lot. For the most part \Sexpr works well for simple variables and also calling R functions.
But other times it will fail, I have found that I can get around this using the <<>>= command. I am interested to know what the difference is, and when I should use which one.
For instance:
I can use \Sexpr{parc.name(parc)} but \Sexpr{p_curve.data.points(p_curve.data);} will not work, however the following will work:
<<echo=false,results=tex>>=
            p_curve.data.points(p_curve.data);
@

Where the functions are defined in a seperate file using source("filename.R")
parc.name <- function(code) {
    conn <- connect();
    res <- dbGetQuery(conn, paste("SELECT displayname FROM machinepark WHERE name='", code, "' LIMIT 1", sep=""));
    disconnect(conn);
    res$displayname[1];
}

and
p_curve.data.points <- function(pc_data) {
    rows <- length(pc_data$power);
    for(i in 1:rows){
        cat("(", pc_data$windspeed[i], ",", pc_data$power[i], ")");
    }
}

A: cat is not appropriate in \Sexpr statements.  I believe it tries to run cat on the value returned from evaluating what's inside the \Sexpr; since cat doesn't return a value, \Sexpr doesn't have anything to output.
See the following .Rnw file for examples.
\documentclass{article}
\begin{document}

<<>>=
sayhi <- function(k=2) {for(i in 1:k) cat("hi",i,"| ") }
sayhi()
@

But with Sexpr, {\tt sayhi()} prints <\Sexpr{sayhi()}>.

Note that {\tt sayhi()} returns nothing; that's why Sexpr doesn't work.

<<>>=
a <- sayhi()
cat(a)
@

<<>>=
savehi <- function(k=2) {
  out <- c()
  for(i in 1:k) {
    out <- paste(out, "hi", i,"| ")
  }
  out
}
hi <- savehi()
cat(hi)
@

And with Sexpr, {\tt savehi()} prints <\Sexpr{savehi()}>.

\end{document}

Aside from original answer: Another "gotcha" with \Sexpr expressions is trying to use curly brackets.  Curly brackets are not allowed in \Sexpr expressions. Instead do the computation in a hidden code chunk and use the result in an \Sexpr.
See the Sweave manual for details.
Also see this question at stackoverflow.


text:
Q: Is it a bad idea do divide the models into directories? I have a over 100 models in my rails application, and just for organization, I'm dividing them into folders, all still under the main model folder, just to make it simpler to navigate on the project and see files that are related.
Is this a bad idea? What is the rails way to do this?

A: No, it's not a bad idea. Many people do it and I couldn't live without it in large applications.
There are two ways of doing it:
The first is to just move your models. You will, however, have to tell Rails to load the wayward models (as it won't know where they are). Something like this should do the trick:
# In config/application.rb
module YourApp
  class Application < Rails::Application
    # Other config options

    config.autoload_paths << Dir["#{Rails.root}/app/models/*"]
  end
end

The first way is easy, but is not really the best way. The second way involves namespacing your models with groups they're in. This means that instead of having User and UserGroup and UserPermissions, you have User, User::Group and User::Permission.
To use this, generate a model like this: rails generate model User::Group. Rails will automatically create all of the folders for you. An added benefit is that with this approach, you won't have to spell out the full model name for associations within a namespace:
class User < ActiveRecord::Base
  belongs_to :group # Rails will detect User::Group as it's in the same namespace
end

class User::Group < ActiveRecord::Base
  has_many :users
end

You can specify however many levels of namespacing as you want, so User::Group::Permission would be possible.

A: For 100 models, it's practically a requirement. 100 models is noisy in one directory.
Try this to get an idea of the Rails Way (tm)
rails new MultiDirectoryExample
cd MultiDirectoryExample
rails generate scaffold User::Photo description:string

Watch the script output and view the generated files.

redpajama_set_name: RedPajamaStackExchange


text:
Q: None block 'while True' using asyncio Using below code I'm attempting to start 2 infinite loops using asyncio:
async def do_job_1():
    while True :
        print('do_job_1')
        await asyncio.sleep(5)

async def do_job_2():
    while True :
        print('do_job_2')
        await asyncio.sleep(5)

if __name__ == '__main__':
    asyncio.run(do_job_1())
    asyncio.run(do_job_2())

do_job_1 blocks do_job_2, as do_job_2 never prints do_job_1. What mistake have I made ?
Ultimately I'm trying to convert kafka consumer code:
from confluent_kafka import Consumer, KafkaError

settings = {
    'bootstrap.servers': 'localhost:9092',
    'group.id': 'mygroup',
    'client.id': 'client-1',
    'enable.auto.commit': True,
    'session.timeout.ms': 6000,
    'default.topic.config': {'auto.offset.reset': 'smallest'}
}

c = Consumer(settings)

c.subscribe(['mytopic'])

try:
    while True:
        msg = c.poll(0.1)
        if msg is None:
            continue
        elif not msg.error():
            print('Received message: {0}'.format(msg.value()))
        elif msg.error().code() == KafkaError._PARTITION_EOF:
            print('End of partition reached {0}/{1}'
                  .format(msg.topic(), msg.partition()))
        else:
            print('Error occured: {0}'.format(msg.error().str()))

except KeyboardInterrupt:
    pass

finally:
    c.close()

taken from https://www.confluent.io/blog/introduction-to-apache-kafka-for-python-programmers to be concurrent so I can parallelize processing of Kafka messages.

A: From help(asyncio.run):

It should be used as a main entry point for asyncio programs, and should ideally only be called once.

But you can use asyncio.gather to join the tasks:
import asyncio

async def do_job_1():
    while True :
        print('do_job_1')
        await asyncio.sleep(5)

async def do_job_2():
    while True :
        print('do_job_2')
        await asyncio.sleep(5)

async def main():
    await asyncio.gather(do_job_1(), do_job_2())

if __name__ == '__main__':
    asyncio.run(main())


text:
Q: How can I have an angular app load data in sequence I'm fairly  new to angular but, i'm getting it...
Using some ui-route states, I am able to have urls (views) that progressively build with the user selected data.  Its similar to a wizard interface.  step 1 => step 2 => step 3 => final result
From start to finish there isn't much of an issue as the data is saved in a service as the user clicks along.  The problem comes when the page is refreshed or entered directly into the browser (i.e. someone sent me a link)
/step-1/step-2 should display the same data as if the user selected step 1 and then step 2
In such a case, I need to get all the user selected data up to that point.
Get the data for step 1, when that data is loaded, get the data for step 2, then get the data for step 3, etc.  However, I only need to get the data if it has not already been retrieved.
To accomplish such an idea i need the service to return data stored in its data property or if that data is empty go get it, save it to its property and then return it.
any ideas on how to implement this?
Here is some pseudo code that illustrates what I am attempting to do in the service.  I am not certain the syntax is 100% correct but it should illustrate the point.
    app.factory('dataService', ['$http', '$q', '$filter', 'ngAuthSettings', 'localStorageService', function ($http, $q, $filter, ngAuthSettings, localStorageService) {

    var ServiceFactory = {};
    var _getData = function () {

        var deferred = $q.defer();
        _Step1Data= localStorageService.get('Step1Data');

        if (_Step1Data) {
            $http.get('api/Step1Data').then(function (response) {
                _data = response.data.results;
                localStorageService.set('Step1Data', _Step1Data);
                deferred.resolve(response);
            });
        }
        else {
            deferred.resolve(_Step1Data);
        }
        return deferred.promise;
    };
    ServiceFactory.getStep1Data = _getStep1Data;
 return ServiceFactory;

}]);

Assuming that the process to get step 2, step 3 data is the same as step 1, the call to load the data would be as follows
dataService.getStep1Data ()
            .then(function (data) {
                vm.Step1Data = data;
                dataService.getStep2Data ()
                .then(function (data) {
                    vm.Step2Data = data;
                }, function (error) {
                    //some error stuff
                })
            }, function (error) {
                //some error stuff
            });

The reason for the stepped approach is that each step depends on the previous steps selected data to get the current steps data.

A: It's the resolve property you are looking for. You can use it to resolve the step data before any step controller is instantiated. The resolved step data can then be injected in your controller.
You might combine this with your dataservice, like so:
step1.state({
  resolve: {
    step1Data: function(dataService) {
      return dataService.getStep1Data ()
    }
  }
  ....
}


text:
Q: Javascript; unset a function? I'm pretty new to javascript. I have this function and I'd like to unset it when the screen size is less than 1024. I have two functions: a document ready function and a window resize function. When resizing the screen below 1024 I'd like the function to be unset. How to manage this?
Here is my code
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<script>
jQuery(document).ready(function($) {
    var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
    if(width > 1024) {
    setTimeout(function(){
        var lcol_height = $("#leftCol2").height() + 80; // add 80 for margin + padding
        var rcol_height = $("#rightCol2").height();

        if(rcol_height > lcol_height) $("#leftCol2").css('height',(rcol_height - 80) + 'px');
        else $("#rightCol2").css('height',lcol_height + 'px');
    }, 500);
    }
});

$(window).resize(function() { //Fires when window is resized
    var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
    if(width < 1024) {
//I'd like the margin function to be unset.
    }
    else {
        setTimeout(function(){
        var lcol_height = $("#leftCol2").height() + 80; // add 80 for margin + padding
        var rcol_height = $("#rightCol2").height();

        if(rcol_height > lcol_height) $("#leftCol2").css('height',(rcol_height - 80) + 'px');
        else $("#rightCol2").css('height',lcol_height + 'px');
    }, 500);
    }

});
</script>

Thank you so much!

A: There's no need to unset it, since you might be needing it again in case the window size increases beyond 1024px. Here is a slightly optimized version of your code:
function handleMargins() {
    var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
    if (width > 1024) {
        setTimeout(function () {
            var lcol_height = $("#leftCol2").height(); // use original margin
            var rcol_height = $("#rightCol2").height();

            if (rcol_height > lcol_height) $("#leftCol2").css('height', (rcol_height - 80) + 'px');
            else $("#rightCol2").css('height', lcol_height + 'px');
        }, 500);
    } else {
        setTimeout(function () {
            var lcol_height = $("#leftCol2").height() + 80; // add 80 for margin + padding
            var rcol_height = $("#rightCol2").height();

            if (rcol_height > lcol_height) $("#leftCol2").css('height', (rcol_height - 80) + 'px');
            else $("#rightCol2").css('height', lcol_height + 'px');
        }, 500);
    }
}

jQuery(document).ready(handleMargins);

$(window).resize(handleMargins);

Apart from being more readable, now the same code executes when you first open the page AND on resize (imagine what would happen in your original code if the window is initially smaller than 1024px).

UPDATE
See if this makes more sense (note, the boundary is set to 400px, so you need to shring that jsfiddle box to about twice the size of the divs): http://jsfiddle.net/wdey6ngf/
I've simplified your logic and everything, just wanted to show you how it works.

NOTE
Depending on how complicated your end logic is going to be, this is something you can accomplish using no JS, just plain CSS with media queries: http://jsfiddle.net/rags7zg2/ It will perform much better than the JS version.

A: If it is a global function, you can redefine it like this:
window.myFunction = function() {
  return false;
}

But you can't do it with anonymous functions obviously. So, first extract your functions:
function myResizer()
{
    var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
    if(width > 1024) {
    setTimeout(function(){
        var lcol_height = $("#leftCol2").height() + 80; // add 80 for margin + padding
        var rcol_height = $("#rightCol2").height();
        if(rcol_height > lcol_height) $("#leftCol2").css('height',(rcol_height - 80) + 'px');
        else $("#rightCol2").css('height',lcol_height + 'px');
    }, 500);
    }
}

And then use this function to set it as a ready function initially:
jQuery(document).ready(myResizer)

Later on, when you need to lose that functionality, just override it with nothing:
jQuery(document).ready(function($) { return false; }

A: Store all your code in an function, use storing settimeout in a variable, and call that in ready and onresize. Then you can use clear interval if (width < 1024).


text:
Q: export-csv is destroying my date-formats In powershell, I create a datatable; there's a column in the datatable, with formatted date:
SELECT RIGHT('0' + cast(day(GETDATE()) as varchar(2)),2) + '-' + CAST(DATENAME(MONTH, GETDATE()) AS VARCHAR(3)) + '-' + cast(DATEPART(year, GETDATE()) as varchar(4))

So the actual value is: dd-MMM-yyyy
Except, when I use the following, the date format is changed to dd-MMM-yy
$dtResult | export-csv $outputFile -notypeinformation

it is crucial to get the date as dd-MMM-yyyy
cheers

A: It sounds like the date is stored in the data table as a DateTime, so it will use the system default for formatting. One way around this is to convert the datatable to a collection of objects first, converting the date to a string in the process:
$dtObjects = $dtResult | Select-Object ID, Name, @{n="DateField";e={$_.DateField.ToString("dd-MMM-yyyy"}}

Replace the field names with your actual field names.


text:
Q: (Windows 8) Change power button to log off Ways to accomplish this.
Perhaps using group policy, registry editor, windows settings, and etc.
Since windows 7 configurations differ somewhat from windows 8, the settings that worked for windows 7 does not work for windows 8.


text:
Q: Camera2 API - Why the same surface needs to be specified twice? Looking at Camera2 API, it appears that a surface needs to be specified twice. Once it is done during createCaptureSession, passing in the list of surfaces. At a later point, we once again specify the same surface to the preview-builder's addTarget method. If we are going to specify the target surfaces later, why do we need to specify the list of surfaces initially during createCaptureSession call? What does addTarget really do with the surface that createCaptureSession is not doing? Regards.

A: For the capture session, you need to list all the Surfaces you might want to use for your requests.  This allows the camera device to configure its hardware processing pipelines to be able to provide all those outputs at the requested sizes and for the requested destinations (such as 1080p preview to SurfaceView/TextureView, full-resolution JPEGs to ImageReaders, 4K video recording buffers to MediaRecorder, and so on)
Then each request includes a subset (or all) of those Surfaces.  Not every request will generally want to include every configured Surface; you'd usually only include the full-resolution JPEG ImageReader Surface for snapshots, and only include the MediaRecorder Surface when actively recording video.
If the Surfaces were only included in the capture requests, then the camera pipeline would have to reconfigure itself on the fly when it sees a new Surface that hasn't been used before.  This generally causes a 300-600 ms pause as the camera hardware flushes out its data and reconfigures itself.
So to ensure smooth operation, the camera2 API requires the application to specify all the desired outputs for the current session up front.


text:
Q: SQL Server Check String for Spaces, Special Characters, and Charcters I have a report that produces a list of values that should all be numbers but are currently stored as a varchar. In my export I am casting the varchar character as an Int but when some one incorrectly enters a char or a special character the report fails because is cannot convert to an INT
Current List
557780
558871
5588a6
5588 7

What I need is something that will swap out those values that contain spaces or characters for an error int like 99999999 so the end result would be
557780
558871
99999999
99999999

I know I can do this by using something like this
CASE WHEN SomeNum LIKE '%_%' THEN 99999999 ELSE SomeNum
     WHEN SomeNum LIKE '%a%' THEN 99999999 ELSE SomeNum END

But is there a better way then to compare to every letter and special charterer individually?

A: you can use do it with pattern
case when SomeNum NOT LIKE '%[^0-9]%' THEN 99999999 ELSE cast(SomeNum as int) END

A: You can use ISNUMERIC if you are in SQL Server 2008 or later. Note this will match money and decimals etc. If you are just looking for integer then you need to regex. See radar's answer.
Their example is this for completeness:
USE AdventureWorks2012;
GO
SELECT City, PostalCode
FROM Person.Address
WHERE ISNUMERIC(PostalCode)<> 1;
GO

If you are pre SQL Server 2008 you could use Radar's answer with a regex

A: You can try this on SQL 2012+:
SELECT COALESCE(TRY_CONVERT(INT, SomeNum), 99999999) AS Value
FROM YourTable


text:
Q: Passing data from .vue to .js in vuejs I am doing report through chartjs.
In User.vue
beforeCreate() {
    axios
      .get("/pct-at/api/users")
      .then((res) => {
        console.log(res.data);
      })
      .catch((error) => {
      });
  },
  data() {
    return {
      startDate: "",
    };
  },

Result res.data :
{"datasets":[{"label":"User active","data":[2,0,0,0,0,0,0,0],"fill":false,"borderColor":"#9ec6cb"}}

In userChart.js
export default {
    lineChart: {
        options: {
            responsive: true,
            maintainAspectRatio: false,
            backgroundColor: false,
            hover: {
                mode: 'label',
            },
        },
        data: data // I want to get data from User.vue here : data
    },
}

Now I want in user.js to receive data in res.data from User.vue, how should I do that? Thanks

A: The best way to do this is to fetch data via axios call in userChart.js itself.
If you want to communicate between components, you can use custom events and props, event bus or mitt.
Specifically for chart.js, please follow the official guide here.


text:
Q: Updating a Django webpage by calling itself in Ajax In the example code below, Ajax calls (in the page.html) the same Python function (page()) which Django used to create the page in the first place. It gets a HTTPResponse object, which contains the page as it should look after the Ajax call. But the possibly modified page in the HTTPResponse object is not applied to modify the actual page. Is it possible to do so, or am I thinking something not doable?
page.html
$( document ).ready(function() {
    $.ajax({
        url: "",
        success: function(data) {
            //Here to make the webpage determined by this page.html
            //to look like how it is rendered in the HTTPResponse object "data"
        }
    })
})

views.py
def page(request):
    //...
    return render(request, page.html)

urls.py
urlpatterns = [
    path('', views.page, name="page"),
]


text:
Q: What's the technique to do expand/compact stack on iPad like Reeder and Photos? On iPad, both the native Photos app as well as Reeder use a "expand/collapse stack" technique. Initially there is a stack of items on top of one another, each angled a bit with different corners showing. When you interact with them, the stack expands into a full screen and the items are laid out in a grid. When you collapse them, they collapse back into a stack.
What's the best way to set up my views to do the same thing? Should I just have a bunch of UIviews (one for each item) and manipulate their coordinates/transforms with an animation, or is there something more to it? Any example apps with code?
(Note: I am not asking about the interaction to invoke expand/collapse, I'm only asking what's the most appropriate way to lay out and set up my items.)

A: These days, use UICollectionView with different layouts and transitioning between layouts.


text:
Q: Write/Read then Save text file Basic4Android I'm creating an application on Basic4android that collects GPS coordinates and equipment deficiencies in a dropdown list (Spinner). The GPS coordinates consists of latitude and longitude shows up on a label field when GPS is ON and the deficiencies shows up under a Spinner field (e.g. dropdown of "Broken cross arm", "Broken Insulator","Rusty Structure"). I was able to get all that done and create a "Submit" button that should copy the three fields (Longitude, Latitude and deficiencies) into a text file. Any idea how to store these fields everytime I press submit? I will be using this application for inspection when I walk by a transmission tower, I will record the coordinates and the obvious deficiency into a file on android.
Thank you,
Eli

A: There are some solutions. one of them is writhing a list file .add a character as delimiter between Longitude, Latitude and deficiencies.
declare list in global section
 Dim list1 as list

initialize list on create activity event
 List1.Initialize

On submit button click
newstring=longt &"|" &lat &"|"& defi
If File.Exists (File.DirInternal & "/","Log.txt") Then
List1 = File.ReadList (File.DirInternal & "/","Log.txt")
end if
List1.add(newstring)
File.Writelist(File.DirInternal & "/","Log.txt",List1)

You can split every line  int to seperated Longitude, Latitude and deficiencies later when you  need.

A: There are several ways to do it. The simplest is to add the values to a Map and use File.WriteMap / ReadMap.
See this tutorial: http://www.basic4ppc.com/android/forum/threads/6690/#content


text:
Q: Formulário não cadastra, nenhum nome fica gravado Meu formulário não está salvando nenhum dado no banco, o que pode ser?

    <?php

      if(isset($_SERVER['REQUEST_METHOD']) AND $_SERVER['REQUEST_METHOD'] == 'POST'){

        extract($_POST);

    if(isset($nome))
        if($nome === '' OR strlen($nome)<4){
            echo 'Insira um nome existente';
        }elseif($sobrenome=='' OR strlen($sobrenome)<6){
            echo 'Insira um sobrenome existente';
        }elseif($email==''){
            echo 'Insira seu e-mail';
        }elseif(!preg_match("/^[az0-9_\.\-]+@[az0-9_\.\-}*{a-z0-9_\-]+\.[a-z]{2,4}$/i",$email)){
            echo 'E-mail invalido tente outro';
        }else{

            include('../../sllapsocial/classes/DB.class.php');

            $verificar = DB::getConn()->prepare("SELECT `id` FROM `usuarios` WHERE `email`=?");
            if($verificar->execute(array($email))){
                if($verificar->rowCount()>=1){
             echo 'Este e-mail ja existe';

         }elseif($senha=='' OR strlen($senha)<4){
            echo'Senha fraca Insira mais caracteres';
         }elseif(strtolower($capctha) <> strtolower($_SESSION['capcthaCadastro'])){
             echo 'Codigo errado';
         }else{
             $senhaInsert = sha1($senha);
             $nascimento = "$ano-$mes-$dia";
             $inserir = DB::getConn()->prepare("INSERT INTO `usuarios` SET `email`=?, `senha` =?, `nome`=? `sobrenome`=?, `sexo`=?, `nascimento`=?`cadastro`=NOW()");

             if($inserir->execute(array($nome,$sobrenome,$email,$senhaInsert,$nascimento,$sexo))){
            header('Location: ./');
               }

            }

           }

        }

        }

      ?>

Para ter acesso,É facil e gratis.

 <form name="cadastro" action="" method="post" >

Nome
         <input name="Nome" type="text" class="txtInput" value="<?php if(!empty($nome)) echo $nome; ?>" size="40"/>

             Sobrenome
             <input name="Sobrenome" type="text" class="txtInput" value="<?php if(!empty($sobrenome)) echo $sobrenome; ?>" size="40"/>

           Seu e-mail
             <input name="Seu e-mail" type="text" class="txtInput" value=" <?php  if(!empty($email)) echo $email; ?>" size="40"/>

             Insira o e-mail novamente
             <input name="Insira o e-mail novamente" type="text" class="txtInput" size="40" value=" <?php if(!empty($email)) echo $email; ?>" />

             Senha
             <input name="Senha" type="password" class="txtInput" size="40" value="<?php  if(!empty($senha)) echo $senha; ?>" />

           Data de nascimento
             <select name="Dia">
               <option value="">Dia</option>
               <?php
         for($d=1;$d<=31;$d++){
             $zero = ($d<10) ? 0 : '';
             if(!empty($dia)==$zero.$d){
             echo '<option selected="selected" value="',$zero,$d,'">',$zero,$d,'</option>';
             }else{
             echo '<option value="',$zero,$d,'">',$zero,$d,'</option>';
             }

         }

      ?>

             </select>

             <select name="Mes">
               <option value="">Mês</option>
               <?php
       $meses = array('','janeiro','fevereiro','março','abril','maio','junho','julho','agosto','setembro','outubro','novembro','dezembro');
       for($m=1;$m<=12;$m++){
       $zero = ($m<10) ? 0 : '';
       if($zero.$m == $meses){
        echo '<option selected="selected"value="',$zero,$m,'">',$meses[$m],'</option>';
       }else{
            echo '<option "value="',$zero,$m,'">',$meses[$m],'</option>';
       }
       }
      ?>

             </select>

             <select name="Ano">
               <option value="">Ano</option>
               <?php
      for($a=date('Y');$a>=(date('Y')-100);$a--){
          if(!empty($ano)){
              echo '<option selected"selected" value="',$a,'">',$a,'</option>';
          }else{
              echo '<option value="',$a,'">',$a,'</option>';
        }
      }
      ?>

             </select>

             Sou do sexo
             <select name="sexo">
               <option <?php if(!empty($sexo) == 'masculino') echo'selected"selected"'; ?> value="masculino" >Masculino</option>
               <option <?php if(!empty($sexo) == 'feminino') echo'selected"selected"'; ?>value="feminino" >Feminino</option>
             </select>

Digite o código acima:
             <input class="txtInput" type="text" name="captcha"  />
             <input type="submit" value="Continue" class="SubmitContinue" name="Continue" />
        </form>

A: 1 - Tome cuidado ao digitar nomes de campos/variáveis no html/php Nome é diferente de nome, veja no seu form como está definição:
<input name="Nome" type="text"

No php depois do extract() ele vai virar $Nome e não $nome.
if(isset($nome))

2- sql
Parecer ser erro de sintaxe no insert:
INSERT INTO `usuarios` SET
 `email`=?,
 `senha` =?,
 `nome`=? <---- falta uma virgula
 `sobrenome`=?,
 `sexo`=?,
 `nascimento`=? <---- aqui também
 `cadastro`=NOW()

Sempre que o mysql retornar o código 1064 sempre é algum erro de sintaxe como nome de coluna/tabela escrito errado ou aspas em lugares errados.
A mesnagem de erro é parecida como:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

Lista dos códigos  de erro mysql
Sintaxe ao alternativa do insert


text:
Q: Nested Macro not expanding correctly I am trying to nest macro calls to ease converting between rust and c ffi types.
The inner macro generates calls to conversion functions from type names like this:
macro_rules! type_conversion {
    ($arg_name:ident, bool, BOOL) => (crate::type_wrappers::type_conversion::convert_rust_bool($arg_name));
    ($arg_name:ident, BOOL, bool) => (crate::type_wrappers::type_conversion::convert_c_bool($arg_name));
}

The outer macro now uses this to generate further conversions.
It basically works like this:
macro_rules! outer {
    ($arg_name:ident, $type1:ty, $type2:ty) => (type_conversion!($arg_name, $type1, $type2));
}

Now, when i try to use the outer macro like this:
fn outer() {
    outer!(hello_world, bool, BOOL);
}

I get this Error:
error: no rules expected the token `bool`
   --> src\type_wrappers\type_conversion.rs:252:77
    |
202 | macro_rules! type_conversion {
    | ---------------------------- when calling this macro
...
252 |     ($arg_name:ident, $type1:ty, $type2:ty) => (type_conversion!($arg_name, $type1, $type2));
    |                                                                             ^^^^^^ no rules expected this token in macro call
...
256 |     outer!(hello_world, bool, BOOL);
    |     ------------------------------- in this macro invocation

I cannot make sense out of this error, especially since CLions Macro expansion tool expands this into:
type_conversion!(hello_world , bool , BOOL )

Which is what i would expect and also, what the Error suggests.
Where is the Error in those Macros?

A: I guess the ty macro type cannot be casted to identifier (which bool & BOOL parameter are) and thus matched. So with ident type it works (playground):
macro_rules! outer {
    ($arg_name:ident, $type1:ident, $type2:ident) => {
        type_conversion!($arg_name, $type1, $type2)
    };
}


text:
Q: how create a flag with EaselJS i find a simple canvas flag, but I have the question of how can I make it with EaselJS?
because in EaselJS documentation don't says about, make another canvas "without DOM interaction", and change pixel positions, but in EaselJS documentation I can't find how make it, and I have some questions:
1 Can i merge EaselJS code with normal Canvas code? Explanation, If I draw an animated North Korean flag star with some textures, can I make the static draw with EaselJS, and animate it with naked canvas code?
2 is possible make it with other library?, such as LimeJS or other libraries
3 I must use a WEBGL Library?, such as Three.js?


text:
Q: How to access foreignkey/ OneToOneField table's data from a ModelForm? I have a model called Profile that is related to the User Model. I would like to make a ModelForm for the model Profile. I would like that form to be able to access user's fields.
class Profile(models.Model):

user=models.OneToOneField(settings.AUTH_USER_MODEL,related_name='profile',on_delete=models.CASCADE)

address = models.CharField(max_length=250)

contact_number = models.IntegerField(max_length=20)

def __str__(self):

return self.user.first_name

class ProfileForm(forms.ModelForm):

class Meta:

model=Profile

fields=['first_name','address','contact_number']

The error shown is
django.core.exceptions.FieldError: Unknown field(s) (first_name) specified for Profile

Thank you.


text:
Q: Why are headings and paragraphs considered as clickable elements (HTML) I am trying to make my webapp (created with Python Dash) more accessible, e.g. for users relying on screen readers. In order to test my webapp I use the Accessibility Inspector built into Firefox. Here I run into issues concerning focusability and interactivity of elements which are supposed to show text (e.g. headings and paragraphs).
First I created my elements like this:
    html.H1(
     children="this is my header"
    )

    html.P(
     children="this is text"
    )`

In these cases the Accessibility Inspector yields the following warning:
Clickable elements must be focusable and should have interactive semantics
In order to resolve this, I added 'tabIndex' to my elements:
    html.H1(
     children="this is my header",
     tabIndex='0'
    )

    html.P(
     children="this is text",
     tabIndex='0'
    )

This eliminated one part of the warning. Now I got this warning:
Focusable elements should have interactive semantics
From what I gathered on accessibility so far it is bad practice to give non interactive elements like headings a 'tabIndex'. So my second approach is probably already going in the wrong direction.
Can you please tell me how to deal with the first warning instead? And why are headings and paragraphs considered as clickable elements? They do not contain a link or anything else.
Update:
If I take a look at the HTML in Firefox, the header looks like this:
screenshot HTML
Solution: I asked my question in the Plotly Community Forum (https://community.plotly.com/t/how-to-remove-events-from-dash-html-components-to-avoid-misinterpretation-by-screen-readers/70477) as well. They pointed me towards the dash mantine components library (https://www.dash-mantine-components.com/), which includes dmc.Title and dmc.Text which can be used instead of html.H1-H6 and html.P. This resolves my issue.

A: I looked at some sample Dash applications, https://dash.gallery/dash-clinical-analytics/, and indeed the headings on that demo are "clickable".

"Clinical Analytics" is an <h5> and "Welcome to the Clinical Analytics Dashboard" is an <h3>.  Both have an event handler for the click event.

That will cause some screen readers to say those elements are "clickable".  Here's what NVDA says when I use the H key to navigate to the headings:

*

*"Clinical Analytics, heading, clickable, level 5"

*"Welcome to the Clinical Analytics Dashboard, heading, clickable, level 3"
The screen reader is trying to help the user let them know that an event handler is on that element and that it can be clicked on.  However, headings are not normally considered interactive elements so it'll be confusing.
This seems like a bug in Dash.
The error you're getting, "Clickable elements must be focusable and should have interactive semantics" is accurate.  It has two parts:

*

*"elements must be focusable" - anything that you can interact with using a mouse should be interactable (word?) with the keyboard.  In order to interact with the element, you first have to be able to get your keyboard focus to it, thus the error message.

*"elements should have interactive semantics" - when a screen reader user navigates to an interactive element, they should hear the role of that element and that role should convey that the element is an interactive element.  The headings do have semantics, NVDA says they're "headings", as noted above, but the error message says it should be "interactive semantics", not just "semantics".
All this info doesn't explain how to fix your problem but I wanted to post the "why" of the error message, and I couldn't fit all this into a simple comment :-)


text:
Q: Calculate $\sum_{n=1}^\infty\frac{1}{n^2}$ and $\sum_{n=1}^\infty\frac{1}{n^4}$ I need to do that using
$$\sum_{n \in \mathbb{Z}}\frac{1}{(z-n)^2}=\left(\frac{\pi}{\sin \pi z}\right)^2$$
I've already prove that this is true. The thing is that this function in meromorphic and it's poles are $\mathbb{Z}$. So the natural evauation in $0$ is not possible. I tried to think of a way to do it with that using that the singular part of this function in $n\in\mathbb{Z}$ is $\frac{1}{(z-n)^2}$, but could find a way. What I was looking was sort of substract the term where $n=0$ and divide by $2$.
For the second sum, I didn't find a clear way. The natural evaluation in $n^2-n$ is not possible since $n$ varies in the sum.
Thanks

A: For the first sum:
For $z = \frac12$ we have
$$\pi^2 = \frac{\pi^2}{\sin^2\frac{\pi}2} = \sum_{n\in\mathbb{Z}}\frac1{\left(n-\frac12\right)^2} = 4\sum_{n\in\mathbb{Z}}\frac1{(2n-1)^2} = 8\sum_{\substack{k\in\mathbb{N} \\ k \text{ odd}}} \frac1{k^2}$$
$$\sum_{\substack{k\in\mathbb{N} \\ k \text{ even}}} \frac1{k^2} = \sum_{\substack{k\in\mathbb{N}}} \frac1{(2k)^2} = \frac14 \sum_{k\in\mathbb{N}} \frac1{k^2}$$
$$S = \sum_{\substack{k\in\mathbb{N}}} \frac1{k^2} = \sum_{\substack{k\in\mathbb{N} \\ k \text{ even}}} \frac1{k^2} + \sum_{\substack{k\in\mathbb{N} \\ k \text{ odd}}} \frac1{k^2} = \frac14 S + \frac{\pi^2}8 \implies S = \frac{\pi^2}6$$

For the second sum differentiate the original series twice:

$$\sum_{n\in\mathbb{Z}} \frac1{(z-n)^2} = \frac{\pi^2}{\sin^2 \pi z}$$
$$-2\sum_{n\in\mathbb{Z}} \frac1{(z-n)^3} = -\frac{2\pi^3\cos \pi z}{\sin^3 \pi z}$$
$$6\sum_{n\in\mathbb{Z}} \frac1{(z-n)^4} = \frac{2\pi^4(\sin^2 \pi z + 3\cos^2\pi z)}{\sin^4 \pi z} = \frac{2\pi^4(2 + \cos(2\pi z))}{\sin^4 \pi z}$$
So $\sum_{n\in\mathbb{Z}} \frac1{(z-n)^4} = \frac{\pi^4(2 + \cos(2\pi z))}{3\sin^4 \pi z}$. Again pluggin in $z = \frac12$ gives
$$\frac{\pi^4}3 = \frac{\pi^4(2 + \cos\pi)}{3\sin^4 \frac\pi2} = \sum_{n\in\mathbb{Z}}\frac1{\left(n-\frac12\right)^4} = 16\sum_{n\in\mathbb{Z}}\frac1{(2n-1)^4} = 32\sum_{\substack{k\in\mathbb{N} \\ k \text{ odd}}} \frac1{k^4}$$
$$\sum_{\substack{k\in\mathbb{N} \\ k \text{ even}}} \frac1{k^4} = \sum_{\substack{k\in\mathbb{N}}} \frac1{(2k)^4} = \frac1{16} \sum_{k\in\mathbb{N}} \frac1{k^4}$$
$$S = \sum_{\substack{k\in\mathbb{N}}} \frac1{k^4} = \sum_{\substack{k\in\mathbb{N} \\ k \text{ even}}} \frac1{k^4} + \sum_{\substack{k\in\mathbb{N} \\ k \text{ odd}}} \frac1{k^4} = \frac1{16} S + \frac{\pi^4}{3\cdot 32} \implies S = \frac{\pi^4}{90}$$

A: Write this as
$$\frac1{z^2}+\sum_{n=1}^\infty\left(\frac{1}{(z-n)^2}+\frac{1}{(z+n)^2}\right).$$
Then
$$\frac1{(z-n)^2}=\frac1{n^2}\frac1{(1-z/n)^2}
=\sum_{k=0}^\infty\frac{(k+1)z^k}{n^{k+2}}$$
and so
$$\frac1{(z-n)^2}+\frac1{(z+n)^2}
=2\sum_{r=0}^\infty\frac{(2r+1)z^{2r}}{n^{2r+2}}.$$
Then
$$\frac1{z^2}+\sum_{n=1}^\infty\left(\frac{1}{(z-n)^2}+\frac{1}{(z+n)^2}\right)=\frac1{z^2}+2\sum_{r=0}^\infty(2r+1)\zeta(2r+2)z^{2r}$$
which you can now compare to the expansion of $\pi^2/\sin^2\pi z$.


text:
Q: Disproving that a sequence in $\mathbb{R}^{n}$ converges
Let $\{x_{n}\}_{n\in \mathbb{N}}$ a bounded sequence in $\mathbb{R}^n$. Let assume that the sequence $\{d(x_n,0)\}_{n\in \mathbb{N}}$ (In the euclidean space) is strictly increasing.
Prove/Disprove: $\{x_{n}\}_{n\in \mathbb{N}}$ converges

I am trying to grasp it conceptually but did not manage.
The sequence $\{x_{n}\}_{n\in \mathbb{N}}$ are bounded, therefore each element of the sequence is bounded and we can look at it, as a sequence of points in a closed ball in $\mathbb{R}^n$.
Now we take the distance of the a point from the origin, and the distance is strictly increasing, but how can it be if the points themselves are bounded?

A: Consider the following sequence in $\mathbb{R^d}$: for $n\geq 1$,
$$x_n=\left((-1)^n\left(1-\frac{1}{n}\right),0,\dots,0\right).$$
Does it satisfy the hypothesis?


text:
Q: shinycssloaders doesn't work when deployed on shinyapps.io I have a app that works just fine without adding shinycssloaders package. But for some reason, after I added the package and added the lines (see below), it stopped working if I deploy it with shinyapps.io. The app runs fine locally, just wouldn't let me deploy it.
# load the library
library(shinycssloaders)

withSpinner(plotOutput("my_plot"))
# if you have `%>%` loaded, you can do plotOutput("my_plot") %>% withSpinner()

The error message I'm getting in the log is attached down below, but I have package shinycssloaders, and I've tried downloading it from CRAN and github, but neither works.
2019-05-13T16:41:39.317482+00:00 shinyapps[890504]: Using pandoc at /opt/connect/ext/pandoc2
2019-05-13T16:41:39.538904+00:00 shinyapps[890504]: Listening on http://127.0.0.1:46817
2019-05-13T16:41:43.893648+00:00 shinyapps[890504]: Warning: Error in withSpinner: could not find function "withSpinner"
2019-05-13T16:41:43.908035+00:00 shinyapps[890504]:   68: div
2019-05-13T16:41:43.908036+00:00 shinyapps[890504]:   67: mainPanel
2019-05-13T16:41:43.908034+00:00 shinyapps[890504]:   69: tags$div
2019-05-13T16:41:43.908032+00:00 shinyapps[890504]:   70: tag

I'm sure this work because it is on their github page, but I'm not sure what I did wrong. Worst case scenario, I'll just get rid of it so it's not a huge issue, but it'd be cool if I can use it. Any help is appreciated!
EDIT
So I attached a sample code, feel free try to deploy it, did't work for me. But works fine locally (since it's a sample app, the loading spinner is extremely quick, but you'd still be able to see it).
library(shiny)
library(shinycssloaders)

ui <- fluidPage(
  actionButton("go", "Go"),
  numericInput("n", "n", 50),
  withSpinner(plotOutput("my_plot"))
)

server <- function(input, output) {

  randomVals <- eventReactive(input$go, {
    runif(input$n)
  })

  output$my_plot <- renderPlot({
    hist(randomVals())
  })
}

shinyApp(ui, server)

A: Since the log says Warning: Error in withSpinner: could not find function "withSpinner"
I went ahead added the package name in front of withSpinner function, so now in the UI function, it should be
shinycssloaders::withSpinner(plotOutput("my_plot", height = 600))

and it works perfect with deploy. Although it seems bizarre, because I indeed attached library(shinycssloaders). In my actual app, I attached it in server.R file, perhaps that's why.


text:
Q: Changing HTML element text with Javascript As a quick preface, I would just like to note that this is a very beginner question, and I might be making an extremely simple mistake or just typing some code wrong. Being the self-taught coder that I am, it probably is, but please forgive me if it turns out to be true. I've looked through various coding learning websites, and I haven't found anything that has worked.
So I have some HTML and Javascript code, and I'm trying to change the HTML element's text with Javascript on a button click. Here is my code that currently works:
HTML:
<!DOCTYPE html>

        <title id="tabTitle"></title>

        <button id="button1"></button>
        <button id="button2"></button>
        <button id="button3"></button>

Javascript:
function startGame() {
    document.getElementById("tabTitle").innerHTML = "Welcome";
    document.getElementById("title").innerHTML = "Welcome, Challenger!";
    document.getElementById("h3").innerHTML = "Would you like to go on an adventure?";

    document.getElementById("button1").innerHTML = "Yes";
    document.getElementById("button2").innerHTML = "No";
    document.getElementById("button3").style.display = "none";

    document.getElementById("button1").addEventListener("click", function(){
        let username = sessionStorage.getItem('username');
        username = prompt("Please enter your name:");
        document.getElementById("title").innerHTML = "Hi, " + username + "!";
        document.getElementById("h3").innerHTML = "";
        document.getElementById("para1").innerHTML = `Welcome to a novel game. These kind of games ask you multiple
        questions as you progress on a predetermined storyline. Each question will have 2 or 3 choices, and it is your
        responsibility to choose which path you want to choose. This game requires you to think, plan, and execute.
        Remember, each choice is predetermined, but you can still choose your own path.`;

        document.getElementById("para2").innerHTML = `We will begin by choosing your class. Will you be a Hunter,
        Warlock, or Titan?`;

        document.getElementById("para3").innerHTML = `WARNING: Reloading this page will lose all of your progress
        untill the saving feature has been added.`;

        document.getElementById("button3").style.display = "block";

        document.getElementById("button1").innerHTML = "Hunter";
        document.getElementById("button2").innerHTML = "Warlock";
        document.getElementById("button3").innerHTML = "Titan";

        document.getElementById("button1").addEventListener("click", function(){
            startHunterGame();
        });
        document.getElementById("button2").addEventListener("click", function(){
            startWarlockGame();
        });
        document.getElementById("button3").addEventListener("click", function(){
            startTitanGame();
        });
    });
    document.getElementById("button2").addEventListener("click", function(){
        document.getElementById("title").innerHTML = "Bye Then...";
        document.getElementById("h3").innerHTML = "";
        document.getElementById("para1").innerHTML = "Why'd you even come here?";
        document.getElementById("button1").style.display = "none";
        document.getElementById("button2").innerHTML = "<button onclick='location.reload()'>Restart</button>";
    });
}

As you can see, I've used a lot of the getElementById tags, which works perfectly fine.
What I'm wondering is if its possible to use a variable, like
var button1 = document.getElementById("button1); and then just use the variable name like button1.innerHTML = "text"; instead of
document.getElementById("button1").innerHTML = "text";.
P.S. Feel free to correct me on any of my code, since i'm still learning.

A: Great starting code!
In answer to your question - yes! It's very useful to do so as you can drastically reduce the physical size of your code & the number of queries to the DOM!
For example, this is a valid re-use of a variable with initial document query:

var p3 = document.getElementById("para3");
var someText = "No";
p3.innerHTML = someText;

Here's some useful learning information:
DOM - What is the DOM?
Variables - JavaScript Variables
Variables Scope - JavaScript Scope

Please note:

*

*Invalid HTML can make any valid JavaScript malfunction

*Invalid JavaScript can freeze a page or have unexpected results

*

 this line of your HTML is invalid, you do not have a closing h1, please substitute with


text:
Q: Equivalence relations on S given no relation? On my assignment, one of the questions ask to list all equivalence relations on S and count how many are of partial orders.

*

*Let S = {u, v, w}. List all equivalence relations on S. How many of these are also partial
orders?

Am I to assume the equivalence relations are the possible combinations of each pair S x S ({}, {{u, u}}, {{u, u}, {u, v}} ...) or should their always be a given relation?

A: HINT: Since $S$ has $3$ elements, $S\times S$ has $3^2=9$ elements. Every subset of $S\times S$ is a relation on $S$, so there are $2^9=512$ relations on $S$. Fortunately, most of them are not equivalence relations, and you can ignore those. For instance, an equivalence relation must by definition be reflexive, so if $E$ is an equivalence relation on $S$, then you know that $E$ must contain each of the ordered pairs $\langle u,u\rangle,\langle v,v\rangle$, and $\langle w,w\rangle$. That leaves only $6$ ordered pairs that might or might not be in $E$. You could then take into account the restrictions on $E$ imposed by the requirements that $E$ be symmetric and transitive. However, this is doing it the hard way.
In fact, you know that every equivalence relation on $S$ determines and is determined by the partition of $S$ whose parts are its equivalence classes. What are the partitions of $S$? One of them is $\big\{\{u,v\},\{w\}\big\}$; what are the others? There aren't many at all.
Once you've listed the partitions, determine which of them represent partial orders. Remember, a partial order is a reflexive, transitive, antisymmetric relation. Your equivalence relations are already reflexive and transitive, so you need only determine which of them are antisymmetric.


text:
Q: Correct way to assign unique group to users Django I read about it on the next articles, trying to find information about my doubt:
https://baxeico.wordpress.com/2014/09/10/group-combo-box-django-user-profile-form/
https://micropyramid.com/blog/django-permissions-and-groups/
https://www.webforefront.com/django/setupdjangousers.html
My premise in my system: an user only can be in an unique group.
My question is about my premise, how is the correct way to assign a unique group to an user from my app?

A: Groups are added to AbstractUser via PermissionsMixin and is a ManyToManyField. There's two ways to do this:

*

*You listen to m2m_changed for the User model and then implement some logic to deny multiple groups.

*You create your own user with a ForeignKey to Group on your new ProjectUser model and reimplement PermissionsMixin and AbstractUser.

The first method is a little tricky and I don't recommend it. The second has the disadvantage that you can pretty much copy 80% of PermissionsMixin and everything, but it's inheritance from AbstractUser, but have to keep it in sync with new releases. It's a shame Django implemented it this way to be honest.
But the upside to the second is that the relation between User and Group is now as you define it in your requirements. So for me, keeping a correct Data Model instead of hacking around it, wins.
Take a look at django.contrib.auth.models for the classes I mentioned.
To clarify the second method:
app/models.py:
from django.contrib.auth.models import AbstractBaseUser, Group

class ProjectUser(AbstractBaseUser):
    group = models.ForeignKey(Group)
    # fields and methods from AbstractUser go here
    # fields and methods from PermissionsMixin go here

(Sorry, it's two classes instead of one you need to copy).


text:
Q: Header line break in PHPWord I'm attempting to create some templates in PHPWord. With the header and footer I would like to have two phrases on the left and right for each. However, using the code below gives an unnecessary line break. Any advice?
$footer = $section->addFooter();
$footer->addPreserveText(htmlspecialchars('Page {PAGE}', ENT_COMPAT, 'UTF-8'), null, array('alignment' => 'left'));
$footer->addText('Document', null, array('alignment' => 'right'));

Thanks

A: You can use a table to get your data to the same line in your footer (/header):
$table = $footer->addTable(array('width' => '5000', 'unit' => 'pct'));
$table->addRow();
$table->addCell(2000)->addPreserveText(htmlspecialchars('Page {PAGE}', ENT_COMPAT, 'UTF-8'));
$table->addCell(2000)->addTextRun(array('align' => 'right'))->addText('Document');


text:
Q: VS2003 error while performing build/rebuild solution in Release Mode I have VS2003 ASP.NET web application and when I perform build/rebuild solution in debug mode it compiles and build perfectly with no errors,
but when I change the mode to Release and try to perform a Build Solution or Rebuild solution I am getting following compile-error for various dlls that I am referencing.
I have replaced name of the name space with generic xyz
The type or namespace name 'xyz' could not be found ( are you missing a using directive or an assembly reference?)
All my refernces are correct and I am able to compile in debug mode without any errors.
My OS is Windows Vista
does anyone know why I am getting this error in Release mode and a possible workaround for this issue?
Following is the sample from output window
i have changed files name , i have not changed the actual errors
------ Rebuild All started: Project: XYZ, Configuration: Release .NET ------

Preparing resources...
Updating references...
Performing main compilation...
C:\xyz\a.cs(4,7): error CS0246: The type or namespace name 'ToolLib' could not be found (are you missing a using directive or an assembly reference?)
C:\xyz\a.cs(5,7): error CS0246: The type or namespace name 'ToolLib' could not be found (are you missing a using directive or an assembly reference?)
C:\xyz\a.cs(4,7): error CS0246: The type or namespace name 'ToolLib' could not be found (are you missing a using directive or an assembly reference?)
C:\xyz\a.cs(5,7): error CS0246: The type or namespace name 'ToolLib' could not be found (are you missing a using directive or an assembly reference?)
C:\xyz\a.cs(4,7): error CS0246: The type or namespace name 'ToolLib' could not be found (are you missing a using directive or an assembly reference?)
C:\xyz\a.cs(4,7): error CS0246: The type or namespace name 'ToolLib' could not be found (are you missing a using directive or an assembly reference?)
c:\xyz\b.cs(4,7): error CS0246: error CS0246: The type or namespace name 'Globals' could not be found (are you missing a using directive or an assembly reference?)
c:\xyz\c.cs(5,7): error CS0246: The type or namespace name 'ToolLib' could not be found (are you missing a using directive or an assembly reference?)
c:\xyz\d.cs(4,7): error CS0246: The type or namespace name 'Logger' could not be found (are you missing a using directive or an assembly reference?)

..........

and so on

----------

Build complete -- 26 errors, 0 warnings
Building satellite assemblies...
Satellite assemblies could not be built because the main project output is missing.

A: I closed the solution and deleted .suo file associated with solution  and opened the solution again and I was able to compile in both debug and release mode.
I have not changed anything else in the solution.
thanks all for your comments.


text: Q: Unsubscribe from Sails models when client logs out I'm making use of Sails' resourceful pubsub to subscribe to models and handle auto-emitted changes with sails.io.  What is the best way, on either client or server, to remove a particular client's subscriptions if they log out?


text:
Q: c# htmlagilitypack get table values I have a webpage that needs to parsed ad values to be stored in sqlserver db. I have tried to use HTMLagility pack.
HtmlDocument hdoc = new HtmlDocument();
hdoc.LoadHtml(HTML);
var cols = hdoc.DocumentNode.SelectNodes("//table[@id='results']//tr//th//td");
for (int i = 0; i < cols.Count; i = i + 2)
{
            DataRow dr = dt.NewRow();
            string name = cols[i].InnerText.Trim();
}

This is how my html looks

            ID

            Entity Name /

            Type

            Registered

            Effective Date

            Status /

            Status Date

            123456

                NAME1 COMPANY

            55 - TRadeUnion Company

            01/12/1912

            Exists Now

            12/14/1943

            A23456

                TESTA, INC.

            09 - Domestic Corporation

            04/29/1926

            Dissolved Company

            06/16/1998

I need to insert entityID,name, hyperlink, type description,registeredeffectivedate,status description,status date. Right now they all print in one single line and I do know how to parse it. Please help.
Thanks
MR

A: The TD's are not nested under TH's.
Try this: SelectNodes("//table[@id='results']/tr/td");


text:
Q: Titanium CLI on Win 7 - "EPERM, operation not permitted 'C:\Program Files\Gemeinsame Dateien'" I don't know what else to do as I tried everything I could find so far.
Situation:
I am trying to use Titanium via CLI on my Windows 7 Laptop.
Installing Node.js, Titanium, Titanium sdk, Android sdk all works fine.
PS C:\Windows\system32> node -v
   v0.12.9
PS C:\Windows\system32> ti -v
   5.0.6

   Installed SDKs:
   4.0.0.GA [selected]

Trying ti info as well as building something produces the following Error:
PS C:\Windows\system32> ti info
Titanium Command-Line Interface, CLI version 5.0.6, Titanium SDK version 4.0.0.GA
Copyright (c) 2012-2015, Appcelerator, Inc.  All Rights Reserved.

Please report bugs to http://jira.appcelerator.org/

 /Error: EPERM, operation not permitted 'C:\Program Files\Gemeinsame Dateien'
    at Error (native)
    at Object.fs.readdirSync (fs.js:761:18)
    at scan (C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\titanium-sdk\lib\emulators\genymotion.js:136:
25)
    at scan (C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\titanium-sdk\lib\emulators\genymotion.js:148:
26)
    at C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\titanium-sdk\lib\emulators\genymotion.js:154:10
    at C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\titanium-sdk\lib\emulators\genymotion.js:111:8
    at Immediate.q.process (C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\async\lib\async.js:731:21)
    at processImmediate [as _immediateCallback] (timers.js:367:17)
---------------------------------------------
    at Object.async.setImmediate (C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\async\lib\async.js:96:15
)
    at C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\async\lib\async.js:696:21
    at Array.forEach (native)
    at _each (C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\async\lib\async.js:32:24)
    at _insert (C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\async\lib\async.js:681:11)
    at Object.q.push (C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\async\lib\async.js:708:15)
    at C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\titanium-sdk\lib\emulators\genymotion.js:127:12
    at Object.queue.drain (C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\node-appc\lib\subprocess.js:108
:3)
    at next (C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\node-appc\node_modules\async\lib\async.js:804
:31)
---------------------------------------------
    at Object.async.setImmediate (C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\node-appc\node_modules\a
sync\lib\async.js:110:15)
    at C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\node-appc\node_modules\async\lib\async.js:768:21
    at Array.forEach (native)
    at _each (C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\node-appc\node_modules\async\lib\async.js:46
:24)
    at _insert (C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\node-appc\node_modules\async\lib\async.js:
753:11)
    at Object.q.push (C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\node-appc\node_modules\async\lib\asy
nc.js:782:15)
    at Object.findExecutable (C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\node-appc\lib\subprocess.js:
113:8)
    at Object.async.parallel.virtualbox (C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\titanium-sdk\lib\
emulators\genymotion.js:97:20)
    at C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\node_modules\async\lib\async.js:524:25

I have to say that i was already trying different versions of Node (4.x, 5.x).
I read about the Genymotion issue.
I have Genymotion installed, never uninstalled it and i did try to delete the genymotion.js from sdk directory.
Deleting this produces:
PS C:\Windows\system32> ti info
Titanium Command-Line Interface, CLI version 5.0.6, Titanium SDK version 4.0.0.GA
    Copyright (c) 2012-2015, Appcelerator, Inc.  All Rights Reserved.

    Please report bugs to http://jira.appcelerator.org/

     |[ERROR] Failed to run command "info"
    [ERROR] Error: Cannot find module 'titanium-sdk/lib/emulators/genymotion'
        at Function.Module._resolveFilename (module.js:336:15)
        at Function.Module._load (module.js:278:25)
        at Module.require (module.js:365:17)
        at require (module.js:384:17)
        at Object.<anonymous> (C:\ProgramData\Titanium\mobilesdk\win32\4.0.0.GA\cli\lib\info.js:12:15)
        at Module._compile (module.js:460:26)
        at Object.Module._extensions..js (module.js:478:10)
        at Module.load (module.js:355:32)
        at Function.Module._load (module.js:310:12)
        at Module.require (module.js:365:17)
        at require (module.js:384:17)
    ---------------------------------------------
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:275:35
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:44:16
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:694:17
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:173:37
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:52:16
        at Object.done (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:248:21)
        at Object.<anonymous> (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:44
    :16)
        at CLI._fireHookCallback (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\lib\hook.js:269:12)
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\lib\hook.js:248:10
    ---------------------------------------------
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:275:35
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:44:16
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:694:17
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:173:37
        at CLI.detectMissingArguments (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\lib\cli.js:695:13)
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:689:13
        at iterate (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:265:13)
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:277:29
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:44:16
    ---------------------------------------------
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:275:35
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:44:16
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:694:17
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:173:37
        at CLI.<anonymous> (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\lib\cli.js:523:9)
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:689:13
        at iterate (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:265:13)
        at async.forEachOfSeries.async.eachOfSeries (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules
    \async\lib\async.js:284:9)
        at _parallel (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:688:9)
    ---------------------------------------------
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:275:35
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:44:16
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:694:17
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:173:37
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\lib\hook.js:243:8
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:689:13
        at iterate (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:265:13)
        at async.forEachOfSeries.async.eachOfSeries (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules
    \async\lib\async.js:284:9)
        at _parallel (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:688:9)
    ---------------------------------------------
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:275:35
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:44:16
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:694:17
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:173:37
        at CLI.processCompletion (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\lib\cli.js:370:2)
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:689:13
        at iterate (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:265:13)
        at process._tickCallback (node.js:355:11)
    ---------------------------------------------
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:275:35
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:44:16
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:694:17
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:173:37
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:52:16
        at Object.done (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:248:21)
        at Object.<anonymous> (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:44
    :16)
        at CLI._fireHookCallback (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\lib\hook.js:269:12)
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\lib\hook.js:248:10
    ---------------------------------------------
        at Object.setImmediate (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:2
    00:9)
        at _insert (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:861:19)
        at Object.q.push (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\async\lib\async.js:888:17)

        at Object.findExecutable (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\node_modules\node-appc\lib\subp
    rocess.js:113:8)
        at resolveNode (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\lib\titanium.js:97:34)
        at C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\lib\titanium.js:74:5
        at Object.<anonymous> (C:\Users\cluecke\AppData\Roaming\npm\node_modules\titanium\lib\titanium.js:80:2)
        at Module._compile (module.js:460:26)
        at Object.Module._extensions..js (module.js:478:10)

Also:
All of this is produced with admin privileges, even though my user has the same permissions on that machine.
Both admin and my user have all permissions on "common files"
last information at this point
PS C:\Windows\system32> ti config
android.ndkPath        = "C:\\Users\\cluecke\\Ti_Android\\android-ndk-r10e"
android.sdkPath        = "C:\\Users\\cluecke\\AppData\\Local\\Android\\sdk1"
app.workspace          = "C:\\Users\\cluecke\\Ti_Workspace"
cli.colors             = true
cli.completion         = false
cli.failOnWrongSDK     = false
cli.httpProxyServer    = ""
cli.ignoreDirs         = "^(\\.svn|_svn|\\.git|\\.hg|\\.?[Cc][Vv][Ss]|\\.bzr|\\$RECYCLE\\.BIN)$"
cli.ignoreFiles        = "^(\\.gitignore|\\.npmignore|\\.cvsignore|\\.DS_Store|\\._.*|[Tt]humbs.db|\\.vspscc|\\.vssscc|\
\.sublime-project|\\.sublime-workspace|\\.project|\\.tmproj)$"
cli.logLevel           = "trace"
cli.progressBars       = true
cli.prompt             = true
cli.rejectUnauthorized = "yes"
cli.width              = 100
paths.commands         = []
paths.hooks            = []
paths.modules          = []
paths.plugins          = []
paths.sdks             = []
paths.templates        = []
sdk.selected           = "4.0.0.GA"
user.email             = "***"
user.locale            = "de"
user.name              = "***"

I hope you can help!

A: Titanium's Genymotion detection code does a naive scan of the "Program Files" directory looking for the VirtualBox installation. Some of the directories in the "Program Files" directory require elevated privileges. Doing a simple fs.readdirSync() in Node.js throws an exception.
The removing the Genymotion file doesn't work anymore. It's directly referenced by the "ti info" code.
So, to workaround this, you simply need to set the "genymotion.executables.vboxmanage" setting to the path of VirtualBox's "VBoxManage.exe" executable:
ti config genymotion.executables.vboxmanage "C:\Program Files\Oracle\VirtualBox\VBoxManage.exe"


text:
Q: Force logged-in users to fill out name and email fields for commenting? This is a bit of a weird request, but I'd like to force loggged-in users (one specifically) to fill out the standard not-logged-in name / email address fields before submitting a comment on the site.
[EDIT: I'm realizing this is probably even more difficult than I thought. I not only don't want the comment form to show this one user as logged-in, I want it to actually submit the comment as a not-logged-in user. Ideally without logging out the user. Is there a way to remove the logged-in check altogether from the comment form and comment-form-submit code? I don't mind forcing all users to fill out a form every time they submit a comment if that's the easiest fix.]
Is this possible? I would prefer not to hack core code but I'm not opposed to writing a static comment form, if that would help. I suspect not since the form-submit is still checking on logged-in status...
Thanks for your help!
[Edit - WHY I NEED THIS: The site is using the Member Access plugin to show select pages/posts to registered users only. However, my client didn't want anyone to actually have to register for a WordPress account - he wanted the login/signup forms to check against an external ESP to see if they were on an email list, and if so log them in automatically. From the user's perspective, they enter their email address and poof! can see the content.
To achieve this, the code does the lookup againt the ESP and if the email addy exists, logs them into a dummy WordPress account I created. But once they're logged in, I want them to each be able to comment individually, not as this dummy account.]

A: I didn't solve this but don't want to waste anyone else's time on it. I decided to create individual user accounts for every visitor instead.


text:
Q: How to modify grunt watch tasks based on the file changed? I'm writing a node.js program that will watch a directory filled with a large (300-ish) amount of scss projects. Grunt-watch (run either through the node module or on its own, whatever works) will be configured so that whenever a scss file is changed, it will be compiled with compass, the output file moved to a separate directory, for example:
./1234/style.scss was changed >> grunt-watch runs grunt-compass >> /foo/bar/baz/1234/style.css updated
The project directory that the file was in is obviously very important (if grunt-compass sent all the compiled files to the same directory, they would be jumbled and unusable and the grunt automation would be purposeless). I order to make sure all files are routed to the correct place, I am dynamically changing the grunt-compass settings every time a css file is updated.
Sample gruntfile:
module.exports = function(grunt) {

grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    watch: {
      files: './*/*.scss',
      tasks: ['compass']
    },
    compass: {
      origin:{
        options: {
          //temportary settings to be changed later
          sassDir: './',
          cssDir: './bar',
          specify: './foo.scss'
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-compass');

  grunt.event.on('watch', function(action, filepath, target) {
    var path = require('path');
    grunt.log.writeln(target + ': ' + filepath + ' might have ' + action);
    var siteDirectory = path.dirname(filepath);

    //changes sass directory to that of the changed file
    var option = 'compass.origin.options.sassDir';
    var result = __dirname + '/' + siteDirectory;
    grunt.log.writeln(option + ' changed to ' + result);
    grunt.config(option, result);

    //customizes css output directory so that file goes to correct place
    option = 'compass.origin.options.cssDir';
    result = path.resolve(__dirname, '../', siteDirectory);
    grunt.log.writeln(option + ' changed to ' + result);
    grunt.config(option, result);

    //grunt.task.run(['compass']);

  });

};

However this doesn't work. If you run 'grunt watch' in verbose mode, you will see that grunt runs both the grunt.event.on function and the watch task in separate processes. The second parsing of the gruntfile reverts all my event.on config changes to the defaults above, and compass fails to run.
As seen in the event.on comments, I attempted to add a grunt.task.run() to make sure that compass was run in the same process as the event.on function, which would preserve my config changes. However the task refused to run, likely because I'm doing it wrong.
Unfortunately, the grunt.event.on variables are not sent to the defined grunt-watch task, otherwise I could write a custom function that would change the compass settings and then run compass in the same process.
I've tried implementing this without grunt, using the watch function build into compass, however compass can only store one static output path per project and can only watch one project at once.
I have currently gotten around this issue by adding a node program that takes the site name as a parameter, rewrites the grunfile.js by running using fs, and then running 'grunt watch' via an exec function. This however has it's own drawbacks (I can't view the grunt.log data) and is horribly convoluted, so I'd like to change it.
Thank you so much for any insight.

A: You need to specify
options : { nospawn : true }
in your watch task config to have the watch run in the same context:
watch: {
  files: './*/*.scss',
  tasks: ['compass'],
  options : { nospawn : true }
}

See this section of documentation for more info on this.


text:
Q: Can I make different attribute for every vertex and every instance When using gl.drawArraysInstanced I can use gl.vertexAttribDivisor and stride and offset to change the behavior how often a attribute changes, and I know what I can do with it.
But I want that the attribute changes for every vertex and every instance like so:
// Vertex buffer
[
  vertex1,
  vertex2,
  vertex3,
]

// Color buffer
[
  color1,
  color2,
  color3,

  // Different colors for second triangle
  color4,
  color5,
  color6,
]

gl .bindBuffer (gl .ARRAY_BUFFER, vertexBuffer);
gl .vertexAttribPointer (vertexLocation, 4, gl .FLOAT, false, 0, 0);
gl .enableVertexAttribArray (vertexLocation);

gl .bindBuffer (gl .ARRAY_BUFFER, colorBuffer);
gl .vertexAttribPointer (colorLocation, 4, gl .FLOAT, false, 0, 0);
gl .enableVertexAttribArray (colorLocation);

// What to do else with colorLocation.

gl .drawArraysInstanced (gl .TRIANGLES, 0, 3, 2);

A: I have now used a FLOAT texture with the needed data in the vertex shader to get the desired results.


text:
Q: Could not get fullduration of my MP3 file I am trying to get fullduration my MP3 file but it returns me NaN,
Here is my code:
 <script>

            $f("player", "http://releases.flowplayer.org/swf/flowplayer-3.2.7.swf", {
                clip: {
                    // our song
                    url: '1.mp3',

                    // when music starts grab song's metadata and display it using content plugin
                    onStart: function(){
                        var fullduration = parseInt(this.getClip().fullDuration, 10);
                        alert(fullduration);
                        var p = this, c = p.getClip(), d;
                        timer = setInterval(function(){
                            d = showtime(c.fullDuration);
                            $("a[href=" + c.url + "] > samp").html(showtime(p.getTime()) + "/" + d);
                        }, 1000);

                    }
                },

                plugins: {

                    // content plugin settings
                    content: {
                        url: 'flowplayer.content-3.2.0.swf',
                        backgroundColor: '#002200',
                        top: 25,
                        right: 25,
                        width: 160,
                        height: 60
                    },

                    // and a bit of controlbar skinning
                    controls: {
                        backgroundColor: '#002200',
                        height: 30,
                        fullscreen: false,
                        autoHide: false,
                        volume: false,
                        mute: true,
                        time: true,
                        stop: false,
                        play: false

                    }
                }
            });
        </script>

A: I had a look at your code using flowplayer version 3.2.7 and 3.2.8. With version 3.2.7 I get the same error and with 3.2.8 I get the duration in seconds which is what is expected. So you'll need to upgrade and change the following from
http://releases.flowplayer.org/swf/flowplayer-3.2.7.swf

to
http://releases.flowplayer.org/swf/flowplayer-3.2.8.swf


text:
Q: Save a NativeScript/Angular ImagePicker selection or get the full file path Upon selecting an Image with the Image Picker I receive a content// url
content://com.android.providers.media.documents/document/image%3A139

When using ImageSource.fromAsset() I am returned in empty object. My current goal is to save that image as a new image so I can send it in a req.
I have also tried Utils.android.getApplicationContext().getContentResolver() with no avail.
    public onSelectSingleTap() {
    return new Promise((resolve, reject) => {
        this.isSingleMode = true;

        let context = imagepicker.create({
            mode: "single",
            mediaType: ImagePickerMediaType.Image,
        });

        context
            .authorize()
            .then(() => {
                return context.present();
            })
            .then((selection) => {
                if (selection.length > 0) {
                    ImageSource.fromAsset(selection[0])
                        .then((imageSource) => {
                            console.log('Image Source: ', imageSource)
                            let documentsFolder = knownFolders.documents();
                            let random = Math.floor(Math.random() * 1000000000);
                            const filePath: string = path.join(documentsFolder.path, 'image' + random.toString());
                            let saved = imageSource.saveToFile(filePath, 'jpg')
                            if (saved) {
                                const savedFilePath: string = path.join(documentsFolder.path, 'image' + random.toString() + '.jpg');
                                const file: File = File.fromPath(savedFilePath);
                                // resolve({file: file, content: selection[0]})
                            }
                        })
                        .catch((err) => console.error("Error loading ImageSource:", err));
                }
            });
    })
}

ImageSource: {"android": {}}
I am not sure if I need to SAVE as a new image or get the actual file path to send it in my request.
Most other answers that I come across are deprecated.

A: I've had to do this in several places in an app I built a few years ago. That app is using @nativescript/core@7.1.3 and @nativescript/imagepicker@1.0.2. I'm thinking it should still work in current versions.
I've implemented a reusable service for triggering the image picker and returning an array of image paths. The array is typed as an array of strings, but I'm not sure what it actually is. (not typing things properly was a huge oversight back then)
import { Injectable } from '@angular/core'
import * as imgPicker from '@nativescript/imagepicker'
import { ImageSource, Folder, knownFolders, path, isAndroid, isIOS } from '@nativescript/core'

@Injectable({
   providedIn: 'root'
})
export class ImagePickerService {
   private iosFolder: Folder
   private iosCounter = 0

   constructor() {}

   public async chooseImages(maxImages: number, folderName: string): Promise<string[]> {
      // init image picker
      const options: imgPicker.Options = {
         mode: maxImages > 1 ? 'multiple' : 'single',
         mediaType: imgPicker.ImagePickerMediaType.Image
      }
      const context = imgPicker.create(options)

      // authorize
      await context.authorize()

      // get selection
      const selection = await context.present()
      const imgPaths = []
      if (!selection || !selection.length) return imgPaths

      // create folder for ios
      if (isIOS) {
         this.iosFolder = knownFolders.documents().getFolder(folderName)
      }

      // get the local path for each image and add it to images array
      for (const imgAsset of selection) {
         if (isIOS) {
            const imgSrc = await ImageSource.fromAsset(imgAsset)

            // imgAsset.ios is PHAsset and not path - so I am creating my own path
            const imgPath = path.join(this.iosFolder.path, `${Date.now()}-${this.iosCounter}.jpg`)
            imgSrc.saveToFile(imgPath, 'jpg')
            imgPaths.push(imgPath)
            this.iosCounter++
         } else if (isAndroid) {
            imgPaths.push(imgAsset.android.toString())
         }
      }

      return imgPaths
   }

   public clearFolder(folderName: string): void {
      if (this.iosFolder) this.iosFolder.clear()
   }
}

Once you have your list of image paths, you can send them to a backend via the background http service:
import { Injectable } from '@angular/core'
import { UtilsService } from './utils.service'
const bgHttp = require('@nativescript/background-http')
const nsLocalStorage = require('@proplugins/nativescript-localstorage')
import { config } from '../config/config'
import { UserError } from '../classes/custom-errors'

@Injectable({
   providedIn: 'root'
})
export class FormdataService {
   private serverUrl = this.utilsService.serverUrl

   constructor(private utilsService: UtilsService) {}

   public uploadPhotos(imgPaths, folder, complete, res) {
      const jwt = nsLocalStorage.getItem('JWT')

      // upload configuration
      const session = bgHttp.session('images')
      const request = {
         url: `${this.serverUrl}/photos/${folder}`,
         method: 'POST',
         headers: {
            'Content-Type': 'application/octet-stream',
            Authorization: `Bearer ${jwt}`
         },
         androidDisplayNotificationProgress: true,
         androidAutoClearNotification: true
      }

      // prepare images for upload
      const uploadImgs = imgPaths.map((image) => {
         if (image.size > config.fileSizeLimit) throw new UserError('One or more photos are too large.')
         return { name: 'images', filename: image, mimeType: 'image/jpeg' }
      })

      // upload images and data
      const task = session.multipartUpload(uploadImgs, request)

      // handle events
      task.on('complete', (e) => complete(e))
      task.on('error', (e) => complete(e))
      task.on('responded', (e) => res(e.data))
   }
}


text:
Q: Qt Creator not launching in OpenSUSE After a few years using Ubuntu, I decided to go back to OpenSUSE.  I installed Qt Creator using the online installer from Qt, along with all the framework versions I wanted.  Qt Creator refuses to launch.  When run from command line, is gives the following error:
static QPlatformTheme* QKdeTheme::createKdeTheme(): Unable to determine KDE dirs

I managed to install Qt 5 Creator from repositories on OpenSUSE, and this one runs.  I can't tell the difference between it and the one from Qt (which I used on Ubuntu).
This version of Qt Creator gives the same error as above, but in the Application Output window every time I run an application.
Any idea what causes this?  Or how to resolve it?
Thanks in advance for any help given.

A: You need to set the kde directory trees into the KDEDIRS environment variable  of your system. In order to do this you can do the following:

*

*List the kde directory trees, by executing the command kde4-config --path config.

*Edit the config file of your connection shell to set the KDEDIRS variable with the output of the above command.
Done!. Reboot your system and hopefully, you will not get this error message each time you run your program with your connection shell running.


text:
Q: Combining XML files and "title" each section I need to combine several xml files and tell the xml which section belongs to each file. Below are the two examples of such files.
D:\pathtoxml\1.xml
<?xml version="1.0"?>

<configuration>
  <configSections>

  </configSections>
  <appSettings>
    <add key="key1" value="valueOfKey1" />
  </appSettings>
</configuration>

D:\pathtoxml\2.xml
<?xml version="1.0"?>

<configuration>
  <appSettings>
    <add key="key1" value="valueofkey1" />
  </appSettings>
  <connectionStrings>
    <add name="connectionstring1" connectionString="connectionstringstuff" />
  </connectionStrings>
</configuration>

The end file needs to look like this
<WebConfigs>
  <path = 'D:\pathtoxml\1.xml'>

    <configuration>
      <configSections>

      </configSections>
      <appSettings>
        <add key="key1" value="valueOfKey1" />
      </appSettings>
    </configuration>
  </path>
  <path = 'D:\pathtoxml\2.xml'>

    <configuration>
      <appSettings>
        <add key="key1" value="valueofkey1" />
      </appSettings>
      <connectionStrings>
        <add name="connectionstring1" connectionString="connectionstringstuff" />
      </connectionStrings>
    </configuration>
  </path>
</WebConfigs>

My current code looks like this however I get all sorts of XML errors
$path1 = 'D:\pathtoxml\1.xml'
$path2 = 'D:\pathtoxml\2.xml'
$exportPath = 'D:\exportPath\combined.xml'

$finalXml = "<path = '" + $path1 + "'>"
[xml]$xml = get-content $path1
$finalXml += $xml.InnerXml
$finalXml += "</path>"
$finalXml += "<path = '" + $path1 + "'>"
[xml]$xml = get-content $path2
$finalXml += $xml.InnerXml
$finalXml += "</path>"
([xml]$finalXml).Save($exportPath)

I did find this question however it doesn't address adding in a way to tell in the combined file where each files source was.

A: As you're already finding out, Powershell's XML is powerful but touchy.  I honestly don't fully understand it at this point, but this operation is pretty straightforward.  I have found that the XmlElement object type is easiest for me to work with when dealing with child nodes and the final product as an XmlDocument object. (The <variable>.<node> constructs imply XmlElement)
$PathList = "C:\Test\1.xml","C:\Test\2.xml"
$exportPath = 'C:\Test\combined.xml'

#Cheating a bit, but we don't need much
$finalXml = [xml]("<xml></xml>")

ForEach($Path in $PathList){
    $CurrentXml = [xml](Get-Content $Path)
    $CurrentXml.configuration.SetAttribute("path",$Path)

    <#
      Powershell's XML is touchy.
      Imports the original document into $finalXml's namespace,
      then appends it to the first level inside $finalXml's document node.
    #>
    $importedNode = $finalXml.ImportNode($CurrentXml.DocumentElement, $true)
    $finalXml.DocumentElement.AppendChild($importedNode)
}

$finalXml.Save($exportPath)

This doesn't follow your output exactly, but the <webconfigs> and <path> nodes are probably superfluous if that's all your output needs to save.  It should look like this:
<xml>
    <configuration path="D:\pathtoxml\1.xml">
        ...
    </configuration>
    <configuration path="D:\pathtoxml\2.xml">
        ...
    </configuration>
</xml>

References:
XmlElement class
XmlDocument class


text:
Q: "javax.crypto.BadPaddingException: pad block corrupted" exception during decryption I am working on an existing app, coming to it having not written it.
I get this exception (javax.crypto.BadPaddingException: pad block corrupted) during decryption of a username and password in this method:
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] decrypted = cipher.doFinal(encrypted);//ERROR HERE////////////////////////////////////////////////////////////////////////////
    return decrypted;
}

The value of encrypted is a byte array with 16 numeric values between -89 and 126. Can anyone see an issue with this code? Here is all of the important code:
Inside the Settings class (the client of the Encryptor class):
private final String ENCRYPTION_SEED = "MH8734()9Akg&*3d";

    public void loadAuthorization() {
                try {
                    username = getStringEncrypted(sharedPreferences, KEY_USERNAME);
                    password = getStringEncrypted(sharedPreferences, KEY_PASSWORD);
                    isAuthorized = sharedPreferences.getBoolean(KEY_IS_AUTHORIZED,
                            false);
                } catch (Exception e) {
                    Log.e("LOAD ERROR", "Exception during loading authorization");
                }
            }

    public String getStringEncrypted(SharedPreferences sharedPreferences,
            String key) {
        try {
            String valueEncrypted = sharedPreferences.getString(key, "NULL");
            String valueDecrypted = Encryptor.decrypt(ENCRYPTION_SEED + key,
                    valueEncrypted);
            return valueDecrypted;
        } catch (Exception e) {
            return "NULL";
        }
    }

public void saveAuthorization() {
    SharedPreferences.Editor ed = sharedPreferences.edit();
    try {
        setStringEncrypted(ed, KEY_USERNAME, username);
        setStringEncrypted(ed, KEY_PASSWORD, password);
        ed.putBoolean(KEY_IS_AUTHORIZED, isAuthorized);
    } catch (Exception e) {
            Log.e("SAVE ERROR", "Exception during saving authorization");
        }
        ed.commit();
    }

public void setStringEncrypted(SharedPreferences.Editor ed, String key,
            String value) {
        try {
            String valueEncrypted = Encryptor.encrypt(ENCRYPTION_SEED + key,
                    value);
            ed.putString(key, valueEncrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

The full Encryptor class:
package com.boolbalabs.petlinx.settings;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Encryptor {

    private final static String HEX = "0123456789ABCDEF";

    private static void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
    }

    private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);//ERROR HERE////////////////////////////////////////////////////////////////////////////
        return decrypted;
    }

    public static String decrypt(String seed, String encrypted) throws Exception {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] enc = toByte(encrypted);
        byte[] result = decrypt(rawKey, enc);
        return new String(result);
    }

    private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
    }

    public static String encrypt(String seed, String cleartext) throws Exception {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] result = encrypt(rawKey, cleartext.getBytes());
        return toHex(result);
    }
    public static String fromHex(String hex) {
        return new String(toByte(hex));
    }

    private static byte[] getRawKey(byte[] seed) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);
        kgen.init(128, sr); // 192 and 256 bits may not be available
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        return raw;
    }

    public static byte[] toByte(String hexString) {
        int len = hexString.length()/2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++)
            result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
        return result;
    }
    public static String toHex(byte[] buf) {
        if (buf == null)
            return "";
        StringBuffer result = new StringBuffer(2*buf.length);
        for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
        }
        return result.toString();
    }
    public static String toHex(String txt) {
        return toHex(txt.getBytes());
    }
}

This answer suggests not to use SecureRandom to generate a key. The code in the app that I'm working on does use SecureRandom for that. How can I fix it?
Here is the code that uses SecureRandom.
private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(seed);
    kgen.init(128, sr); // 192 and 256 bits may not be available
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    return raw;
}


text:
Q: sscanf error on scanning a formatted file I am trying to read and parse an input file using fgets() and sscanf(). Here is my function (only the relevant part is listed here):
void reading_file(char* file)
{
    FILE *f = fopen(file, "r");
    char line[256];
    while(fgets(line, sizeof(line), f))
    {
        int i = 0;
        char str[20];
        sscanf(line, "%d %s", &i, str);
        printf("%d %s\n", i, str);
    }
}

The input file is:
0 be68c5bc1ee7be6f20728579ee082aed6214825b
1 e2d6c1bb794ff4545ef2f101ca904dbbb3ed3923

The output of this piece of code is:
875849270 aa71dbd21bd2b05f3bd261256f443fd5f9f7272e
1633890352 465c63da3d0168553c1027eb00ca364c337ced44

Totally wrong.
The funny part is here. If I use a struct to hold the input lines, the output is correct! Code after revising is here:
typedef struct s_s{
    int id;
    char hash[20];
} s_t;

void reading_file(char* file)
{
    FILE *f = fopen(file, "r");
    char line[256];
    while(fgets(line, sizeof(line), f))
    {
        s_t s;
        sscanf(line, "%d %s", &s.id, s.hash);
        printf("%d %s\n", s.id, s.hash);
    }
}

The output is exact the same as the input file. Why is that? Does anyone have an explanation?

A: *

*shouldn't while(fgets(line, sizeof(line), file)) be while(fgets(line, sizeof(line), f)) ?
You can check the man page of fgets().

*Next, to correct the issue in your code, char str[20]; needs to be changed to something like char str[128]; because, the input from the file for the string is much longer than that of 20 charracters.
However, IMO, for the use of a structure returning the correct answer, is a part of Undefined behaviour.


text:
Q: Combining 2 Hex Values Into 1 Hex Value I have a coordinate pair of values that each range from [0,15]. For now I can use an unsigned, however since 16 x 16 = 256 total possible coordinate locations, this also represents all the binary and hex values of 1 byte. So to keep memory compact I'm starting to prefer the idea of using a BYTE or an unsigned char. What I want to do with this coordinate pair is this:
Let's say we have a coordinate pair with the hex value [0x05,0x0C], I would like the final value to be 0x5C. I would also like to do the reverse as well, but I think I've already found an answer with a solution to the reverse. I was thinking on the lines of using & or | however, I'm missing something for I'm not getting the correct values.
However as I was typing this and looking at the reverse of this: this is what I came up with and it appears to be working.
byte a = 0x04;
byte b = 0x0C;

byte c = (a << 4) | b;

std::cout << +c;

And the value that is printing is 76; which converted to hex is 0x4C.
Since I have figured out the calculation for this, is there a more efficient way?
EDIT
After doing some testing the operation to combine the initial two is giving me the correct value, however when I'm doing the reverse operation as such:
byte example = c;
byte nibble1 = 0x0F & example;
byte nibble2 = (0xF0 & example) >> 4;

std::cout << +nibble1 << " " << +nibble2 << std::endl;

It is printout 12 4. Is this correct or should this be a concern? If worst comes to worst I can rename the values to indicate which coordinate value they are.
EDIT
After thinking about this for a little bit and from some of the suggestions I had to modify the reverse operation to this:
 byte example = c;
 byte nibble1 = (0xF0 & example) >> 4;
 byte nibble2 = (0x0F & example);

 std:cout << +nibble1 << " " << +nibble2 << std::endl;

And this prints out 4 12 which is the correct order of what I am looking for!

A: First of all, be careful about there are in fact 17 values in the range 0..16. Your values are probably 0..15, because if they actually range both from 0 to 16, you won't be able to uniquely store every possible coordinate pair into a single byte.
The code extract you submitted is pretty efficient, you are using bit operators, which are the quickest thing you can ask a processor to do.
For the "reverse" (splitting your byte into two 4-bit values), you are right when thinking about using &. Just apply a 4-bit shift at the right time.


text:
Q: jQuery date picker not closing on outside click I have a jquery date picker that opens when clicking on a icon. The date picker is opening correctly and the logic is also happening correctly. I'm facing an issue where the date picker is not closing when clicking outside (or losing focus). How can i close the datepicker when clicking outside?
The code is like this
<i class="fad fa-calendar-week" id="edit-checkin-date" onclick="editCheckoutDates();"></i>

the function
function editCheckoutDates(){
  jQuery(function ($) {
  jQuery("#edit-checkin-date")
  .datepicker({
    language: "en",
    range: true,
    dateFormat: "M d",
    multipleDatesSeparator: " - ",
    minDate: from_min_date,
    maxDate: to_max_date,
    onSelect: function(formattedDate, date, inst) {
      if (date[0]) {
        $("#from").val(
          ("0" + (date[0].getMonth() + 1)).slice(-2) +
          "/" + //month
          ("0" + date[0].getDate()).slice(-2) +
          "/" + //day
            date[0].getFullYear()
        ); //year);
      }
      if (date[1]) {
        $("#to").val(
          ("0" + (date[1].getMonth() + 1)).slice(-2) +
          "/" + //month
          ("0" + date[1].getDate()).slice(-2) +
          "/" + //day
            date[1].getFullYear()
        ); //year);
      }

      if (2 !== date.length) return;

    }
  });
});
}

Here the date picker is opening when clicking on the icon stated above. But the issue is when clicking outside the date picker does not close.

A: try adding this,
$("#edit-checkin-date").on("blur", function(e) { $(this).datepicker("hide"); });