text:
Q: Vaadin and JPARepository: transaction errors I'm having troubles in integrating Vaadin and spring-data (JPARepositories in particular).
After following the guidance of Vaadin's team with their last webinar I managed to configure my application using Spring starter (spring boot), adding Vaadin, JPA and a Postgresql database. Using this method was really straightforward and loading entities to a table works out of the box by simply having this
@Autowired private ProjectDAO projects;

// other code here ...
grid.setContainerDataSource(new BeanItemContainer<Project>(Project.class, projects.findAll()));

My repository is just
@Repository
public class ProjectDAO implements JPARepository<Project, Long> {

}

And, as I said, this works flawlessly. The problem is when I try to save something: when trying to save a project via a button click, for example
btnSave.addClickListener(e -> saveCurrent());

private void saveCurrent() {
// ... here I do some filesystem operations, nothing that requires DB connection
    setModified();
}

public void setModified() {
    project.setLastAccess(new Date());
    projects.saveAndFlush(project);
}

I get an exception:
org.springframework.dao.InvalidDataAccessApiUsageException: no transaction is in progress; nested exception is javax.persistence.TransactionRequiredException: no transaction is in progress.

I've tried many different things, such as marking the setModified method as @Transactional, or encapsulating the setModified into a service class, but everything always throws this exception.
I find it rather strange that this doesn't work "out of the box", and I'd rather not work with transactions myself, since there are already the instruments to do that.
Any help would be really appreciated
EDIT 12/05/2015
It seems that this problem only appears when using an external server, not the embedded one provided by spring-boot. For test purposes I can manage to use the built-in, but eventually I will have to deploy the application on an existing server, so what could the issue be? Tomcat's configuration?

A: If anyone needs the answer I'll leave here what I found out after a few days of breaking my head on it.
Before deploying the application I changed some configurations on the main class that was generated by Spring Initializr (The application one) and made it extend SpringBootServletInitializer because I was following the guide I found in the official spring blog. Turns out that this was in fact not necessary because I set up "WAR" in Spring Initializr from the beginning, thus the application already had a class extending that one, and as a result when deploying it on Tomcat, the web application started twice, so the application was configured twice and two persistence units were instantiated. This probably was the error, because after reverting the changes I made to the application everything worked fine.
TL;DR: if you use Spring Initializr to create a WAR application don't touch anything.


text:
Q: get the bars in barplot to have the same height How do I get the bars in my barplot to have the same height?
> head(data.m)
  Classes variable        value
1    rRNA  KO1.DOC 4.890821e+04
2    rRNA  KO1.DOC 3.068479e+03
3   Other  KO1.DOC 7.618553e+01
4   Other  KO1.DOC 4.043281e-01
5   Other  KO1.DOC 0.000000e+00
6   Other  KO1.DOC 0.000000e+00

ggplot(data.m, aes(variable, fill=Classes, order = -as.numeric(Classes))) +
  geom_bar(aes(y=value), position="stack", stat="identity") +
  theme_bw(base_size=8)

A: The answer is to use position="fill" for geom_bar:
# regular barplot
ggplot(mtcars, aes(x=factor(cyl), fill=factor(vs))) +
  geom_bar()
# "filled"
ggplot(mtcars, aes(x=factor(cyl), fill=factor(vs))) +
  geom_bar(position="fill")

A: data.m <- melt(data=data, id.vars="Classes")
head(data.m)
dt <- data.table(data.m)
data.m <- dt[, list(count = sum(value)), by=list(Classes,variable)]
data.m <- data.m[, list(Classes=Classes, prop = count/sum(count)), by=variable]

ggplot(data.m, aes(variable,fill=Classes, order = -as.numeric(Classes))) +
geom_bar(aes(y=prop), position="stack", stat="identity") +
theme_bw(base_size=8)

redpajama_set_name: RedPajamaStackExchange


text:
Q: ¿Como comprobar si existe una tabla con un mismo nombre en una base de datos con php? ¡Hola!,quisiera saber como puedo comprobar si existe una tabla con el mismo nombre con php , estoy haciendo una validacion para ver si existe , en caso de que existe no me haga nada y me envie un mensaje y en caso de que si me produzca la accion, pongo codigo :

include "conexion.php";

