text:
Q: Sphinx 3 Search engine: Having problems reading JSON from CSV source When I try to read JSON content from a field I get:
WARNING: document 1, attribute assorted: JSON error: syntax error, unexpected TOK_IDENT, expecting $end near 'a:foo'
Here are the details:
This is the (super simplified) CSV file I'm trying to read:
1,hello world, document number one,a:foo
22,hello again, document number two,foo:bar
23,hello now, This is some stuff,foo:{bar:baz}
24,hello cow, more test stuff and things,{foo:bar}
55,hello suess, box and sox and goats and moats,[a]
56,hello raven, nevermore said the thing,foo:bar

When I run the indexer this is the result I get:

../bin/indexer --config /home/ec2-user/sphinx/etc/sphinx.conf --all --rotate

Sphinx 3.3.1 (commit b72d67b)
Copyright (c) 2001-2020, Andrew Aksyonoff
Copyright (c) 2008-2016, Sphinx Technologies Inc (http://sphinxsearch.com)

using config file '/home/ec2-user/sphinx/etc/sphinx.conf'...
indexing index 'csvtest'...
WARNING: document 1, attribute assorted: JSON error: syntax error, unexpected TOK_IDENT, expecting $end near 'a:foo'
WARNING: document 22, attribute assorted: JSON error: syntax error, unexpected TOK_IDENT, expecting $end near 'foo:bar'
WARNING: document 23, attribute assorted: JSON error: syntax error, unexpected TOK_IDENT, expecting $end near 'foo:{bar:baz}'
WARNING: document 24, attribute assorted: JSON error: syntax error, unexpected '}', expecting '[' near '}'
WARNING: document 55, attribute assorted: JSON error: syntax error, unexpected ']', expecting '[' near ']'
WARNING: document 56, attribute assorted: JSON error: syntax error, unexpected TOK_IDENT, expecting $end near 'foo:bar'
collected 6 docs, 0.0 MB
sorted 0.0 Mhits, 100.0% done
total 6 docs, 0.1 Kb
total 0.0 sec, 17.7 Kb/sec, 1709 docs/sec
rotating indices: successfully sent SIGHUP to searchd (pid=14393).

This is the entire config file:
source csvsrc
{
    type = csvpipe
    csvpipe_delimiter = ,
    csvpipe_command = cat /home/ec2-user/sphinx/etc/example.csv
    csvpipe_field_string =t
    csvpipe_attr_string =c
    csvpipe_attr_json =assorted
}

index csvtest
{
    source          = csvsrc
    path            = /var/data/test7
    morphology      = stem_en
    rt_field = t
    rt_field = c
    rt_field = assorted

}

indexer
{
    mem_limit       = 128M
}

searchd
{
    listen          = 9312
    listen          = 9306:mysql41
    log             = /var/log/searchd.log
    query_log       = /var/log/query.log
    pid_file        = /var/log/searchd.pid
    binlog_path     = /var/data
}

And If I do log in and query, it's pretty obvious that the JSON was not, in fact, indexed (as expected from the warnings)
 select * from csvtest;
+------+-------------+----------------------------------+----------+
| id   | t           | c                                | assorted |
+------+-------------+----------------------------------+----------+
|    1 | hello world |  document number one             | NULL     |
|   22 | hello again |  document number two             | NULL     |
|   23 | hello now   |  This is some stuff              | NULL     |
|   24 | hello cow   |  more test stuff and things      | NULL     |
|   55 | hello suess |  box and sox and goats and moats | NULL     |
|   56 | hello raven |  nevermore said the thing        | NULL     |
+------+-------------+----------------------------------+----------+
6 rows in set (0.00 sec)

I have tried a few things, but I'm just groping in the dark.
Some things I have tried:

*

*Alternate formats of JSON. I have tried using {foo:bar} and {[foo:bar]} and [{foo,bar}] based on some experiences with other JSON inputs where they want it to be either an array or dict at the top level. These actually generate slightly different errors:

WARNING: document 24, attribute assorted: JSON error: syntax error, unexpected '}', expecting '[' near '}'
WARNING: document 55, attribute assorted: JSON error: syntax error, unexpected ']', expecting '[' near ']'

*I have tried adding a trailing comma thinking that might be the $end token that the parser is looking for. This generates an actual error ERROR: index 'csvtest': source 'csvsrc': not all columns found (found=5, total=4, line=1). which prevents index generation. That makes sense to me

2a) I tried adding a whole other column after the JSON so I could have the ending comma but not get an error that would prevent the index from generating. This did generate the index, but did not provide the $end token that the JSON parser was looking for.
I'm totally stumped.

A: Well as such a:foo isnt a valid JSON value AFAIK. LOoks like it meant to be object? So would need {...} surrounding it.
But even {foo:bar} is not valid either. At the very least the 'value' shoud be quoted {foo:"bar"}. But really the keys quoting too {"foo":"bar"}
Javascript Objects technically allow unquoted key names, but JSON requires the quoting.
... but also remember it CSV. Quotes are typically used for quoting (eg when columns contain commas), so the quotes need double encoding! Ends up a bit messy...
24,hello cow, more test stuff and things,"{""foo"":""bar""}"


text: Q: Чтение информации из радиомодуля Хотелось бы узнать, как можно добраться до радиомодуля? Мне нужна информация о мощности базовой станции, частоте, на которой она работает и т.д., т.е. низкоуровневая информация, к которой нет доступа в стандартной Android SDK.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ERROR in ./node_modules/@elastic/elasticsearch/lib/Connection.js Module not found: Error: Can't resolve 'http' I am working on an angular 6 project and I updated the version of elasticsearch from 6 to 7 on the server, after changing the code of the old API to use the new one, these errors occurred, does anyone have any idea how to correct?
The angular application is made on visual studio code and elasticsearch is on a linux server.
import { Injectable } from '@angular/core';
// import { Clientex } from 'elasticsearch-browser';
import { Client } from '@elastic/elasticsearch';
// import * as elasticsearch from 'elasticsearch-browser';
// import { concatMapTo } from 'rxjs/operators';
// import { stringify } from '@angular/core/src/render3/util';

@Injectable({
  providedIn: 'root'
})

export class ElasticsearchService {

  private client: Client;
  // private clientex: Clientex;

  constructor() {
    if (!this.client) {
      this.connect();
    }
  }

  private connect() {
    /*this.client = new Client(
      {node: 'http://localhost:9200'}
    );*/
    this.client = new Client();
  }

  isAvailable(): Promise<any> {
    return this.client.ping({
    });
  }

  // tslint:disable-next-line:member-ordering
  private queryalldocs = {
    'query': {
      'match_all': {}
    }
  };

  getAllDocuments(_index, _type): any {
    this.client.search({
      index: _index,
      body: this.queryalldocs
    }, {
      ignore: [404]
    }, (err, { body, statusCode, headers, warnings }) => {
      if (err) { console.log(err); }
    });
}

  getAllDocumentsByKey(_index, _type, campo, valor) {
    const string = 'let match = {' + campo + ':' + valor + '}';
    return this.client.search({
      index: _index,
      type: _type,
      body: {
           // tslint:disable-next-line:no-shadowed-variable
           eval(string) {}
      }
    });
  }

  createDocument(value: any) {
    // return this.client.index(value);
    this.client.create(value);
  }

}

ERRORS:

ERROR in ./node_modules/@elastic/elasticsearch/lib/Connection.js
Module not found: Error: Can't resolve 'http' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules@elastic\elasticsearch\lib'
ERROR in ./node_modules/@elastic/elasticsearch/lib/Connection.js
Module not found: Error: Can't resolve 'https' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules@elastic\elasticsearch\lib'
ERROR in ./node_modules/@elastic/elasticsearch/lib/Transport.js Module
not found: Error: Can't resolve 'os' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules@elastic\elasticsearch\lib'
ERROR in ./node_modules/decompress-response/index.js Module not found:
Error: Can't resolve 'stream' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules\decompress-response'
ERROR in ./node_modules/@elastic/elasticsearch/lib/Transport.js Module
not found: Error: Can't resolve 'zlib' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules@elastic\elasticsearch\lib'
ERROR in ./node_modules/decompress-response/index.js Module not found:
Error: Can't resolve 'zlib' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules\decompress-response'

A: According to the elastic search documentation (https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/5.x/breaking-changes.html), all browser clients are handled via the elasticsearch-browser npm package:

No more browser support, for that will be distributed via another module, @elastic/elasticsearch-browser. This module is intended for Node.js only.

A: I believe you need to install elasticsearch-browser and then:
import { Client } from 'elasticsearch-browser';


text:
Q: Ruby on Rails: Check whether a word is matched to any attributes in database I am doing my Ruby on Rails project now. PostgreSQL is used as database.I have a table called pets, where stores all pets information(name, gender, age, etc.), which are shown as follows.
{Pet id: 1, name: "Jean", gender: "Female", pet_type: "Cat", age: "0", body_weight: 1, breed: "Abyssinian", created_at: "2015-04-26 23:50:01", updated_at: "2015-04-26 23:50:01"}
{Pet id: 2, ...}
...
{Pet id: 10, ...}
Now I am going to check whether there is a Abyssinian breed cat in table pets. If there is, return the Pet id, otherwise return "no such cat found".
Is there anyone know how to do this? Thanks in advance.

A: To find the first pet where breed == "Abyssinian":
pet = Pet.find_by(breed: "Abyssinian", pet_type: "Cat")

So, to combine that with your required logic:
pet = Pet.find_by(breed: "Abyssinian", pet_type: "Cat")
output = pet ? pet : "no such cat found"

You could simply this even further to:
output = Pet.find_by(breed: "Abyssinian", pet_type: "Cat") || "no such cat found"

A: Is "breed" a field in the pets table? If so, you could do something like:
if Pet.exists?( breed: "Abyssinian" )
  x = Pet.where( breed: "Abyssinian" )
else
  x = "No such cat found"
end

The danger in this is that there could be multiple Pets returned. If you want to find one and only one, you could do
if Pet.where( breed: "Abyssinian" ).count == 1

instead.
REVISION
@infused's answer is more succinct, I would encourage an implementation similar to his, assuming a breed column exists.


text:
Q: How to skip invoking another method to create a mock object? I have a class of methods, if I want to test one method, but the objects created in this method depend on other methods in the class. I don't want to actually call the other methods, I just want to create mock objects to test. How should I do it?
@Test
public void testLoadException(String id) {

    WorkflowExecution mockWorkflowExection = getWorkflowExecution(id);

}

I tried to just do so
WorkflowExecution mockExecution = EasyMock.create(WorkflowExecution.class);
Easy.expect(this.test.getWorkflowExecution(EasyMock.anyString())).andReturn(mockExecution);

But this does not work, the test gives me Nullpointer exception.
So can I skip the calling of getWorkflowExecution(id), Thanks!

A: You need a partial mock. Your example doesn't make much sense. So here is what you seem to want.
public class WorkflowExecution {
    public void theRealMethodIWantToCall() {
        theMethodIWantToMock();
    }

    void theMethodIWantToMock() {

    }
}

@Test
public void testLoadException() {
    WorkflowExecution execution = partialMockBuilder(WorkflowExecution.class)
            .addMockedMethod("theMethodIWantToMock")
            .mock();
    execution.theMethodIWantToMock();
    replay(execution);

    execution.theRealMethodIWantToCall();

    verify(execution);
}


