text:
Q: Error:Program type already present: android.support.design.widget.CoordinatorLayout$Behavior Lot of problem after updating my api level in my previous project,
Error:Program type already present: android.support.design.widget.CoordinatorLayout$Behavior
    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.3'
        classpath 'com.google.gms:google-services:3.2.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        google()

        //admob 24 june 2018

        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

here i also get red mark at     implementation 'com.android.support:appcompat-v7:27.1.1' and     implementation 'com.google.android.gms:play-services-games:15.0.1'
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '27.0.3'
    defaultConfig {
        applicationId "com.david.aquiz"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 2
        versionName "1.0.1"
        //multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    //mobfox
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.google.android.gms:play-services-games:15.0.1'
    implementation 'com.google.android.gms:play-services-ads:15.0.1'
    implementation 'com.google.android.gms:play-services-plus:15.0.1'
    implementation  'com.google.firebase:firebase-ads:15.0.1'
    implementation 'com.google.firebase:firebase-core:16.0.1'
    //compile 'com.google.android.gms:play-services:10.0.1'
    //dex error
    //compile 'com.android.support:multidex:1.0.1'
}
apply plugin: 'com.google.gms.google-services'

A: Update your support design to 27.1.1
implementation 'com.android.support:design:27.1.1'
And
compileSdkVersion to 27 : compileSdkVersion 27