$db->query('CREATE TABLE `daem' . date('Y') . '`
(
id int(240) auto_increment not null,
nombre varchar(40) null,edad varchar(40) null,fecha_registro TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT pk_daem PRIMARY KEY(id)
)

'); // create table
$db->query('CREATE TABLE `salud' . date('Y') . '`
(
id int(240) auto_increment not null,
nombre varchar(40) null,edad varchar(40) null,fecha_registro TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT pk_salud PRIMARY KEY(id)
)

'); // create table

if ($db->connect_error) {
    echo "NO SE PRODUJO ya que existe una tabla ya creada con el mismo nombre";
} else {
    echo "Si se produjo";
}

Intente producir un connect_error  o un connect_errno Pero me indica que ya se produjo la accion osea que ya creo las tablas pero ya estan creadas ,de antemano Muchas Gracias!
(Editado)
Estoy usando mysqli y la variable $db es la variable de conexion

A: Esta pregunta viene derivada de otras que has hecho y creo que lo mejor que puedes hacer es crear una tabla donde lleves un registro de los años creados, que te va a servir para mostrar el selector y para verificar que ya las tienes creadas, por ejemplo:
CREATE TABLE `years` (
    `year` mediumint NOT NULL DEFAULT 0,
    `crated` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY(`year`)
);

Cuando vayas a crear las nuevas tablas, creas un formulario y solo deja la opción para crear el siguiente periodo:
<?php
include "conexion.php";
// Por defecto, el año actual
$nuevoPeriodo = date('Y');
// Lees el último periodo guardado
$res = $db->query('SELECT `year` FROM `years` LIMIT 1 ORDER BY `year` DESC');
if($row = $res->fetch_assoc()) {
    // Leer el último periodo
    $nuevoPeriodo = $row['year'];
}
// Incrementar año para el nuevo periodo
$nuevoPeriodo ++;
?>

<form method="POST" action="crearperiodo.php">
    <input name="nuevo_periodo" value="<?php echo $nuevoPeriodo; ?>">
    <button type="submit">Crear periodo</button>
</form>

Para procesar el formulario, revisas primero los permisos de usuario, suponiendo que solo el administrador puede crear nuevos periodos y también revisa que el periodo a crear sea el que corresponde:
<?php
include "conexion.php";
// Aquí deberías verificar rol de usuario
// Por defecto, el año actual
$nuevoPeriodo = (isset($_POST['nuevo_periodo'])) ? $_POST['nuevo_periodo'] : date('Y');
// Lees el último periodo guardado
$res = $db->query('SELECT `year` FROM `years` LIMIT 1 ORDER BY `year` DESC');
if($row = $res->fetch_assoc()) {
    // Leer el último periodo
    $ultimoPeriodo = $row['year'];
    // Validar
    if(($nuevoPeriodo - $ultimoPeriodo) != 1) {
        die('Los periodos deben ser consecutivos);
    }
}
// Aquí insertas el nuevo periodo en la tabla
$sql = 'INSERT INTO `years` SET `year` = ?';
$stmt = $db->prepare($sql);
if($stmt->execute([$nuevoPeriodo])) {
    // El registro se insertó correctamente
    // Aquí creas las tablas
}

En las consultas para crear las nuevas tablas solo remplaza date('Y') con $nuevoPeriodo. Si hiciste todo correctamente, no es necesario revisar si la tabla existe o no y, en todo caso, puedes agregar IF NOT EXISTS:
CREATE TABLE IF NOT EXISTS nombre_de_tabla ...


text:
Q: Chang the citation style alphabetic of biblatex Is there a citation style in biblatex like alphabetic but without the numbers representing the year?
I.e. a book from 'Bach' and 'Schulz' written in 1978 schould get the label [BS] and not [BS79].
\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english]{babel}
\usepackage{csquotes}
\usepackage[style=alphabetic,maxnames=10]{biblatex}
\addbibresource{references.bib}
\usepackage{filecontents}
\begin{filecontents}{references.bib}
@book{key,
  author = {Baur, S and Schmid, A},
  year = {2001},
  title = {Title},
  publisher = {Publisher},
}
\end{filecontents}
\begin{document}
\nocite{*}
\printbibliography[heading=bibintoc]
\end{document}

A: You can configure the appearance from your label in the alphabetic styles with \DeclareLabelalphaTemplate:
\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english]{babel}
\usepackage{csquotes}
\usepackage[style=alphabetic,maxnames=10]{biblatex}
\addbibresource{references.bib}
\usepackage{filecontents}
\begin{filecontents}{references.bib}
@book{key1,
  author = {Baur, S and Schmid, A},
  year = {2001},
  title = {Title},
  publisher = {Publisher},
}

@book{key2,
  author = {Baur, S and Schmid, A},
  year = {2001},
  title = {Title},
  publisher = {Publisher},
}
\end{filecontents}

\DeclareLabelalphaTemplate{
    \labelelement{
        \field[final]{shorthand}
        \field{label}
        \field[strwidth=3,strside=left,ifnames=1]{labelname}
        \field[strwidth=1,strside=left]{labelname}
    }
%   \labelelement{ % this is removed from the default LabelalphaTemplate
%       \field[strwidth=2,strside=right]{year}
%   }
}

\DeclareFieldFormat{extraalpha}{#1}

\begin{document}
\nocite{*}
\printbibliography[heading=bibintoc]
\end{document}

In your case, as you want to remove the year digits from it. I simply commented the part corresponding to in the the default LabelalphaTemplate.
The result:


text:
Q: jQuery invoke function only when ajax of the previous function was executed I have the following problem:
$('#id').on('click', '.class', function(){
 // it is doing something and
 // executing AJAX request
 // with the data from request it is doing something
} // this is onclick handler

Later in the code I need to execute it as well and after executing I need to run another function which depends on the ajax execution of this onclick handler, so I am doing something like this
$('#id .class').click();
anotherFunction();

It is not working. The problem is understandable, because the ajax request has not finished.
I tried to achieve the right execution using the idea of Deferred object.
$.when( $('#id .class').click() ).then( anotherFunction() );

And using the idea of autoexecuted functions with callback:
(function(o, callback){
    $('#id .class').click()
})(null, anotherFunction() );

Both ideas failed.
Is there any way to achieve the intended functionality without modifying anotherFunction() and onclick function?

A: Not sure if I entirely understand your question, but what keeps you from executing your onsuccess / onerror code in the corresponding $.ajax response methods?
$.ajax({
  type: 'POST',
  url: "your url",
  data: "your data",
  error: function(jqXHR, textStatus, errorThrown) { ... },
  success: function (data, textStatus, jqXHR) { ... }
});

Also, why don't you put the ajax executing part to an own function and call it from the event handler and on every other place, like this?
function ajaxMe(onerror, onsuccess)
{
    $.ajax({
      type: 'POST',
      url: "your url",
      data: "your data",
      error: function(jqXHR, textStatus, errorThrown) { onerror(...) },
      success: function (data, textStatus, jqXHR) { onsuccess(...) }
    });
}


text:
Q: How to export a jpg from ArcScene? How can I switch to layout view in ArcScene and export a map in jpg format?

A: There is no Layout View in ArcScene.
You can export your scene to JPG by using File > Export Scene > 2D... and selecting JPEG in the Save As Type drop-down of the Export Map dialog.


text:
Q: Login to ajax loading of home page I am trying to create a dynamic login screen where my whole 'logged in' page isnt loaded into the dom until the form validates where the login screen scrolls down into the homepage without 'actually' scrolling.
I was thinking of doing this by
form -> ajax -> validate -> on validate ajax load expanding div under login area and load home page with ajax -> jquery hide login area.
Is there any easier way? if I already have both pages combined currently to just hide that part of the dom?

A: In general, I'd propose to give XAJAX a try.
The XAJAX library integrates well with PHP and e.g. allows to update several DOM elements at once.
In general, I'd prefer to run the login-operation in a non-AJAX fashion. But that's more or less a matter of taste. Once the user is logged in, I'd switch to AJAX.
Moreover, I wouldn't just hide the logged-in DOM element.

A: May be this could help you: Login y logout con PHP, MySQL, JQuery y Ajax (Spanish) http://bit.ly/tBmHtV
It have worked for me.


text:
Q: How to enforce that only a single object, out of all objects, of a Model has a specified value for a field I am writing a model ModelX and it would have several obj1, obj2 etc for it
ModelX has a field fieldX
I want to ensure that for all obj1, obj2, obj3 etc, there is only one of them that has fieldX = "XXX", and none of the others have
I can put asserts in pre_save() or post_save(), but is there a cleaner way of doing this at database level, so that it raises an IntegrityError?
Thanks
update
I have a Link model, which has a foreignkey to User, an access_token = textfield, and bool is_active
I want to enforce that any time, for Link objects for a particular user, only zero or one object can have is_active True, and any number of objects can have is_active = False

A: UNIQUE constraint works for both True and False values. If you really want to use it you have to make the is_active field nullable and use None (NULL) instead of False, as two NULLs are not considered equal (at least in PostgreSQL and MySQL).

A: Yes, use the 'unique' field option in the model definition https://docs.djangoproject.com/en/dev/ref/models/fields/#unique


text:
Q: parse json into a relational database or use a NoSQL? I am retrieving a JSON file from an API which size varies between 100kb to 7mb. The structure of the response is:

I initially thought in storing the response in a relational database, with the following tables and fields:

*

*operator

*

*id

*name

*short_name

*operator_accounts:

*

*id

*operator_id

*account_type

*account_name

*….

*operator_records

*

*id

*operator_account_id

*date

*text

*amount

*type

*category

*operator_kpis:

*

*id

*operator_id

*kpi1

*kp2

An operator will have between 1 to 20 operator_accounts. An operator_account might have thousands of operator_records. Operator_kpis will always be 1 row per operator.
I am intended to build an application where the users can visualize the operator_records and change/fix some of the rows. The operator_kpis is mainly based/calculated from the operator_records, each time the user change/fix values in the operator_records then the operators_kpis will be updated.
My question is:
I saw lately a video of NoSQL, (I am just getting familiar with them) and now I am confused as I am not sure if I should stay with a relational database like postgres or if I should use something like AWS dynamodb or MongoDB
From my understanding DynamoDB might not work for me due to size limit, but I am not sure if there will be a better way to distribute the JSON in dynamo or use mongo to store the file. Or simple store as S3 and read the information and amend the s3 object if the user made any changes in the records.

A: Most goals are accomplishable in either type of database system, but you'll likely find more flexibility in how you can query the data (inclusive of modifying data) with a relational database, at the tradeoff (in your case) of having to convert from JSON into a normalized form.
I think for maintaining data between two objects (operator_records and operator_kpis) you'll find a relational database system easier to utilize, given that your data objects are related already.


text:
Q: Excel Office Script : iterate through a 2D array and use setValues to write the data I currenty use Excel Office Script to get a response from Jotform API.
In my Json response, on the first level of my Array, I get some informations like "Submission ID" and "timestamp from Submission", then I have a Key "Answers" with all the answers from that Submission (could be 150 anwers). So it's a 2D array.
I'm having trouble being able use setValues after all the iterations and write all the answers in Excel in one shot.
Here is my iteration where rows will be "Submission ID + Timestamp", then next to it, subRows which will have all the answers for that submission, each answers being one Excel row each
    let rows: (string | boolean | number)[][] = [];
    let subRows: (string | boolean | number)[][] = [];

    for (const [key, value] of Object.entries(result)) {
        rows.push([value["id"], value["created_at"]]);
        for (const [subKey, subValue] of Object.entries(value["answers"])) {

                if (subValue.hasOwnProperty("answer")) {
                    subRows.push([checkAnswer(subValue["answer"])]);
                }

        }

    }

    // This function is important because sometimes I have several answers in one answer, so I join it when necessary.
    function checkAnswer(answer: string[]) {
        if (answer.length > 1) {
            return (typeof answer == "string" ? answer : answer.join("||"));
        }
        return answer;
    }
 // Here are the methods I use to write the result on my Excel file. The first one is great, it is one Excel row/ one result.

    const targetRange = workSheet.getRange('A5').getResizedRange(rows.length - 1, rows[0].length - 1);
    targetRange.setValues(rows);

    // I TRANSPOSE so that the subROWS get in line, not vertically.
    subRows = subRows[0].map((_, colIndex) => subRows.map(row => row[colIndex]));

    const subTargetRange = workSheet.getRangeByIndexes(4, 2, subRows.length, subRows[0].length).setValues(subRows);

My problem is that all the subrows (all the answers) are being written in one line, there is not one answer/one row.
I could use setValues inside the iteration, but I always try not too as it slows down the work.
The best being able to make one big array and do everything in one setValues.
Any idea ?
Thank you very much,
Cedric

A: You can definitely create one array and write it out at once using SetValues. Where it gets tricky is that SetValues expects the 2-d array in a certain structure. So you can't just supply any 2d array and expect it to work with SetValues. If you use GetValues on the range and log it to the console, it will let you know of the structure it expects it in. Please see a few examples below. The stringified values are just some random data I put into a worksheet:
function main(workbook: ExcelScript.Workbook) {
  let sheet: ExcelScript.Worksheet = workbook.getWorksheet("Sheet1");
  let rang1: ExcelScript.Range = sheet.getRange("A1:A5");
  console.log(rang1.getValues()); //(5) [Array(1), Array(1), Array(1), Array(1), Array(1)]
  console.log(JSON.stringify(rang1.getValues())); //[["A"],[0],[1],[2],[3]]

  let rang2: ExcelScript.Range = sheet.getRange("A1:B5");
  console.log(rang2.getValues()); //(5) [Array(2), Array(2), Array(2), Array(2), Array(2)]
  console.log(JSON.stringify(rang2.getValues())); //[["A","B"],[0,1],[1,2],[2,3],[3,4]]

  let rang3: ExcelScript.Range = sheet.getRange("D1:H1");
  console.log(rang3.getValues()); //(1) [Array(5)]
  console.log(JSON.stringify(rang3.getValues())); //[["A","B","C","D","E"]]

  let rang4: ExcelScript.Range = sheet.getRange("D1:H2");
  console.log(rang4.getValues()); //(2) [Array(5), Array(5)]
  console.log(JSON.stringify(rang4.getValues())); //[["A","B","C","D","E"],["B","C","D","E","F"]]
}

If the array does not come in the necessary structure, one thing you can try to do is write the array values to a 1d array. From there, you'd need to create a 2d array in the same structure as expected by SetValues for the range.


text:
Q: T-SQL error when trying to insert into a temp I have a temp table I'm trying to populate from a select statement.
However I'm getting this error :

Column name or number of supplied values does not match table definition

I have tracked it down to the column endtime that using the LEAD; if I removed this LEAD column, would it work?
Not sure what I'm missing
Thanks Mike
IF OBJECT_ID('tempdb.dbo.#flextx', 'U') IS NOT NULL
     DROP TABLE #flextx;

 CREATE TABLE dbo.#flextx
 (
     OmanId VARCHAR(255),
     MRDF VARCHAR(255),
     status VARCHAR(255),
     statusid BIGINT,
     EVENT_ACTION BIGINT,
     starttime DATETIME,
     endtime DATETIME
 )

INSERT INTO dbo.#flextx
    SELECT
        f.OmanId,
        f.MRDF,
        s.status,
        s.statusid,
        f.EVENT_ACTION,
        (f.TIMESTAMP) AS starttime,
        (LEAD(f.TIMESTAMP, 1, GETDATE()) OVER (ORDER BY f.TIMESTAMP)) AS endtime
    FROM
        dbo.#flext f
    LEFT JOIN
        dbo.statues AS s ON s.flexstatus = f.JOB_STATUS_TEXT
    WHERE
        EVENT_ACTION IN (225, 226)
        AND s.statusid = 23
    ORDER BY
        MRDF, EVENT_ACTION

A: This is a compile-time error.  Add a GO after the CREATE TABLE statement.
What is happening is that you are redefining the table.  The old definition is used when the script is compiled.  You should also be able to fix this by just deleting the existing version of the table.

A: you have a typo I think you want endtime to be the next start time that would be like this:
     (f.starttime) AS starttime,
      ( LEAD(f.starttime,1,GetDate()) OVER (ORDER BY mrdf, event_action) ) AS endtime

there is no TIMESTAMP column


text:
Q: How ZenTest works in detecting file save? I read some source code of ZenTest but didn't find where it is implemented.
Could you give me give some clue? Thanks in advance.

A: It looks like its in autotest.rb the method is called find_files_to_test, the algorithm is pretty basic, every second it checks the dates on all the files that affect testing and then, using some dependency analysis on the changed files, it decides which tests to run.
In Windows this would be significantly faster if it used a file system watcher.
The sleep time is defined initialize self.sleep = 1 and invoked from wait_for_changes
Kernel.sleep self.sleep until find_files_to_test


text:
Q: Angular13 Issues when running npm start Versions ->
PS C:\Users\user> npm --version
8.8.0
PS C:\Users\user> node --version
v16.15.0

Then i Run the next command->
npx -p @angular/cli ng new JokeFrontB

Then I just run Serve -> npm start
and I get the following
PS D:\C#\JokeSaver\JokeFrontB> npm start

> joke-front-b@0.0.0 start
> ng serve

√ Browser application bundle generation complete.

Initial Chunk Files | Names         |  Raw Size
vendor.js           | vendor        |   1.81 MB |
polyfills.js        | polyfills     | 123.15 kB |
main.js             | main          |  50.54 kB |
runtime.js          | runtime       |   6.35 kB |
styles.css          | styles        |   1.27 kB |

                    | Initial Total |   1.99 MB

Build at: 2022-05-03T01:01:34.976Z - Hash: 28244047a1cd8312 - Time: 11880ms

    Error: Module not found: Error: Can't resolve 'D:/C#/JokeSaver/JokeFrontB/src/app/app.component.scss?ngResource' in 'D:\C#\JokeSaver\JokeFrontB'

    Error: Module not found: Error: Can't resolve 'D:\C#\JokeSaver\JokeFrontB\node_modules\webpack-dev-server\client\index.js?protocol=auto%3A&username=&password=&hostname=0.0.0.0&port=0&pathname=%2Fws&logging=info&reconnect=10' in 'D:\C#\JokeSaver\JokeFrontB'

    Error: The loader "D:/C#/JokeSaver/JokeFrontB/src/app/app.component.scss" didn't return a string.

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **

× Failed to compile.

I have no idea what it could be...
Package.json looks like this
  {
      "name": "joke-front-b",
      "version": "0.0.0",
      "scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build",
        "watch": "ng build --watch --configuration development",
        "test": "ng test"
      },
      "private": true,
      "dependencies": {
        "@angular/animations": "~13.3.0",
        "@angular/common": "~13.3.0",
        "@angular/compiler": "~13.3.0",
        "@angular/core": "~13.3.0",
        "@angular/forms": "~13.3.0",
        "@angular/platform-browser": "~13.3.0",
        "@angular/platform-browser-dynamic": "~13.3.0",
        "@angular/router": "~13.3.0",
        "rxjs": "~7.5.0",
        "tslib": "^2.3.0",
        "zone.js": "~0.11.4"
      },
      "devDependencies": {
        "@angular-devkit/build-angular": "~13.3.4",
        "@angular/cli": "~13.3.4",
        "@angular/compiler-cli": "~13.3.0",
        "@types/jasmine": "~3.10.0",
        "@types/node": "^12.11.1",
        "jasmine-core": "~4.0.0",
        "karma": "~6.3.0",
        "karma-chrome-launcher": "~3.1.0",
        "karma-coverage": "~2.1.0",
        "karma-jasmine": "~4.0.0",
        "karma-jasmine-html-reporter": "~1.7.0",
        "typescript": "~4.6.2"
      }
    }

    tsconfig.json looks like this

    {
      "compileOnSave": false,
      "compilerOptions": {
        "baseUrl": "./",
        "outDir": "./dist/out-tsc",
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "noImplicitOverride": true,
        "noPropertyAccessFromIndexSignature": true,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true,
        "sourceMap": true,
        "declaration": false,
        "downlevelIteration": true,
        "experimentalDecorators": true,
        "moduleResolution": "node",
        "importHelpers": true,
        "target": "es2017",
        "module": "es2020",
        "lib": [
          "es2020",
          "dom"
        ]
      },
      "angularCompilerOptions": {
        "enableI18nLegacyMessageIdFormat": false,
        "strictInjectionParameters": true,
        "strictInputAccessModifiers": true,
        "strictTemplates": true
      }
    }

angular.json
    {
      "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
      "version": 1,
      "newProjectRoot": "projects",
      "projects": {
        "JokeFrontB": {
          "projectType": "application",
          "schematics": {
            "@schematics/angular:component": {
              "style": "scss"
            },
            "@schematics/angular:application": {
              "strict": true
            }
          },
          "root": "",
          "sourceRoot": "src",
          "prefix": "app",
          "architect": {
            "build": {
              "builder": "@angular-devkit/build-angular:browser",
              "options": {
                "outputPath": "dist/joke-front-b",
                "index": "src/index.html",
                "main": "src/main.ts",
                "polyfills": "src/polyfills.ts",
                "tsConfig": "tsconfig.app.json",
                "inlineStyleLanguage": "scss",
                "assets": [
                  "src/favicon.ico",
                  "src/assets"
                ],
                "styles": [
                  "src/styles.scss"
                ],
                "scripts": []
              },
              "configurations": {
                "production": {
                  "budgets": [
                    {
                      "type": "initial",
                      "maximumWarning": "500kb",
                      "maximumError": "1mb"
                    },
                    {
                      "type": "anyComponentStyle",
                      "maximumWarning": "2kb",
                      "maximumError": "4kb"
                    }
                  ],
                  "fileReplacements": [
                    {
                      "replace": "src/environments/environment.ts",
                      "with": "src/environments/environment.prod.ts"
                    }
                  ],
                  "outputHashing": "all"
                },
                "development": {
                  "buildOptimizer": false,
                  "optimization": false,
                  "vendorChunk": true,
                  "extractLicenses": false,
                  "sourceMap": true,
                  "namedChunks": true
                }
              },
              "defaultConfiguration": "production"
            },
            "serve": {
              "builder": "@angular-devkit/build-angular:dev-server",
              "configurations": {
                "production": {
                  "browserTarget": "JokeFrontB:build:production"
                },
                "development": {
                  "browserTarget": "JokeFrontB:build:development"
                }
              },
              "defaultConfiguration": "development"
            },
            "extract-i18n": {
              "builder": "@angular-devkit/build-angular:extract-i18n",
              "options": {
                "browserTarget": "JokeFrontB:build"
              }
            },
            "test": {
              "builder": "@angular-devkit/build-angular:karma",
              "options": {
                "main": "src/test.ts",
                "polyfills": "src/polyfills.ts",
                "tsConfig": "tsconfig.spec.json",
                "karmaConfig": "karma.conf.js",
                "inlineStyleLanguage": "scss",
                "assets": [
                  "src/favicon.ico",
                  "src/assets"
                ],
                "styles": [
                  "src/styles.scss"
                ],
                "scripts": []
              }
            }
          }
        }
      },
      "defaultProject": "JokeFrontB"
    }

What have I tried?

*

*install older versions of both npm node and angular

*install angular latest globally

*install angular older version globally

*Create a project delete node_modules and run npm install

*delete node_modules and package.json and run npm install

*tried getting the same version on rxjs installing latest

 app's folder structure

A: i had the same issue and its do with webpack i believe, it read # as a space and not the character # so change the file structure to d://


text:
Q: Parsing Savon XML Response Here is the response from a SOAP request in SOAPUI
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
  <PostApplication_V5Response xmlns="http://QuiddiServicePricePoints.org/">
     <PostApplication_V5Result><![CDATA[<QuiddiSerivce>
        <Application>
           <Status>PURCHASED</Status>
           <RedirectURL>http://www.google.com?test=abc&xyz=123</RedirectURL>
        </Application>
     </QuiddiSerivce>]]></PostApplication_V5Result>
  </PostApplication_V5Response>
 </soap:Body>
</soap:Envelope>

However when I get the response.body from the Savon request it returns
{:post_application_v5_response=>{:post_application_v5_result=>"<QuiddiSerivce><Application><Status>PURCHASED</Status><RedirectURL>http://www.google.com?test=abc&xyz=123</RedirectURL></Application></QuiddiSerivce>", :@xmlns=>"http://QuiddiServicePricePoints.org/"}}

As you can see, the data I need, namely Status and RedirectURL, our still in XML format.
I've tried to convert [:post_application_v5_response][:post_application_v5_result] to a Hash using Hash.from_xml(), but it fails due to illegal characters in the RedirectURL.
How can I correctly escape characters in the RedirectURL so that I can convert the result to a hash, or otherwise access the Status and RedirectURL?

A: You could use Nokogiri to parse response body. And then search parsed document for desired values.
require 'nokogiri'
response_body = {:post_application_v5_response=>{:post_application_v5_result=>"<QuiddiSerivce><Application><Status>PURCHASED</Status><RedirectURL>http://www.google.com?test=abc&xyz=123</RedirectURL></Application></QuiddiSerivce>", :@xmlns=>"http://QuiddiServicePricePoints.org/"}}
res = Nokogiri.XML(response_body[:post_application_v5_response][:post_application_v5_result])
p res.search('Status').text
p res.search("RedirectURL").text

The result is:
#=> "PURCHASED"
#=> "http://www.google.com?test=abc=123"


text:
Q: extracting multiple values from xml using R I am having a hard time extracting values from an XML file. I would like to take the average of each "length" (value between the <length> tags) for each hour of the day. In this XML file, all of the data comes from the same day: 2013-11-28
An example is shown below:
 <root>
        <item>
            <time>2013-11-28T00:00:00-05:00</time>
            <day>2013-11-28</day>
            <length>150</length>
        </item>
        <item>
            <time>2010-11-28T00:15:00-05:00</time>
            <day>2010-11-28</day>
            <length>200</length>
        </item>
        <item>
            <time>2010-11-28T00:30:00-05:00</time>
            <day>2010-11-28</day>
            <length>127.83</length>
        </item>
</root>

I would like the output to look something like this:
   hour         average_length
12:00-12:59     some_average
1:00-1:59       some_average
2:00-2:59       some_average

Thank you!

A: How to read and format xml
Using the xml2 package and assuming text as in your example, we use
 xml_obj <- read_xml(text)

to create a xml object.
We can navigate in this objects using the various functions in the library that you can read about here. In this particular case we want to find all the elements of types time and length and then bind them in a data.frame.
# Find all elements of type time
times <- xml_find_all(xml_obj, '//time') %>% xml_text()
# Find all elements of type length
lengths <- xml_find_all(xml_obj, '//length') %>% xml_text()

# Merge the two to create the final data.frame
final <- data.frame(time = times, length = lengths)

Hope this helps


text:
Q: Can't get critical section to be atomic I'm currently learning about critical section & semaphores and I'm stuck atm with this part. I hope you guys can give me an insight.
I have these 3 types of threads: one will do pop() on a stack, another does push() on the same stack and the last one prints the values of that stack. At the moment, I've put wait() and signal() on what I assumed as critical sections.
class Example{

  public static void main(){

    //create thread objects
    StackPop p1 = new StackPop();
    StackPop p2 = new StackPop();
    StackPop p3 = new StackPop();

    StackPush ps1 = new StackPush();
    StackPush ps2 = new StackPush();
    StackPush ps3 = new StackPush();

    StackValues s1 = new StackValues();
    StackValues s2 = new StackValues();
    StackValues s3 = new StackValues();

    //then we start these threads in mix orders

    p1.start();
    s3.start();
    ps2.start();
    // etc
  }
}

class StackPop extends Thread{

  public void run(){

    mutex.wait();
    pop();
    SOP("value popped is " + get.popVal);
    mutex.signal();

  }
}

class StackPush extends Thread{

  public void run(){

    mutex.wait();
    push();
    SOP("value inserted is " + get.pushVal);
    mutex.signal();

  }
}

class StackValues extends Thread{

  public void run(){

    mutex.wait();

    for(int i = 0; i<stack.size(); i++)
        S.O.P.("["+getVal(i)+"]");   //where getVal() will retrieve value at that index

    mutex.signal();
  }
}

The above code is a simplified version, but the idea is the same. My problem is even though I used wait() and signal(), I still get a really weird output. For example part of my output will show "[1][2][3] value inserted is 3 [5][@][@]" (where @ means no number inside). I realize this is because the processor is letting another thread run while the for loop is getting the value. I was assuming wait() and signal() will make it atomic automatically but maybe I missed something.

A: You can use locks or "synchronized" on your critical section. You can see more in http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html
You can use the same idea to pop() push() ect..
With mutex;
try {
     mutex.acquire();
     try
     {
     // work
     } finally {
     mutex.release();
  }
} catch(InterruptedException ie) {// ...}

source -> http://java.dzone.com/articles/dnp-java-concurrency-–-part-4
"I have these 3 types of threads: one will do pop() on a stack, another does push() on the same stack and the last one prints the values of that stack"
You are using 3 different stack on for each Thread, thats why you have a unexpected. You make pop on one stack, you push from different stack and finally you print from a another stack.
You should do something like :
public class Teste {

    Thread t1;
    Thread t2;
    Thread t3;

    Stack<Integer> stack = new Stack <Integer>();
    private final Semaphore mutex = new Semaphore(1);

    public Teste ()
    {
        Runnable r1 = new Runnable()
        {
            public void run()
            {
            pop();
            } // run()
        }; // runnable

        Runnable r2 = new Runnable()
        {
            public void run()
            {
                for(int x = 0; x < 3; x++)
                   push(x);
            } // run()
        }; // runnable

        Runnable r3 = new Runnable()
        {
            public void run()
            {
                for(int x = 0; x < 3; x++)
                   print();
            } // run()
        }; // runnable

        this.t1 = new Thread(r1); // Create the thread associating the runnable
        this.t2 = new Thread(r2);
        this.t3 = new Thread(r3);
    }

    public void pop()
    {
        try {
            mutex.acquire();
        } catch (InterruptedException e) {

            e.printStackTrace();
        }
        stack.pop();
        mutex.release();
    }

    // Similar to pop
    public void push(int x){ //..}

    public void print(){
        try {
            mutex.acquire();
        } catch (InterruptedException e) {e.printStackTrace();}

        for(int i = 0; i<stack.size(); i++)
            System.out.println("["+stack.get(i)+"]");

        mutex.release();
    }

}

public static void main(String argv[])
  {

    Teste t = new Teste();
    t.t2.start();
    t.t1.start();
    t.t3.start();
  }

A: Be careful, wait is inherited from Object, its opposite is notify - you are likely to be calling the wrong methods.
Also, Java has a native synchronization mechanism, the synchronized keyword, you may want to investigate that.


text:
Q: asyncio tcp socket: How to cancel asyncio.sleep() when socket is closed? I am currently implementing the TCP socket protocol. The protocol requires sending heartbeat messages every five minutes. I am implementing a protocol using asyncio in Python. The source code below is a program that connects to localhost:8889, sends hello, and disconnects the socket after 1 second. In this case, the connection is disconnected after one second (if this actually happens, the network is down or the server is disconnected). The problem is that the send_heartbeat function waits 5 minutes without knowing that the socket is down. I would like to cancel the coroutine immediately instead of waiting 5 minutes when the socket is disconnected. What's the best way to do it?
import asyncio

async def run(host: str, port: int):
    while True:
        try:
            reader, writer = await asyncio.open_connection(host, port)

        except OSError as e:
            print('connection failed:', e)
            await asyncio.sleep(0.5)
            continue

        await asyncio.wait([
            handle_stream(reader, writer),
            send_heartbeat(reader, writer),
        ], return_when=asyncio.FIRST_COMPLETED)  # will stop after 1 second

        writer.close()  # close socket after 1 second
        await writer.wait_closed()

async def handle_stream(reader, writer):
    writer.write(b'hello\n')  # will success because socket is alive
    await writer.drain()

    await asyncio.sleep(1)

async def send_heartbeat(reader, writer):
    while True:
        await asyncio.sleep(300)

        heartbeat_message = b'heartbeat\n'
        writer.write(heartbeat_message)  # will fail because socket is already closed after 1 second
        await writer.drain()

if __name__ == '__main__':
    asyncio.run(run('127.0.0.1', 8889))

A: You can cancel the sleep by canceling a task that executes it. Creating send_heartbeat as a separate task ensures that it runs in parallel to handle_stream while you await the latter:
async def run(host: str, port: int):
    while True:
        ...
        heartbeat = asyncio.create_task(send_heartbeat(reader, writer))
        try:
            await handle_stream(reader, writer)
        finally:
            heartbeat.cancel()
            writer.close()
        await writer.wait_closed()

BTW, since you're awaiting writer.drain() inside handle_stream, there is no guarantee that handle_stream will always complete in 1 second. This might be a place where you might want to avoid the drain, or you can use asyncio.wait_for when awaiting handle_stream(...).


text:
Q: How to call a C# method from C using SWIG? I have been searching for some explanations/code snippets that illustrate how to call a C# method from C using SWIG. The best that I could find is this: Callback from C++ to C# using SWIG. Alas, this is for C++ and not C. How can we achieve the same functionality but for C?

A: You can do this using SWIG to help (a little) still, but fundamentally if you're using a C compiler you can't enable SWIG directors, which the example you linked to relies upon:
test.i:1: Error: Directors are not supported for C code and require the -c++ option

So you'll have to rebuild some parts of that functionality in C in order to do this. I built an example of a C++ enabled director/callbacks setup and used that as a basis to build my understanding of the C# mechanics. Let's work this through backwards, starting with the test we want to run:
public class TestImpl : CallbackInterface {
    public override void callback() {
        System.Console.WriteLine("handling event...");
    }

    public static void Main() {
        CallbackInterface cb = new TestImpl();
        test.test_runner(cb);
    }
}

We want to define an abstract class, CallbackInterface that we can pass instances around and have our C code call the C# callback implementation.
Here's my .i SWIG interface file:
%module test
%{
#include <assert.h>
%}

%typemap(csclassmodifiers) struct CallbackInterface "public abstract class";
%typemap(cscode) struct CallbackInterface %{
  public delegate void callback0(); // [2]

  public CallbackInterface() : this(null) { // [3]
    connect();
  }

  private void connect() {
    setCallback(new callback0(callback));
  }

  public abstract void callback();
%}

// [4]
%typemap(cstype) cb0 "CallbackInterface.callback0";
%typemap(imtype) cb0 "CallbackInterface.callback0";
%typemap(csin) cb0 "$csinput";
%ignore CallbackInterface::cb;

%extend struct CallbackInterface {
  CallbackInterface(cb0 cb) { // [3]
    struct CallbackInterface *ret = malloc(sizeof *ret);
    ret->cb = cb;
    return ret;
  }

  void setCallback(cb0 cb) {
    $self->cb = cb;
  }
}

%inline %{
  typedef void (*cb0)();

  struct CallbackInterface {
    cb0 cb; // [1]
  };

  static void test_runner(struct CallbackInterface *interface) {
    assert(interface->cb);
    fprintf(stderr, "Doing test, pointer=%p, cb=%p\n", interface, interface->cb);
    interface->cb();
  }
%}

From investigating the normal directors implementation in C# it seems that the C++ layer is working with function pointers through the pinvoke interface. So we define a struct in our interface at 1, which has a single member, a function pointer.
In order to actually get a function pointer out of our C# code we need to use a delegate, we've set things up for this at 2, which is C# code that's going to be part of our CallbackInterface class.
In SWIG we've "extended" (but just using C still) our struct to provide a constructor, which takes a delegate as an argument at 3. This is a little bit weird, because we only pass null in here, but that works as a handy overload for our default constructor later and ensures that we do at least initalise the cb member of the struct too when we create an instance, with a delegated constructor call at 3. (Aside: I originally tried to create the delegate here, but this is a static context it would seem so you can't do that at this point). Then inside the body of the default constructor we call our private connect method that sets up a delegate and uses our %extend setCallback method to actually modify the struct.
If you were so inclined you could provide an overload of setCallback as well, such that C function pointers can be set up as handlers, but that's an added extra especially given the C limitation means you can't write classes at all. With some extra typemaps at 4 to make sure that the delegate gets passed through to the C as a function pointer we're in business and so this Makefile below can run and test things for us:
.PHONY: run

all: run

test_wrap.c: test.i
    swig -csharp -Wall -debug-tmsearch test.i

test.cs: test_wrap.c
CallbackInterface.cs: test_wrap.c
testPINVOKE.cs: test_wrap.c

test.exe: test.cs runme.cs CallbackInterface.cs testPINVOKE.cs
    mcs $^

libtest.so: test_wrap.c
    gcc -shared -Wall -Wextra $^ -o $@ -fPIC

run: test.exe libtest.so
    LD_LIBRARY_PATH=. ./test.exe

With Mono on Ubuntu at least that does work as expected.


text:
Q: MQTT client connection not running in background I have created an MQTT client that is able to receive messages when app is open and when it is in the background but when i close the app it loses connection. I need it to stay connected as the messages that are being sent will launch my app. I have done some research and seen that creating a service would fix this. I've created the service but still it loses connection when app is closed and I cant figure out why. this is my MQTT service
    public class MQTTService extends Service {
        private MqttAndroidClient clientPhone;
        BroadcastReceiver m_ScreenOffReceiver;
        final String serverUri = "tcp://hairdresser.cloudmqtt.com:15767";
        final String clientId = "CarCrashDetection";
        final String subscriptionTopic = "Topic/+";
        final String username = "username";
        final String password = "password";

        public void     MQTTService() {
            clientPhone = new MqttAndroidClient(this, serverUri, clientId);
            clientPhone.setCallback(new MqttCallback() {
                public void connectComplete(boolean b, String s) {

                }
                @Override
                public void connectionLost(Throwable throwable) {

                }
                @Override
                public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                    Log.w("Mqtt", mqttMessage.toString());
                    Log.e("message ", String.valueOf(mqttMessage));
                    Toast.makeText(MQTTService.this, "Crash Occurred", Toast.LENGTH_SHORT).show();
                    Intent dialogIntent = new Intent(MQTTService.this, alert.class);
                    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(dialogIntent);
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                }
            });
        }
        @Override
        public IBinder onBind(Intent intent) {
            // TODO: Return the communication channel to the service.
            throw new UnsupportedOperationException("Not yet implemented");
        }

        @Override
        public void onCreate() {
            super.onCreate();
            registerReceiver();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    MQTTService.this.MQTTService();
                }
            }).start();
        }

        public void setCallback(MqttCallback callback) {
            clientPhone.setCallback(callback);
        }
        private MqttConnectOptions getOptions(){
            MqttConnectOptions options = new MqttConnectOptions();

            if(clientPhone.getServerURI().contains("ssl")) {
                //set ssl config.for example:
                //options.setSocketFactory(clientPhone.getSSLSocketFactory(YOUR_KEYSTORE_FILE, "YOUR_KEYSTORE_PASSWORD"));
                //...
            }
            options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
            options.setAutomaticReconnect(true);
            options.setCleanSession(false);;
            //options.setWill(...);
            options.setUserName(username);
            options.setPassword(password.toCharArray());

            return options;
        }
        private void connectMQTT() {
            try {
                //getOptions is a method that returns your MqttConnectOptions object
                IMqttToken token = clientPhone.connect(getOptions());
                token.setActionCallback(new IMqttActionListener() {
                    @Override
                    public void onSuccess(IMqttToken asyncActionToken) {
                        //do something
                        DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
                        disconnectedBufferOptions.setBufferEnabled(true);
                        disconnectedBufferOptions.setBufferSize(100);
                        disconnectedBufferOptions.setPersistBuffer(false);
                        disconnectedBufferOptions.setDeleteOldestMessages(false);
                        clientPhone.setBufferOpts(disconnectedBufferOptions);
                        subscribeToTopic();
                    }
                    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
                    @Override
                    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                        //do something
                    }
                });
            } catch (MqttException e) {
                //do something
                e.printStackTrace();
            }
        }
        private void subscribeToTopic() {
            try {
                clientPhone.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
                    @Override
                    public void onSuccess(IMqttToken asyncActionToken) {
                        Log.w("Mqtt","Subscribed!");
                    }

                    @Override
                    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                        Log.w("Mqtt", "Subscribed fail!");
                    }
                });

            } catch (MqttException ex) {
                System.err.println("Exception whilst subscribing");
                ex.printStackTrace();
            }
        }
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            //do something
            return START_STICKY;
        }

        private void registerReceiver(){
            m_ScreenOffReceiver = new BroadcastReceiver(){
                @Override
                public void onReceive(final Context context, Intent intent){
                    //Log.d(TAG,"onReceive of Wifi_State_Change called");
                    if(intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION))
                    {
                        int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
                        if(wifiState != WifiManager.WIFI_STATE_ENABLED)
                            return;

                        final WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                                String ssid = wifiInfo.getSSID();

                                Toast.makeText(context, "active wifi:" + ssid, Toast.LENGTH_SHORT).show();

                                //You can connect to the your mqtt broker again:
                                connectMQTT();
                            }
                        }, 10000);
                    }
                }
            };

            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
            registerReceiver(m_ScreenOffReceiver, intentFilter);
        }
        @Override
        public void onDestroy() {
            if(clientPhone!=null) {
            /*unregisterResources is needed,otherwise receive this error:
              has leaked ServiceConnection org.eclipse.paho.android.service.MqttAndroidClient*/
                try {
                    clientPhone.unregisterResources();
                    clientPhone.close();
                    clientPhone.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            unregisterReceiver(m_ScreenOffReceiver);
            m_ScreenOffReceiver = null;

            super.onDestroy();
        }
    }

And I am calling it in my main Activity like so:
  Intent intent = new Intent(MainActivity.this, MQTTService.class);
        startService(intent);

Like I said it only loses connection when my app is closed and I thought this would fix it but I cant see where I am going wrong. Any suggestions?


text:
Q: ColumnChart with dynamic number of columns I have a question about the ColumnChart in Flex 3.
a simple ColumnChart is like:

    <mx:horizontalAxis>
       <mx:CategoryAxis
            dataProvider="{myDP}"
            categoryField="date"
       />
    </mx:horizontalAxis>

    <mx:series>
         <mx:ColumnSeries
                xField="date"
                yField="Expense"
                displayName="Expense"
           />
           <mx:ColumnSeries
                xField="date"
                yField="Income"
                displayName="Income"
           />
      </mx:series>

But how to make a ColumnChart with dynamic number of columns which come from the dataprovider? Here the columns for "expense" and "income" are hardcoded. But how can we do if they come from the dataprovider, and number is not fixed, for example, yFields can be "expense 1", "expense 2", ... "Income 1", "Income 2", ...etc.

A: You can try to add new ColumnSeries() objects something like...
var series:Series = new Series();
for(...) // execute loop as per data provider
{
  var tmp:ColumnSeries = new ColumnSeries();
  tmp.xField....
  tmp.yField...
  ...

  series.addChild(tmp);
}

i think this, or similar solution should work

A: Matt, thanks for your solution.
Just a small detail that I found. without it, it can't display.
var tmp:ColumnSeries = new ColumnSeries();
//this line is very important.
this.myChart.series = [tmp];
for(var i:int=0; i< lens ; i++) // execute loop as per data provider
{
tmp = new ColumnSeries();
tmp.xField....
tmp.yField...
...
this.myChart.series[i]=tmp;
}
More details


text:
Q: Iterating over unique pairs in a HashSet (Java) I want to iterate over unique pairs in a HashSet, Ideally, I'd be able to make a copy of the iterator and when it has exhausted itself, iterate the iterator I am making copies of, but Iterators do not like being copied, and I suspect that there is a good reason for this, but I do not know what that is.
More specifically, what prevents this (below) behavior from being supported?
Iterator<Object> iter = myhash.iterator();
while(iter.hasNext()){
    object=iter.next();
    Iterator<Object> iterclone = iter.clone();
    while(iterclone.hasNext()){
        setOfObjectPairs.add(object,iterclone.next());
    }
}

Edit: The point of doing this is to save the current state of the iterator, which is already pointing at the i-th element.

A: If you cloned an Iterator and the clone modified the underlying Iterable, the original Iterator will throw a ConcurrentModificationException.
You can simply use another iterator for the same set.
Iterator<Object> iter = h.iterator();
        while(iter.hasNext()){
            Object o=iter.next();
            Iterator<Object> iterclone = h.iterator();
            while(iterclone.hasNext()){
                //logic
            }
        }

or you can use and array and iterate over it.

A: If the order to generate the pairs doesn't matter, then you could use the following code, which avoids having to clone the iterator, while still running in O(n*n) time:
HashSet<Integer> set = new HashSet<Integer>();
for (int i = 0; i < 10; i++) {
    set.add(i);
}
int to = 0;
for (int a : set) {
    int index = 0;
    for (int b : set) {
        if (index++ >= to) {
            break;
        }
        System.out.println(a + ", " + b);
    }
    to++;
}

A: If you will not change iterator (you're only want to save state)
The best way is to do it here is with for each loop I guess
I expect iterators to be only for cases when I modify collection in loop through this collection. For example remove() method from this iterator.
The best way I see it is:
    HashSet<Integer> set = new HashSet<Integer>();
    for (int i = 0; i < 10; i++) {
        set.add(i);
    }
    LinkedList<Integer> arr = new LinkedList<Integer>(set);
    for (Integer i : set) {
        arr.pollFirst();
        for (Integer k : arr) {
            System.out.println(i + " " + k);
        }
    }

Here you're coping you're hashset to LinkedList and you're droping first element from LinkedList every time you're iterating through hashset
Cloning anything in Java is not good practice. See for example Clone() vs Copy constructor- which is recommended in java


text:
Q: how to block someone from placing in the same spot TIC TAC TOE I'm trying to learn how to block someone from placing an X or an O on the spots where has already been played. how do I make so when picture X is displayed, picture O cannot be placed in the same spot as the X? What i've done so far is the Nombreup and Nombre are the keybinds that you can use to place either X or O. I just do not know how to prevent it to place an O or X on a spot where an O or X has been placed (prevent cheating during a tic tac toe game).
Here is my code :
document.onkeydown = Nombre;
Nombreup1 = 49; Nombreup2 = 50; Nombreup3 = 51;
Nombreup4   = 52; Nombreup5 = 53; Nombreup6 = 54;
Nombreup7   = 55; Nombreup8 = 56; Nombreup9 = 57;
Nombre7 = 103; Nombre8 = 104; Nombre9 = 105;
Nombre4 = 100; Nombre5 = 101; Nombre6 = 102;
Nombre3 = 99; Nombre2 = 98; Nombre1 = 97;

function Nombre(e){
  toucheCourante = e.keyCode;

  if (toucheCourante == Nombre7){
  lettreO7();

  } else if (toucheCourante == Nombre8){
    lettreO8();

  } else if (toucheCourante == Nombre9){
    lettreO9();

  } else if (toucheCourante == Nombre6){
    lettreO6();

  } else if (toucheCourante == Nombre5){
    lettreO5();

  } else if (toucheCourante == Nombre4){
    lettreO4();

  } else if (toucheCourante == Nombre3){
    lettreO3();

  } else if (toucheCourante == Nombre2){
    lettreO2();

  } else if (toucheCourante == Nombre1){
    lettreO1();
    }
/////////////////////////////////////////

    if (toucheCourante == Nombreup7){
    lettreX7();

  } else if (toucheCourante == Nombreup8){
      lettreX8();

  } else if (toucheCourante == Nombreup9){
      lettreX9();

  } else if (toucheCourante == Nombreup6){
      lettreX6();

  } else if (toucheCourante == Nombreup5){
      lettreX5();

  } else if (toucheCourante == Nombreup4){
      lettreX4();

  } else if (toucheCourante == Nombreup3){
      lettreX3();

  } else if (toucheCourante == Nombreup2){
      lettreX2();

  } else if (toucheCourante == Nombreup1){
      lettreX1();
      }

}

function casearret(){
 if (c1 < cup1) {

 }
}

function lettreO1()
{
  lettreO = new Image();
  lettreO.src = 'O.jpg';
  lettreO.onload = function(){
  context.drawImage(lettreO, 40, 265,95,93);

  }
}

function lettreX1()
{
  lettreX = new Image();
  lettreX.src = 'X.PNG';
  lettreX.onload = function(){
  context.drawImage(lettreX, 40, 265,95,93);

  }
}

function lettreO2()
{
  lettreO = new Image();
  lettreO.src = 'O.jpg';
  lettreO.onload = function(){
  context.drawImage(lettreO, 145, 265,110,93);

  }
}

function lettreX2()
{
  lettreX = new Image();
  lettreX.src = 'X.PNG';
  lettreX.onload = function(){
  context.drawImage(lettreX, 145, 265,110,93);

  }
}

function lettreO3()
{
  lettreO = new Image();
  lettreO.src = 'O.jpg';
  lettreO.onload = function(){
  context.drawImage(lettreO, 265, 265,95,93);
  }
}

function lettreX3()
{
  lettreX = new Image();
  lettreX.src = 'X.PNG';
  lettreX.onload = function(){
  context.drawImage(lettreX, 265, 265,95,93);
  }
}

function lettreO4()
{
  lettreO = new Image();
  lettreO.src = 'O.jpg';
  lettreO.onload = function(){
  context.drawImage(lettreO, 40,149,95,107);

  }
}

function lettreX4()
{
  lettreX = new Image();
  lettreX.src = 'X.PNG';
  lettreX.onload = function(){
  context.drawImage(lettreX, 40,149,95,107);

  }
}

function lettreO5()
{
  lettreO = new Image();
  lettreO.src = 'O.jpg';
  lettreO.onload = function(){
  context.drawImage(lettreO, 145,149,110,107);

  }
}

function lettreX5()
{
  lettreX = new Image();
  lettreX.src = 'X.PNG';
  lettreX.onload = function(){
  context.drawImage(lettreX, 145,149,110,107);

  }
}

function lettreO6()
{
  lettreO = new Image();
  lettreO.src = 'O.jpg';
  lettreO.onload = function(){
  context.drawImage(lettreO, 265,149,95,107);
  }
}

function lettreX6()
{
  lettreX = new Image();
  lettreX.src = 'X.PNG';
  lettreX.onload = function(){
  context.drawImage(lettreX, 265,149,95,107);

  }
}

function lettreO7()
{
  lettreO = new Image();
  lettreO.src = 'O.jpg';
  lettreO.onload = function(){
  context.drawImage(lettreO, 40,40,95,101);
  }
}

function lettreX7()
{
  lettreX = new Image();
  lettreX.src = 'X.PNG';
  lettreX.onload = function(){
  context.drawImage(lettreX, 40,40,95,101);

  }
}

function lettreO8()
{
  lettreO = new Image();
  lettreO.src = 'O.jpg';
  lettreO.onload = function(){
  context.drawImage(lettreO, 145,40,110,101);

  }
}
function lettreX8()
{
  lettreX = new Image();
  lettreX.src = 'X.PNG';
  lettreX.onload = function(){
context.drawImage(lettreX, 145,40,110,101);

  }
}
function lettreO9()
{
  lettreO = new Image();
  lettreO.src = 'O.jpg';
  lettreO.onload = function(){
  context.drawImage(lettreO, 265,40,95,101);
  }
}

function lettreX9()
{
  lettreX = new Image();
  lettreX.src = 'X.PNG';
  lettreX.onload = function(){
  context.drawImage(lettreX, 265,40,95,101);
  }
}

A: What I would normally do is have an array of values to store the moves already taken. For each move, I'd update it with whatever player put their mark in, then check for the default value before letting someone else place their symbol in that spot. FYI, arrays are zero based, so the first index is 0, not 1.
Moves = [0, 0, 0, 0, 0, 0, 0, 0, 0];
...
} else if (toucheCourante == Nombre9){
    if (Moves[8] == 0){
        Moves[8] = 2;
        lettreO9();
    }
}

There's quite a bit that could improve your code by learning about arrays.
NombresUp = [49, 50, 51, 52 ,53 ,54, 55, 56, 57];
Nombres = [97, 98, 99, 100, 101, 102, 103, 104, 105];
...
} else if (toucheCourante == Nombres[8]){ // this was Nombre9

There's also a lot that could be improved by passing parameters to your methods, too.
function lettre1(imageSource)
{
  var lettre = new Image();
  lettre.src = imageSource;
  lettre.onload = function(){
    context.drawImage(lettre, 40, 265, 95, 93);
  }
}
...
lettre1('O.jpg');
// or
lettre1('X.jpg');

Learning about objects would further clean up your code, but it seems like you already have a fair bit to learn and be comfortable with first, so I won't go into that. There's a lot of other improvements I could suggest, but I won't go into any of them either. I would basically be rewriting your game for you, so you probably wouldn't learn anything anyway. Since you are still learning, that's not a good way to teach you.
If you want to be real basic with this, put your global variable assignments (Nobmre1-9 & Nombreup1-9) in a method and call it for each game, then you can give them an invalid number when someone uses the spot. Since this is a ASCII number from the keyboard, you can make the invalid number -1.  This is not a good way to do it, but it would work.


text:
Q: Trigger an action when an app is pushed to cloudfoundry I know that cloud foundry events can be pulled with cf api request. But can I do anything to make cf perform some operation immediately when an app is pushed to it (or is stopped, or any other event)? For example, once I've pushed the app to cf I want cf to automatically send a message. Is it possible?

A: I don't know of a way to make the platform do this for you, not with out-of-the-box features, but you might consider using CI/CD pipelines to deploy your apps. In that case, you can simply have the pipeline send a message once the app has deployed successfully.
If you can't/don't want to do that, you'd need to have something that polls the events api. There is no "push" event, so you'd need to look for an even that is triggered when a push occurs, like audit.app.create and audit.app.update. When you find one, you could then kick off some action, like sending a message.
Just be careful with how often you're polling this API as it will add load onto your Cloud Controllers.


text:
Q: Python Pandas - loc create fortran ordered numpy array For example:
nrow = 10
ncol= 10
a = np.arange(nrow*ncol,dtype=np.int32).reshape(nrow,ncol)
a = pd.DataFrame(a)
ix_list = np.arange(nrow,dtype=np.int32)

print np.isfortran(a.values) #  False
print np.isfortran(a.loc[ix_list,:].values) #  True

Why is .loc create pandas dataframe with fortran ordered numpy array? Can I force it to create pandas dataframe with C ordered numpy array?

A: Can't answer to your first question but calling .values on your dataframe will return a numpy ndarray so:

*

*To check if the array is fortran, as written in the doc, you should better use numpy alternative .flags.f_contiguous (https://docs.scipy.org/doc/numpy/reference/generated/numpy.isfortran.html)

*To force your ndarray use np.ascontiguousarray()
or np.asfortranarray()
Hope it helps!

A: In [423]: adf = pd.DataFrame(a)
In [424]: ix_list = np.arange(nrow,dtype=np.int32)

Your problem indexing creates a F ordered array, as seen in flags and strides.  This is what I expect to see when doing transpose on an ordinary numpy array.
    In [426]: adf.loc[ix_list].values.flags
    Out[426]:
      C_CONTIGUOUS : False
      F_CONTIGUOUS : True
      OWNDATA : False
      WRITEABLE : True
      ALIGNED : True
      UPDATEIFCOPY : False
    In [427]: adf.loc[ix_list].values.strides
    Out[427]: (4, 40)

But other loc indexing produces a C order array:
In [428]: adf.loc[:].values.flags
Out[428]:
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  ....
In [429]: adf.loc[ix_list[::2]].values.flags
Out[429]:
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  ...
In [430]: adf.loc[ix_list[:-2]].values.flags
Out[430]:
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  ...

That looks a bug in the pandas loc indexer.
I'm guessing that np.ascontiguousarray is the cheapest way to ensure all cases are C ordered, since it does a np.array(..., copy=False), which is a conditional copy.  Arrays that are already C won't make a copy.
In quick time tests, adding a copy or np.ascontiguousarray does not slow things down at all.
In [439]: timeit np.ascontiguousarray(adf.loc[ix_list].values).flags
514 µs ± 7.07 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [440]: timeit adf.loc[ix_list].values.copy().flags
509 µs ± 5.94 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [441]: timeit adf.loc[ix_list].values.flags
513 µs ± 18.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [442]: timeit adf.loc[:].values.flags
24.9 µs ± 11.1 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [443]: timeit np.ascontiguousarray(adf.loc[:].values).flags
30 µs ± 865 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [444]: timeit adf.loc[ix_list[:-1]].values.flags
559 µs ± 12.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [445]: timeit np.ascontiguousarray(adf.loc[ix_list[:-1]].values).flags
559 µs ± 1.41 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Selecting rows on the numpy array is considerably faster than using loc:
In [446]: timeit adf.loc[:].values[ix_list].flags
32.9 µs ± 1.33 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [447]: timeit adf.values[ix_list].flags
20.9 µs ± 1.09 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)


text:
Q: Generate multiple buttons for distinct list elements I have a lot of data sets. I want to plot all of them and export some of them to file (or print them as in example below) by clicking buttons generated next to plots.
(*Create list of 5 random data sets*)
datalist = RandomInteger[10, {5, 20}];

(*Plot all data sets and create buttons to print raw data*)
Table[{ListPlot[data], Button["Print data", Print[data]]}, {data, datalist}]//Grid

My approach is not working, as the action of the button is executed outside of the scope of 'Table' function. How can I procedurally generate distinct buttons binded to different elements from list?

A: That's a typical use of With[]:
(*Create list of 5 random data sets*)
datalist = RandomInteger[10, {5, 20}];

(*Plot all data sets and create buttons to print raw data*)
Table[
  {ListPlot[data],
   With[{data00=data},Button["Print data",Print[data00]]]},
  {data, datalist}] //
Grid

data00=data ... Print[data00] could perfectly be replaced by data=data ... Print[data]

When you push a button, then the data are printed :

{5,4,3,9,10,9,2,9,4,5,9,6,8,5,0,9,4,9,6,4}

A: Grid[{ListPlot[#], Button["Print", Print[#]]} & /@ datalist]


text:
Q: Disable orientation animations when launching activity I have set my app's orientation to sensor and I am having the app handle all the orientation changes. Everything is working as expected while the app is running.
The problem occurs during the initial launch of the app.  If the phone is in portrait mode and a user starts my app, I see my app background appear,  then it will do an orientation rotation to landscape view, because I use setRequestedOrientation() within my app.  I want the orientation change but I don't want the rotation animation that comes with it.  I just want a hard switch between portrait and landscape.
I have tried using overridePendingTransition(0,0) in onCreate, surfaceChanged, or in onConfigurationChanged with no luck.  Is there somewhere else I should put this? I believe that using (0,0) should disable the pending animation.
I get the desired effect if I set System Settings->Display->Animations to none.  I have tried to set styles for my activity and that did not work either.

A: If the problem is only at application startup time, you can do this to force the landscape orientation with no animation:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp"
    android:versionCode="1"
    android:versionName="1.0">

    <application android:icon="@drawable/icon"
                 android:label="@string/app_name">

        <activity android:name="com.example.myapp.MyActivity"
                  android:screenOrientation="landscape">

        ...

        </activity>

    </application>
</manifest>

And then you can programmatically change the android:screenOrientation setting later in the code to allow landscape and portatit if you would like to.


text:
Q: Word2vec Vector Quality vs Number of Training Iterations I was looking at this paper http://arxiv.org/pdf/1605.07891v1.pdf and at one point it states
When training the local models, we sampled
1000 documents from p(d) with replacement.
To compensate for the much smaller corpus
size, we ran word2vec training for 80 iterations.
Does this mean that if your corpus is too small to produce good word vectors, you can just bump up the number of training iterations and the quality would improve?

A: Basically when a deep learning neural network runs, you want to optimize the weights on each neuron given the data and model. These "ideal weights" are very hard to compute exactly, so instead you run gradient descent to update the weights some on each iteration and get a good approximation.
The more iterations you do, the better your performance, but you're never going to do better than your model+data would with an optimal choice of weights.
So yes, you can improve the performance of Word2Vec some by increasing the number of iterations. But in practice, I haven't seen much gain beyond 20-30 iterations, and there's a hard upper bound on performance imposed by the quality and quantity of data you have.


text:
Q: Wordpress. Как вывести отдельные типы записей и таксономии + слайдер Не смог разобраться с выводом отдельного типа записи и таксономии
Есть отдельный тип записей "estate" и таксономия "Рекомендуемые"(которая распространяется почти на все типы записей) recom и хочу вывести из термина recomend
Есть к нему слайдер

1

2

3

4

5

6

Как сделать нормальный вывод из типа estate и таксономии Рекомендуемые?
Делал так:

         <?php
   $the_query = new WP_Query(array(
    'post_type' => 'estate',
'taxonomy' => 'recomend',
    'posts_per_page' => 12
    ));
   while ( $the_query->have_posts() ) :
   $the_query->the_post();
  ?>

                     <?php the_post_thumbnail('lg');?>

  <?php endwhile; wp_reset_postdata();?>

Но как итог выводится только все записи, а не из рекомендуемых

A: Решил всё таким путём

<?php
   $args = array(
      'post_type' => 'estate',
      'tax_query' => array(
         array(
            'taxonomy' => 'recom',
            'field' => 'slug',
            'terms' => 'recomend'
         )
      )
   );
   $estate = new WP_Query( $args );
   if( $estate->have_posts() ) {
      while( $estate->have_posts() ) {
         $estate->the_post();
         ?>

                     <?php the_post_thumbnail('lg');?>

         <?php
      }
   }
   else {
      echo 'На данный момент нету рекомендуемых';
   }
?>


text:
Q: Dispatcher only draws last object from array I have a multi-dimensional array of Tile objects.
My program starts by selecting a Tile in a random position (eg. (0,0)),  visits a random neighbour Tile, marks it as visited and moves to the next neighbour until there are no unvisited neighbours available.
This is my code:
while (HasUnvisitedNeighbours())
{
    Task.Run(() =>
    {
        Application.Current.Dispatcher.BeginInvoke(new Action(() =>
        {
            CurrentTile.Draw();
        }));
        Thread.Sleep(500);
    });

    //1. Choose randomly a neighbour
    List<char> Keys = new List<char>(CurrentTile.Neighbours.Keys);
    char randomKey = Keys[rnd.Next(Keys.Count)];

    CurrentTile = CurrentTile.Neighbours[randomKey];
    CurrentTile.HasBeenVisited = true;
}

I've debugged through my program, and I've confirmed that:
CurrentTile = CurrentTile.Neighbours[randomKey];

Correctly changes each loop to a correct neighbour and that the loop will stop when there are no unvisited neighbours next to it.
But in:
Task.Run(() =>
{
    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
    {
        CurrentTile.Draw();
    }));
    Thread.Sleep(500);
});

CurrentTile.Draw() always seems to have the same value, in the debugger (the last value of CurrentTile = CurrentTile.Neighbours[randomKey];. So it seems the dispatcher waits for the whole loop to finish and THEN it draws the last Tile object.
My intention is to draw the current Tile -> move to a neighbour -> mark it as current tile -> draw the current tile ->...

A: Your BeginInvoke is scheduling (queuing) some "work" to be done by a particular Dispatcher i.e. typically your main UI message loop/handling thread.
When you are in your "while loop" you are already processing/doing work on the Dispatcher thread (but it is for a different/previous message).
(Normally) The Dispatcher can't process the next "dispatch" message from the queue, till you have finished what you are doing and control returns to the Dispatcher...and then the Dispatcher can choose which message to process next (which might be yours, or it might be someone elses depending on priority).
(for a more indepth description of how the windows message loop/dispatcher works, see this: Does using dispatcher.Invoke make my thread safe?)
This bit of code will start off a Task which will keep causing random tiles to be visited until all your HasUnvisitedNeighbours() returns false.
You could alternatively use .Invoke (the synchronous version) instead of the .BeginInvoke and .Wait combination.
Note: it's often said to be preferable to use .BeginInvoke, rather than .Invoke as in certain situations .Invoke can deadlock....but I think in this case you could use either.
You could do your HasUnvisitedNeighbours(); and then the the .Draw, and selection of next tile in just a single "invoke" if you preferred.
However, I split it into 2 "invokes" as you could restructure it possibly so that you got the list of unvisited tiles only once (by querying all the tiles .HasBeenVisited property), and then only modify that list instead of asking all the tiles again - that's because you are the one visiting the tiles...so you know if they have now been visited.
void VisitAllNeighbours()
{
    Task.Run(() =>
    {
        while (true)
        {
            bool bHasUnvisitedNeighbours = false;

            DispatcherOperation dispopunvisitedtiles = Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                bHasUnvisitedNeighbours = HasUnvisitedNeighbours();
            };

            dispopunvisitedtiles.Wait();

            if (!bHasUnvisitedNeighbours)
                break;

            DispatcherOperation dispopvisitnext = Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                CurrentTile.Draw();

                //1. Choose randomly a neighbour
                List<char> Keys = new List<char>(CurrentTile.Neighbours.Keys);
                randomKey = Keys[rnd.Next(Keys.Count)];

                CurrentTile = CurrentTile.Neighbours[randomKey];
                CurrentTile.HasBeenVisited = true;

            }));

            // Take out this "wait" if you want multiple "visits" to be
            // pending/scheduled instead of only one at a time - be
            // careful that your "random visiting" selection code
            // doesn't cause too many "visits" to be outstanding though!
            //
            // Note: each visit never occurs at the same time as another
            // one as the "Dispatcher"/message loop is providing the
            // serialization.

            dispopvisitnext.Wait();

            Thread.Sleep(500); // if you want a "delay" between each Tile visit
        );
    }
}