text:
Q: iOS - Any Customized UI for UITextField and UILabel Here is a UI for iOS I am looking for:
In a view of my application for iOS,
a user is asked to fill out all underline blanks in not fixed number of distinct questions of the following form(for example):

My ID is _ _ _ _ and telephone number is _ _ _ - _ _ _ _.

Since questions are not fixed, UIText is not enough to use for my requirement. I spent three days on finding proper UI control and view but did not find it.
Is there any UI control and view for my requirement?
If not, I need to build some my own UI control and view using UIKit. Could you recommend any good reference for building customized UI using UIKit? Any suggestion would be very welcomed. Thank you.

A: You can look this link. Here he has covered many UI Controls and their customizations


text:
Q: .htaccess convert url from route parameter to query string with blank parameter value I have .htaccess  issue where url is in route parameter but I want's to convert it on query string format.
Current path is :
http://localhost:4200/act/sso/app/2040/token/7d2f-4ddd-924f-3fd36572/address/chd/city/chd/state/chd
I want's to convert it on : http://localhost:4200/act/sso?app=2040&token=7d2f-4ddd-924f-3fd36572&address=chd&city=chd&state=chd
I have write below .htaccess rule.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^act/sso/app/32/token/([^/]*)/address/([^/]*)/city/([^/]*)/state/([^/]*)

RewriteRule ^act/sso/app/32/token/([^/]*)/address/([^/]*)/city/([^/]*)/state/([^/]*) act/sso?appID=32&mfaToken=$1&address=$2&city=$3&state=$4 [R=301,L]

My problem is when we are getting optional parameter value, my route rule is not matching.
See in below example.
http://localhost:4200/act/sso/app/2040/token/7d2f-4ddd-924f-3fd36572/address//city//state/chd

http://localhost:4200/act/sso/app/2040/token/7d2f-4ddd-924f-3fd36572/address/chd/city//state/chd

http://localhost:4200/act/sso/app/2040/token/7d2f-4ddd-924f-3fd36572/address/chd/city/chd/state/

Please help on this.

A: Could you please try following, written and tested with shown samples.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/act/sso/app/([0-9]+)/token/([^/]*)/address/([^/]*)/city/([^/]*)/state/([^/]*)$
RewriteRule ^.*$ /act/sso?app=%1&token=%2&address=%3&city=%4=state=%5 [L,NE,NC,QSA]


text:
Q: Потоки и общая очередь Пишу программу для обхода веб-графа в ширину.
Входные параметры: набор исходных ссылок, глубина обхода, максимальное число загружаемых страниц.
Во время загрузки каждой страницы из нее извлекаются ссылки на страницы.
По одной ссылке можно пройти только 1 раз.
Программа должна завершать работы при достижении заданной глубины обхода или при достижении максимального числа загружаемых страниц.

Хочу реализовать программу так: создать 2 потока, каждому отдать на вход по половине исходных ссылок и запустить их. Дальше мне нужно получать от потоков информацию о том, сколько страниц они посетили и какие они ссылки при этом извлекли. Извлеченные ссылки хочу запихнуть в Set (это будет гарантировать то, что среди новых ссылок, по которым побегут потоки не будет одинаковых) и заново разделить этот сет на 2 части и раздать потокам.
Собственно вопрос: как мне получать информацию о количестве загруженных страниц и массив ссылок, которые удалось достать при посещении страниц?
UPDATE
    public static Pattern linkPattern = Pattern.compile("<a href=\"([^\"#]+)\"");