text:
Q: Can I sell buildings? If so, how? I accidentally bought way too many Red Toad houses as I thought they would stack in the same location, on top of each other(they don't).  Can I sell my unused buildings? If so, how?

A: As a matter of fact, no, you can't. However, it shouldn't take long to earn the coins needed to buy things again!

A: No you can't but you can put them away, to do this go to the main screen tap Build then Put away than tap what you want to put away.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How To Export My Runnable Jar With Images And Sound? I am making a basic program for my friend that shows this funny picture of him and loops a sound. When i export my JAR it didn't work so I opened the JAR with WinRar and the files were there but they weren't playing
CODE:
//imports
 public class twerk {
static File fl = new File("res//sounds//liver.au");
static int loo = 1;
static JFrame frame = new JFrame("COLLIN");
public static void frame(){
    frame.setSize(1086,800);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    ImageIcon image = new ImageIcon("res//images//collin.jpg");
    JLabel label = new JLabel(image);
    frame.add(label, BorderLayout.NORTH);
    frame.setIconImage(image.getImage());
    frame.setVisible(true);
    try
    {

        String st =fl.getPath();
        InputStream in = new FileInputStream(st);
        AudioStream au = new AudioStream(in);
        AudioPlayer.player.start(au);
        if(loo == 1){
            Thread.sleep(1900);
            frame();
        }

    } catch(Exception e){}
}
    public static void main(String[] args){

    frame();

}

}

A picture of the JAR file open in WinRar

So you can see that the images and sounds folder are in the jar file, but they aren't being used

A: By the time of deployment, those resources have become an embedded-resource.  That being the case, the resource must be accessed by URL instead of File.  See the info page for the tag, for a way to form an URL.
Note on paths.  According to that listing:
"res//images//collin.jpg"

Should become:
"/images/collin.jpg"


text:
Q: Qt database drivers I built qt with -plugin-sql-mysql -plugin-sql-sqlite flags. I have libqsqlmysql.a and libqsqlite.a. I use qt in my project. But my build system is not qt, I use waf.
I have the following problem when I  try to run my application which establishes connection with mysql database:
QSqlDatabase: QMYSQL driver not loaded
QSqlDatabase: available drivers:
QSqlDatabase: an instance of QCoreApplication is required for loading driver plugins
INFO - Failed to connect to root mysql admin

I added -lqsqlmysql to compiler options when I build the app.
Can you please explain how qt drivers work, how and when it tries to load driver. What is a qt driver (dll, lib, ....)?

A: I think your app is trying to load the database plugin dynamically, from a DLL. This document will help you find the appropriate location for the database driver DLL. Alternatively, you could link your app against the plugin statically, here's how.

A: Qt has plugins for several types of databases and these plugins are located in the following location:
$(QTDIR)/plugins/sqldrivers

First check if mysql plugin is present there. If plugin is not there then it means you didn't compile Qt properly, so you should recompile Qt with enabled MySql plugin. Otherwise probably your application doesn't load mysql plugin properly. Qt plugins are loaded dynamically during initialization of application i.e when QSqlDatabase object will be initialized. If plugin location is not set properly then none of plugins will be loaded. You can check location where your application expect to find plugins via following Qt API:
QStringList QCoreApplication::libraryPaths ()

If application doesn't point to right location you can set plugin path by calling of:
void QCoreApplication::addLibraryPath ( const QString & path )

Or by creation of qt.conf file in folder where your executable is placed. In this file you can configure plugins location in the following way:
[Paths]
Plugins = %pluginlocation%


text:
Q: Comando para criar atalho de um site no smartphone? Solicitar ao usuário que crie um ícone do meu site na tela inicial do seu smartphone.
Preciso que quando o usuário entrar no site ele receba uma notificação para criar o icone. Preciso saber o comando que faz isso. Já pesquisei e nada encontrei.

A: Informar o utilizador
Para websites não existe tal comando, o controlo do que acontece no dispositivo está no utilizador do mesmo e não no que ele utiliza.
Deverás apresentar uma popup ou algo do género para informar o visitante que pode aceder ao menu X e adicionar um atalho à tela inicial.

alert("Olá, adiciona-me ao teu homescreen fazendo uso do menu principal do teu navegador!");

Também podes ter um texto a detalhar como realizar a tarefa de forma a facilitar a vida ao utilizador:

Como adicionar este website à tela inicial
iOS
  Clique no ícone que se parece com uma caixa com um salto seta fora dela (isso também permite que você tweet, imprimir ou enviar a página que você está). Clique em "Adicionar à tela inicial".
Android
  No Android há algumas maneiras diferentes de conseguir isso:

*

*Adicionar o website aos favoritos

*Vá para a tela inicial onde deseja adicionar o link / marcador

*Tocar continuamente num espaço vazio até abrir o menu "Adicionar à tela inicial"

*Selecione "Atalhos"

*Selecione "Favoritos"

*Escolha o marcador que você acabou de criar

  Dependendo do seu dispositivo e versão do Android, isso pode funcionar:

*

*Adicionar o website aos favoritos

*Abrir a gestão de favoritos

*Tocar continuamente sobre o marcador do website

*Selecionar "Adicionar à tela Início"

Preparar a página com Icon, nome e cores a usar
Podes é ter a tua página com toda a informação necessária para dar a conhecer ao smartphone o icon e nome a utilizar no caso do utilizador adicionar o web site ao homescreen:
Apple
Link para documentação completa (Inglês)
<meta name="apple-mobile-web-app-capable" content="yes"/>
<meta name="apple-mobile-web-app-status-bar-style" content="black"/>
<meta name="apple-mobile-web-app-title" content="Meu Site"/>

<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png" />
<link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png" />
<link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png" />
<link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png" />
<link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png" />
<link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png" />
<link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png" />

Microsoft
Link para documentação completa (Inglês)
<meta name="application-name" content="Meu Site"/>
<meta name="msapplication-TileColor" content="#000000"/>
<meta name="msapplication-TileImage" content="http://www.example.com/windows_tile.png"/>

Outros
<title>Meu Site</title>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />

Nota:
O concenso é os navegadores localizarem os icons identificativos das páginas web na raiz do domínio: http://www.example.com/favicon.ico mas podes especificar outras localizações fazendo uso das meta tags em cima.
Para gerar icons a partir de um só ficheiro, esta ferramenta é excelente.

A: Desculpe, mas acho que não da via web.
As opções seriam:

*

*O usuário, utilizando os recursos do smartphone fará isso manualmente

*Você terá que criar um aplicativo nativo android que apenas abra seu site, terá um ícone e abrirá seu site como uma aplicativo, seria como se seu app fosse um 'navegador' (existe esse recurso) e abriria sua página web;

*Você utilizaria algum framework multiplataforma (exemplo phonegap) para criar esse 'app' para visualizar seu site;

Acredito que utilizando o Phonegap ou outra ferramenta multiplataforma (que usa javascript, html5, css e tal) seria mais prático, e não seria custoso (hardware do smartphone) pois só abriria sua página web (já que normalmente esse tipo de aplicativo é mais pesado). Além disso você poderia compilar o mesmo código para outras plataformas como windows phone, firefox os, ios, etc.
O nativo seria mais trabalhoso, porém mais leve (como já dito, pra proposta, não irá interferir no desempenho) e exclusivo para android.
http://phonegap.com/
http://docs.phonegap.com/en/3.5.0/cordova_plugins_pluginapis.md.html#Plugin%20APIs
https://github.com/apache/cordova-plugin-inappbrowser/blob/master/doc/index


text: Q: Convergence of empirical distribution function of a sequence from dependent identically distributed rvs We know by the Law of Large Numbers that the empirical distribution function converges to the common distribution of an iid sequence. What happens if we drop the independence requirement. Will the empirical distribution function converge to something, even though we don't know that something? Is that something a distribution function?


text:
Q: How to implementing expandable list row in appcelerator I'm building a simple application with appcelerator studio.
Then I want create a TableView in my Window, that when the user click on one row, I want to expand the row with other rows.
So I want implement Expandable List Row like Android.
This is my .js code:
var ds = arguments[0] || {};
//header table

      var view1 = Ti.UI.createView({
          left : 0,
          width : "35%",
          top: "30px"
      });
      var view2 = Ti.UI.createView({
          left : "35%",
          width : "25%",
          top: "30px"
      });
      var view3 = Ti.UI.createView({
          left : "60%",
          width : "25%",
          top: "30px"
      });
      var view4 = Ti.UI.createView({
          left : "85%",
          width : "15%",
          top: "30px"
      });

      view1.add(createHeader(L(lang+"kinship")));
      view2.add(createHeader(L(lang+"sex")));
      view3.add(createHeader(L(lang+"date_of_birthday")));
      view4.add(createHeader(L(lang+"observation")));

var row = Ti.UI.createTableViewRow();
var rowData = [];

row.add(view1);
row.add(view2);
row.add(view3);
row.add(view4);
rowData.push(row);

//CONTENUTO DELLA TABELLA
var argsView = [];
var row;

//1 COLONNA
var argView = {
    left : 0,     width : "35%", height: Ti.UI.Size, backgroundColor : "#44b7e3"
};
row = {
    view : argView,
    text: "Gastric fundectomy"
};
argsView.push(row);
//2 COLONNA
argView = {
    left : "35%", width : "25%", height: Ti.UI.Size, backgroundColor : "#44b7e3"
};
row = {
    view : argView,
    text: "13-06-2016"
};
argsView.push(row);
//3 COLONNA
argView = {
    left : "60%", width : "25%", height: Ti.UI.Size, backgroundColor : "#44b7e3"
};
row = {
    view : argView,
    text: "16-06-2016"
};
argsView.push(row);
//4 COLONNA
argView = {
    left : "85%", width : "15%", height: Ti.UI.Size, backgroundColor : "#44b7e3"
};
row = {
    view : argView,
    text: "procedure"
};
argsView.push(row);

//stampo la riga in pagina
rowData.push(createRow(argsView));

$.table.data=rowData;

function createHeader(headerText){
   var heading = Ti.UI.createView({
      backgroundColor : "#0c7b84"
   });

   var headingText = $.UI.create("Label", {
       classes: 'headerTableLabel'
   });
   headingText.text = headerText;

   heading.add(headingText);

   return heading;
}

function createRow(arrayViewRow)
{
    // Create Table Row
    var tableRow = Ti.UI.createTableViewRow({ height: 50 });

    for (i=0; i<arrayViewRow.length; i++) {
        //a questo punto conosco quante colonne avrà la mia tabella
        var view = arrayViewRow[i];
            //creo le colonne
            var colonnaView   = Ti.UI.createView(view.view);
            colonnaView.add($.UI.create("Label", {
               classes: 'bodyTableLabel',
               text : view.text
           }));
            tableRow.add(colonnaView);
    }
    return tableRow;
}

So, with this code, I can see the table with row but I'm not able to insert expandable list row.
How can I fixed it?

A: You can try the below code for expandable and collapsable tableview row in iOS.
var win = Ti.UI.createWindow({});
var container = Ti.UI.createView({
backgroundColor : "white",
layout : "vertical"

});
var layout = [{
title : "Parent 1",
isparent : true,
opened : false,
sub : [{
    title : "Child 1"
}, {
    title : "Child 2"
}]
}, {
title : "Parent 2",
isparent : true,
opened : false,
sub : [{
    title : "Child 3"
}, {
    title : "Child 4"
}]
}];
var tableView = Ti.UI.createTableView({
style : Titanium.UI.iPhone.TableViewStyle.GROUPED,
top : 0,
height : Ti.Platform.displayCaps.platformHeight,
data : layout

});
tableView.addEventListener("click", function(e) {

//Is this a parent cell?
if (e.row.isparent) {

    //Is it opened?
    if (e.row.opened) {
        for (var i = e.row.sub.length; i > 0; i = i - 1) {
            tableView.deleteRow(e.index + i);
        }
        e.row.opened = false;
    } else {
        //Add teh children.
        var currentIndex = e.index;
        for (var i = 0; i < e.row.sub.length; i++) {
            tableView.insertRowAfter(currentIndex, e.row.sub[i]);
            currentIndex++;
        }
        e.row.opened = true;
    }

}

});
container.add(tableView);
win.add(container);
win.open();


text:
Q: I am trying to set cookie from backend but it is not showing and not getting console.log I am trying to set cookie called JWT from backend but it is not able to set and I am not getting cookie in browser too where I am going wrong?
backend code for storing cookie
exports.login = async (req, res) => {
  const findData = await Registeration.findOne({ email: req.body.email });
  console.log(findData);
  if (findData === null || findData === {}) {
    res.status(404).json({message:"user not found",statusCode:res.statusCode});
  } else {
    if (findData.password === req.body.password) {
      const token = await findData.generateAuthToken();
      console.log(token);
      res.cookie("jwt", token, {
        path: "/",
        expires: new Date(Date.now() + 1000 * 30 * 100),
        httpOnly: true,
        sameSite: "lax",
      });
      console.log("cookie : ",req.cookies.jwt)// getting undefined
      if (findData.isSeller === true) {
        res.status(200).json({message:"logged into as seller",statusCode:res.statusCode});
      } else {
        res.status(200).json({message:"welcome to customer page",statusCode:res.statusCode});
      }
    } else {
      res.status(401).send("ircorrect password");
    }
  }
}


text:
Q: How to call WCF service from .NET 1.1 I have a WCF service which I'm trying to call from a simple .NET 1.1 client. The problem I'm having relates to the sending of "Client Credentials" to the service. In .NET 3.5 I can add the following lines so that the username and password are sent in the message (SOAP) header:
service.ClientCredentials.UserName.UserName = "USERNAME";
service.ClientCredentials.UserName.Password = "PASSWORD";

How can I replicate this functionality using .NET 1.1?
Thanks in advance,
Jose

A: You cannot - WCF is a .NET 3.0 and up technology.
All you can do from .NET 1.1 is to call

*

*WCF services with basicHttpBinding (and basically no security)

*WCF REST services (webHttpBinding) through the browser/http stack


text:
Q: Regex to filter out Datetime time from string Requirement: I am receiving an email with a template and I need to filter out some text from the email. I am converting all the email body text as a string.
email text looks like this:
some body text which I don't need

Discussion:
Tue 26/04/2022/2:48 PM UTC+10/ ABC User-

TEST description - this should be logged as a comment.  --- This is the part I need

ABC Company Australia | XYZ St | Sydney NSW 2000

I was thinking of having a regex that looks for

*

*A word "Discussion"

*Next line look for DateTime format with "Tue 26/04/2022/2:48 PM UTC+10/ ABC User-"

*Pick up the next line until we find this line - "ABC Company Australia | XYZ St | Sydney NSW 2000" address

Is it possible? can someone plz help with regex?
TIA.

A: If it was just about the content the OP is interested in, the following regex already is sufficient enough ... /Discussion:\n[a-zA-Z]{1,3}\s+\d{2}\/\d{2}\/\d{4}.*\n+(?<content>.*)/

const multilineMail = `Discussion:
Tue 26/04/2022/2:48 PM UTC+10/ ABC User-

TEST description - this should be logged as a comment.  --- This is the part I need

ABC Company Australia | XYZ St | Sydney NSW 2000`;

// see ... [https://regex101.com/r/v8FXCA/3]
const regXMailContent =
  /Discussion:\n[a-zA-Z]{1,3}\s+\d{2}\/\d{2}\/\d{4}.*\n+(?<content>.*)/;

console.log(
  regXMailContent.exec(multilineMail)?.groups?.content
);

In case the company footer has to match exactly, one has to make it part of the above regex like follows ... /Discussion:\n[a-zA-Z]{1,3}\s+\d{2}\/\d{2}\/\d{4}.*\n+(?<content>.*)\n+ABC Company Australia \| XYZ St \| Sydney NSW 2000/

const multilineMail = `Discussion:
Tue 26/04/2022/2:48 PM UTC+10/ ABC User-

TEST description - this should be logged as a comment.  --- This is the part I need

ABC Company Australia | XYZ St | Sydney NSW 2000`;

// see ... [https://regex101.com/r/v8FXCA/4]
const regXMailContent =
  /Discussion:\n[a-zA-Z]{1,3}\s+\d{2}\/\d{2}\/\d{4}.*\n+(?<content>.*)\n+ABC Company Australia \| XYZ St \| Sydney NSW 2000/;

console.log(
  regXMailContent.exec(multilineMail)?.groups?.content
);

If the OP wants to also save date and user, one would enhance the firstly provided regex like with ...

*

*/Discussion:\n(?<date>[a-zA-Z]{1,3}\s+\d{2}\/\d{2}\/\d{4}).*\n+(?<content>.*)/

*/Discussion:\n(?<date>[a-zA-Z]{1,3}\s+\d{2}\/\d{2}\/\d{4}\/[^/]+)\/\s*(?<user>.*?)-?\s*\n+(?<content>.*)/

const multilineMail = `Discussion:
Tue 26/04/2022/2:48 PM UTC+10/ ABC User-

TEST description - this should be logged as a comment.  --- This is the part I need

ABC Company Australia | XYZ St | Sydney NSW 2000`;

// see ... [https://regex101.com/r/v8FXCA/2]
const regXMailDateAndContent =
  /Discussion:\n(?<date>[a-zA-Z]{1,3}\s+\d{2}\/\d{2}\/\d{4}).*\n+(?<content>.*)/;

// see ... [https://regex101.com/r/v8FXCA/1]
const regXMailDateUserAndContent =
  /Discussion:\n(?<date>[a-zA-Z]{1,3}\s+\d{2}\/\d{2}\/\d{4}\/[^/]+)\/\s*(?<user>.*?)-?\s*\n+(?<content>.*)/;

console.log(
  regXMailDateAndContent.exec(multilineMail)?.groups
);
console.log(
  regXMailDateUserAndContent.exec(multilineMail)?.groups
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

But in case the to be extracted content is a multiline text, the regex has to feature the company footer in order to identify the correct match. The 2ndly provided regex then changes to ... /Discussion:\n[a-zA-Z]{1,3}\s+\d{2}\/\d{2}\/\d{4}.*\n+(?<content>(?:.*\n)*)ABC Company Australia \| XYZ St \| Sydney NSW 2000/

const multilineMail = `Discussion:
Tue 26/04/2022/2:48 PM UTC+10/ ABC User-

TEST

description - this should be
logged as a comment.  --- This is

the part I need

ABC Company Australia | XYZ St | Sydney NSW 2000`;

// see ... [https://regex101.com/r/v8FXCA/5]
const regXMailMultilineContent =
  /Discussion:\n[a-zA-Z]{1,3}\s+\d{2}\/\d{2}\/\d{4}.*\n+(?<content>(?:.*\n)*)ABC Company Australia \| XYZ St \| Sydney NSW 2000/;

console.log(
  regXMailMultilineContent.exec(multilineMail)?.groups?.content
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

All of the above regex patterns make use of named capturing groups.

A: You may try this regex:
Discussion.*?\n+([A-Za-z]+ +(?:\d{2}\/){2}\d{4}\/\d+:\d+ +[^\n]+)(.*)?ABC Company Australia \| XYZ St \| Sydney NSW 2000

Explanation:

*

*Discussion.*?\n+ The regex starts from where the String Discussion begins.

*.*?\n+ keeps looking for additional word and newlines

*([A-Za-z]+ +(?:\d{2}\/){2}\d{4}\/\d+:\d+ +[^\n]+) next it looks for the date format as you described . It will fetch all until it reaches a newline [^\n+]

*(.*)?It will fetch everything from the previous date line

*ABC Company Australia \| XYZ St \| Sydney NSW 2000 and will
conclude matching whenever it finds this.

*Here I have kept the Date format line in group 1 and the body you
need in group 2

Demo
source:

const regex = /Discussion.*?\n+([A-Za-z]+ +(?:\d{2}\/){2}\d{4}\/\d+:\d+ +[^\n]+)(.*)?ABC Company Australia \| XYZ St \| Sydney NSW 2000/gms;

const str = `some body text which I don't need

Discussion:
Tue 26/04/2022/2:48 PM UTC+10/ ABC User-

TEST description - this should be logged as a comment.  --- This is the part I need

ABC Company Australia | XYZ St | Sydney NSW 2000
`;

var match = regex.exec(str);
if(match!=null){
console.log(match[1]);
console.log(match[2]);
}


text:
Q: Is there any reliable data for benchmarking math library? I'm going to test the performance for some math function like pow, exp and log etc. Is there any reliable test data for that?
As those functions were highly optimized in exist modern system library like glibm or in OpenJDK, the general random inputs may lead to a quick convergence, or triggered some short path.

A: Call them in a loop to test throughput or latency, depending on whether the input to the next call depends on the output of the previous or not.  Probably with data from a small to medium sized array of random values for the throughput test.
You want your compiler to produce an asm loop that does minimal work beyond the function call, so use appropriate techniques for whatever language and compiler you choose.  (Idiomatic way of performance evaluation?)
You might disassemble or single-step through their execution to look for data-dependent branching to figure out which ranges of inputs might be faster or slower.  (Or for open-source math libraries like glibc, the commented source could be good to look at.)


text:
Q: Converting nvarchar(50) column to datetime in SQL CE 4.0 I'm new to SQL and have inherited a database which uses nvarchar(50) as the data type for the "Date" column. I want to convert this column into datetime format but I cannot figure out how to do so as I am using SQL CE 4.0 and can only find solutions for SQL.
This is an example in SQL of what I would like to do:
SET DATEFORMAT dmy
alter TABLE [dbo].[tablename]
ALTER COLUMN columnname datetime

I know I will probably need to create a new column and copy/convert the data from the old column into the new one using a query. I just need some guidance on how to do this.
Currently the Date column is in the format "dd/MM/yyyy hh:mm:ss tt".
I have been using Microsoft WebMatrix if that is helpful at all.
Thanks!

A: I agree with you: the best solution is to create a new column
ALTER TABLE yourTable ADD COLUMN newColumn DATETIME

(the SET DATEFORMAT statement doesn't exist in SQL Server Compact)
and copy data converting the format
UPDATE yourTable SET newColumn = CONVERT(datetime, oldColumn, 103)

For an in depth description of the SQL Server Compact commands look at http://technet.microsoft.com/en-us/library/ms173372.aspx


text:
Q: Display php selected JSON data with angular ngRepeat I want to display data which I select from a mySQL database using PHP. The data should be shown in angular variables.
I can see the JSON when clicking a button I installed. But the data will not show up in the angular variables. So I think the problem is the communication between php and angular on the way back from php to angular.
Here are the files I use. Where do i have to make changes to get what I want?
Thank you!
index.html
<!DOCTYPE html>

    <title>nutrimeal</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/main.css">

M E A L S

        <form action="./php/meal_select.php" method="post">
          <input class="btn btn-default" type="submit" value="display meals"/>
        </form>

The meals should be shown underneath

            {{ meal.name }}
            {{ meal.daytime }}

app.js
var app = angular.module('MyApp', ['ngRoute'])

// MealsController
app.controller('MealsController', [ '$http', function($scope, $http) {
  $scope.displayData = function(){
    var meals =  $http.get('./backend/meal_select.php')
//   .then(function (response) {$scope.accounts = response.data.records;} );
    .then(function (data) {
      $scope.meals = data });
};
$scope.displayData()
}]);

meal_select.php
<?php

// connection settings
$servername = "localhost";
$username = "root";
$password = "qwertz";
$dbname = "example_nutrition";

// create connection to db
$conn = new mysqli($servername, $username, $password, $dbname);

// check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// set SQL command
$sql = "SELECT meal_id, name, daytime FROM meal";

// query db
$result = $conn->query($sql);

// show results
if ($result->num_rows > 0) {
    // output data of each row
    $r=array()
    while($row = $result->fetch_assoc()) {
       $r=[] = $row;
//simple output
    // echo " Account Name: " . $row["account_name"].
      //    " Balance: " . $row["initial_balance"].
        //  " Currency: " . $row["currency"].  "
";

// output as JSON
     //$json_array = json_encode($row);
     $json_array = json_encode($r);
     header('Content-type: application/json');
     echo $json_array;
  }
}
// if nothing was found
          else {
            echo "0 results";
}

// close connection to db
$conn->close();
?>

JSON displayed after clicking the button

{"meal_id":"1","name":"cheeseburger","daytime":"lunch"}
      {"meal_id":"2","name":"chili con carne","daytime":"lunch"}

A: EDIT
PHP
$row = array();
$sql = "SELECT * FROM ...";
$result = mysqli_query($conn,$sql);
if($result){
while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;
}
print json_encode($rows);

Angular
  $scope.showData = function(){
    $http.get('data.php').then(function(response){
                $scope.data = response.data;
   }
   $scope.showData();

});
HTML

 {{d.name}}

 {{d.age}}

 ...

I think this code above is simple and you can understand , but I will explain a bit. In angular we have  two options for ng-repeat:
1.Object
2.Array
If you are using an object inside ng-repeat then you need to use it something like this:

 {{ key }} : {{ value }}

And if you are using array inside ng-repeat then you can do like this:

{{ d.name}}

{{ d.age}}

Now understand what is happening here, you are getting a response from server which is an object  and trying to print it like an array and it reason why it not work (and you forget invoked function). This is why I talk you add two line code in php
$row = array();
$rows[] = $r;

If you dont have two line , your json is object and you cant print it like array . But if you have two line ,  your json is array and you can print it like array


text:
Q: Using ruby gem coderay gets me inline text in *.html.erb file I am focused on the wrong layer of abstraction here, but can't figure out where.
I have this file views/pages/overview.html.erb
<%= stylesheet_link_tag "cust/coderay"%>

Overview

Here's my code test:

<%= html = CodeRay.scan("puts 'Hello, world!'", :ruby).div(:line_numbers => :table)%>

Back <%=link_to "home", "home"%>.

It took <%="%.3f" %(Time.now-@start_time)%> seconds to generate this page.

To my surprise, the pages renders like so:

When I view source on the page I get:
<!DOCTYPE html>

  <title>Dash</title>
  <link href="/assets/application-all.css?body=1" media="all" rel="stylesheet" type="text/css" />
<link href="/assets/all/pages.css?body=1" media="all" rel="stylesheet" type="text/css" />

  <meta content="authenticity_token" name="csrf-param" />
<meta content="SydEiDhSNHuEE6vCfr4rajIksxBbqnm89sddC08msjs=" name="csrf-token" />

Overview

Here's my code test:

<table class="CodeRay"><tr>
  <td class="line-numbers" title="double click to toggle" ondblclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>

</pre></td>
  <td class="code"><pre>puts <span style="background-color:hsla(0,100%,50%,0.05)"><span style="color:#710">'</span><span style="color:#D20">Hello, world!</span><span style="color:#710">'</span></span></pre></td>

</tr></table>

Back home.

It took 0.006 seconds to generate this page.

Why is the bracketed css displaying as inline text?  What should my usage of coderay look like here?
Many thanks -

A: Rails escapes your HTML by default in ERB templates. You need to turn off HTML escaping like so:
<%=raw CodeRay.scan("puts 'Hello, world!'", :ruby).div(:line_numbers => :table) %>

See more at this question and these release notes.


text:
Q: ASSIGN win XP commandline output to variable i would like to translate a following script from linux shell to Windows XP shell
GPSID=$(awk '/GPSID/ {print $3}' gora.RTK )
awk -v variable=${GPSID} 'BEGIN {printf "Numer seryjny : " variable,$1}' >>out.txt

The second line has been translated; the problem is with defining a variable that contains shell output in windows :-(

A: ok problem fixed
for /f "tokens=*" %%a in ('awk "/GPSID/ {print $3}" gora.RTK ') do set var=%%a
awk "BEGIN {printf \"GPSID : \" }" >out.txt
echo %var% >>out.txt

This code basicly does what I wanted to do.
You are great  Thanks !!!!!

A: If you need to recurse through the output of the command, you can use for /f. Something like:
for /f "usebackq" %%L in (`awk '/GPSID/ {print $3}' gora.RTK`) do (
    awk 'BEGIN {printf "Numer seryjny : " %%L,$1}' >> out.txt
)

A: How about ...
for /f "tokens=*" %%a in ('echo Hello World') do set var=%%a
NOTE: use %a instead of %%a when trying on the command line else keep it as %%a if using in a batch file.
Where 'echo Hello World' is the command whose output you want to capture and "var" is the name of the variable where the output will be stored.


text:
Q: Comparison of $L^2$ and $L^1$ norms for functions In the context of Lebesgue Integrals, I have came across $L^2$ as the set of measurable functions $f:[a,b] \rightarrow \mathbb{C}$ that have Lebesgue integrable squares - that is $x \to  |f(x)|^2$ is Lebesgue integrable.
I have also been introduced to the concepts of the norms:
$$\lVert f\rVert_2 = \left( \int_a^b |f(x)|^2 dx \right)^{\frac{1}{2}}$$
$$\lVert f\rVert_1 =  \int_a^b |f(x)| dx$$
An exercise is asking whether it is true that for every $f \in L^2$, there exists some constant $C \in (0, \infty)$ such that $\lVert f \rVert_1 \leq C\lVert f \rVert _2$, and also whether the converse is true.
I'm very stuck on how to approach this... It seems very intuitive but I am struggling on how to begin a rigorous proof of this.
Any tips or advice would be much appreciated!

A: Yes, the inequality is given by Cauchy-Schwarz:
$$ \|f\|_{L^1} = \int_a^b |f(x)|\, dx \le \left(\int_a^b |f(x)|^2\, dx\right)^{1/2}\left(\int_a^b \, dx\right)^{1/2} = \sqrt{b - a}\|f\|_{L^2}. $$

A: Hint: Try using the Hölder inequality for integrals on the function $f\cdot 1$.
In general this will not be true. It is of great importance that your measure space (here: $[a,b]$) has finite measure. Then the $L^p$ spaces fit nicely into each other, i.e. $L^q\subseteq L^p$ whenever $p\le q$ (cf. in the section "embeddings" of https://en.wikipedia.org/wiki/Lp_space#Lp_spaces_and_Lebesgue_integrals for a general solution).


text:
Q: JavaScript animation not behaving when switch browser tabs Live site: http://tt.fbcwinterretreat.org/
I'm trying to make a carousel effect by jQuery. Please be noted to better understand what is going on, you have to reduce the window height.
The problem is: If you keep looking at the page, the carousel goes well, but if you switch to another browser tab, wait for a few seconds, and then switch back, you will see the carousel gets displaced. The longer you stay at other browser tab, the more it is displaced.
It seems the problem is coming from this function:
function getRelativeClientRect(el) {
  var rect = el.getBoundingClientRect(),
      parentRect = el.offsetParent.getBoundingClientRect();
  return {
    bottom: parentRect.bottom - rect.bottom,
    height: rect.height,
    left: rect.left - parentRect.left,
    right: parentRect.right - rect.right,
    top: rect.top - parentRect.top,
    width: rect.width
  };
}

which I got from this SO question: How do I get the actual values for left/right/top/bottom of an absolutely positioned element?.
The following are the HTML and codes of my site:
HTML:

CSS:
.marquee-container{position:relative;overflow:hidden}
.image-container{position:absolute;transition:all 1s ease;  display: -webkit-box;display: -moz-box;display: -ms-flexbox;display: -webkit-flex;display: flex;}
.image{float:left;background-size:cover;cursor:pointer}

JS:There are two related JS scripts,the first one is located before closing body tag, I use it to make the images auto fit the height of screen

The seconde one is located at http://tt.fbcwinterretreat.org/templates/rt_chimera/js/custom.js, I use it to implement the carousel effect. I know its readability is low, so I have added some comments to it.

A: After looking on the behavior on the site online, my best bet is that the browser optimizes CPU by not playing all the frames of the transition while the tab is not visible, and catches up on the current frame when the tab becomes visible again, which causing the flickering on the screen.
What reinforces this theory is that the bug happens on Chrome, but not on Firefox.
I think a possible solution to workaround the issue is to implement the animation in JavaScript instead of CSS... or to wait for Chrome to fix the issue.

A: I think the problem is with setTimeout and setInterval. Chrome doesn't properly keep track of the timers for setTimeout and setInterval if you switch to a different tab. I guess the intention is to improve the browser's performance, but in this case, it's clearly not what you wanted. I don't think the chrome team intends to 'fix' this.


text:
Q: Prove lower bound of integral I have a continuous function $h:[a,b]\rightarrow\Bbb C$.
Let
$$M=\sup_{x\in [a,b]}|h(x)|$$
I need to find function $f\in L^2[a,b]$ with: $${||f||}^2=\int_{a}^b|f(x)|^2dx=1$$
such that:
$$ \int_{a}^b|f(x)|^2\cdot|h(x)|^2dx\ge M^2 $$

A: It can't be done.  Think about $h(x) = x$.  Then the only way the result can be true is if $f(x) = 0$ for almost every $x < b$.  And since $\{b\}$ is a set of measure zero, that means $f = 0$ a.e.


text:
Q: How can I add more cars to the Special Vehicle list? I went to the Garage that isn't the one at the safe house. I noticed that there was a prompt to press D-pad Right to access Special vehicles. So a list of one car opened and I selected it. This spawned me outside in a Eleghy RH8. Now not matter what I do to the car, I can go back to the garage and spawn a new one (Nothing custom saved from the previous afaik). So this seemed like a good way to always have a car other than the standard your Character has.
What I want to know, I how do I increase that list? Is that where buying cars comes into it?
So if anyone has already increased that special vehicle list, Please let me know how you did it :).

A: I think this is for cars bought in the Rockstar Store. The first one you get for free by joining the Rockstar Social Club. Cars bought on a dealers website are only delivered once to your garage. For the marina it is a bit different: There is only one slot and you can choose (by pressing LEFT on the D-Dad) which vessel to spawn there. You can do this an infinite number of times. This also applies to the helipads and hangars. You can only spawn vessels bought on a dealers website before.

A: Vehicles purchased from the game Internet for game cash only appear in the garage once, ie if you trash it you gotta buy another. The special vehicle list must be something else (I've only got the Elegy too).

A: Thats where the collector's edition unique vehicles are :) like the Hotknife and Carbon RS, but you can only get those with a DLC code if you bought the collector's edition game.. or maybe buy a code on eBay.

A: I have not tried it for the garage itself yet, but I bought a slip at the marina and subsequently purchased boats from the "Internet" ingame. These appear in a list at the marina, which seems to be the same mechanic.
So I´d say, purchased vehicles are likely to appear in that list.


text:
Q: How to draw several regions using one function returning List of True's and False's? This is what I want:
RegionPlot[
{
   y < x^2,
   y < 0.5 + 0.5 x
},
{x, 0, 2},
{y, 0, 4}
]

This code does not work (draws only one region):
rf[x_, y_] := {
   y < x^2,
   y < 0.5 + 0.5 x
};
RegionPlot[
 rf[x, y],
 {x, 0, 2},
 {y, 0, 4}
]

Actual function rf is very complex (CPU consuming), and I don't want to calculate it twice like here:
(* it works, but calculates rf twice *)
rf[x_, y_] := {
   y < x^2,
   y < 0.5 + 0.5 x
};
RegionPlot[
 {rf[x, y][[1]], rf[x, y][[2]]},
 {x, 0, 2},
 {y, 0, 4}
]

Using Map does not help:
rf[x_, y_] := {
   y < x^2,
   y < 0.5 + 0.5 x
};
RegionPlot[
 {#[[1]], #[[2]]}& /@ rf[x, y],
 {x, 0, 2},
 {y, 0, 4}
]

ImplicitRegion::bcond: {y,x^2}&&{y,0.5 +0.5 x} should be a Boolean combination of equations, inequalities, and Element statements.

A: You can memoize the complex function so that it is only called once for a particular value of $x$ and $y$:
Clear[z];
z[x_, y_] := z[x,y] = {y<x^2, y<.5+.5x}

RegionPlot[
    {Indexed[z[x, y], 1], Indexed[z[x, y], 2]},
    {x, 0, 2},
    {y, 0, 4}
]


text:
Q: CABasicAnimation to emulate a 'pulse' effect animation on a non-circle shape I am using CBasicAnimation to create a pulsating effect on a button.
The effect pulses out the shape of a UIView, with border only.
While the animation works properly, I am not getting the desired effect using CABasicAnimation(keyPath: "transform.scale").
I am using an animation group with 3 animations: borderWidth, transform.scale and opacity.
class Pulsing: CALayer {

var animationGroup = CAAnimationGroup()

var initialPulseScale:Float = 1
var nextPulseAfter:TimeInterval = 0
var animationDuration:TimeInterval = 1.5
var numberOfPulses:Float = Float.infinity

override init(layer: Any) {
    super.init(layer: layer)
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

init (numberOfPulses:Float = Float.infinity, position:CGPoint, pulseFromView:UIView, rounded: CGFloat) {
    super.init()

    self.borderColor = UIColor.black.cgColor

    self.contentsScale = UIScreen.main.scale
    self.opacity = 1
    self.numberOfPulses = numberOfPulses
    self.position = position

    self.bounds = CGRect(x: 0, y: 0, width: pulseFromView.frame.width, height: pulseFromView.frame.height)
    self.cornerRadius = rounded

    DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
        self.setupAnimationGroup(view: pulseFromView)

        DispatchQueue.main.async {
             self.add(self.animationGroup, forKey: "pulse")
        }
    }

}

func borderWidthAnimation() -> CABasicAnimation {
    let widthAnimation = CABasicAnimation(keyPath: "borderWidth")
    widthAnimation.fromValue = 2
    widthAnimation.toValue = 0.5
    widthAnimation.duration = animationDuration

    return widthAnimation
}

func createScaleAnimation (view:UIView) -> CABasicAnimation {
    let scale = CABasicAnimation(keyPath: "transform.scale")
    DispatchQueue.main.async {
            scale.fromValue = view.layer.value(forKeyPath: "transform.scale")
    }

    scale.toValue = NSNumber(value: 1.1)
    scale.duration = 1.0
    scale.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)

    return scale
}

func createOpacityAnimation() -> CABasicAnimation {
    let opacityAnimation = CABasicAnimation(keyPath: "opacity")
    opacityAnimation.duration = animationDuration
    opacityAnimation.fromValue = 1
    opacityAnimation.toValue = 0
    opacityAnimation.fillMode = .removed

    return opacityAnimation
}

func setupAnimationGroup(view:UIView) {
    self.animationGroup = CAAnimationGroup()
    self.animationGroup.duration = animationDuration + nextPulseAfter
    self.animationGroup.repeatCount = numberOfPulses

    self.animationGroup.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default)

    self.animationGroup.animations = [createScaleAnimation(view: view), borderWidthAnimation(), createOpacityAnimation()]
}

}

class ViewController: UIViewController {

@IBOutlet weak var pulsingView: UIView!

let roundd:CGFloat = 20

override func viewDidLoad() {
    super.viewDidLoad()
    pulsingView.layer.cornerRadius = roundd
    let pulse = Pulsing(
        numberOfPulses: .greatestFiniteMagnitude,
        position: CGPoint(x: pulsingView.frame.width/2,
                          y: pulsingView.frame.height/2)
        , pulseFromView: pulsingView, rounded: roundd)

    pulse.zPosition = -10
    self.pulsingView.layer.insertSublayer(pulse, at: 0)
}

}

My problem is transform.scale is maintaining the aspect ratio of the UIView it's pulsating from during the animation.
How can I make the pulse grow so there's uniform spacing on both the height and the width? See screenshot.

A: Scaling the width and height by the same factor is going to result in unequal spacing around the edges. You need to increase the layer's width and height by the same value. This is an addition operation, not multiplication. Now, for this pulsating effect you need to animate the layer's bounds.
If you want the spacing between the edges to be dynamic, then pick a scale factor and apply it to a single dimension. Whether you choose the width or the the height doesn't matter so long as it's only applied to one. Let's say you choose the width to grow by a factor of 1.1. Compute your target width, then compute the delta.
let scaleFactor: CGFloat = 1.1
let targetWidth = view.bounds.size.width * scaleFactor
let delta = targetWidth - view.bounds.size.width

Once you have your delta, apply it to the layer's bounds in the x and the y dimension. Take advantage of the insetBy(dx:) method to compute the resulting rectangle.
let targetBounds = self.bounds.insetBy(dx: -delta / 2, dy: -delta / 2)

For clarity's sake, I've renamed your createScaleAnimation(view:) method to createExpansionAnimation(view:). Tying it all together we have:
func createExpansionAnimation(view: UIView) -> CABasicAnimation {

    let anim = CABasicAnimation(keyPath: "bounds")

    DispatchQueue.main.async {

        let scaleFactor: CGFloat = 1.1
        let targetWidth = view.bounds.size.width * scaleFactor
        let delta = targetWidth - view.bounds.size.width

        let targetBounds = self.bounds.insetBy(dx: -delta / 2, dy: -delta / 2)

        anim.duration = 1.0
        anim.fromValue = NSValue(cgRect: self.bounds)
        anim.toValue = NSValue(cgRect: targetBounds)
    }

    return anim
}


text:
Q: jQuery to update values with done, fail jQuery to update values with done, fail
The Javascript, jQuery asynchronous and scope things are driving me crazy.
Output is:
3rd: 5 5 5 5
1st 1: 5 5 5 5
1st 2: 9 36 284 340
2nd 9 36 284 340
1st 1: 9 36 284 340
1st 2: 10 37 284 340
2nd 10 37 284 340
...

All I want is to make the output to be:
1st 2: 10 37 284 340
2nd 10 37 284 340
3rd: 10 37 284 340
...

so that I can pass the updated values:
Code is as follows:
series: [{
    data: (
        function() {

            y1 = 5,
            y2 = 5,
            y3 = 5,
            y4 = 5;

            function myFunction() {
                return $.ajax({
                    type: "GET",
                    url: "/getTest",
                    success: function(data) {
                        console.log("1st 1:", y1, y2, y3, y4);
                        y1 = data.V1;
                        y2 = data.V2;
                        y3 = data.V3;
                        y4 = data.V4;
                        console.log("1st 2:", y1, y2, y3, y4);
                    }
                });
            };

            var data = [],
                time = (new Date()).getTime(),
                i;
            for (i = -60; i <= 0; i++) {
                myFunction().done(function() {
                    console.log("2nd", y1, y2, y3, y4);
                }).fail(function() {
                    console.log("Fail");
                });
                console.log("3rd:", y1, y2, y3, y4);
                data.push({
                    x: time + i * 30,
                    y: 0
                });
            }
            return data;
        }()
    )
}],

The problem is console.log("3rd:"~), runs first so it is not being updated. What should I do to return the values from GET in HighChart.

A: Your anonymous function is returning the array before any of your AJAX calls return. You need to set up your chart, then make your data calls and set the value of your series when they return. Something like:
var chart = $('#container').highcharts({
    series: [{
        data: (

        function () {

            //We'll initialize an array of zeroes to set your series up
            var initialData = [];
                //This will eventually be populated with our data
            var ajaxData = [];
            //References to all our requests we'll make
            var ajaxRequests = [];

            y1 = 5,
            y2 = 5,
            y3 = 5,
            y4 = 5;

            function myFunction(x) {
                return $.ajax({
                    type: "GET",
                    url: "/getTest",
                    success: function (data) {
                        console.log("1st 1:", y1, y2, y3, y4);
                        y1 = data.V1;
                        y2 = data.V2;
                        y3 = data.V3;
                        y4 = data.V4;
                        console.log("1st 2:", y1, y2, y3, y4);
                        //Add the returned data to our array in the correct position
                        ajaxData.push({
                            x: x,
                            y: y1
                        });
                    }
                });
            };

            var time = (new Date()).getTime(),
                i;

            for (i = -60; i <= 0; i++) {
                //Push this initial node
                var x = time + i * 30;
                initialData.push({
                    x: x,
                    y: 0
                });
                //Fire off our ajax request, passing in the x value
                ajaxRequests.push(myFunction(x));
            }

            //Create a "master" request that will only be complete when all the ajax is done
            //When all requests are done, load the data into the chart
            //"apply" passes our array as arguments, i.e. function.apply($, [1, 2, 3]) === $.function(1,2,3)
            $.when.apply($, ajaxRequests).then(function() {
                console.log('Done getting ' + ajaxData.length + ' points');
                //Update the data of the first series in the chart
                chart.series[0].setData(ajaxData);
            });

            //Remember, this is dummy data...
            return initialData;
        }())
    }] //...
});

http://jsfiddle.net/2s2bf69c/3/


text:
Q: Secure communication between linked SQL Servers Is the data transferred between two SQL Servers protected (encrypted) by default? If not, is there a way to accomplish this?
I have two SQL Server 2005 databases running on separate servers, separate machines, separate networks. How can I ensure that data transmitted from one server to another is secure? I have tried researching the subject but am unable to find anything.
Many thanks,
Sebastian

A: Encrypt Via SQL Server

*

*Provision a certificate on both machines.

*Configure any non-server clients to trust the certificate's root signing authority. See How to enable SSL encryption for an instance of SQL Server by using Microsoft Management Console.

*Configure the server(s) to force all incoming connections to use SSL so that any clients that do not support this will fail to connect. In SQL Server Configuration Manager, set the ForceEncryption parameter to "Yes" in the Protocols section.

*OR, instead of the prior step, you can add Encrypted=yes to the provider/connection string for the connection/linked server. If, for example, you register the linked server using sp_addlinkedserver it might look something like this:
EXEC master.dbo.sp_addlinkedserver
   @server = N'LinkedServerName',
   @srvproduct = N'',
   @provider = N'SQLNCLI',
   @datasrc = N'Server\InstanceName',
   @provstr = N'Encrypt=yes;',
   @catalog = 'DatabaseName'
;

I do NOT recommend that you use the option TrustServerCertificate=True because this will disable the client from validating the identity of the server it is connected to.
Also, if using ODBC, the encryption property can be specified in a DSN.
Note that while servers don't require certificates to be installed since you can configure them to automatically create and sign their own certificates, it is best to manually install them, because you can run into problems with the self-created certificates since they change on each restart.
The best security is when the client specifically requests channel encryption, because this not only encrypts the data but the client also attempts to validate the identity of the server via the certificate, helping to mitigate a man-in-the-middle attack.
Encrypt Via The Network
Another option is to set up a secure tunnel (such as a VPN) between the two servers' networks, and ensure that the routing for traffic between them is entirely through said tunnel. This is 100% secure as well, as long as you are sure the traffic goes over the right route.

A: I realize this is a very old thread, but there's something in here that I just found out is potentially misleading.
"3.  Configure the server(s) to force all incoming connections to use SSL so that any clients that do not support this will fail to connect. In SQL Server Configuration Manager, set the ForceEncryption parameter to "Yes" in the Protocols section."
The ForceEncryption parameter on the SQL server side does not fail clients that do not have Encrypt = True set on the client end.  Importantly, you can create insecure connections to the SQL server instance even when ForceEncryption is set to "Yes" on the server.
You can validate this by setting ForceEncryption = Yes on the server side, then by connecting to that SQL server using SSMS and choosing not to encrypt the connection on the client side.
You can check the encryption state of the client connection by visiting the Properties of the server in Object Explorer, then clicking on View Connection Properties (right click on the servername in Object Explorer, then click Properties).
You can then see that the value for the Encypted property is set to No.

You can then do a select or other SQL statement to confirm that you are able to access data from the server side, without encryption.  I believe that in order to have full end-to-end encryption, you must set encryption on both the client and the server side.
Here is a Microsoft link explaining this issue.
And a screenshot in case that link doesn't work.

And another Microsoft link saying the same thing.
And another screenshot in case that link doesn't work.


text:
Q: How to get localized description string of file size in iOS? Following is my code:
- (NSString *)fileSizeDescriptionForFileAtPath:(NSString *)filePath {

    NSError* error;
    NSDictionary *fileDictionary = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath
                                                                                error: &error];
    NSNumber *size = [fileDictionary objectForKey:NSFileSize];

    NSString *desc = [NSByteCountFormatter stringFromByteCount:size.longLongValue
                                         countStyle:NSByteCountFormatterCountStyleFile];

return desc;
}

Is this code will correctly format the file size for any localization?
I found no reference in NSByteCountFormatter documentation that formatted strings are localized.
Thanks for any advise.

A: So, I tried the above code with several locales and the result looks perfectly localized.


text:
Q: How to be able to apply implict conversions in a recursive way in Scala I am trying to write a conversions library for converting some scala types to an HTML representation. I would want, say, to execute List(1,2).toHtml and obtain

1

2

, as a String.
So far i've written a set of implicit conversions that work well on detecting the result type and applying the correct toHtml.
Let me show a sample:
object Conversions {

  implicit def fromIterable[A](l : Iterable[A]) = new Object {
       def toHtml =
 { l.map{ e =>
{ e }
 } }
 toString
  }
}
import Conversions._

With this code, whenever i ask the compiler List(1,2).toHtml i get the correct conversion. As it would with any other Iterable val.
My problem and question here is how can i use this toHtml conversion recursively? Because if i typed List( List(1,2), List(3,4) ).toHtml i would want to get

1

2

3

4

, the toHtml conversion applied recursively to every element of the input Iterable.
I tried to change the toHtml definition to def toHtml =
 { l.map{ e =>
{ e.toHtml  }
 } }
 toString which didn't work because the compiler told me value toHtml is not a member of type parameter A which makes perfect sense.
I know that my problem probably resides in the new Object { ... } i am returning from the fromIterable[A] implicit definition, which should probably be returning a class with a trait or something.
I've tried reading a lot about implicits but i haven't figured it out yet out to be able to apply recursively this toHtml conversion without de-parametizing the fromIterable signature and defining several specific cases like fromIterable(l : List[List[Any]]) or something like that...
Can you guys please me give me some advices on how to achieve it and what am i doing wrong?
Thanks!

A: You can solve this kind of problem in an elegant and type-safe way with type classes:
// Evidence that we can turn an A into some XML:
trait Markup[-A] { def toHtml(a: A): xml.Node }

def baseMarkup[A] = new Markup[A] { def toHtml(a: A) = xml.Text(a.toString) }

implicit def markup[A](implicit m: Markup[A] = baseMarkup[A]) =
  new Markup[Iterable[A]] {
    def toHtml(c: Iterable[A]) =

      { c.map(child =>
{ m.toHtml(child) }
) }

  }

implicit def fromMarkup[A](a: A)(implicit m: Markup[A]) = new {
  def toHtml = m toHtml a
}

This works for nested lists of arbitrary depth:
val messy = List(List(List("a")), List(List("b", "c"), List("c")))

val printer = new xml.PrettyPrinter(80, 2)

And then:
scala> printer format messy.toHtml
res1: String =

a

b

c

c

See my answer here for a more detailed explanation of the methods above.

A: Let's first see how we can do it without the whole implicit/object and conversions stuff. I also removed the toString but feel free to add it on call.
def toHtml[A](l:Iterable[A]):scala.xml.Elem  =

 {l.map( _ match{
    case e:Iterable[_] =>
{toHtml(e)}

    case e =>
{e}

  })}

// Exiting paste mode, now interpreting.

toHtml: [A](l: Iterable[A])scala.xml.Elem
scala> toHtml(List(List(1,2), List(3,4)))
res17: scala.xml.Elem =

1

2

3

4

Let us now re-wrap everything in order to answer your question:
object Conversions {
  implicit def fromIterable[A](l : Iterable[A]):Object{def toHtml:xml.Elem} = new Object {
    def toHtml:xml.Elem  =

{l.map( _ match{
        case e:Iterable[_] =>
{e.toHtml}

        case e =>
{e}

      })}

  }
}
import Conversions._

Which gives the desired result:
scala> List(List(1,2), List(3,4)).toHtml
res3: scala.xml.Elem =

1

2

3

4

A few remarks:

*

*Second, I had to give the return type of the 'fromIterable' method. I am sure that there exists a better solution but I am not that experienced with implicit conversions.

*Finally, I will be glad to edit my answer if anyone has suggestions. (Or feel free to edit)


text:
Q: Workflow question: copy existing PrestaShop 1.7 to localhost and work on styles and js scripts I have an existing Prestashop 1.7 that work on a www hosting. I want to copy it (the best with database) to my localhost for fast reloading after changes (style, js) - without sending it on ftp and refreshing domain.
I tried to use xampp, but ineffectively.
After copy all the files from public_html to C:\xampp\htdocs\xxx and run xampp i have 500 error:
URL: http://localhost/xxx/
Method: GET
Remote adress: 127.0.0.1:80
Error: 500


text:
Q: JS file in chrome is never cached I dynamically create javascript files on the server that contain translated strings.
When I look at chrome inspector this file never gets cached, (other actual JS files that are in the Scripts folder do get cached)
*Why isn't it?*
<script src="somepath/Scripts/translate-nl-BE.js"></script>
or
<script src="somepath/Scripts/translate-en-GB.js"></script>

this is mapped to the following MVC action:
[HttpGet]
public ActionResult TranslateJS(string culturecode) {
     ViewBag.JSCulture = culturecode;
     Response.ContentType = "text/javascript";
     return PartialView("TranslateJS");
}

here's the view:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%
    string culturecode = ViewBag.JSCulture;
%>
var translations = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize((ViewBag.Translate as List<ERPManager.TranslationService.FlatTranslation>).Where(x=>x.CultureCode==culturecode).ToDictionary(t=>t.Key,f=>f.Value)) %>;

this basically just serializes a json array (I know this looks dirtyer than just returning a jsonresult but i can't ajax call this file, it need sto be linked into a script tag
This is the response I get from the server:
Cache-Control:private
Content-Length:10987
Content-Type:text/javascript; charset=utf-8
Date:Thu, 04 Apr 2013 10:15:11 GMT
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:3.0
X-Powered-By:ASP.NET

here's a preview of the file that get's returned: it's basically just a key value dictionary of translations.
var translations = {"vertaald":"Vertaald","gerelateerd":"Gerelateerd","details":"Details"};

A: It sounds like what you want is an expires HTTP header
You can set this in your MVC code:
[HttpGet]
public ActionResult TranslateJS(string culturecode) {
   ViewBag.JSCulture = culturecode;
   Response.ContentType = "text/javascript";
   Response.Expires = (60*24);//24 hours
   return PartialView("TranslateJS");
}

Bear in mind if you set an expires header the browser will not request the file again until after the cached content has "expired". Use with caution!


text:
Q: Testes paralelos usando Selenium/TestNg e Banco de dados Tenho 1165 testes cases e isso ta demorando 36 horas para rodar + rodar isso tudo em 3 diferentes browsers e estou ficando louca com essa demora.
A minha dúvida é se tem como rodar testes paralelos usando selenium/testng sendo que suas classes precisam acessar o mesmo banco de dados?
Vou tentar explicar melhor.
Digamos que eu tenha a classe chamada TesteParaCartaoDeCredito, essa classe tem vários testes dentro que acessam o banco de dados, como por exemplo, criar novo cartão de credito, alterar os limites, bloquear cartão e por ai vai.
Hoje se eu tento rodar em paralelo, usando chrome e firefox por exemplo, meu segundo test case sempre falha, porque o primeiro browser já rodou o mesmo teste e já alterou isso lá no banco de dados (por exemplo o primeiro browser rodou o teste de bloquear o cartão e ai o segundo browser quando roda qualquer outro, falha).
Qualquer ideia é bem vinda.

A: No seu teste rondando em paralelo você consegue clonar a sua base? Caso positivo você poderia ter duas bases para rodar em paralelo. Nesse caso uma não iria interferir na outra porque estão apontando para bases diferentes


text:
Q: Feature doesn't display on map using PyQGIS? I want to create a layer using PyQGIS, then draw a point in a specific place on a map and add some data to the attribute table. Everything went fine, the script below works but no point seems to be displayed on a map canvas.
 The code below is from the PuQGIS Developer Cookbook (http://docs.qgis.org/2.18/en/docs/pyqgis_developer_cookbook/vector.html#id8) but nonetheless the point is not visible.
What can be the ploblem?
 def create_layer(self, point, values):
    vl = QgsVectorLayer("Point", "Temporary point layer", "memory")
    pr = vl.dataProvider()

    vl.startEditing()

    pr.addAttributes( [ QgsField("ID", QVariant.Int),
                        QgsField("R",  QVariant.Int),
                        QgsField("G", QVariant.Int),
                        QgsField("B", QVariant.Int),
                        QgsField("Class", QVariant.String)] )
    vl.updateFields()

    feat = QgsFeature()
    feat.setGeometry( QgsGeometry.fromPoint(QgsPoint(500253, 8180778)))
    feat.setAttributes([0, int(values[0]), int(values[1]), int(values[2])])
    pr.addFeatures([feat])

    vl.updateExtents()
    vl.commitChanges()
    QgsMapLayerRegistry.instance().addMapLayer(vl)
    layer = iface.setActiveLayer(vl)
    if not layer:
        self.dlg.l_status.setText("Error: Layer failed to load!")
    else:
        QgsMapCanvas().setLayerSet( [ QgsMapCanvasLayer(vl) ] )
        iface.zoomToActiveLayer()

Here is a screenshot. I zoomed to a temporary layer with a point.

A: Thanks to hint from @mgri, I found the solution. It was all about CRS. I had to specify CRS programmatically while creating a temporary layer so instead of
vl = QgsVectorLayer("Point", "Temporary point layer", "memory")

I used
vl = QgsVectorLayer("Point?crs=epsg:32645", "Temporary point layer", "memory")

And now everything works fine.


text:
Q: How to configure the Web App Builder Coordinate widget to show Z as well as X and Y? Is there a way to configure / edit the default coordinate widget to show elevation (Z) along the X, Y values just as is possible in a 3D application but in a 2D application? If possible, this would be the ideal solution.
See capture 1 showing default OOTB coordinate widget in a 2D web appp.
See capture 2 for closeup of the widget with a coordinate placed on map.
Alternatively, can I obtain XYZ values from a DEM service? We've tried this and although we can get the elevation value from in a popup we don't seem to be able to get the cell X and Y coordinate as well as the elevation cell value in one popup.
See capture 3 for a popup showing an elevation (Z) value obtained from a DEM exported to server as image service.
Having to obtain XY values using a widget then getting the Z value from a popup is a bit cumbersome so I am basically looking for a solution that will allow me to obtain all 3 values (X,Y,Z) from a single click on a map.
Capture 1:

Capture 2:

Capture 3:

A: I created a workaround to get the results I needed.
I basically created a vector version of the raster:

*

*Converted a raster to points which gave me the points with elevations

*Run "Add XY Coorinates" tool to add the XY so I had points with X,Y,Z coordinates.

*I needed the same raster as polygon cells identical to the input raster so to get around the limitation of the "Raster to Polygon" tool which merges cells of the same value together I converted the point feature class to raster using the unique OBJECTID for value then once created I converted this raster back to polygons which worked (33,000,000 features)

*I now attempted to run a spatial join on 33 million features to bring the X,Y,Z values from the points into the polygons. This bombed out a few times with background geoprocessing turned off (a known bug as i found out later) so i turned backround geoprocessing on and after 10 hours the spatial join completed only 6% of the features.  If it succeed it would take 10 days to run. Stopped the processing and back to square 1. well 2.

*Built my own addin with VS .Net and ArcObjects to convert points to square polygon cells (tool takes a size of cell as parameter and also allows user to control how often the cursor is flushed - default 10,000 to ensure stable performance) I also put in some ligic to automatically copy over the attributes.  I succesfully converted all 33 million features into polygons with all necessary XYZ attributes.

*Because I am no longer limited to how many attributes i have, I added Lat and Long as well and also a XYZ concatinated string the end used can copy in one shot instead of copying 3 values seperately.
I noticed the feature class drew very slowly in ArcMap so I copied it to a new FGDB and compressed the database since it ws not going to be edited anyway. Peformace improved very significantly and the size of the geodatabase went down to 500MB from the original ~ 6GB.

*Uploaded the map service (no cache) to my web server and added to my web maps. WE only allow the end users to use the map service in beyond 1:2000 but I was very suprised how well and quickly it works:


text:
Q: can the order of the fragments in the backstack be changed programmatically Having A->B->c in back stack, A is at top.
At the time it would like to have C to be on top, and keep A, B in the order in the stack. In the requirement it cannot have two C instances in the stack. The problem is if pop the C then all A, B is removed.
What it wants is to have C->A->B now.
Is it possible to achieve this with FragmentManager's api?

A: FragmentManagerdoes not readily support changing the ordering of the backstack or removing items that aren't at the top of the stack.
You may want to consider managing your own version of a Fragment backstack.

A: put below code inside your activiy
FragmentManager fragmentManager

//add fragment A
fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager .beginTransaction();
ft.add(resId, fragmentA);
ft.addToBackstack("tag");
ft.commit();

//add fragmentB
fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager .beginTransaction();
ft.replace(resId, fragmentB);
ft.addToBackstack("tag1");
ft.commit();

//add fragmentC
fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager .beginTransaction();
ft.replace(resId, fragmentC);
ft.addToBackstack("tag2");
ft.commit();

 //then try to take back click of B and C fragment here through interface

//backclick of C
public void backClick()
{
fragmentManager.popBackStack("tag1",0);
}

//back click of B
public void backClick1()
{
fragmentManager.popBackStack("tag",0);
}

A: keep fragment hide and if you want show it.


text:
Q: Problems saving and retrieving numbers I am working on an app that uses CoreData.
I am strong numbers and retrieving them, but when i store more than one field it only shows the last field with the number but a 0 in all the others. below is my codes.
to store them...
 let CWConvert = Double(CWeight.text!)
                            storeTranscription18CW(pageText: (CWConvert)!, textFileUrlString: "cWeight")
                                savePlus += 1

                            let TWConvert = Double(TWeight.text!)
                            storeTranscription18TW(pageText: (TWConvert)!, textFileUrlString: "tWeight")

and...
        func getContext () -> NSManagedObjectContext {
    _ = UIApplication.shared.delegate as! AppDelegate
    return DataController().managedObjectContext
}

func storeTranscription18CW (pageText: Double, textFileUrlString: String) {

    let context = getContext()

    //retrieve the entity that we just created
    let entity =  NSEntityDescription.entity(forEntityName: "TextInputs", in: context)

    let transc = NSManagedObject(entity: entity!, insertInto: context)

    // set the entity values

        transc.setValue(pageText, forKey: "cWeight")

    //save the object
    do {
        try context.save()
        print("saved!")
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    } catch {

    }
}

func storeTranscription18TW (pageText: Double, textFileUrlString: String) {
    let contexta = getContext()

    //retrieve the entity that we just created
    let entitya =  NSEntityDescription.entity(forEntityName: "TextInputs", in: contexta)

    let transc = NSManagedObject(entity: entitya!, insertInto: contexta)

    // set the entity values

        transc.setValue(pageText, forKey: "tWeight")

    //save the object
    do {
        try contexta.save()
        print("saved!")
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    } catch {

    }
}

and to retrive.
    func getTranscriptions18CW () {
    //create a fetch request, telling it about the entity
    let fetchRequesta: NSFetchRequest<TextInputs> = TextInputs.fetchRequest()
    do {
        //go get the results
        let searchResults18CW = try getContext().fetch(fetchRequesta)

            for transa in searchResults18CW as [NSManagedObject] {
                if let resulta = transa.value(forKey: "cWeight") {
                    if let stra = resulta as? String {
                        CWeight.text = stra
                    }else {
                        CWeight?.text = "\(resulta)"
                    }
                }
            }
            //get the Key Value pairs (although there may be a better
    }catch {
        print("Error with request: \(error)")
    }
}

func getTranscriptions18TW () {
    //create a fetch request, telling it about the entity
    let fetchRequest: NSFetchRequest<TextInputs> = TextInputs.fetchRequest()
    do {
        //go get the results
        let searchResults18TW = try getContext().fetch(fetchRequest)

            for trans in searchResults18TW as [NSManagedObject] {
                if let result = trans.value(forKey: "tWeight") {
                    if let str = result as? String {
                        TWeight.text = str
                    }else {
                        TWeight?.text = "\(result)"

                }
            }
            //get the Key Value pairs (although there may be a better way to do that...
        }
    }catch {
        print("Error with request: \(error)")
    }
}

i have tried different names but get the same it only shows the last one as the real number if i moment out the last one then the first shows the real value.

A: Try something more like this to save so that you are saving both in the same row.
func storeTranscription18TW () {
    let contexta = getContext()

    //retrieve the entity that we just created
    let entitya =  NSEntityDescription.entity(forEntityName: "TextInputs", in: contexta)

    let transc = NSManagedObject(entity: entitya!, insertInto: contexta)

    // set the entity values
    transc.setValue(CWConvert, forKey: "cWeight") // Note the change from pageText
    transc.setValue(TWConvert, forKey: "tWeight") // Note the change from pageText

    //save the object
    do {
       try contexta.save()
       print("saved!")
       } catch let error as NSError  {
          print("Could not save \(error), \(error.userInfo)")
       } catch {

   }
}

Then when you do a get they would both be done in the same function as well.


text:
Q: Using Wick's theorem on already normal-ordered functions The book Quantum Field Theory of Many Body systems (X. G. Wen) defines Wick's theorem as follows.

I would like to employ this definition to simplify the 4-operator product $$\hat{O}\;=\;a_p^\dagger a_q^\dagger a_r a_s$$ into a sum of two-operator products. However, as this operator is already normal ordered, the terms $W$ and $:W:$ are the same in the above expression, and therefore all other terms on the RHS would equal zero. Could someone kindly provide pointers on the correct implementation of Wick's theorem in this case?

A: The operator is already normal-ordered and does not require any further simplification. Note that it annihilates the vacuum state. On the other hand, simplifying operator $a_s a_r a_q^\dagger a_p^\dagger$ could be a useful exercise.

A: It is already normal ordered, as you say, so there is no point in applying the normal ordering to it.
Now, I haven't studied the applications of QFT to many bodies, so I don't know what purpose Wick's theorem has in this book/area, but I don't think you should be using it to re-express an ordinary operator; i.e. istead of applying the formula you attach just apply the conmutation relations of the annihilation-creation operators to normal order it, thus deriving the factors you may or may'nt have. I only use Wick's theorem to go from time ordering from normal ordering, albeit my knowledge in the subject is very limited at present.
Of course, the two approaches are equivalent, but since you asked for pointers in applying it, I feel like you would get more familiar with it by working out the expression yourself rather than simply applying a formula.
Sorry for the lengthy -and subjective- answer, have a nice day :)


text:
Q: Failed to Generate Incremental ID with Following Python Code in the Code Block. What's the mistake in my code? I am trying to add a field with incremental ID for a shapefile with certain feature classes. I know this can be done by using Sort tool and then use the Add Incremental ID field tool. But since I'm learning Python, and this seems like not too difficult a problem to tackle with Python, I want to use Python to handle this to enhance my Python skills.
Below is the code I put in the Code Block:
def letsdothis():
    rec = 0
    vStart = 1
    vDelta = 1
    if rec == 0:
        rec += vStart
    else:
        rec += vDelta
    return rec

And the function I use of course is letsdothis()
To show it better:

My reasoning is this:
The first one will be rec += 1, then rec will equal 1. Then the next one, since rec != 0. it will be (the new rec value) += 1, which will be 2. And so on and so on.
But the results are all 1. My understanding is that for every row cell/feature class, the function will be called from scratch therefore rec will equal 0 instead hold the value that's calculated in the previous feature class/row.
Is this the problem with my code? I am very new to writing my own Python code in GIS. I've only used other's code and tweaked them to fit my purpose before so I don't know how to really do this.

If I can make rec == 1 in the first row, how shall I make that value pass on to the nest row?

A: This is a def variable scope related confusion that you have. Basically each and every row calculation creates an instance of your def and its rec value is always 0! Therefore you should control its incremental behaviour outside of the def.
The original code puts rec variable outside of the def and declares rec as global inside the def. Check the first part of the answer of this post out.


text:
Q: gstreamer correct pipeline to decode rtsp stream to raw video using gstreamer-1.10 I have been trying several version of pipeline to decode an RTSP stream that starts as a webrtc connection.
ffprobe reports stream as
Duration: N/A, start: 0.128000, bitrate: N/A
Stream #0:0: Audio: aac (LC), 48000 Hz, stereo, fltp
Stream #0:1: Video: h264 (Constrained Baseline), yuv420p, 512x288 [SAR 1:1 DAR 16:9], 30 fps, 30 tbr, 90k tbn, 60 tbc

using variations of the following pipeline
GST_DEBUG=3 gst-launch-1.0  -e rtspsrc location=rtsp://xxx.xxx.xxx.xxx:1935/alpha/Stream1  \
! decodebin name=decode \
decode. \
! x264enc bitrate=512 speed-preset=6 \
! video/x-h264, profile=baseline  \
! queue ! mp4mux name=mp4mux ! filesink location=file.mp4 \
decode. ! avenc_aac bitrate=96000 ! aacparse ! queue  ! mp4mux.

I get the following errors
0:00:00.299416405  7705 0x7f0d48001e80 WARN                 default grammar.y:510:gst_parse_no_more_pads:<decode> warning: Delayed linking failed.
0:00:00.299435518  7705 0x7f0d48001e80 WARN                 default grammar.y:510:gst_parse_no_more_pads:<decode> warning: failed delayed linking some pad of GstDecodeBin named decode to some pad of GstX264Enc named x264enc0
WARNING: from element /GstPipeline:pipeline0/GstDecodeBin:decode: Delayed linking failed.
Additional debug info:
./grammar.y(510): gst_parse_no_more_pads (): /GstPipeline:pipeline0/GstDecodeBin:decode:
failed delayed linking some pad of GstDecodeBin named decode to some pad of GstX264Enc named x264enc0
0:00:01.296295371  7705 0x7f0d6402a8f0 WARN                 basesrc gstbasesrc.c:2951:gst_base_src_loop:<udpsrc3> error: Internal data stream error.
0:00:01.296324999  7705 0x7f0d6402a8f0 WARN                 basesrc gstbasesrc.c:2951:gst_base_src_loop:<udpsrc3> error: streaming stopped, reason not-linked (-1)

what is the correct pipeline to decode this stream?


text:
Q: How to import psycopg2 into a new module im writing So to simplify, I'm trying to write my own module (test.py) that looks as follows:
import psycopg2

get_data(xyz):

    connection = psycopg2.connect(user="",
                                  password="",
                                  host="",
                                  port="",
                                  database="")

    last_qry = """select * from xyz.abc"""

    cursor = connection.cursor()

    cursor.execute(last_qry)

    last_data = cursor.fetchone()

    cursor.close()

    connection.close()

    return last_data

in a different file I am running:
import test

get_data(xyz)

and I get the following error:
name 'psycopg2' is not defined

What am I doing wrong?

A: There are many bugs in these code snippets that you put here:

*

*Your import should be like this:
from test import get_data

or in this way:
import test
test.get_data()

*What is the use of xyz ? the second code snippet must return
NameError because xyz is not define;if you want to use it in last_qry you must have .format() for it.

*What is the structure of directory that included the second file ?
and where is the first file?


text:
Q: Translate Delphi asm to C++ Builder asm I am trying to convert part of a Delphi project to a C++Builder project.
I reduced the problem to the following code:
procedure Test;
asm
    MOV     EAX, OFFSET @test
@test:
    db 00H
end;

If I try to compile this, and several variations, I get an error:

[BCC32 Fehler] Unit1.cpp(21): E2451 Undefiniertes Symbol '@test'

Can anybody help?

A: Your code has some problems like You can not forward reference labels in C++ asm with one exception (jmp instruction)...
The inbuild help and online one too:

*

*Embarcadero Assembler Syntax
suggest that the syntax for labels is the same as in Pascal ... that is true however usage of labels is very different !!! up to a point they are almost useless I still did not get it to work even after 15+ years they changed it as you can use labels only for jumps and maybe calls but nothing else...
Perhaps there is some directive or keyword that allows label usage but have not found any yet as all examples are in pascal syntax which does not work in C++ environment.
Another problem is that you use test label ... You are forgetting that test is assembly instruction so the names are in conflict!!!
You can still workaround:

*

*reorder your code so you do not need forward referencing
This is doable as jmp is still working as should with labels however you can forget about simple selfmodifying code...

*convert your local asm variables to C++ local variables
local C++ variables are directly accessible from asm. Beware function operands are not so if you need them copy them into local variables first.

*convert addressing syntax to C++
You know this:
MOV     EAX, OFFSET @test

Is not doing what you intend in C++ you have to use LEA instruction instead of OFFSET ... just create a breakpoint and see what the OFFSET will return (in my case its always 0xFFFFFFFF instead of real address) while LEA obtains correct address.
Putting all together You can try something like this instead:
void asmtest()
    {
    BYTE a=0x00;
    asm {
        lea eax,a
        }
    }

In case you have a really nasty code you can also convert the code into fully assembler code (no C++) and compile as asm code instead ... Then compiled/linked obj file can be linked into your C++ project. IIRC in BCB5 was an option for this however haven't use that for many years so this feature might be removed however you can still compile with any assembler (TASM,NASM...) borland was always compatible with TASM (as it was used internaly) so I recommend to use that to avoid additional problems...

A: Why are you trying to translate assembler to assembler at all? The code you showed is defining a single byte in memory and then returning its memory address to the caller. That can and should be written in native C++ instead, let the compiler handle creating the necessary assembler for you, ie:
const char* Test() {
    static const char ch = 0;
    return &ch;
}


text:
Q: Where/how can I fight stuff in the starter Mustang Alpha ship? I purchased a starter package consisting of a Mustang Alpha ship. Whenever I travel to a Comm Array to do an open-world mission, it inevitably gets destroyed after only a few volleys. I've looked into buying some modules, but I can't really afford any at this time. This leads to a few related questions with the goal of having fun in the ship I purchased.

*

*Is there any combat-oriented places I can take my ship and at least have it survive long enough to possibly destroy other ships?

*How can I earn additional UEC so I can purchase upgrades?

*What are some optimal upgrades I should look to get to make my ship more viable in combat engagements?

A: Please bear in mind that, as of today (23/01/16), Star Citizen is still very firmly in the actual definition of Alpha - i.e. not feature complete. All of the stuff I mention below will change in the next few years.

Can I fight stuff in a Mustang Alpha?

If I'm honest, I would suggest getting a handle on the combat before trying to fight in Crusader (if you're having trouble with the pirates). I recommend this because of the decreased time between respawning and being able to practice.
Places you can do this include:

*

*The flight tutorial (which is unfortunately bugged in the current build, 2.1(.1)

*Vanduul Swarm (Arena Commander)

Of the two, due to the bugs, AC / Vanduul Swarm is the best option, as you can also play with other players (as well as being able to earn REC).

How can I earn additional UEC to purchase upgrades?

Currently you cannot earn UEC in game. You can purchase it for roughly 1000/1$, but don't do that - in fact, don't spend UEC at the moment, as everything is still very far from final.
However, you can earn REC (Rental Equipment Credit) by playing public games of Arena Commander - including Vanduul Swarm. When you have earnt sufficient REC, you can rent equipment to use with your ship in the Electronic Access store (as well as other ships).

What are some upgrades I can get for the Mustang Alpha to make it better in combat?

Based on the ship data available here, we can see that the Mustang Alpha comes with two gimballed M3A Laser Cannons (on the nose), and two unused S1 hardpoints (under the wings). It also has an S2 shield slot, but only comes with an INK-1 (S1).
Assuming your powerplant can handle it, you could upgrade the shield to an S2 (such as the INK-MARK 204-ID or INK-MARK 204-IS, which protect better against projectiles and missiles respectively), and add two S1 weapons to the unused mounts (even replacing the M3As, if you prefer other weapons).


text:
Q: How to add the legend for the barchart superimposed onto a ggplot2 map (annotation_custom)? In: "How to plot barchart onto ggplot2 map"
Inscaven has proposed an efficient way for adding barplot onto a map without using subplot library.
But how adding the legend for any barplot since
theme(legend.position = "topright") does not work ?

A: If you want to place the legend in the top right corner, instead of "topright" you can specify a legend position as coordinates:
ggplot(...) + theme(legend.position = c(0.9, 0.9))

(0,0) corresponds to the bottom left corner and (1,1) is top right.


text:
Q: Blue dot doesn't appear in geolocation (Ionic 3) I'm making an app using the plugin "Geolocation", everything is ok, I can geolocate myself but I don't see a blue dot (like in google map) or just a marker to show the actual position in the map. Someone can help me ? Here is my function to show the map in the View.
showMap(){
  this.geolocation.getCurrentPosition().then((position) => {
    let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    let mapOption = {
      center: latLng,
      zoom: 18,
      mapTypeId:google.maps.MapTypeId.ROADMAP
    }
    this.map = new google.maps.Map(this.mapRef.nativeElement, mapOption);
  }, (err) => {
    console.log(err)
  }
);}

Thank you.
Screen

A: There is no native way of setting a dot (as in native MKMapView) for the current location. But as described in the Ionic Docs for Geolocation plugin, you can watch for location changes and get the current latitude and longitude:
let watch = this.geolocation.watchPosition();
watch.subscribe((data) => {
  // data can be a set of coordinates, or an error (if an error occurred).
  // data.coords.latitude
  // data.coords.longitude
});

Then you set a custom marker on the current location.


text:
Q: Is there a method in Magento that allows to create MySQL triggers and stored procedures? I am trying to find out if Magento has a method available that allows to create MySQL triggers and Stored Procedures.
Currently, i am using the core resource DB adapter to insert the raw SQL directly from my setup script, and was wondering if there was in fact a method available for this, similar to the way we add foreign keys, etc.
Does anyone know of anything like this either in EE or CE? A library or custom script perhaps?

A: Ok, so i haven't had much response from this so started digging around myself am able to answer half of the question i asked.
Did a simple "grep" and came across the following class tucked away in the lib folder: lib/Magento/Db/Sql/Trigger.php
Its pretty straight forward and here is what i have come up with that does work (can be placed in your install/ upgrade script):
<?php
/** @var $installer Mage_Core_Model_Resource_Setup */
$installer = $this;
$installer->startSetup();

// Trigger
$trigger = new Magento_Db_Sql_Trigger();

// Set time SQL_TIME_BEFORE / SQL_TIME_AFTER
$trigger->setTime($trigger::SQL_TIME_BEFORE);

// Set time SQL_EVENT_INSERT / SQL_EVENT_UPDATE / SQL_EVENT_DELETE
$trigger->setEvent($trigger::SQL_EVENT_INSERT);

// Set target table name
$trigger->setTarget($installer->getTable('fontera_trader/leaderboards_global_tmp'));

// Set Body
$trigger->setBody(
'INSERT INTO '.$installer->getTable('fontera_trader/leaderboards_global').'
    (entity_id, customer_id , credit_value, prize_value, games_played, rank, prev_rank)
    VALUES
    (NEW.entity_id, NEW.customer_id, NEW.credit_value, NEW.prize_value, NEW.games_played, NEW.rank, NEW.prev_rank)
    ON DUPLICATE KEY UPDATE
    customer_id = NEW.customer_id,
    credit_value = NEW.credit_value,
    prize_value = NEW.prize_value,
    games_played = NEW.games_played,
    rank = NEW.rank,
    prev_rank = NEW.prev_rank;

    SET @r = 0;

    UPDATE '.$installer->getTable('fontera_trader/leaderboards_global').'
    SET
    prev_rank = rank,
    rank = @r:= (@r+1)
    ORDER BY
    credit_value
    DESC;
'
);

// Assemble query, returns direct SQL for trigger
$triggerCreateQuery = $trigger->assemble();

// Adapter initiates query
$this->getConnection()->query($triggerCreateQuery);

$installer->endSetup();

I have added comments to give a basic idea of what can be used, else best go check the class out yourself. The body is basically raw SQL but can be compiled using Magento's conventional methods. I have used raw SQL for demonstration purposes.
That out of the way, i am still trying to find a way to implement STORED PROCEDURES without success. Has anyone come across anything like this in Magento that may be tucked away for future use?


text:
Q: video capture from firewire c++ windows I'm using eclipse and c++ on windows and I have to capture a video from a firewire camera but I have no ideas of which libraries should I use.
I prefer to not install anything, but using some libraries if it's possible.
if you can also post a code example of how to capture the video it would be very helpfull.
thank you

A: Video capture API in Windows is DirectShow or Media Foundation. With DirectShow you can capture video in a way similar to other video sources (frame grabbers, web cameras etc). See Capture firewire video: does this require DirectShow?.


text:
Q: Wordpress REST API json - How to activate gzip compression? Im currently trying to activate the gzip compression on a Wordpress website.
But the json output of the wordpress embed api doesn't seem to be affected by my htaccess settings.
Here they are:
<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml
  AddOutputFilterByType DEFLATE application/json

  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>

Does anyone has a clue where my mistake is?
Thanks!

A: I used your exact set of .htaccess directives to achive json gzip'ing.  Took my files from 23k to 4k.
So I would assume its one of the two following things:

*

*Your.htaccess is not allowed to use these directives so it ignores them. Thus you either need to do one of the following: a) edit the httpd.conf or /etc/apache/sites-available/site.conf or httpd-vhosts.conf (depending on the system you are on) and add the gzip stuff there.  b) edit the same files and give your.htaccess the rights to override these settings. c) check your are really running apache so .htaccess works ;D

*Check that mod_deflate is loaded and if not, enable it.  Again this might not be working as you are not running apache or the directives in the htttpd.conf (or wherever) do not cover application/json

If you do have .conf access to make these changes then put the deflate rules in there rather than in the .htaccess, that way the server learns about it at setup time, and not on every file access. increases speed (slightly).
If you do not have .conf access, you need to speak to the  server people or hosting company and get them to add the AddOutputFilterByType DEFLATE application/json for your website, perhaps consider all of the settings you have done above.
As a bonus, if you really want uber small, Brotli compression was specifically made to make fonts smaller, and works on all file types.  If you work with a host, ask them if this is possible also as well as gzip, so you have backwards compatibility.


text:
Q: Updating MySQL DB by "rolling up" similar items Not sure if such functionality exists but I'm curious if I have the following DB as shown below, if it can be updated such that wherever first_name and last_name match all deduction and pay columns are added together, and thus a single line formed.  I know a query can be written to get me such information, but I need this query result to actually become the database. (i.e. cleaning superfluous extra lines sort to speak).
i.e.
first_name | last_name | deduction | pay
skywalker  | luke      | 100       | 200
vader      | darth     |  50       | 100
skywalker  | luke      | 400       | 500

becomes
first_name | last_name | deduction | pay
skywalker  | luke      | 500       | 700
vader      | darth     |  50       | 100

Thanks for the help/advice!

A: Answer 1
Create a trigger and another table
You could create a table called star_wars and another called star_wars_roll_up. Then a trigger on star_wars that aggregate data to star_wars_roll_up. You write to star_wars and read from star_wars_roll_up. It is safe to delete anything from star_wars whenever you feel like it.
create table star_wars (name varchar(100), deduction int, pay int);
create table star_wars_roll_up (name varchar(100), deduction int, pay int, primary key (name));
delimiter //
create trigger roll_up before insert on star_wars for each row begin insert into star_wars_roll_up values (new.name, new.deduction, new.pay) on duplicate key update deduction = deduction + new.deduction, pay = pay + new.pay;
end //
delimiter ;

insert into star_wars values ('luke', 100, 100);
insert into star_wars values ('luke', 100, 100);
insert into star_wars values ('luke', 100, 100);
select * from star_wars; select * from star_wars_roll_up;

A: Answer 2.
You could do the view and then periodically drop the extra data (like every night)
create table star_wars_new as select * from star_wars_view;
drop table star_wars;
rename table star_wars_new to star_wars;

A: If you only want to do this once, you can just do
CREATE TABLE new_table SELECT …;

where the SELECT pulls the new data you want for the table. Then just rename to replace the table.
RENAME TABLE current_table TO old_table, new_table TO current_table;