A:
So it seems the dispatcher waits for the whole loop to finish and THEN it draws the last Tile object.

Yes, Dispatcher.BeginInvoke schedules a delegate to be eventually executed on the dispatcher thread. But why are you starting a new task only to call Dispatcher.BeginInvoke? This doesn't make much sense.
You could use the synchronous Invoke method to wait until the method has been excecuted on the dispatcher thread:
while (HasUnvisitedNeighbours())
{
    Application.Current.Dispatcher.Invoke(new Action(() => CurrentTile.Draw()));
    Thread.Sleep(500);

    List<char> Keys = new List<char>(CurrentTile.Neighbours.Keys);
    char randomKey = Keys[rnd.Next(Keys.Count)];

    CurrentTile = CurrentTile.Neighbours[randomKey];
    CurrentTile.HasBeenVisited = true;
}

Edit:
The UI thread cannot both execute your loop and update the UI simultaneously. You could try to run your code on a background thread:
private void Method()
{
    Task.Run(async () =>
    {
        while (HasUnvisitedNeighbours())
        {
            await Application.Current.Dispatcher.BeginInvoke(new Action(() => CurrentTile.Draw()));
            await Task.Delay(500);

            List<char> Keys = new List<char>(CurrentTile.Neighbours.Keys);
            char randomKey = Keys[rnd.Next(Keys.Count)];

            CurrentTile = CurrentTile.Neighbours[randomKey];
            CurrentTile.HasBeenVisited = true;
        }
    });
}