public static String getContent(URL url) {
    StringBuilder page = new StringBuilder ();
    BufferedReader in;
    try {
        URLConnection conn = url.openConnection();
        String contentType = conn.getContentType();
        if (contentType != null && contentType.startsWith("text/html")) {
            if (contentType.indexOf("charset=") == -1) {
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            } else {
                String encoding = contentType.substring(contentType.indexOf("charset=") + 8);
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
            }
            String str;
            while ((str = in.readLine()) != null) {
                page.append(str);
            }
            in.close();
            return page.toString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

public static Set<String> getLinks(URL url, String content) {
    Set<String> links = new HashSet<String>();
    Matcher matcher = linkPattern.matcher(content);
    while (matcher.find()) {
        try {
            URI link = new URI(new URL(url, matcher.group(1)).toString());
            links.add(link.toString());
        } catch (MalformedURLException e) {
        } catch (URISyntaxException e) {
        }
    }
    return links;
}

A: Делайте не так. Организуйте очередь заданий: множество ссылок, которые надо посетить, причём для каждой ссылки указана её глубина.
Очередь заданий будет всегда упорядочена по глубине.
Каждый поток делает следующее:

*

*Берёт страницу из начала очереди заданий, удаляет её оттуда, помещает в список "отработанных заданий".

*Скачивает страницу, если её глубина максимальна, возвращается к пункту 1.

*Находит ссылки, выбрасывает те, которые уже в списке отработанных заданий.

*Оставшиеся ссылки получают глубину на 1 большую, чем глубина их исходной страницы. Поток добавляет эти ссылки в очередь заданий так, чтобы не нарушить сортировку по глубине. То есть, если n -- глубина добавляемых ссылок, они добавляются после ссылок с глубиной n-1 и перед ссылками с глубиной n+1. Если какая-то из ссылок уже есть в очереди и имеет меньшую глубину, новый экземпляр не добавляется. Если какая-то из ссылок уже есть в очереди и имеет большую глубину, она заменяется на новый экземпляр.

*Возвращаемся к шагу 1, если заданий нет, ждём, пока они появятся; однако же если все потоки в ожидании, а заданий нет, алгоритм окончен.

Описанный алгоритм работает с любым количеством потоком, разумеется.
A: Новый код в свете новой постановки задачи
private static class Element {
    public String url;
    public int onLvl;
    public Future<String> pageText;

    public Element(String u) {
        url = u;
    }

    public int hashCode() {
        return url.hashCode();
    }

    public boolean equals(Object that) {
        if (that == null || that.getClass() != Element.class)
            return false;
        return url.equals(((Element)that).url);
    }

}

private static List<Element> getAllUrlsFrom(String text, int lvl) {
    // здесь должен быть код достающий новые урлы
    // У всех возвращаемых Element уровень вложенности lvl + 1
    return new ArrayList<Element>();
}

private static class Downloader implements Callable<String> {

    private String url;

    public Downloader(String url) {
    // сюда же можно передавать сокет ли HttpClient для скачки
        this.url = url;
    }

    @Override
    public String call() throws Exception {
        // код загрузки
        return null;
    }

}

/**
 */
public static void main(String[] args) throws Exception {

    int MAXLVL = 10;

    // 2 - кол-во соединений
    ExecutorService executer = Executors.newFixedThreadPool(2);

    Queue<Element> queue = new LinkedList<Element>();
    Set<Element> explored = new HashSet<Element>();

    Element first = new Element("link");
    first.pageText = executer.submit(new Downloader(first.url));
    // или first.pageText = new Downloader(first.url).call() для синхронного вызова
    queue.add(first); // first

    while (queue.size() > 0) {

        Element el = queue.poll();

        if (explored.contains(el))
            continue;

        explored.add(el);

        if (el.onLvl == MAXLVL)
            continue;

        List<Element> childs = getAllUrlsFrom(el.pageText.get(), el.onLvl);

        for (Element c : childs) {
            if (!explored.contains(c)) {
                c.pageText = executer.submit(new Downloader(c.url));
                queue.add(c);
            }
        }
    }

}


text:
Q: Mute and unmute music once it's started playing in Adobe Animate I'm trying to create a game that demonstrates the different instruments in a band. I've managed it in AS3, but I'm struggling in Javascript.
You can either listen to all the instruments playing a piece of music, or click on an instrument to enable or disable it, thus bringing it in or taking it out of the mix.
I have 8 tracks that play simultaneously when the play button (play_btn) is pressed. But whether each instument plays or is muted depends on whether another button (e.g. congas_btn) is pressed. If it isn't pressed, the conga player, for example, (congaPlayer_mc) is greyed out and the conga audio track is muted. If it is pressed, the conga player has full alpha and is unmuted.
Each instrument should be able to be muted or unmuted at will whilst the track is playing.
What actually happens is that whichever state I choose (muted or unmuted) before I click play, determines whether the track plays muted or unmuted. But once the track has started, the congas_btn doesn't have any more effect on the volume. It just toggles its alpha value.
How do I get it to carry on affecting the volume for as long as the track is playing?
Thanks.
This is my code:
let root = this

let congasActive = false
let audioPlaying = false

this.congaPlayer_mc.alpha = 0.5

this.play_btn.addEventListener("click", playAudio.bind(this))

function playAudio() {

    const playCongas = createjs.Sound.play("congas")

    if(!audioPlaying){

        audioPlaying = true

        if(congasActive){
            playCongas.volume = 1
        } else {
            playCongas.volume = 0
        }

    } else {

    audioPlaying = false

    const stopCongas = createjs.Sound.stop("congas")

    }

}

this.congas_btn.addEventListener("click", activateCongas.bind(this))

function activateCongas() {

    if(!congasActive){

        congasActive = true
        root.congaPlayer_mc.alpha = 1

    } else {

        congasActive = false
        root.congaPlayer_mc.alpha = 0.5

    }

}


text:
Q: How do I get powershell or windows terminal to print color text using ansi escape codes? I'm trying to learn to write python code that will output in the terminal different colour text using ansi escape characters. I'm watching a tutorial on python sockets and just learning to communicate between different terminals. I've tried the following on command prompt, powershell and windows terminal and same results.
message = "$([char]0x1b)[30;41m YOUR_TEXT_HERE $([char]0x1b)[0m"

print(message)

When I try this, the output in the terminal shows
$([char]0x1b)[30;41m YOUR_TEXT_HERE $([char]0x1b)[0m

I also tried to use this so that the double quotes were in the line
message = "$([char]0x1b)[30;41m YOUR_TEXT_HERE $([char]0x1b)[0m"

print('\"'+message+'\"')

but it just outputs this
"$([char]0x1b)[30;41m YOUR_TEXT_HERE $([char]0x1b)[0m"

If I type
"$([char]0x1b)[30;41m YOUR_TEXT_HERE $([char]0x1b)[0m"
into the terminal and press enter, it shows correct with red background and black text
I've tried to google and youtube about this but can't seem to find an answer. Please help. Thanks

A: The $([char]0x1b) should be \x1b in Python. So this should work:
message = "\x1b[30;41m YOUR_TEXT_HERE \x1b[0m"

print(message)


text:
Q: Using rowid in a delete statement Is there any SEVERE contraindications to delete using rowid?
DELETE FROM NETATEMP.SFAC_TESTATA_CASISTICHE
      WHERE ROWID IN (  SELECT MIN (ROWID)
                          FROM NETATEMP.SFAC_TESTATA_CASISTICHE
                      GROUP BY ID_CASO,
                               DESCRIZIONE_TECNICA,
                               DESCRIZIONE_ANALISI,
                               PDF,
                               SCARTI,
                               DATA_INIZIO_ANALISI,
                               DATA_FINE_ANALISI,
                               DATA_INSTRADAMENTO,
                               DATA_RISOLUZIONE,
                               STRINGA_RICERCA,
                               SETTIMANA,
                               DATA_INIZIO_SETT,
                               DATA_FINE_SETT,
                               FATTURAZIONE,
                               IN_ELABORAZIONE
                        HAVING COUNT (1) > 1);

A: If you assume that min(rowid) returns the "earliest" row, then yes, you have a problem (because it won't)
If you use min(rowid) only to get one of the duplicates (and you don't care which), then no, there is nothing wrong with that statement.

A: A few things to be aware of.  It seems you are depending on the rowid to give you the earliest row for your particular grouping (select min(rowid) ...).  This won't always be true.  The only way to guarantee you are deleting the earliest record is to use some column (like timestamp) that you can order by.  Tom Kyte explains this better than I could.

A rowid implies NOTHING other than the location of the row physically.
  It does not imply age,  order of insertion, or anything like that.

Also, depending on the size of the table, you will generate a lot of redo/undo, and it may be beneficial in large tables to use pl/sql to delete in chunks and commit every x rows.
Just my thoughts


text:
Q: What does $x \in \{y | p(y)\} \Longleftrightarrow p(x)$ mean? Is it even true? Is there a name for : $x \in \{y | p(y)\} \Longleftrightarrow p(x)$? Is this even true, and if so, what does it mean? An example might be helpful.

A: The "set-builder notation" $\{y\mid p(y)\}$ says that the elements of the aforementioned set are precisely the ones that fulfill the formula $p(y)$.  Thus, to say that $x\in \{y \mid p(y)\}$ means that $p(x)$.  This is a definition of the notation.
For example, take the set $\{x\in \mathbb{R}\mid x^2=1\}$.  The solutions to $x^2=1$ are $-1,1$, and thus the only elements of the set are $-1$ and $1$; no other element of $\mathbb{R}$ can be an element of the set because they wouldn't fulfill the condition set on $x$.
A typical way to read the set-builder notation is as "The set of all $y$ such that $p(y)$ is true".

A: Yes, if $x$ is among the set of values $y$ for which the predicate $p(y)$ holds, then (by definition of that set) the predicate $p(x)$ must hold. For an example, take any predicate ($p(y)$: $y$ is a composite number will do fine) and take any $x$ in the domain of the predicate (in the example, any number). Just read what it says.


text:
Q: Open Source Java Report + Graph I would need some suggestion about open source framework to generate reports (pdf, doc) which contains graphs.
A long time ago I used JasperReport and I guess it is still alive, but no idea if right now there is better options.
It would be great if the framework supports changes easily in the report/graph format.
Thanks!

A: Innovent Solutions has made some reviews about Birt (Eclipse foundation), JasperReports and Pentaho (comparison matrix). Maybe you can start there.

A: Look into Primefaces. Its a JSF extended library. the flexibility I have seen in that library is unbelievable. very slick. combined with POJO, its real fast and very very powerful.
Ajax, jQuery, JS, HTML/CSS are part of it.
Look it up


text:
Q: Closed form of this integral After putting values into Wolfram for the integral
$$\int_{2}^\infty \frac{x^k}{1 - x^{2k}} dx$$
And it seems that it can return the values.
If we have this, how might one go about solving
$$\int_{2}^\infty \frac{x^{k-1}}{1 - x^{2k}} dx$$

A: $$ \int_{2}^{+\infty}\frac{x^k}{1-x^{2k}}\,dx = -\int_{2}^{+\infty}\frac{x^k}{x^{2k}-1}\,dx = -\int_{0}^{1/2}\frac{y^{k-2}}{1-y^{2k}}\,dy $$
can be computed in explicit terms for any integer $k\geq 2$ by partial fraction decomposition, and it equals
$$ -\int_{0}^{1/2}\sum_{n\geq 0} y^{(2n+1)k-2}\,dy =-\sum_{n\geq 0}\frac{1}{\left[(2n+1)k-1\right]2^{(2n+1)k-1}}$$
(which is a hypergeometric ${}_2 F_1$ function evaluated at $4^{-k}$) for any $k>1$.
The situation for $\int_{2}^{+\infty}\frac{x^{k-1}}{1-x^{2k}}\,dx$ is much simpler: this is just $-\frac{1}{k}\text{arctanh}(2^{-k})$, for any $k>0$.


text:
Q: Throws Null pointer Exception in java ## Class B ##
    public class ClassB{

    public ClassB() {
    }

    public String getAddress() {
        return "Address";
    }
      }

## Class A ##
    public class ClassA{
    private ClassB classb;

    public ClassA() {
    }

    public void setClassb(ClassB classb) {
    this.classb = classb;
}
    public void getAddress() {
         System.out.println(classb.getAddress());
    }
      }

## Main Class ##
        public class MainClass{

    public static void main(String[] args){
        ClassA classa = new ClassA();
        classa.getAddress();
    }}

----------

When I run this program, it return nullpointer exception. Can somebody please explain me the reason for the Nullpointer Exception? Thank you. I have tried use setter method but still throw nullpointer exception

A: The classB instance inside ClassA is not instiated.
You have to instantiate the ClassB when creating ClassA instance
public class ClassA{
private ClassB classb;

public ClassA() {
    classb = new ClassB()
}

public void getAddress() {
     System.out.println(classb.getAddress());
}
}

A: classb is declared in your ClassA, but it's not initialized, so when you try classb.getAddress(), you get a NullPointerException. You can initialize it in your constructor for ClassA:
 public ClassA()
 {
    classb = new ClassB();
 }

A: classb is just a reference variable which will point to a object. To get anything done from ClassB, you first need to create the object of the class as shown below
solution 1:
//initialize at the time of declaration
private ClassB classb = new ClassB();

solution 2 :
//provide a setter method:
private ClassB classb;
public void setClassb(ClassB classb)
{
     this.classb= classb;
}

EDIT:
in your main class
instead of these statements :
    ClassA classa = new ClassA();
    classa.getAddress();

try with these statements:
    ClassA classa = new ClassA();
    classa.setClassb(new ClassB());//new statement to be inserted!
    classa.getAddress();

A: fix this by:
    public class ClassA{
    private ClassB classb = new ClassB(); //initialize

    public ClassA() {
    }

    public void getAddress() {
         System.out.println(classb.getAddress());
    }
   }

A: As others have said, it's due to your classb member in classa not being initialized. To correct this you can either initialize it when you initialize a ClassA object or, since you're returning a static value from ClassB's getAddress() method, make the getAddress() method of ClassB static, don't bother initializing a ClassB object, and reference the ClassB's getAddress() method statically from ClassA's getAddress() method.
Example:
// Class B
public class ClassB
{
    public ClassB()
    {
    }

    public static String getAddress()
    {
        return "Address";
    }
}

// Class A
public class ClassA
{
    public ClassA()
    {
    }

    public void getAddress()
    {
        System.out.println(ClassB.getAddress());
    }
}

// Main Class
public class MainClass
{
    public static void main(String[] args)
    {
        ClassA classa = new ClassA();
        classa.getAddress();
    }
}

A: In ClassA the ClassB is not initialized
private ClassB classb = new ClassB();
Take a look http://www.artima.com/designtechniques/initializationP.html


text:
Q: Value does not fall within expected range when applying property to Windows 10 Shortcut I'm attempting to modify the TargetPath of a shortcut on Windows using PowerShell, and when I go to apply the new path, I'm receiving a 'Value does not fall within the expected range' error. I'm assuming it has something to do with quotation marks, but I'm not sure how to fix it.
$shell = New-Object -COM WScript.Shell
$AppPath = '"app.exe"'
$AppFullPath = '"C:\Program Files (x86)\app\app.exe"'
$TargetPath = "C:\WINDOWS\system32\cmd.exe /c start $AppPath /high $AppFullPath"
$DesktopShortcut = $shell.CreateShortcut('C:\users\user\desktop\app.lnk')
$DesktopShortcut.TargetPath = $TargetPath

$TargetPath looks good, and I can manually set its output through the GUI and it works as expected, but not in PowerShell.
C:\WINDOWS\system32\cmd.exe /c start "app.exe" /high "C:\Program Files (x86)\app\app.exe"

A: Turns out you have to add arguments for something like this
$shell = New-Object -COM WScript.Shell
$AppPath = '"app.exe"'
$AppFullPath = '"C:\Program Files (x86)\app\app.exe"'
$cmd = "C:\WINDOWS\system32\cmd.exe"
$cmdargs = "/c start $AppPath /high $AppFullPath"
$DesktopShortcut = $shell.CreateShortcut('C:\users\user\desktop\app.lnk')
$DesktopShortcut.TargetPath = $cmd
$DesktopShortcut.Arguments = $cmdargs
$DesktopShortcut.Save()


text:
Q: How can I configure the RingBuffer used by ReliableTopic in Hazelcast? I have multiple topics I am creating multiple reliable topics in Hazelcast. As I understand from the documentation, it is backed by a ringbuffer. How can I configure the ringbuffer for a topic to suit my needs?
I want to persist only top 100 messages for one topic and entire history for another.

A: You can configure the reliable topic backing ring buffers by using the prefix _hz_rb_ in front of your reliable topic's name. For instance; assume that you have a reliable topic with the name myReliableTopic. The ring buffer backing this reliable topic will have the name as _hz_rb_myReliableTopic. So, you can configure it as below:
<ringbuffer name="_hz_rb_myReliableTopic">
    <capacity>100</capacity>
</ringbuffer>

You can access this prefix using the RingbufferService.TOPIC_RB_PREFIX static field in the application.
Please remind that this prefix is not a part of the public API, thus it is not guaranteed to be kept unchanged in future releases.

A: Keeping the name same for ReliableTopic & RingBuffer does not work. While getting RingBuffer Object we have to prefix it with _hz_rb_as said by Alparslan Avci ealier is the only solution. Hazelcast document says otherwise but it does not work. Looks like a bug in Hazelcast.
Rakesh


text:
Q: Having Trouble with an odd/even script I'm trying to make a script that outputs user names based on weather they are assigned an odd or even value. I think I've managed to get the odd ones working but the even ones wont output. Here is what it looks like. The 'commentid' is the value which determines if they are to be assigned to odd or even.
<?php

$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbname', $db);

$query2 = "SELECT * FROM comments";
$result2 = mysql_query($query2);

while ($row2 = mysql_fetch_assoc($result2))

    if ( $row2['commentid'] % 2  )
    {
        echo $row2['name'];
        echo "
";
    }
    elseif (!$row2['commentid'] % 2)
    {
        echo $row2['name'];
    }
    else
    {
        echo "";
    }
?>

I think it has something to do with either the $row2['name'] or (!$row2['commentid'] % 2) or maybe I need to assign rows to strings or something but I can't figure out what I'm doing wrong.
EDIT I really should have made it more clear exactly what I am trying to do with this script because while your answers make sense they dont solve my problem. On the same page as this script I have another script running. This script calls a value from a different table in the same database. It's running on a timed cron event that resets daily so the value is different every day. It looks like this and is working as it should.
<?
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbnamesameasother', $db);

$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_array($result))

if ( $row['pool'] % 2 )
{
echo "
Result 1
";
echo "
";
}
else
{
echo "
Result 2
";
echo "
";
}
?>

What I am trying to do is only call up the names associated with either the odd or even value based on the number the script above dictates. So if this script chooses Result 1, I only want to display the user names who would fall under Result 1.

A: It is sufficient to do a:
if ($row2['commentid'] % 2)
{
    // odd
}
else
{
    // even
}

If you want to know whats wrong with your logic, you should learn something about operator precedence in PHP. According to the chart, ! has higher precendence than %. The  expression !$row2['commentid'] % 2 is thus evaluated as follows:

*

*when $row2['commentid'] is 0

*

*!0 = true

*true % 2 = 1

*when $row2['commentid'] is 1

*

*!1 = false

*false % 2 = 0

*when $row2['commentid'] is 2

*

*!2 = false

*false % 2 = 0

A: Hope this helps
if ( $row2['commentid'] % 2 ==0 )
{
echo $row2['name'];
echo "
";
}
else
{
echo $row2['name'];
}

A: if ( $row2['commentid'] % 2  )
{
echo $row2['name'];
echo "
";
}
elseif (!$row2['commentid'] % 2)
{
echo $row2['name'];
}
else
{
echo "";
}

replace this code with
if ( $row2['commentid'] % 2  )
{
echo $row2['name'];
echo "
";
}
else
{
echo $row2['name'];
}

since  there is only two posibility either it commentid divisible by 2 or not divisible by 2

A: There is a problem. If you delete a comment, you will get 2 adiacent rows with/without
. You should use a an iterator variable, like this:
$i=1;
while ($row2 = mysql_fetch_assoc($result2)){

    echo $row2['name'];
    if($i % 2 == 0){
        echo "
";
    }
    $i++;
}


text:
Q: How to read quoted string from File and write it without quotes? I am trying to write a python script to convert rows in a file to json output, where each line contains a json blob.
My code so far is:
with open( "/Users/me/tmp/events.txt" ) as f:
        content = f.readlines()

# strip to remove newlines
lines = [x.strip() for x in content]

i = 1

for line in lines:
        filename = "input" + str(i) + ".json"
        i += 1
        f = open(filename, "w")
        f.write(line)
        f.close()

However, I am running into an issue where if I have an entry in the file that is quoted, for example:
client:"mac"

This will be output as:
"client:""mac"""

Using a second strip on writing to file will give:
client:""mac

But I want to see:
client:"mac"

Is there any way to force Python to read text in the format ' "something" ' without appending extra quotes around it?

A: Instead of creating an auxiliary list to strip the newline from content, just open the input and output files at the same time. Write to the output file as you iterate through the lines of the input and stripping whatever you deem necessary. Try something like this:
with open('events.txt', 'rb') as infile, open('input1.json', 'wb') as outfile:
    for line in infile:
        line = line.strip('"')
        outfile.write(line)


text:
Q: Robotframework selenium execution through jenkins not working I am not able to execute selenium test cases using robotframework through Jenkins.
Installed
Firefox, geekodriver.
Works without using Jenkins.
Getting the exception
WebDriverException: Message: Process unexpectedly closed with status: 1

Its a simple test case that has
*** Settings ****
Library    Selenium2Library

*** Test Cases ***
Testing Selenium
     Open Browser    http://google.com    Firefox

Jenkins shell command configuration
pybot test.robot

A: Install xvfb in the robotframework server. Also use xvfb plugin in Jenkins.
Seems like xvfb is deprecated and heard that there is a vncserver plugin. Need to try this.


text:
Q: how to set leaflet marker to center of div tag in leafletjs I want the marker to be in the center of the map, but it is wrong.
I read the rest of the articles, but my problem was not solved.

 var map = L.map('map').setView([lat, lng], 18);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk', {
    maxZoom: 18,
    id: 'mapbox.streets',
    accessToken: 'pk',
    attribution: 'nemajoo',
    watch: true
}).addTo(map);
var LeafIcon = L.Icon.extend({
    options: {

        iconSize:     [28, 60],
        shadowSize:   [50, 64],
        iconAnchor:   [22, 94],
        shadowAnchor: [4, 62],
        popupAnchor:  [-3, -76]
    }
});
var greenIcon = new LeafIcon({iconUrl: 'images/mrk.png'});
var center = map.getCenter();
var marker = L.marker([center.lat, center.lng],{icon: greenIcon}).addTo(map);

A: The problem here could be in any of the 3 configurations given we don't have the image:

*

*mrk.png has some spacing inside the image, this can be fixed with any image editing tool.

*the options object, on the anchor tag moves the image, making it look like it's not centered.

*When you set the center, as far as I can see, you first get the center from the map, then use this center to position the icon, this is nicely done but markers with distant zooming don't represent it's center accurately.

In resume:
The problem is on the png or the anchor configuration, modify those values and try again.
If this does not work you can upload a sample minimal project so we can check (don't upload api keys or similar)


text:
Q: Find matching value or round up in case number is higher then closest value I'm trying to implement function where user enters a number to the application, for example 101.
Based on this number, function should loop through an array and find matching value. If not found, it should find closest values and round up to higher one. I'm not sure how to explain this properly, but here is an example:
Array consists numbers 100, 150, 200.
• User enters number 101. No exact number was found, function should return value 150.
• User enters number 151. No exact number was found, function should return value 200.
• User enters number 150. Exact number was found, function should return value 150.
I've made a function which finds matching or closest value, but this isn't quite what I want, because it doesn't round the number up, in case exact match wasn't found.
$arr(100, 150, 200)
$search = 101;

function getClosest($search, $arr) {
$closest = null;
foreach ($arr as $item) {
  if ($closest === null || abs($search - $closest) > abs($item - $search)) {
     $closest = $item;
  }
}
return $closest;
}

In this case it returns the closest number to 101, which is 100. I would like it to return 150. How can I fix this?

A: You can do something like this. Sort the array first so you can get the next highest value.
  <?php
$array = array(100,150,200);
$number = 101;
echo closest($array, $number);
function closest($array, $number) {

    sort($array);
    foreach ($array as $a) {
        if ($a >= $number) return $a;
    }
    return end($array); // or return NULL;
}
?>


text:
Q: How would I specify a sort order for my data in my ArrayList in java? I have an array that holds the ranks of playing cards:
A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K. (The "T" represents the 10).
I have all of these stored in an ArrayList.
For example, I have an ArrayList that represents the clubs and has all of the card ranks in it:
ArrayList<Character> clubs = new ArrayList<Character>();

If I print all of the elements in this ArrayList, they print out in the following order:
3 2 4 5 6 8 7 9 T J Q K A

I then added this to sort the collection:
Collections.sort(clubs);

With the collection sort, it prints the elements in this order:
2 3 4 5 6 7 8 9 A J K Q T

How can I make it so that it prints in this order: ?
A 2 3 4 5 6 7 8 9 T J Q K

A:    Collections.sort(list, new Comparator<String>() {
        public int compare(String a, String b) {
            //write here the easy code to provide you the right order
            //return -1 if a should appear before b or 1 otherwise
        }

    });

A: You need to implement your own comparator
public class CardComparator implements Comparator<Character>{
  public int compare(Character c1, Character c2){
   //implement your own logic for comparing.
   }
}

Once its implemented, you should invoke
Collections.sort(clubs, new CardComparator);

A: Implement java.util.Comparator
public class CharacterComparator implements Comparator<Character> {
    public int compare(Character o1, Character o2) {
        // ...

Then call sort
List<Character> characters = ...
Collections.sort(characters, new CharacterComparator());

A: As an alternative solution to implementing your own Comparator consider using Google Guava. This library contains many helpful utility classes and functions.
It provides the class Ordering which makes this quite simple:
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;

//explicitly state the ordering
Ordering<String> ordering = Ordering.explicit("A","1","2","K");

//create unsorted list
List<String> list = Lists.newArrayList("1","1","A","2","K","K","1","A");

System.out.println(ordering.sortedCopy(list)); //sort, but not in place

Collections.sort(list, ordering); //in place sort
System.out.println(list);


text:
Q: Use a c# assembly's namespace in a f# application? There is a c# assembly with a public static class Something.
It has a public static method DoSomething(string source, string dest, string file, string arch)
I do not know f# and there is no one in the shop who knows it anymore, but I need to replace an API that one f# project uses with what's in the c# assembly.
I wanted to use that method in another solution's f# project, and added a reference to the first assembly's \bin\Debug\Something.exe (yes, it doubles as a command line EXE).
Then I added open Something to the f# unit where it is needed. Once the .NET versions were in sync, the assembly seemed to have loaded.
Now that I code this snippet:
let src = "C:\"
let dst = "D:\"
let file = "readme.txt"
let arch = "E:\"
Something.DoSomething src dst file arch

it does not build due to this error:
Error   2
The member or object constructor 'DoSomething' takes 4 argument(s) but is here given 1.
The required signature is 'Something.DoSomething(source: string, dest: string, ?file: string, ?archive: string) : bool'.

Am I really passing just 1 argument erroneously believing I am passing all 4?

A: You need to treat it as a tupled method:
Something.DoSomething (src, dst, file, arch)

This should allow it to compile and call the method correctly.


text:
Q: Application crashes when double tap on DatePicker i managed to get a custom DatePicker and add it to my project , the problem is , that when i tape Twice on a date , the application crashes !
custom datePicker code :
package com.example.logindesign;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewParent;
import android.widget.CalendarView;

public class CalendarViewScrollable extends CalendarView {
    public CalendarViewScrollable(Context context) {
        super(context);
    }

    public CalendarViewScrollable(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CalendarViewScrollable(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev)
    {
        if (ev.getActionMasked() == MotionEvent.ACTION_DOWN)
        {
            ViewParent p = getParent();
            if (p != null)
                p.requestDisallowInterceptTouchEvent(true);
        }

        return false;
    }

}

and this is how i used that class in my main activity :
final TextView dateT=(TextView)findViewById(R.id.TextDate);
    dateT.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v){
            DatePickerDialog datepicker= new DatePickerDialog(MainActivity.this,new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month,
                            int day) {
                        // TO DO Auto-generated method stub
                        month+=1;
                        dateT.setText(+year + "  /  " + month + "  /  " + day);
                        jn=day;
                        mn=month;
                        an=year;
                    }
                },1990,1,1);
        datepicker.setTitle("Sélectionner la date de naissance");
        datepicker.updateDate(1990, 1, 1);
        datepicker.show();

        }
    });

Logcat :
04-28 20:02:39.504: E/AndroidRuntime(27825): FATAL EXCEPTION: main
04-28 20:02:39.504: E/AndroidRuntime(27825): Process:       com.example.logindesign, PID: 27825
04-28 20:02:39.504: E/AndroidRuntime(27825):     java.util.IllegalFormatConversionException: %d can't format java.lang.String    arguments
04-28 20:02:39.504: E/AndroidRuntime(27825):    at  java.util.Formatter.badArgumentType(Formatter.java:1489)
04-28 20:02:39.504: E/AndroidRuntime(27825):    at java.util.Formatter.transformFromInteger(Formatter.java:1689)
04-28 20:02:39.504: E/AndroidRuntime(27825):    at java.util.Formatter.transform(Formatter.java:1461)
04-28 20:02:39.504: E/AndroidRuntime(27825):    at java.util.Formatter.doFormat(Formatter.java:1081)
04-28 20:02:39.504: E/AndroidRuntime(27825):    at java.util.Formatter.format(Formatter.java:1042)
04-28 20:02:39.504: E/AndroidRuntime(27825):    at java.util.Formatter.format(Formatter.java:1011)
04-28 20:02:39.504: E/AndroidRuntime(27825):    at java.lang.String.format(String.java:1803)
04-28 20:02:39.504: E/AndroidRuntime(27825):    at android.content.res.Resources.getString(Resources.java:668)
04-28 20:02:39.504: E/AndroidRuntime(27825):    at android.content.Context.getString(Context.java:390)
04-28 20:02:39.504: E/AndroidRuntime(27825):    at android.widget.SimpleMonthView$MonthViewTouchHelper.getItemDescription(SimpleMonthView.java:683)
04-28 20:02:39.504: E/AndroidRuntime(27825):    at android.widget.SimpleMonthView$MonthViewTouchHelper.onPopulateEventForVirtualVie w(SimpleMonthView.java:620)
04-28 20:02:39.504: E/AndroidRuntime(27825):    at     com.android.internal.widget.ExploreByTouchHelper.createEventForChild(ExploreByTo    uchHelper.java:294)

A: It is a problem with specific devices
to log or prompt for selected date, DatePicker uses
https://android.googlesource.com/platform/frameworks/opt/datetimepicker/+/master/res/values-es/strings.xml#29
but for some reason it gets "%d selected" and format date is not an integer.
See this answer: https://stackoverflow.com/a/31855744/848072. It proposes a patch. Using a theme that do not look for an incorrect resource, leading to a format error.
Maybe there will be no patch for these so, use the workaround meanwhile


text:
Q: Nginx regular expression server_name How can you use regular expression to do this:
preprod.*.company.com > root to /home/preprod_folder
*.company.com > root to /home/prod_folder

I know that to match *.company.com I will create:
server_name *.company.com

But what about for a regular expression that match before *.company.com, this rule preprod.allsubdomains.company.com
preprod.*.company.com is not working, and that's normal.
Could you help me please?
Thanks.

A: You say "redirect", but it looks like your intent is to set the root directory instead. Perhaps this is what you are looking for:
    server_name ~^preprod\.(?<subdomain>\w+).company.com;
    root /home/prepod_folder;


text:
Q: Providing production MySQL access to outside company We have one main production MySQL database with a read replica. This database has some sensitive data from clients that we need to protect.
My goal is to provide access to an external Business Intelligence reporting tool. As with all tools like this, they all say "we have great security, and we never store anything that we don't need, etc." I am still paranoid.
So what I am considering creating a bunch of views on the replica database (read-only) which leave out sensitive data and provide the minimum information that they need. After that, I will provision a new user on the database that only has access to those views. This way they only see the data that I want to give them and it's already read-only so nothing can be modified.
My question is, is this a good way to go about this considering my database has sensitive client information? In general, is this a relatively secure approach?

A: Your approach seems to be sound. However, I am unsure of what real business intelligence can be gleaned if the reporting is made off of incomplete data. Create a dedicated user with limited privileges (IE No writing/dropping allowed). There is always a tradeoff of information security and information quality.
Perhaps it would be best to understand what you're hoping to accomplish with this reporting and identify what sensitive info can be removed.

A: Another technique is to GRANT no access to the sensitive columns.  (A GRANT can apply to "all" (*.*), one database (db.*), one table (db.tbl), or one column.)  It might take a lot of GRANT statements to set it all up, but you might feel more secure.
And, of course, limit access to the physical server.


text:
Q: Expected Value of a Randomly decreasing function We are asked to find the expected value of the following function
RDF(N, K)
for i = 1 to K
    do N = random(N)
return N

Random(N) returns any integer in the range $[0, N)$ with equal probability and Random(0) = 0.
Let's have a case-
N = 4 and K = 3
Our function will return values
4 → 0 → 0 with probability 1/4.
4 → 1 → 0 with probability 1/4.
4 → 2 → 0 with probability 1/8.
4 → 2 → 1 with probability 1/8.
4 → 3 → 0 with probability 1/12.
4 → 3 → 1 with probability 1/12.
4 → 3 → 2 with probability 1/12.
Hence the expected value is
0 * 1/4 + 0 * 1/4 + 0 * 1/8 + 1 * 1/8 + 0 * 1/12 + 1 * 1/12 + 2 * 1/12 = 1/8 + 1/12 + 1/6 = 3/8 = 0.375

A: If the result of random($N$) were from $[0,N]$ instead of $[0,N)$, things would be easier and the answer would be $\frac n{2^k}$ :
If $k=0$, then $n$ is returned immediately.
Otherwise, the expected result is
$$\mathbb E(R(n,k))=\frac1{n+1}\sum_{j=0}^n\mathbb E(R(j,k-1))=\frac1{n+1}\sum_{j=0}^n\frac{j}{2^{k-1}}=\frac1{n+1}\frac{n(n+1)}{2\cdot2^{k-1}} =\frac n{2^k}$$
by induction.


text:
Q: ErrorListPlot crops error bars The default behaviour of ErrorListPlot often crops error bars, as in the example below. How can this be fixed in a clean way?
Needs["ErrorBarPlots`"];
data = Table[{{x, Cos[x]}, ErrorBar[Cos[x]^2]}, {x, 0, 2 Pi}];
plot = ErrorListPlot[data, PlotRangePadding -> Scaled[.05]]

A: You can just Show plot with the option PlotRange -> All:
Show[plot, PlotRange -> All]

Why?
plot already  contains full lines which you can see by looking at plot[[1]] which contains all the graphics directives and primitives:
Graphics[plot[[1]]]

Somehow, the FrontEnd thinks displaying the cropped version is in some sense better. You can always override the rendering choices of the FrontEnd using Show with appropriate options.

A: Here is my solution. Calculate the value of each data point plus (and minus) it's error bar. Then you can calculate the location of the highest (and lowest) error bar. Then use this to specify the PlotRange.
data = Table[{{x, Cos[x]}, ErrorBar[Cos[x]^2]}, {x, 0, 2 Pi}];
minima = #[[1]][[2]] - #[[2]][[1]] & /@ data;
maxima = #[[1]][[2]] + #[[2]][[1]] & /@ data;
plot = ErrorListPlot[data, PlotRange -> {Min[minima], Max[maxima]}, PlotRangePadding -> Scaled[.05]]

We can make a nice little function that we can use in a similar way to ErrorListPlot but takes care of the PlotRange automatically as we desired. The difference here is that other optional arguments have to be grouped together into a list. I'm sure there's a nicer way to do this with optional arguments, but I don't know how to implement it.
errorListPlot[data_, opts_] := Module[{minima, maxima},
  minima = #[[1]][[2]] - #[[2]][[1]] & /@ data;
  maxima = #[[1]][[2]] + #[[2]][[1]] & /@ data;
  ErrorListPlot[data, PlotRange -> {Min[minima], Max[maxima]}, opts]
  ]

data = Table[{{x, Cos[x]}, ErrorBar[Cos[x]^2]}, {x, 0, 2 Pi}];
errorListPlot[data, {PlotRangePadding -> Scaled[.05], PlotStyle -> Red}]


text:
Q: Is there any way by which we can change the values of environment variables dynamically in an Angular 10 application? I have an Angular application that currently has the same source code but with different environment based on whether the country is Canada or the US.
I have wrapped up the application using Capacitor.js to create mobile applications for iOS and Android.
Now I am stuck at a point where I need the same application to use Different Environment Variables based on User Selection (Canada or the US)
I need a way to integrate the above logic in the same mobile application source code, or otherwise, I'll have to create a separate mobile application for both countries.
Let me know if you know anyway or work around for this issue.

A: The environment replacement happens at build time, so you'd need different builds for different targets. You probably want a service with some logic to determine which logic you want. You could also change the property from the environment at runtime (for instance in the app initializer).


text:
Q: Zulu time format I've a script which generates Zulu time zone. How do I change the format in shell /bash script like this ?
20140730000255 -> 2014-07-30
Thank you in advance
Regards

A: Try this:
#!/bin/bash

LongDateTime=$1;

if ["$LongDateTime" = ""]
then
    LongDateTime=20140730000255;
fi

Year=${LongDateTime:0:4}
Month=${LongDateTime:4:2}
Day=${LongDateTime:6:2}

echo $LongDateTime

echo $Year
echo $Month
echo $Day

YMD="$Year-$Month-$Day"

echo $YMD

Hope this helps.


text:
Q: Axios returns cached data When making a fetch request to my dev.to profile (fetching my publishes aka posts), axios returns an array of old data. what I mean by that is, I recently created a new post on dev.to, in total i now have 3 posts. when making a request to fetch all the posts using axios, it returns only 2.
Fetching:
useEffect(() => {
    axios
      .get('https://dev.to/api/articles?username=timbogdanov', {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-Type': 'application/json',
        },
      })
      .then((res) => {
        setPosts(res.data);
      });
  }, []);

Data I get back:
https://puu.sh/Gu3lr/61725cc204.png
Data i should get back:

https://dev.to/api/articles?username=timbogdanov


text:
Q: How do I use "format=json&data=" in post requests when developing in python? format=json&data={
  "pickup_location": {
    "pin": "110096",
    "add": "address",
    "phone": "1111111111",
    "state": "Delhi",
    "city": "Delhi",
    "country": "India",
    "name": "name of pickup/warehouse location registered with delhivery"
  }
}

The data above is the payload of the post required on the API document.
I don't know how to transfer this data because of "format=json&data=".
payload = {
    "pickup_location": {
        "pin": "110096",``
        "add": "Changsha",  # address of warehouse
        "phone": "1111111111",
        "state": "Delhi",
        "city": "Delhi",
        "country": "India"
    }
}

payload = 'format=json&data={}'.format(payload)
r = requests.post(url_test, json=payload, headers=headers)

payload = {
    'format': 'json',
    'data': {
        "pickup_location": {
            "pin": "110096",
            "add": "Changsha",  # address of warehouse
            "phone": "1111111111",
            "state": "Delhi",
           "city": "Delhi",
           "country": "India"
        }
    }
}

payload = 'format=json&data={}'.format(payload)
r = requests.post(url_test, json=payload, headers=headers)

These are the two pieces of code I've tried.
The end result is the same: "format key missing in POST".
I also looked it up on the Internet, but I couldn't find the right answer.
So I came to ask for help, 3Q.

A: I had also same problem actually payload is raw data
so do this
payload = {
"pickup_location": {
    "pin": "110096",``
    "add": "Changsha",  # address of warehouse
    "phone": "1111111111",
    "state": "Delhi",
    "city": "Delhi",
    "country": "India"
}
}

payload = f'format=json&data={json.dumps(payload,default=str,indent=4)}'
response=requests.post(url_order,data=payload,headers=headers)

A: The format and data key must be sent in body x-www-form-urlencoded type

A: I was same problem in spring boot .
when i was start searching .
Then i was find this question and i am writing this answer for spring boot developers.
Packages
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

Code
@Autowired
private RestTemplate restTemplate;

private HttpHeaders getHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Token yourToken");
    headers.set("Content-Type","application/json");
    return headers;
}

@Override
public Object save(ExpressDeliveryVO expressDelivery) throws JsonProcessingException {

    HttpHeaders headers = getHeaders();

    ObjectMapper mapper = new ObjectMapper();

    HttpEntity<String> entity = new HttpEntity<>("format=json&data="+mapper.writeValueAsString(expressDelivery), headers);

    return restTemplate
            .postForEntity("https://staging-express.delhivery.com/api/cmu/create.json", entity, Object.class)
            .getBody();

}

A: payload = {
    "pickup_location": {
        "pin": "110096",
        "add": "Changsha",
        "phone": "1111111111",
        "state": "Delhi",
        "city": "Delhi",
        "country": "India"
    }
}

payload = 'format=json&data={}'.format(payload).replace("'",'"')  # replace is very important
r = requests.post(url_test, json=payload, headers=headers)

Python strings default to double quotes on the outside and single quotes on the inside. But the api requires double quotes for the parameter key.

A: //This code working fine for me in node fetch
const option = {
method: 'POST',
headers: {
  Authorization: "Token " + apikey,
  accept: 'application/json',
  'Content-Type': 'application/json',
},
body: `format=json&data= ${JSON.stringify(createData)}`

}


text:
Q: Android Location service working only after maps loaded I am running android studio and its emulator with API 23. I am using a location manager and the object location to obtain the current position of a user and eventually update it. I am sending positions using the device monitor or telnet and then geofix command.
The application is able to retrieve a not-null position or an updated one just if I load google maps application in the emulator i.e., if I need to update a position I need before to load google maps and then the application is able to access to the new one. Is someone able to help me? Thanks


text:
Q: VM9878:1 Uncaught SyntaxError: Unexpected identifier I have a probleme with my script. But, this problem one time appear, and one time not, without modification of the code.
My HTML :

        <button class="btn btn-default" type="button" onclick="security();"></button>

    <input id="inhuman" type="text" class="form-control" name="inputhuman" onblur="verificationSecurity();">

    <button id="send-mail" class="btn btn-primary pull-right w100" onclick="validation();">

    </button>

My Javascript :
function securityCode() {

    [... MAKING THE SECURITY CODE ...]

    document.getElementById('inhuman').placeholder = secCode;
}

function verificationSecurity() {
    var secCode = document.getElementById('inhuman').placeholder;
    var secResult = document.getElementById('inhuman').value;
    var code = eval(secCode);

    if(code == secResult) {
        document.getElementById('humanerror').className = 'input-group-addon form-ok';
        document.getElementById('humanerror').innerHTML = '';
        return true;
    } else {
        document.getElementById('humanerror').className = 'input-group-addon form-error';
        document.getElementById('humanerror').innerHTML = '';
        return false;
    }
}

function validation() {
    [... SOME OTHERS TESTS OK ...]
    var securityOK = verificationSecurity(document.getElementById('inhuman'));

    if(nameOK && emailOK && objectOK && messageOK && securityOK) {
        alert('ONLY FOR TESTS - OK');
    } else {
        alert('ONLY FOR TESTS - NOT OK');
    }
}

When i test the form, some time i have problem and some time all is OK. When it's not OK, i have problem on these lines (Chrome Dev Console) :

*

*var code = eval(secCode); > in function verificationSecurity()

*var securityOK = verificationSecurity(document.getElementById('inhuman')); > in function validation()

Sorry for my broken english and thanks in advance for your help.


text:
Q: How to pass a default argument to a function from a wrapper function I have 2 functions: a main function (foo) - I didn't write this function and I don't have access to its source - and a function that wraps the main function (foo_wrapper).
For example:
def foo(arg1, arg2, callback=??? [OPTIONAL]):
   #do stuff

def foo_wrapper(arg1, arg2, callback=None):
   #do stuff
   #then
   foo(arg1, arg2, ....)

callback is a callback function and is optional. My question is, can I call foo more elegantly than using:
if callback is None:
   foo(arg1, arg2)
else:
   foo(arg1, arg2, callback)


text:
Q: How to add custom close icon for Alert component in Material UI, globally We can globally customise the severity icons shown in the Alert component through the theme:
  MuiAlert: {
    defaultProps: {
      iconMapping: {
        info: <Info/>,
        success: <Success/>,
        warning: <Warning>,
        error: <Error/>,
      }
    },
    styleOverrides: {
    ...
    }

But, is there a way to do the same for the close icon, the one displayed when the OnClose prop is defined?
  /**
   * Callback fired when the component requests to be closed.
   * When provided and no `action` prop is set, a close icon button is displayed that triggers the callback when clicked.
   * @param {React.SyntheticEvent} event The event source of the callback.
   */
  onClose?: (event: React.SyntheticEvent) => void;

I know the alternative solution is to create my own styled component derived from the Alert component and set the my custom close icon, but would like to avoid that and see if it is possible through the theme components customisation.
Otherwise I think it would be a nice to have and maybe should open a request for that.

A: Yes this is possible! Looking at the MUI Alert api docs there is a prop components where you can define the icon you want to display for the close icon, same with the button.
Then when you create your custom theme you can simply add that components prop to the defaultProps.
Note that we're not passing the actual <HomeIcon /> but just the function.
import { createTheme, ThemeProvider } from "@mui/material/styles";
import Alert from "@mui/material/Alert";
import HomeIcon from "@mui/icons-material/Home";

const theme = createTheme({
  components: {
    // Name of the component
    MuiAlert: {
      defaultProps: {
        // The default props to change
        components: {
          CloseIcon: HomeIcon,
        },
      },
    },
  },
});

export default function DefaultProps() {
  return (
    <ThemeProvider theme={theme}>
      <Alert onClose={() => {}}>Your alert with custom icon :)</Alert>
    </ThemeProvider>
  );
}


text:
Q: MailChimp Integaration with MVC 5 I am working on an MVC5 project, the client is interested in using MailChimp for sending emails. I have explored the MailChimp and wrappers ( MailChimp.NET ) and tried in my project as well. I tested the REST API as well and it seems to work , for example; I was able to grab lists and templates using REST API. But, still I am having issues with sending email through MailChimp.
So far, I have tried the following code and its working. Now I want to send an email to a newly registered user. Kindly give me detailed code example that How can I achieve this, because I am  totally struck here..
  var apiKey = "myapikey-us11";
    var listId = "mylistid";
    var subscribeRequest = new
                    {
                        apikey = apiKey,
                        id = listId,
                        email = new
                        {
                            email = "muhammad.waqas@seventechnology.co.uk"
                        },
                        double_optin = true,
                    };
    var requestJson = JsonConvert.SerializeObject(subscribeRequest);
    var reqresult = CallMailChimpApi("lists/", requestJson);

CallMailChimApi
    private static string CallMailChimpApi(string method, string requestJson)
    {
       var endpoint = String.Format("https://{0}.api.mailchimp.com/3.0/{1}", "us11", method);
        var wc = new WebClient();

        try
        {
            return wc.UploadString(endpoint, requestJson);
        }
        catch (WebException we)
        {
            using (var sr = new      StreamReader(we.Response.GetResponseStream()))
            {
                return sr.ReadToEnd();
            }
        }
    }

A: I Use this function and it work successfully
public   void  SendEmailByApiMailChimp ()
{
try
{
string UserEmail = " Exemple@gmail.com ";
MailChimpManager mc = new MailChimpManager("16d***********-us14");
EmailParameter email = new EmailParameter()
{
Email = UserEmail
};
            EmailParameter resulte = mc.Subscribe("yourlistnumber", email);
            var test = resulte;
        }
        catch (Exception ex)
        {
            var ters = ex;
        }

    }


text:
Q: Shell not showing properlly in VSCode I'm using zsh with the Powershell theme and I have a customized prompt that works properly in iTerm, but it's not displaying correctly in VSCode. I have already made the setting for the terminal to inherit.
iTerm prompt:

VSCode prompt:

Amy I missing a setting somewhere?

A: My iTerm was using a different font, I had to change the one in Visual Studio to match it.


text:
Q: Conditional Update / Insert - Incorrect Syntax Near 'END' I'm having some difficulty writing a query that updates or inserts, based on whether there is an existing entry.
The current query I'm running is:
IF EXISTS (SELECT 1 FROM dbContactEmails WHERE contID = 1)
BEGIN
    UPDATE dbContactEmails
    SET contEmail = 'test@test.com'
    WHERE contID = 1
    AND contCode = 'HOME'
END
ELSE
    INSERT INTO dbContactEmails (contID, contEmail, contCode, contOrder, contActive)
    VALUES (1, 'test@test.com', 'HOME', 0, 1)
END

Unfortunately this doesn't work, with the error "incorrect syntax near 'END'" being thrown.

A: Put BEGIN after ELSE
IF EXISTS (SELECT 1 FROM dbContactEmails WHERE contID = 1)
BEGIN
    UPDATE dbContactEmails
    SET contEmail = 'test@test.com'
    WHERE contID = 1
    AND contCode = 'HOME'
END
ELSE
BEGIN
    INSERT INTO dbContactEmails (contID, contEmail, contCode, contOrder, contActive)
    VALUES (1, 'test@test.com', 'HOME', 0, 1)
END


text:
Q: DAX - Work out days in an overlapping period I am fairly new to DAX and seem to be coping ok so far but I am completely stuck on an issue. I think it relates to 'in progress' events
I have a "Leave" table which shows periods of Annual Leave, Sick, and Public Holidays. I want to calculate how much of each has been taken the previous month. To add to the complication, I only wish to calculate working days of each. I have a related "Calendar" table that has a column called "Working Day" so I've just been using COUNTROWS and filtering to Yes to only show these rows. The part I'm struggling with is sometimes the period on a row will run over more than one month as you can see with the "SICK" row. For example I'd expect the values for Sick to show -
June - 6
July - 22
August - 1
Can this be done with a measure?

Any help would be really appreciated.

A: You may try this solution:
LeaveWorkDay =
var __date = GENERATE(Leave, FILTER('Calendar', 'Calendar'[Date] >= [Start] && 'Calendar'[Date] <= [End] && 'Calendar'[workingdays] = 1))
return
countrows(__date)

where my test model looks like:

Used field:

Output:


text:
Q: StringBuilder uft-8 support in Java I created csv file in Java and inserted some values.This is source
try {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.now();
        System.out.println(dtf.format(localDate).toString() + ".csv");

        String filename = dtf.format(localDate).toString() + ".csv";

        StringBuilder builder = new StringBuilder();

        if (Files.exists(Paths.get("D:\\" + filename))) {
            System.out.println("File existed");

        } else {
            System.out.println("File not found!");
            String ColumnNamesList = "UID,name,personalNumber,nationality,dateofbirth,dateofexp,documentcode,gender,issueState,documentType";
            builder.append(ColumnNamesList + "\n");

        }
        builder.append(UID + ",");
        builder.append(name + ",");
        builder.append(personalNumber + ",");
        builder.append(nationality + ",");
        builder.append(dateofbirth + ",");
        builder.append(dateofexp + ",");
        builder.append(documentcode + ",");
        builder.append(gender + ",");
        builder.append(issueState + ",");
        builder.append(documentType + ",");

        builder.append('\n');

        File file = new File("D:\\" + filename);
        FileWriter fw = new FileWriter(file, true); // the true will append the new data
        fw.write(builder.toString());
        fw.close();
        System.out.println("done!");

    } catch (IOException ioe) {
        System.err.println("IOException: " + ioe.getMessage());
    }

Problem is that,my "name" value is not English alphabet and result in my file is null.
Is it a possible to add uft-8 support StringBuilder ? or how i can save some values in file with uft-8?
thanks

A: Try this:
 Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");


text:
Q: Firefox changed it's default search engine --without any update--, is this possible? Suddenly the default serach engine of my Firefox browser on ArchLinux is changed. I have no idea how this happend. This morning I worked o the machine and everything seemd okay, now serveral hours later, the search engine is changed without any intervetion (AFAIK). No updates were made.
Please help to detect what happened.

A: The Firefox profile manager found an issue with my Firefox profile and loaded the default factory settings. If you encounter similar issues, make sure you have loaded the expected profile.
Note you can start the Firefox profile manager from terminal with
$ firefox --ProfileManager


text:
Q: How to force Magento to use APC cache I just installed Magento Commerce on my hosting account and am getting fairly sluggish performance. To help speed up the site, I installed the APC cache but am having trouble getting it to work. I used these install instructions.
I followed all the steps and seemed to get APC installed. No problems. When I check APC.php, it only shows 1 hit and 1 miss to the cache, which can't be right... Making me think APC isn't active or being used.
I tried to ensure Magento uses APC by adding the following to /var/www/app/etc/local.xml.
            <cache>
                    <backend>apc</backend>
                    <prefix>alphanumeric</prefix>
            </cache>

Any help is much appreciated.

A: I suggest that you use a unique string other than "alphanumeric". That way if you are sharing APC with other users or applications, your cache will be differentiated.
Have you placed the xml nodes in the correct location in local.xml?  The context should be like this:
  ...
  <session_save><![CDATA[db]]></session_save>
  <cache>
    <backend>apc</backend>
    <prefix>ReplaceThisWithSomeUniqueString</prefix>
  </cache>
</global>

Also, make sure that you did a rm -rf /var/www/var/cache/* after changing local.xml.

A: Check your server logs and look for segmentation violations. When you ever only see 1 hit/miss, it's a sure sign that each hit kills the server process. This is a problem with certain combinations of PHP and APC versions.
If you're using the mmap backend, try compiling APC again without mmap. (I often experienced crashes using the mmap backend.)
A question, do you use PHP 5.2 or 5.3?

A: I ran into the same issue. In my case I set the parameter for the max file size in the wrong way. I didn't append a M behind the value.
So instead of apc.max_file_size=10M I wrote apc.max_file_size=10.


text:
Q: Alter datatype of clustered index primary key in table I have a table with
 CONSTRAINT [user_const] PRIMARY KEY CLUSTERED ([id] ASC, [group] ASC)

I want to change the datatype of group to NVARCHAR from NCHAR.
Simply running
ALTER TABLE [dbo].[user] ALTER COLUMN [group] NVARCHAR (50) NOT NULL;

gives me an error:

The object 'user_const' is dependent on column 'group'.

CHECK NOCHECK does not work as

This action applies only to foreign key and check constraints.

So, I thought I should drop the constraint and recreate it
ALTER TABLE [dbo].[user] DROP CONSTRAINT [user_const];
ALTER TABLE [dbo].[user] ALTER COLUMN [group] NVARCHAR (50) NOT NULL;
ALTER TABLE [dbo].[user] ADD CONSTRAINT CONSTRAINT [user_const] PRIMARY KEY CLUSTERED ([id] ASC, [group] ASC)

But error reads

Tables without a clustered index are not supported in this version of SQL Server.

How can I alter the datatype of a column which is a primary key constraint?

A: Azure does not support tables without clustered indexes. Read here
http://msdn.microsoft.com/library/azure/ee336245.aspx#cir
In order to change the data type, you are going to have to create a second table with the new datatypes, move the data over, and then rename.

A: Since you're changing the primary key, you're effectively rebuilding the entire table anyway, so you might as well build a new table with the new format and rename to get the name right.  I haven't run this so it might need a little tweaking, but something like this:
-- check to see if we've already run this script and swap table names and just run it again with the old data if we have
IF EXISTS (SELECT * FROM SysObjects WHERE name='MyTable_bak' AND type='U')
    IF EXISTS (SELECT * FROM SysObjects WHERE name='MyTable' AND type='U')
        DROP TABLE MyTable
    ELSE
        EXEC sp_rename 'MyTable', 'MyTable_bak'
GO

-- create the new table with updated columns
CREATE TABLE MyTable (
    [id] BIGINT NOT NULL,
    [group] NVARCHAR(50) NOT NULL,
CONSTRAINT PK_MyTable PRIMARY KEY CLUSTERED
(
    [id] ASC, [group] ASC
))
GO

-- copy in the data from the old version
INSERT MyTable([id],[group])
SELECT [id],[group]
FROM MyTable_bak
GO

-- drop the old table (maybe wait to do this until testing is complete?)
DROP TABLE MyTable_bak


text:
Q: OpenShift and Restheart I have to use Restheart APIs in an OpenShift application.
I tried to execute restheart.jar as suggested in the installation and use guide, but it produced an error, due to the difference between the installed java version (openjdk 7) and the required one (oracle java 8).
Is there any trick to get Restheart APIs working in an OpenShift app?

A: OpenShift does not support JDK 8 but that doesn't mean you can't run Java 8 applications.
You can use a DIY cartridge and install your own JDK version.


text:
Q: Modified algorithm for Max-Heapify in a question I have to answer they asking to write an algorithm Modified-Max-Heapify for a random value insertion.enter image description here The question is in below link. Can anyone help me to figure this out?

A: I'm not going to do your homework for you, but here's a hint.  Suppose that instead of A[i] being set to a random value, you were told that A[i] was set to a value that was larger any other item in the heap. Let's call it ∞. Would you know how to fix up the heap?  Remember that in your fixed up heap, whatever is in A[i] has to percolate to A[0], since it's the largest element.
If you can do that, you can now solve the original problem.

*

*temp = A[i]

*A[i] = ∞

*Fix up the heap using what you figured out above.

*Remove the largest element of the heap, which we know is the ∞ we put into A[i] in step 2.

*Add temp to the heap using standard heap algorithms.

There is a faster but more complicated way of doing this.  Remember that every help of a max-heap is smaller than its parent and bigger than its children.
If an element is too big for its spot, you can repeatedly move it up the tree, swapping it with its parent, until the element reaches the root or is smaller than its parent.
If an element is too small for its spot, you can repeatedly move it down the tree, swapping it with its largest child, until the element has no children or is larger than its children.
If the structure is a heap except for the spot where your element is, it is easy to show that it remains a heap, except for the spot where your element has moved it, after a swap.
Code this.


text:
Q: making a servlet in netbeans and index.jsp i am trying to make a servlet in netbeans. It has to be called from an html form and take some data from it.
i overwrite doget and dopost putting just some testing outs in them.
when i try to run the servlet it only shows a hello word jsp page i found out that this was the index.jsp page that the servlet had by default.
How can i make the servlet run and actually make some output? other than the index welcome page?
Which url mast i use in order to call the servlet from the form?
th doget and dopost methods look like this
 public void doPost(HttpServletRequest request,
                  HttpServletResponse response)
    throws IOException, ServletException
    ResourceBundle rb =
    ResourceBundle.getBundle("LocalStrings",request.getLocale());
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("");
    out.println("");

    String title = rb.getString("helloworld.title");

    out.println("<title>" + title + "this is my anser</title>");
    out.println("");
    out.println("");

   protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
          this.doPost(request, response);}

A:
How can i make the servlet run and actually make some output? other than the index welcome page?

You should dispatch the request into the desired JSP page. You can do this with RequestDispatcher.
request.getRequestDispatcher("page.jsp").forward(request, response);

Which url mast i use in order to call the servlet from the form?

The one which you've mapped in web.xml.
You should also be putting HTML in JSP page only, not in servlet. It's also not a good practice to let doGet() and doPost() do the same. The doGet() is merely there to preprocess the data before displaying in JSP. The doPost() is merely there to postprocess the data after a HTML form submit.
In the tag info about [servlets] tag here you can find a hello world example and more links about starting with JSP/servlets.


text:
Q: Неожиданное взаимодействие canvas c элементами "relative" Всем привет. Помогите пожалуйста советом или источником, где найти информацию по проблеме, а проблема состоит в следующем:
Есть задача создать скрипт для шахматной доски. Все довольно-таки просто, иметь возможность перетаскивать шахматы на доску. Это сделано. Также задачка гласит, что нужно иметь возможность рисовать стрелочки - что-то типа маршрута шахмат и сделать это нужно средствами html,css и js, после чего сохранить в виде изображения эту доску. Вот тут и возникла затыка. Делаю сохранение следующим образом:

$('#saveImage').on('click',function(){
    html2canvas($('.game'), {
        onrendered: function (canvas) {
            var newCanvas = document.createElement("canvas");
            newCanvas.setAttribute('width',700);
            newCanvas.setAttribute('height',700);
            var ctx = newCanvas.getContext('2d');
            ctx.drawImage(canvas,0,0,canvas.width, canvas.height,0,0,700,700);
            var dataURL = newCanvas.toDataURL();
            var img = $(document.createElement('img'));
            img.attr('src', dataURL);
            $('#download').attr('href', newCanvas.toDataURL("image/png"));
            $('#download').attr('download','new file.png');
            $('#download')[0].click();
        }
    });
});

Само сохранение работает, но в виду того что стрелочки сделаны самым костыльным, по моему мнению, методом из всех возможных, в виду того, что другого выхода не нашел. Происходит это так:

.arrow{
    height: 5px;
    width: 40px;
    display: block;
    position: relative;
    top: 100px;
    left: 100px;
    -webkit-transform: rotate(-50deg);
    -moz-transform: rotate(-50deg);
    -o-transform: rotate(-50deg);
    -ms-transform: rotate(-50deg);
    transform: rotate(-50deg);
    cursor: pointer;}
#arrowHead{
    width: 5px !important;
    height: 3px;
    font-size: 10px;
    font-weight: 800;
    float: left;
    position: relative;
    top: 0;
    right: 0;
    color: green;}
#arrowBody{
    width: 33px;
    height: 3px;
    margin-top: 1px;
    background-color: green;
    float: left;
    position: relative;
    top: 2.5px;
    left: 2px;}
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>

Проблема в том, что при сохранении изображения, стрелочки теряют свою форму и выглядят не совсем как стрелочки.
Ниже то что получается сохранить, из сanvas:

А так должно быть на самом деле, по крайней мере мне этого очень хотелось бы:

Скажите, возможно я что-то делаю совсем не так или есть методы обойти эту проблему ибо все элементы, у которых статическое позиционирование отображаются нормально.
Буду благодарен за любую информацию. Заранее спасибо.

A: Трансформы не подерживаются этим плагином:
https://github.com/niklasvh/html2canvas/issues/220
Вам нужно искать способ нарисовать стрелки без transform: rotate.
Например, нарисовать стрелки прямо на canvas:

function canvas_arrow(context, fromx, fromy, tox, toy){
    var headlen = 15;   // длина стрелок
    var angle = Math.atan2(toy-fromy,tox-fromx);

    context.moveTo(fromx, fromy);
    context.lineTo(tox, toy);
    context.moveTo(tox, toy);
    context.lineTo(tox-headlen*Math.cos(angle-Math.PI/6),toy-headlen*Math.sin(angle-Math.PI/6));
    context.moveTo(tox, toy);
    context.lineTo(tox-headlen*Math.cos(angle+Math.PI/6),toy-headlen*Math.sin(angle+Math.PI/6));
}

ctx = document.getElementById("c").getContext("2d");
ctx.beginPath();
canvas_arrow(ctx,10,90,90,10);// функция, рисующая стрелку, описана выше
ctx.lineWidth=3;// ширина линий
ctx.strokeStyle="#005500";// цвет линий
ctx.stroke();

<canvas id='c' width="100" height="100">

A: Неделю думаю над подобной проблемой (начинающий программист-любитель), пока не придумал ничего лучше, как сделать 3 слоя:

*

*основная сетка (у меня div'ы) + картинки;

*канвас

*прозрачная сетка из div'ов, которые точно совпадают с 1 слоем.

Обернулось все еще в div, для позиционирования и трансформаций.
П.С. это ответ на вопрос ниже.


text:
Q: Can't set a test license token in an Outlook addin I'm trying to set a test license token in an Outlook add-in. According to the documentation, I have to set it in the SourceLocation in the manifest file:
<Form xsi:type="ItemRead">
  <DesktopSettings>
    <SourceLocation DefaultValue="https://localhost:3000?et=%3Cr%3E%0A%20%20%3..."/>
    <RequestedHeight>250</RequestedHeight>
  </DesktopSettings>
</Form>

The problem is, when I try to get the URL query params, it won't work. window.location looks like this:
https://localhost:3000/?et=
Any idea why it's happening?
When I update the source location of the Action ShowTaskpane, it won't start the addin:
<Action xsi:type="ShowTaskpane">
    <SourceLocation resid="messageReadTaskPaneUrl" />
</Action>

...

<bt:Url id="messageReadTaskPaneUrl" DefaultValue="https://localhost:3000?et=%3Cr%3E%0A%20%20%...">

If I set it like this, when I start the addin, it says:
Sorry, but we can't start this add-in because it isn't set up properly.
I use the following test token:
<r>
  <t
    aid="WA907006056"
    pid="{4FB601F2-5469-4542-B9FC-B96345DC8B39}"
    cid="32F3E7FC559F4F49"
    did="{0672BAE9-B41B-48FE-87F1-7F4D3DD3F3B1}"
    ts="30"
    et="Trial"
    ad="2012-01-12T21:58:13Z"
    ed="2019-06-30T21:58:13Z"
    sd="2012-01-12T00:00:00Z"
    test="true"
    te="2019-06-30T02:49:34Z" />
  <d>VNNAnf36IrkyUVZlihQJNdUUZl/YFEfJOeldWBtd3IM=</d>
</r>

And use the following service to encode the url:
https://www.urlencoder.org/

A: The problem is with URL encoding. When encoding the token, you have to remove all the new lines. Otherwise, it will throw an error. So, before encoding, take the token...
<r>
  <t
    aid="WA907006056"
    pid="{4FB601F2-5469-4542-B9FC-B96345DC8B39}"
    cid="32F3E7FC559F4F49"
    did="{0672BAE9-B41B-48FE-87F1-7F4D3DD3F3B1}"
    ts="30"
    et="Trial"
    ad="2012-01-12T21:58:13Z"
    ed="2019-06-30T21:58:13Z"
    sd="2012-01-12T00:00:00Z"
    test="true"
    te="2019-06-30T02:49:34Z" />
  <d>VNNAnf36IrkyUVZlihQJNdUUZl/YFEfJOeldWBtd3IM=</d>
</r>

and remove all the new lines like this:
<r> <t aid="WA907006056" pid="{4FB601F2-5469-4542-B9FC-B96345DC8B39}" cid="32F3E7FC559F4F49" did="{0672BAE9-B41B-48FE-87F1-7F4D3DD3F3B1}" ts="30" et="Trial" ad="2012-01-12T21:58:13Z" ed="2019-06-30T21:58:13Z" sd="2012-01-12T00:00:00Z" test="true" te="2019-06-30T02:49:34Z" /> <d>VNNAnf36IrkyUVZlihQJNdUUZl/YFEfJOeldWBtd3IM=</d> </r>

Finally encode it and add to all the source locations.


text:
Q: Java - breaking out of a incursion method and returning the value Good morning all,
Today is my first time trying to make a recursion method. Just when I thought it would work I got the error; missing return statement. This confuses me because it literally has a return value ( the total string from the Stringbuilder ) after n < 1
This is what I got:
    import java.util.Scanner;

    public class P5_4MethodRepeatString {
        public void main(String[] args){

            Scanner sc = new Scanner(System.in);
            System.out.println("Enter a string followed by the times you want
            it repeated:");
            String input = sc.nextLine();
            int count = sc.nextInt();

            String total = repeat(input, count);

            System.out.println(total);
        }

        public static String repeat(String str, int n) {
            StringBuilder full = new StringBuilder();
            if(n < 1) {return full.toString();}
            repeat(str, n - 1);
            for(int i = 0; i < n; i++){
                full.append(str);
            }
        }
    }

A: if(n < 1) {return full.toString();} but if n >= 1 you don't return anything. It should be return repeat(str, n - 1); but then you need to move the for... part

A: The immediate cause of your problem is that not all conditional flows in your repeat() method have a return value.  But I am not sure if even making that change would result in working code.  Consider the following refactor:
public void repeat(StringBuilder result, String str, int n) {
    if (n == 0) return;
    result.append(str);
    repeat(result, str, n - 1);
    return;
}

Here we are passing in a StringBuilder object which we want to contain our repeated string results.  We also pass the string to be repeated, and the number of remaining turns.  The base case occurs where there are no more turns, in which case we simply return from the recursive method.  Otherwise, we add one copy of the string and make a recursive call.
Your original recursive attempt had the following for loop:
for (int i=0; i < n; i++) {
    full.append(str);
}

This does not look recursive, and looping to repeatedly add the string defeats the point of doing recursion (though I would probably use a loop in real life if I had to do this).


text:
Q: update multiple rows with checkbox Created a gridview that should allow the used to check a checkbox beside each record in a gridview. After selecting the checkbox they can select a button that should change each status of the checked record. The code below does the updating if i check 1 or 2 rows but error if i try to update all records at once.
<asp:GridView ID="GridViewwork" runat="server" AutoGenerateColumns="False"
    DataSourceID="SqlDataSourcework" Width="90%" ShowFooter="True"
    onselectedindexchanged="GridViewwork_SelectedIndexChanged"
    DataKeyNames="WorkID" CellPadding="0" CellSpacing="2" GridLines="None">
    <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />

        <asp:TemplateField >
            <ItemTemplate>

               <asp:CheckBox ID="CheckBoxcomplete" runat="server" onselectedindexchanged="GridView1_SelectedIndexChanged" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="DIAS Employee" SortExpression="employee">
            <EditItemTemplate>
                <asp:TextBox ID="employee_txt" runat="server" Text='<%# Bind("employee") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("employee") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>

        <asp:Button ID="btSubmit" runat="server" Text="Mark as Complete" onclick=" btButton_Click"></asp:Button>

        </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="File Number" SortExpression="filenumber">
            <EditItemTemplate>
                <asp:TextBox ID="filenumber_txt" runat="server" Text='<%# Bind("filenumber") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Bind("filenumber") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Action" SortExpression="action">
            <EditItemTemplate>
                <asp:TextBox ID="action_txt" runat="server" Text='<%# Bind("action") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label3" runat="server" Text='<%# Bind("action") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Start Date" SortExpression="workdate">
            <EditItemTemplate>
                <asp:TextBox ID="workdate_txt" runat="server" Text='<%# Bind("workdate") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label4" runat="server" Text='<%# Bind("workdate") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Remarks" SortExpression="remarks">
            <EditItemTemplate>
                <asp:TextBox ID="remarks_txt" runat="server" Text='<%# Bind("remarks") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label6" runat="server" Text='<%# Bind("remarks") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

    </Columns>

Code behind
protected void btButton_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in GridViewwork.Rows)
    {
        CheckBox chkUpdate = (CheckBox)row.FindControl("CheckBoxcomplete");
        if (chkUpdate.Checked)
        {
            SqlConnection sqlcon = <my connection.
            string query = "Update WorkFlowActivity set completedate=@completedate, workstatus=@workstatus where WorkID = @WorkID";
            SqlCommand sqlcom = new SqlCommand(query, sqlcon);

            sqlcom.Parameters.AddWithValue("@completedate", DateTime.Now.ToString());
            sqlcom.Parameters.AddWithValue("@workstatus", "Yes");
            sqlcom.Parameters.AddWithValue("@WorkID", GridViewwork.DataKeys[row.RowIndex].Value);
            sqlcon.Open();
            try
            {
                sqlcom.ExecuteNonQuery();
                GridViewwork.DataBind();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            sqlcon.Close();
        }
    }
}

When I try to update all records at once I get
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
This is on the line that I add the parameter @WorkID. Really not sure where I am going wrong.

A: Collection of grid view rows are all the rows along with data rows (including header, footer, etc)
In order for you to over come it, you need to check the index of the row not be -1 while fetching data from the GridView row. Something like;
if(row.RowIndex != -1)
    string dataValue = row["columnName"].ToString();

In your case, you need to get this done before you are fetching the checkbox control from the row.
Hope this helps.
Happy Coding..!!
Nayan


text:
Q: Tornado periodiccallback invocation is not skipped if callback takes longer then callback_time Consider the following code:

from tornado import ioloop, gen

@gen.coroutine
def test_callback():
    print 'entering test_callback'
    yield gen.sleep(10)
    print 'exiting test_callback'

if __name__ == '__main__':
    ioloop.PeriodicCallback(test_callback, 1000 * 5).start()
    ioloop.IOLoop.current().start()

This is the output:
entering test_callback
entering test_callback
entering test_callback
exiting test_callback
entering test_callback
exiting test_callback
entering test_callback
...

The documentation says that if the callback takes longer then callback_time subsequent invocations will be skipped. But in this case this is not happening. What can I do to make sure that the callback is only called after the previous callback invocation finishes?

A: I found the solution on this thread.
Basically if a callback takes more then callback_time to execute subsequent invocations are only skipped if the callback is synchronous. If the callback calls another asynchronous routine PeriodicCallback has no way of knowing all will start the another invocation of the callback.
In this case we need an async-aware equivalent of PeriodicCallback:
from tornado import ioloop, gen

@gen.coroutine
def test_callback():
    print 'entering test_callback'
    yield gen.sleep(10)
    print 'exiting test_callback'

@gen.coroutine
def periodic():
    loop = ioloop.IOLoop.current()
    while True:
        start = loop.time()
        yield test_callback()
        duration = loop.time() - start
        yield gen.Task(loop.add_timeout, max(5 - duration, 0))

if __name__ == '__main__':
    ioloop.IOLoop.current().add_callback(periodic)
    ioloop.IOLoop.current().start()

This is the output:
entering test_callback
exiting test_callback
entering test_callback
exiting test_callback
entering test_callback
exiting test_callback
...

A: The following solution based on python 3.5 can be used too.
from tornado import ioloop, httpclient
class testCls:
  def __init__(self):
    self.n=0
    self.inProcess=False
  async def f1(self):
    url2='http://yoosofan.github.io/en/'
    http_client1 = httpclient.AsyncHTTPClient()
    response = await http_client1.fetch(url2)
    print('dd: ',self.n)
    self.n +=1
  async def my_function(self):
    print('z',end=' ')
    if self.inProcess==False:
    self.inProcess=True
    await self.f1()
    self.inProcess=False
if __name__ == '__main__':
  t1=testCls()
  ioloop.PeriodicCallback(t1.my_function, 60).start()
  ioloop.IOLoop.current().start()