text:
Q: Android Emulator boot I'm starting android development from just three days, I have downloaded the SDK and install the platform and define the emulator, but it takes a lot of time to boot every time I run the application
Is there a way to run the emulator once and then run the application and to be updated on the emulator without closing it and re-opening it again
I'm using eclipse classic please any one try to help

A: Yes, just hit "Run" again, it will be reinstalled automatically if you changed code, otherwise you will see a message like "brought to front".
I recommend to not stop the emulator as long as you don't have to.

A: You don't need to close your emulator every time. Assuming you are using eclipse--> Right click on project-->Run-->Android application, if any changes, those will be deployed. Otherwise same screen will showup.

A: Yes. I usually just leave it open and launching the program from Eclipse updates the program in the emulator and launches it.
One weird thing is that the first time I launch it I get an error from Eclipse telling me that it has not been able to connect to the emulator, and the next time I launch the application a new emulator is launched. Usually I just close the first emulator,  launch it again and then it works as it should.


text:
Q: call object on click and wait for dispose i am developing an Virtual keyboard module.
KeyBoardModule.java
KeyBoardModule kbm = new KeyBoardModule("small", false, null);

is called when in Other jForm(MainFrame.java) is clickevent on textbox
then I get new JFrame with keyboard(its like popup window),
When JButton enter is pressed it saves data to variable textFieldValue from textarea of KeyBoardModule.
than frame.disponse()
the main class calls MainFrame and mainframe call on click the keyboard, and i need to return value from keyboard to mainframe..
without using actionlistener(for enter button) in mainframe

A: To return a value directly from  GUI1 to another GUI2 , GUI1 must have a reference to the object of GUI2. So that whenever you want to pass any message from GUI1 to GUI2 , you could do it by calling the appropriate method of GUI2. For example consider the code given below. While creating the object of InputBoard in MainFrame we pass the current object of MainFrame to InputBoard's constructor so that InputBoard could pass its input to MainFrame GUI using appropriate public method of MainFrame. Here MainFrame opens the InputBoard frame on click of button. And whenever some input is passed to the JTextField in InputBoard it is reflected within the JTextArea of MainFrame.
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;

class MainFrame extends JFrame implements ActionListener
{
    private JButton button;
    private JTextArea tArea;
    private InputBoard inBoard;
    public void prepareAndShowGUI()
    {
        setTitle("Main Frame");
        tArea = new JTextArea(10,30);
        button = new JButton("Click Me");
        inBoard = new InputBoard(this);
        inBoard.prepareGUI();
        JScrollPane tFieldPane = new JScrollPane(tArea);
        tArea.setLineWrap(true);
        tArea.setWrapStyleWord(true);
        tArea.setEditable(false);
        button.addActionListener(this);
        getContentPane().add(tFieldPane);
        getContentPane().add(button,BorderLayout.SOUTH);
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        button.requestFocus();
    }
    @Override
    public void actionPerformed(ActionEvent evt)
    {
        if (!inBoard.isVisible())
        {
            inBoard.setVisible(true);
        }
        inBoard.toFront();
    }
    public void setText(final String s)
    {
        tArea.setText(s);
    }
    public static void main(String[] st)
    {
        SwingUtilities.invokeLater( new Runnable()
        {
            @Override
            public void run()
            {
                MainFrame mf = new MainFrame();
                mf.prepareAndShowGUI();
            }
        });
    }
}
class InputBoard extends JFrame implements DocumentListener
{
    MainFrame mainFrame ;
    JTextField inField;
    public InputBoard(MainFrame mainFrame)
    {
        this.mainFrame = mainFrame;
    }
    public void prepareGUI()
    {
        setTitle("Input Board");
        inField = new JTextField(40);
        getContentPane().setLayout(new FlowLayout());
        getContentPane().add(inField);
        inField.getDocument().addDocumentListener(this);
        setLocationRelativeTo(mainFrame);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pack();
    }
    @Override
    public void changedUpdate(DocumentEvent evt)
    {
        mainFrame.setText(inField.getText());
    }
    @Override
    public void insertUpdate(DocumentEvent evt)
    {
        mainFrame.setText(inField.getText());
    }
    @Override
    public void removeUpdate(DocumentEvent evt)
    {
        mainFrame.setText(inField.getText());
    }
}


text:
Q: set data as tkinter background? so i found this code:
import Image,ImageDraw
import cStringIO
from random import randint as rint

def randgradient():
    img = Image.new("RGB", (300,300), "#FFFFFF")
    draw = ImageDraw.Draw(img)

    r,g,b = rint(0,255), rint(0,255), rint(0,255)
    dr = (rint(0,255) - r)/300.
    dg = (rint(0,255) - g)/300.
    db = (rint(0,255) - b)/300.
    for i in range(300):
        r,g,b = r+dr, g+dg, b+db
        draw.line((i,0,i,300), fill=(int(r),int(g),int(b)))

    f = cStringIO.StringIO()
    img.save(f, "PNG")

    print "Content-type: image/png\n"
    f.seek(0)
    print f.read()

if __name__ == "__main__":
    randgradient()

this code has a picture in the memory and im trying to make it a tkinter background with posibly this bit of code:
from Tkinter import *
Admin=Tk()
image1 = PhotoImage(file="f.png")
w = image1.width()
h = image1.height()
Admin.geometry("%dx%d+0+0" % (w, h))
panel1 = Label(Admin, image=image1)
panel1.pack()
Admin.mainloop

it doesn't really matter how i do it but the way just above does not work so how would i go about it?

A: You can convert an image to a Tk image using PIL's ImageTk module. See the PhotoImage class examples.


text:
Q: How do I approach crashes where there is no sign of my own code? E.g. I have this trace.
Thread : Crashed: com.apple.main-thread
0  libsystem_kernel.dylib         0x32fe2df0 __pthread_kill + 8
1  libsystem_pthread.dylib        0x33062c97 pthread_kill + 62
2  libsystem_c.dylib              0x32f81939 abort + 76
3  libc++abi.dylib                0x3217fbbd __cxa_bad_cast
4  libc++abi.dylib                0x3219966f default_terminate_handler() + 266
5  libobjc.A.dylib                0x32973f11 _objc_terminate() + 192

or this
Thread : Crashed: com.apple.main-thread
0  CoreFoundation                 0x2d60eab8 __CFBasicHashDeallocate + 48
1  CoreFoundation                 0x2d52488f CFRelease + 462
2  QuartzCore                     0x2fa8d635 CA::release_objects(X::List<void const*>*) + 16
3  QuartzCore                     0x2fa8cec7 CA::Layer::~Layer() + 242
4  QuartzCore                     0x2fa8e431 CA::release_root_if_unused(CA::Layer*, CA::Layer*, void*) + 48
5  QuartzCore                     0x2fa8e3ad x_hash_table_remove_if + 68
6  QuartzCore                     0x2fa89443 CA::Transaction::commit() + 142
7  UIKit                          0x2fe0940b _afterCACommitHandler + 126
8  CoreFoundation                 0x2d5bf255 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 20
9  CoreFoundation                 0x2d5bcbf9 __CFRunLoopDoObservers + 284
10 CoreFoundation                 0x2d5bcf3b __CFRunLoopRun + 730
11 CoreFoundation                 0x2d527ebf CFRunLoopRunSpecific + 522
12 CoreFoundation                 0x2d527ca3 CFRunLoopRunInMode + 106
13 GraphicsServices               0x3244e663 GSEventRunModal + 138
14 UIKit                          0x2fe7414d UIApplicationMain + 1136
15 myapp                          0x0009c6f3 main (main.m:6)

or this
Thread : Crashed: WebThread
0  libobjc.A.dylib                0x31ea0f46 objc_msgSend + 5
1  UIKit                          0x272eeea1 +[UIViewAnimationState popAnimationState] + 320
2  MediaPlayer                    0x2563056b -[MPVolumeSlider _layoutForAvailableRoutes] + 1410
3  MediaPlayer                    0x2562f1b5 -[MPVolumeSlider layoutSubviews] + 60
4  UIKit                          0x272ba7ff -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 514
5  QuartzCore                     0x26ce0835 -[CALayer layoutSublayers] + 136
6  QuartzCore                     0x26cdc20d CA::Layer::layout_if_needed(CA::Transaction*) + 360
7  UIKit                          0x272ccf77 -[UIView(Hierarchy) layoutBelowIfNeeded] + 138
8  UIKit                          0x272d2463 -[UISlider setValue:animated:] + 178
9  MediaPlayer                    0x2562f8ab -[MPVolumeSlider volumeController:volumeValueDidChange:] + 78
10 MediaPlayer                    0x2569391d -[MPVolumeController updateVolumeValue] + 252
11 MediaPlayer                    0x2562f2c3 -[MPVolumeSlider didMoveToSuperview] + 126
12 UIKit                          0x272b9721 -[UIView(Hierarchy) _postMovedFromSuperview:] + 428
13 UIKit                          0x272c3bcf -[UIView(Internal) _addSubview:positioned:relativeTo:] + 1462
14 UIKit                          0x272c360f -[UIView(Hierarchy) addSubview:] + 30
15 MediaPlayer                    0x25632099 -[MPVolumeView _createSubviews] + 236
16 MediaPlayer                    0x25630ce5 -[MPVolumeView _initWithStyle:] + 212
17 MediaPlayer                    0x25630d79 -[MPVolumeView initWithFrame:style:] + 80
18 MediaPlayer                    0x25630d23 -[MPVolumeView initWithFrame:] + 38
19 UIKit                          0x272da3a1 -[UIView init] + 44
20 WebCore                        0x2fdcd1cf -[WebMediaSessionHelper initWithCallback:] + 178
21 WebCore                        0x2fdcc611 WebCore::MediaSessionManageriOS::MediaSessionManageriOS() + 172
22 WebCore                        0x2fdcc4fd WebCore::MediaSessionManager::sharedManager() + 124
23 WebCore                        0x2fdcb785 WebCore::MediaSession::MediaSession(WebCore::MediaSessionClient&) + 32
24 WebCore                        0x2fa5fe75 WebCore::HTMLMediaSession::create(WebCore::MediaSessionClient&) + 20
25 WebCore                        0x2fa4e81f WebCore::HTMLMediaElement::HTMLMediaElement(WebCore::QualifiedName const&, WebCore::Document&, bool) + 1046
26 WebCore                        0x2fa77917 WebCore::HTMLVideoElement::create(WebCore::QualifiedName const&, WebCore::Document&, bool) + 38
27 WebCore                        0x2fa41b79 WebCore::videoConstructor(WebCore::QualifiedName const&, WebCore::Document&, WebCore::HTMLFormElement*, bool) + 56
28 WebCore                        0x2fa412cd WebCore::HTMLElementFactory::createElement(WebCore::QualifiedName const&, WebCore::Document&, WebCore::HTMLFormElement*, bool) + 232
29 WebCore                        0x2f64b53d WebCore::HTMLDocument::createElement(WTF::AtomicString const&, int&) + 88
30 WebCore                        0x2f64b47f WebCore::jsDocumentPrototypeFunctionCreateElement(JSC::ExecState*) + 242
31 JavaScriptCore                 0x2521d783 llint_entry + 21314
32 JavaScriptCore                 0x2521d377 llint_entry + 20278
33 JavaScriptCore                 0x2521d377 llint_entry + 20278
34 JavaScriptCore                 0x2521d377 llint_entry + 20278
35 JavaScriptCore                 0x2521822f callToJavaScript + 334
36 JavaScriptCore                 0x251a7d09 JSC::JITCode::execute(JSC::VM*, JSC::ProtoCallFrame*) + 36
37 JavaScriptCore                 0x24fde3fb JSC::Interpreter::execute(JSC::ProgramExecutable*, JSC::ExecState*, JSC::JSObject*) + 5738
38 JavaScriptCore                 0x24fdcc43 JSC::evaluate(JSC::ExecState*, JSC::SourceCode const&, JSC::JSValue, JSC::JSValue*) + 358
39 WebCore                        0x2fefd539 WebCore::ScriptController::evaluateInWorld(WebCore::ScriptSourceCode const&, WebCore::DOMWrapperWorld&) + 196
40 WebCore                        0x2f666173 WebCore::ScriptController::evaluate(WebCore::ScriptSourceCode const&) + 26
41 WebCore                        0x2f666117 WebCore::ScriptElement::executeScript(WebCore::ScriptSourceCode const&) + 234
42 WebCore                        0x2f6ecb05 WebCore::HTMLScriptRunner::executePendingScriptAndDispatchEvent(WebCore::PendingScript&) + 156
43 WebCore                        0x2f6e8059 WebCore::HTMLScriptRunner::executeParsingBlockingScripts() + 244
44 WebCore                        0x2f6e576d WebCore::HTMLDocumentParser::runScriptsForPausedTreeBuilder() + 52
45 WebCore                        0x2f68dd77 WebCore::HTMLDocumentParser::canTakeNextToken(WebCore::HTMLDocumentParser::SynchronousMode, WebCore::PumpSession&) + 50
46 WebCore                        0x2f68d305 WebCore::HTMLDocumentParser::pumpTokenizer(WebCore::HTMLDocumentParser::SynchronousMode) + 344
47 WebCore                        0x2f6edf3f WebCore::HTMLDocumentParser::resumeParsingAfterScriptExecution() + 78
48 WebCore                        0x2f672c1d WebCore::HTMLDocumentParser::executeScriptsWaitingForStylesheets() + 44
49 WebCore                        0x2f66ff7b WebCore::Document::didRemoveAllPendingStylesheet() + 66
50 WebCore                        0x2f738151 WebCore::HTMLLinkElement::sheetLoaded() + 76
51 WebCore                        0x2f66fe93 WebCore::StyleSheetContents::checkLoaded() + 130
52 WebCore                        0x2fa4d415 WebCore::HTMLLinkElement::setCSSStyleSheet(WTF::String const&, WebCore::URL const&, WTF::String const&, WebCore::CachedCSSStyleSheet const*) + 508
53 WebCore                        0x2f6ee08b WebCore::CachedCSSStyleSheet::checkNotify() + 246
54 WebCore                        0x2f737a79 WebCore::CachedCSSStyleSheet::finishLoading(WebCore::ResourceBuffer*) + 192
55 WebCore                        0x2f6e9893 WebCore::SubresourceLoader::didFinishLoading(double) + 78
56 CFNetwork                      0x2380df5f ___ZN27URLConnectionClient_Classic26_delegate_didFinishLoadingEU13block_pointerFvvE_block_invoke + 78
57 CFNetwork                      0x238aaff9 ___ZN27URLConnectionClient_Classic18_withDelegateAsyncEPKcU13block_pointerFvP16_CFURLConnectionPK33CFURLConnectionClientCurrent_VMaxE_block_invoke_2 + 60
58 CFNetwork                      0x237fed8d RunloopBlockContext::_invoke_block(void const*, void*) + 60
59 CoreFoundation                 0x23cb1e1d CFArrayApplyFunction + 36
60 CFNetwork                      0x237fec47 RunloopBlockContext::perform() + 182
61 CFNetwork                      0x237feb0d MultiplexerSource::perform() + 216
62 CFNetwork                      0x237fe9a1 MultiplexerSource::_perform(void*) + 48
63 CoreFoundation                 0x23d66fbf __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 14
64 CoreFoundation                 0x23d663cf __CFRunLoopDoSources0 + 218
65 CoreFoundation                 0x23d64a35 __CFRunLoopRun + 772
66 CoreFoundation                 0x23cb23b1 CFRunLoopRunSpecific + 476
67 CoreFoundation                 0x23cb21c3 CFRunLoopRunInMode + 106
68 WebCore                        0x2f6a9483 RunWebThread(void*) + 418
69 libsystem_pthread.dylib        0x32567e23 _pthread_body + 138
70 libsystem_pthread.dylib        0x32567d97 _pthread_start + 118

How can I go about to solve these?

A: I'm also seeing the crashes described above in all of my apps (Hockeyapp reporting). I have no idea what I can do to resolve them, as they seem to be happening in iOS API's. They are only showing up on iOS8 devices...


text:
Q: sharing singleton java class by Service and Activity Is there a potential issue using a Singleton Java class by both a Service and Activity in an Android application?
Example: Singleton is Singleton
Activity is A
Service S
Service S has a handle to Singleton. S requests Singleton to launch Activity. Activity calls operational methods defined in Singleton.
I have several Singletons in my application which encapsulate various operations for a functional area. So Activities will interact with various Singletons to perform various operations.

A: I don't think there is an issue with this approach. I use singletons quite often and never had any problems. You just need to keep in mind that android might remove the singleton instance when it needs the memory, so you need to check for null every time you get the singleton instance.

A: Usually it won't introduce the issue. The only case You could expect it - using service running in separate process (service has android:process attribute defined which starts with '.'). In that case You'll simply has two instances of the singleton - one for each process.