text:
Q: Combining Cypher results with APOC SQL queries I am trying to update node properties of a PostgreSQL database that I have running in a virtual environment. I am building a Jazz knowledge base and would like to use the node ids to query additional properties from the PSQL database using APOC.
I have tried unwinding the ids and using them to run the SQL statements with APOC.
This is the code I have tried thus far:
MATCH (a:Artist)
WHERE a.genre = 'jazz'
WITH COLLECT(a.mbid) AS ids
UNWIND ids AS id
CALL apoc.load.jdbc('myDB',
"select DISTINCT a.gid, ar.name as country FROM artist a INNER JOIN area ar on a.area = ar.id WHERE a.gid = ?", [id]) YIELD row
MATCH (a:Artist) WHERE a.mbid = row.gid SET a.country = row.country
RETURN COUNT(a.country)

I am running into an error saying "ERROR: operator does not exist: uuid = character varying". Is there anyway to use the ids from the Cypher query to update each node individually through individual SQL statements with APOC?

A: Assuming the gid column is a UUID type in your Postgres database and that the error is when executing the query via apoc.load.jdbc, the following explicit casts of your IDs in the SQL should at least have the comparison work and have the query return a string value you can compare on:
MATCH (a:Artist)
WHERE a.genre = 'jazz'
WITH COLLECT(a.mbid) AS ids
UNWIND ids AS id
CALL apoc.load.jdbc('myDB',
"select DISTINCT a.gid::text, ar.name as country FROM artist a INNER JOIN area ar on a.area = ar.id WHERE a.gid = UUID(?)", [id]) YIELD row
MATCH (a:Artist) WHERE a.mbid = row.gid SET a.country = row.country
RETURN COUNT(a.country)


text:
Q: How to sort an array in a unique order Given an array:
var myList = [ 'Normal', 'Urgent', 'Alert', 'Casual', 'Follow up' ];

I want to output this list in say, a dropdown. I want 'Urgent' to show up first, followed by 'Alert'. The rest should be sorted alphabetically.
I'm aware I can alphabetically sort the entire array with myList.sort() but is there a way to sort this list to my unique requirements? I'm hoping this can be done as an array without converting it to an object and assigning priority identifiers - but I may be wrong.
Also, what if Urgent or Alert doesn't exist?
EDIT: Here is what I tried: https://jsfiddle.net/reala/rqacrz0k/

A: It's best if you keep your prioritized elements separate from the main list, if you can't guarantee they will be present. I would filter those elements out, sort the rest, and concatenate the results with your special list.

var special = ["Urgent","Alert"];
var myList = [ 'Normal', 'Urgent', 'Alert', 'Casual', 'Follow up' ];

myList = special.concat(myList.filter(function(el){ return special.indexOf(el) == -1; }).sort());

alert(myList);

A: You could use an object for the sort order.

var array = [ 'Normal', 'Urgent', 'Alert', 'Casual', 'Follow up' ];

array.sort(function (a, b) {
    var order = { Urgent: -2, Alert: -1 };
    return (order[a] || 0) - (order[b] || 0) || a.localeCompare(b);
});

console.log(array);

A: You could use filter to get the special values, sort the rest, and concatenate the parts:

var myList = [ 'Normal', 'Urgent', 'Alert', 'Casual', 'Follow up' ];

myList = myList.filter( v => v === 'Urgent' ).concat(
            myList.filter( v => v === 'Alert' ),
            myList.filter( v => !['Alert','Urgent'].includes(v) ).sort());

console.log(myList);

A:

var myList = [ 'Normal', 'Urgent', 'Alert', 'Casual', 'Follow up' ];

console.log(['Urgent', 'Alert', ...myList.filter(item => item !== 'Urgent' && item !== 'Alert').sort()]);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove Matched Pattern from Beginning of First Line in Text File I am trying to remove a matched pattern (-import_file) from the beginning of the first line in a text file. Using sed vs. awk seems like the way to go.
Attempt
sed -i 's/^-import_file//g' /home/weather/f00.txt

f00.txt
-import_file file1 -rpn sto_1
-import_file file2 -rpn sto_2
-import_file file3 -rpn sto_3
-import_file file4 -rpn sto_4
-import_file file5 -rpn sto_5
-import_file file6

This does not appear to actually be doing anything to the first matched pattern at the start of Line 1.

A: Please try this near-equivalent POSIX AWK solution (removes leading space from edited line):
awk 'NR==1 {$1=""; print substr($0,2); next} 1' ~weather/f00.txt > temp && mv temp ~weather/f00.txt

I could not replicate your issue on my machine.
$ sed --version |head -1
sed (GNU sed) 4.4

$ sed '1s/^-import_file//g' ~weather/f00.txt
 file1 -rpn sto_1
-import_file file2 -rpn sto_2
-import_file file3 -rpn sto_3
-import_file file4 -rpn sto_4
-import_file file5 -rpn sto_5
-import_file file6


text:
Q: Luxon migration: moment.utc() I'm working on migrating our codebase to Luxon from moment, and I've run into an issue that I cannot find a solution for.

<script type="module">

import {default as moment} from 'https://unpkg.com/moment@2.29.4/dist/moment.js';
import * as luxon from 'https://unpkg.com/luxon@3.0.1/build/es6/luxon.js';

const momentObject = moment.utc(
  input, // Moment object or valid date string
  this.acceptedFormats(), // Array of acceptable formats, which returns true or false when isValid() is called
  true // Use strict parsing?
);

</script>

How can I create a similar object with Luxon, which will return false when accessing momentObject.isValid?


text:
Q: UNIX terminal - shell won't terminate, stuck in for loop I'm having some trouble terminating a shell. I'm starting several filkontroll.sh in the background to regularly check files to see if they have been changed or deleted. It seems to be running fine except that when all the files have been modified, the program won't terminate. It's seems to be stuck in the for-loop somehow.
filkontroll.sh :
#!/bin/bash
clear

declare -i status=1
if [ -f $1 ]
        then
        status=0
        timestamp=$(stat -f "%Sm" -t "%H%M%S" $1)
fi
while [ 0 ]
        do
        if [ -f $1 ] && [ $status -eq 1 ]
                then
                echo "Filen $1 ble opprettet."
                break
        elif [ ! -f $1 ] && [ $status -eq 0 ]
                then
                echo "Filen $1 ble slettet."
                break
        elif [ -f $1 ]
                then
                sistEndret=$(stat -f "%Sm" -t "%H%M%S" $1)
                if [ ! $sistEndret -eq $timestamp ]
                        then
                        echo "Filen $1 ble endret."
                        break
                fi
         fi
        sleep $2
done

kontrollflerefiler.sh:
#!/bin/bash
clear

for fil in $@
do
        . filkontroll.sh $fil 2 &

done


text:
Q: JNI issue while passing a string to android code we are facing an issue while passing string from JNI .c code to android. Given below the codes
.c code
char* getSignatureMd5(JNIEnv* env, jobject obj)

{`char * sign = loadSignature(env, obj);`

    MD5_CTX context = { 0 };
    MD5Init(&context);
    MD5Update(&context, (unsigned char*)sign, strlen(sign));
    unsigned char dest[16] = { 0 };
    MD5Final(dest, &context);

    int i;
    static char destination[32]={0};
    for (i = 0; i < 16; i++) {
            sprintf(destination, "%s%02x", destination, dest[i]);
    }

    return destination;
}

JNIEXPORT jstring JNICALL Java_com_sign_signaturecapturesbi_MainActivity_getToken(JNIEnv *env, jobject obj,
                                                                    jstring string) {
__android_log_print(ANDROID_LOG_VERBOSE, "MyApp", "inside getToken");
char *signValue = getSignatureMd5(env, obj);
__android_log_print(ANDROID_LOG_VERBOSE, "MyApp", "inside ExceptionCheck if %s", signValue);
 char* msg = signValue;

jstring result;

 puts(msg);

__android_log_print(ANDROID_LOG_VERBOSE, "MyApp", "msg %s", msg);

result = (*env)->NewStringUTF(env,msg);
 return result;
}

Android native code
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
   mJavaText = (TextView) findViewById(R.id.java_sign);
  mJniText = (TextView) findViewById(R.id.jni_sign);
   // mJavaText.setText("Get token from jni:" + getPackage());
    //mJniText.setText("Get token from jni:" + getToken());
    try {

        String tokenvalue =  getSignature();
        System.out.println("tokenpackage in android ffi "+ tokenvalue);
       mJniText.setText("Get token from jni:" + tokenvalue);
        // mJniText.setText("Get token from jni:" + getPackage);
    }catch (Exception e) {
        // This will catch any exception, because they are all descended from Exception
        System.out.println("Error in android ffi "+ e.getMessage());

    }

}

static {
    System.loadLibrary("check-sign");

}
public native String getToken(String str);
public native String getPackage();

public String getSignature(){
        //mJavaText.setText("Get token from jni:" + getPackage());
    String valuetoken =  getToken("hello");

System.out.println("valuepackage in android ffi "+ valuetoken);
    // mJniText.setText("Get token from jni:" + getToken());
    return valuetoken;

    }

    }

But here i am getting below error
JNI DETECTED ERROR IN APPLICATION: JNI NewStringUTF called with pending exception 'java.lang.NullPointerException' thrown in unknown throw location
Please help me to get it resolev this issue
I have tried with below code. still I am getting Null pointer exception
jstring Java_com_sign_signaturecapturesbi_MainActivity_getToken(JNIEnv *env, jobject obj)
{
__android_log_print(ANDROID_LOG_VERBOSE, "MyApp", "inside signature");
   char *signValue = (char*)malloc(50);
   strcpy(signValue, getSignatureMd5(env, obj));
   jstring result = (*env)->NewStringUTF(env, signValue);
   __android_log_print(ANDROID_LOG_VERBOSE, "MyApp", "result if %s", result);
   return result;
}

Added loadSignature method & jstringTostring method
char* loadSignature(JNIEnv* env, jobject obj)

{
 jclass cls = (*env)->FindClass(env, "android/content/ContextWrapper");
 //this.getPackageManager();
 jmethodID mid = (*env)->GetMethodID(env, cls, "getPackageManager",
         "()Landroid/content/pm/PackageManager;");
 if (mid == NULL) {
     return "";
 }
 jobject pm = (*env)->CallObjectMethod(env, obj, mid);
 if (pm == NULL) {
     return "";
 }

 //this.getPackageName();
 mid = (*env)->GetMethodID(env, cls, "getPackageName", "()Ljava/lang/String;");
 if (mid == NULL) {
     return "";
 }

 jstring packageName = (jstring)(*env)->CallObjectMethod(env, obj, mid);

 // packageManager->getPackageInfo(packageName, GET_SIGNATURES);
 cls = (*env)->GetObjectClass(env, pm);
 mid  = (*env)->GetMethodID(env, cls, "getPackageInfo", "(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;");

 jobject packageInfo = (*env)->CallObjectMethod(env, pm, mid, packageName, 0x40); //GET_SIGNATURES = 64;

 cls = (*env)->GetObjectClass(env, packageInfo);
 jfieldID fid = (*env)->GetFieldID(env, cls, "signatures", "[Landroid/content/pm/Signature;");
 jobjectArray signatures = (jobjectArray)(*env)->GetObjectField(env, packageInfo, fid);
 jobject sign = (*env)->GetObjectArrayElement(env, signatures, 0);

 cls = (*env)->GetObjectClass(env, sign);
 mid = (*env)->GetMethodID(env, cls, "toCharsString", "()Ljava/lang/String;");
 if(mid == NULL){
     return "";
 }

 jstring signString = (jstring)(*env)->CallObjectMethod(env, sign, mid);

 return jstringTostring(env, signString);
 }

char* jstringTostring(JNIEnv* env, jstring jstr)

{
 char* rtn = NULL;

jclass clsstring = (*env)->FindClass(env, "java/lang/String");
 jstring strencode = (*env)->NewStringUTF(env, "utf-8");
 jmethodID mid = (*env)->GetMethodID(env, clsstring, "getBytes", "(Ljava/lang/String;)[B");
 jbyteArray barr= (jbyteArray)(*env)->CallObjectMethod(env, jstr, mid, strencode);
 jsize alen = (*env)->GetArrayLength(env, barr);
 jbyte* ba = (*env)->GetByteArrayElements(env, barr, JNI_FALSE);
 if (alen > 0)
 {
     rtn = (char*)malloc(alen + 1);
     memcpy(rtn, ba, alen);
     rtn[alen] = 0;
 }
 (*env)->ReleaseByteArrayElements(env, barr, ba, 0);
 return rtn;

}


text:
Q: How could I resolve a non-working Eclipse indexer? My Eclipse C indexer does not work, in the .metadata/.log file it writes an entry:
!ENTRY org.eclipse.cdt.core 1 0 2022-10-24 16:46:02.674
!MESSAGE Indexed 'eio_valto' (0 sources, 0 headers) in 0,008 sec: 0 declarations; 0 references; 0 unresolved inclusions; 0 syntax errors; 0 unresolved names (0%)
In the indexer settings "Index source and header files opened in editor" is ticked, so it should find at least one file, which is opened in my editor.
How could I resolve this?
This is a C project, which I created with File --> New --> C/C++ Project, and I use and external Makefile to build. It is the same as in all my other project, but the others work fine, only this does not.
Thanks in advance!
The entire log:
!SESSION 2022-10-24 16:16:41.372 -----------------------------------------------
eclipse.buildId=4.7.3.M20180330-0640
java.version=1.8.0_172
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=hu_HU
Framework arguments:  -product org.eclipse.epp.package.cpp.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.cpp.product

!ENTRY org.eclipse.jface 2 0 2022-10-24 16:16:51.319
!MESSAGE Keybinding conflicts occurred.  They may interfere with normal accelerator operation.
!SUBENTRY 1 org.eclipse.jface 2 0 2022-10-24 16:16:51.319
!MESSAGE A conflict occurred for ALT+CTRL+T:
Binding(ALT+CTRL+T,
    ParameterizedCommand(Command(org.eclipse.search.ui.performTextSearchWorkspace,Find Text in Workspace,
        Searches the files in the workspace for specific text.,
        Category(org.eclipse.search.ui.category.search,Search,Search command category,true),
        org.eclipse.ui.internal.WorkbenchHandlerServiceHandler@407b41e6,
        ,,true),null),
    org.eclipse.ui.defaultAcceleratorConfiguration,
    org.eclipse.ui.contexts.window,hu,,system)
Binding(ALT+CTRL+T,
    ParameterizedCommand(Command(org.eclipse.tm.terminal.connector.local.command.launch,Open Local Terminal on Selection,
        ,
        Category(org.eclipse.tm.terminal.view.ui.commands.category,Terminal Commands,null,true),
        org.eclipse.ui.internal.WorkbenchHandlerServiceHandler@3291d9c2,
        ,,true),null),
    org.eclipse.ui.defaultAcceleratorConfiguration,
    org.eclipse.ui.contexts.window,,,system)

!ENTRY org.eclipse.egit.ui 2 0 2022-10-24 16:17:03.170
!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git
user global configuration and to define the default location to store repositories: 'C:\Users\mester.adam'. If this is
not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and
EGit might behave differently since they see different configuration options.
This warning can be switched off on the Team > Git > Confirmations and Warnings preference page.

!ENTRY org.eclipse.epp.logging.aeri.ide 2 17 2022-10-24 16:17:07.658
!MESSAGE Server 'org.eclipse.epp.logging.aeri.ide.server' failed with exception: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $. ; version: 2.0.7.v20170906-1327
!STACK 0
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)
    at com.google.gson.Gson.fromJson(Gson.java:887)
    at com.google.gson.Gson.fromJson(Gson.java:852)
    at com.google.gson.Gson.fromJson(Gson.java:801)
    at org.eclipse.epp.internal.logging.aeri.ide.server.json.Json.deserialize(Json.java:91)
    at org.eclipse.epp.internal.logging.aeri.ide.server.mars.IO.refreshConfiguration(IO.java:66)
    at org.eclipse.epp.internal.logging.aeri.ide.server.mars.ServerConnection.startUp(ServerConnection.java:124)
    at com.google.common.util.concurrent.AbstractIdleService$DelegateService$1.run(AbstractIdleService.java:62)
    at com.google.common.util.concurrent.Callables$4.run(Callables.java:122)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
    at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:385)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:213)
    ... 9 more

!ENTRY org.eclipse.launchbar.core 2 0 2022-10-24 16:17:08.381
!MESSAGE Enablement expression is missing for descriptor type org.eclipse.cdt.debug.core.coreBuildDescriptorType

!ENTRY org.eclipse.launchbar.core 2 0 2022-10-24 16:17:08.399
!MESSAGE Enablement expression is missing for config provider for org.eclipse.cdt.debug.core.coreBuildDescriptorType

!ENTRY org.eclipse.launchbar.core 2 0 2022-10-24 16:17:08.413
!MESSAGE Enablement expression is missing for config provider for org.eclipse.cdt.debug.core.coreBuildDescriptorType

!ENTRY org.eclipse.cdt.core 1 0 2022-10-24 16:19:33.058
!MESSAGE Indexed 'eio_valto' (0 sources, 0 headers) in 0,145 sec: 0 declarations; 0 references; 0 unresolved inclusions; 0 syntax errors; 0 unresolved names (0%)

!ENTRY org.eclipse.cdt.core 1 0 2022-10-24 16:37:01.920
!MESSAGE Indexed 'eio_valto' (0 sources, 0 headers) in 0,127 sec: 0 declarations; 0 references; 0 unresolved inclusions; 0 syntax errors; 0 unresolved names (0%)

!ENTRY org.eclipse.cdt.core 1 0 2022-10-24 16:37:53.391
!MESSAGE Indexed 'eio_valto' (0 sources, 0 headers) in 0,103 sec: 0 declarations; 0 references; 0 unresolved inclusions; 0 syntax errors; 0 unresolved names (0%)

A: I have tried the followings:

*

*rebuild index

*close and reopen project, and then rebuild index

*refresh project, and then rebuild index

*delete the project and reimport it into the workspace

None of them helped.
Finally: I have deleted the project and created a new project with my files, but I had to create and re-configure all my build configurations. Now it works fine, the indexer too, but it is strange, because the workspace settings are the same, and I have set the project settings to the same too. So I don't accept my method as a solution, it is just a workaround. But now, I can't reproduce the issue, so I really don't know, how to find the proper solution for this problem.


text:
Q: Отсутствие реакции на подставной запрос Сразу скажу... в PHP я никогда не работал, столкнулся только сейчас по учебным целям. Работаю на JS и осваиваю C++. Осталась только одна загвоздка в последней лабораторной работе, над которой я пыхтел почти 4 дня... пробовал 3 метода решения, ничего не сработало... сейчас решил написать и выложить здесь самую упрощенную версию:
$query="
    (
    SELECT
    `pilots`.`fio`
    FROM `pilots`
    WHERE `pilots`.`fio` LIKE ?
    )";

$stmt = $mysqli->prepare($query);

$pilot_fio='%';

if(isset($_GET['pilot_fio']) && $_GET['pilot_fio']!='')
{
$pilot_fio='%'.$_GET['pilot_fio'].'%';
}

$stmt->bind_param("s", $pilot_fio);
$stmt->execute();
$result=$stmt->get_result();
$result=$mysqli->query($query);
var_dump($query);print('{----------}');

Суть в том, что данный запрос не выводит ничего, абсолютно... ни ошибки... ни варнинга... ни результата... ничего... в JS подстановка устроена полегче...
Я должен сравнить введенное имя извне с тем, что есть в БД, однако ответом мне служит только пустота... если я буду пробовать методы в виде подстановки строки в запрос, все будет работать, и по сути если убрать LIKE ? и вернуть обычный механизм, то все будет пахать.. однако по заданию, требуется реализовать данный способ...
Вывод запроса: string(116) " ( SELECT pilots.pilot_id, pilots.fio FROM pilots WHERE pilots.fio LIKE ? )" {----------}
P.S: Все имена таблиц и столбцов правильны и использованы в моих предыдущих работах.

A: $stmt = new mysqli(.......);  // надеюсь, не забыли подключиться к базе данных

if(isset($_GET['pilot_fio'])) {

    $query = " SELECT * FROM pilots WHERE fio LIKE ?";

    $pilot_fio = "%{$_GET['pilot_fio']}%";

    $stmt = $mysqli->prepare($query);

    $stmt->bind_param("s", $pilot_fio);

    $stmt->execute();

    $result = $stmt->get_result();

    if($stmt->affected_rows) {

        echo "совпадение найдено";

    }

}else {

    echo "pilot_fio не определено, запрос не может быть выполнен";

}

$stmt->close();

A: Есть таблица pilots, в которой существует поле fio, которое необходимо вывести и по которому необходимо фильтровать.
На странице есть поле ввода fio.
Подключение есть заранее и находится в stmt. Закрывается также в нужное время.
При попытке ввода в него значения "Петков", выдает следующее:
Input: %Петков% ---------------NON ROWS! ERROR! -------------- string(74) " SELECT pilots.fio AS fio FROM pilots WHERE fio LIKE ?" {----------}
Из чего делаю вывод, что поле он читает однако не "засовывает" в запрос значение.
Внизу представлен ваш интерапритированый код, однако он немного не подходит, ибо нужно также выводить строки без фильтра. поэтому я решил добавить код после else без фильтрации.
Однако и в этом случае получаем:
NON FILTER ----------------string(74) " SELECT pilots.fio AS fio FROM pilots WHERE fio" {----------}
if($stmt->affected_rows) - тут уже эта строка не дает результата...
Что делать? Вот уже тот же эффект несколько дней...
if(isset($_GET['fio']) && $_GET['fio']!='') {
echo "WITH FILTER -----------------";
$query = "
SELECT
`pilots`.`fio` AS `fio`
FROM `pilots`
WHERE `fio` LIKE ?";

$pilot_fio = "%{$_GET['fio']}%";

echo "Input: {$pilot_fio} ---------------";
$stmt = $mysqli->prepare($query);

$stmt->bind_param("s", $pilot_fio);

$stmt->execute();

$result = $stmt->get_result();

if($stmt->affected_rows) {
    echo "NON ROWS! ERROR! -------------- ";
}
} else {
echo "NON FILTER ----------------";
$query = "
SELECT `pilots`.`fio` AS `fio`
FROM `pilots`
WHERE `fio`";

$stmt = $mysqli->prepare($query);
$stmt->execute();
$result = $stmt->get_result();

if($stmt->affected_rows) {
    echo "NON ROWS! ERROR! -------------- ";
}
}

var_dump($query);print('{----------}');


text:
Q: calculate how long ago a file was modified I need a script that calculates how long ago a file was modified. This can be days ago or just minutes ago.
I already was able to get the modification date and time from the stat-command. I stored this data in two different variables.
Now I need to calculate the difference between this date and time with "now".
I can find lots of examples of getting the difference between two dates or time. But what if my time goes back more then a day.
ex. modif date 2013-06-25  23:55:00
    now        2013-06-26  00:10:08
If I calculate the difference between these two I need the answer 15 minutes and 8 seconds.
Can anybody help me?

A: Jens answer works, here's an example.
#!/bin/bash

MOD_TIME=`stat -c %Y thisfile.txt`
RIGHTNOW=`date +%s`
HOW_LONG=`expr $RIGHTNOW - $MOD_TIME`
NUM_MINS=`expr $HOW_LONG / 60`
NUM_SECS=`expr $HOW_LONG % 60`

echo "$NUM_MINS minutes, $NUM_SECS seconds since modified."

A: Make stat give you the times in seconds, then subtract the values. Divide by 60 if you want minutes, use modulo 60 to get the remainder in seconds.


text:
Q: Telling ember-simple-auth that the user is now invalidated/logged-out, inside a custom authenticator From a custom authenticator; is there a way of telling ember-simple-auth that a user is now invalidated/logged-out?
Some background: I am building an authenticator with token refresh, similar to oauth2-password-grant. While I haven't experimented with the oauth2 authenticator directly, it seems we face the same issue: if the token refresh fails to update, for example due to an expired token, the user remains logged in as far as ember-simple-auth is concerned.
EDIT: (to address comments for further clarification)
Ah, I use JWTs and the server does not maintain sessions; the server has no idea who is logged in nor does it matter. The authentication is done via username/password after which the server issues a JWT token along with a time when it expires. To prolong the expiry time, you may refresh this token (as long as its valid) and get a new token with an updated expiry time. All is well and good except that ember-simple-auth does keep track of whether the user is logged in, as it should. However, if a call to refresh the token fails the user should be considered logged out (the token is invalid/expired and any attempts to make a call to an API that requires authentication will fail).
My question is how do I tell ember-simple-auth that this user has been logged out.


text:
Q: Calculate SUM between two dates SQL SERVER I'm having two tables
Calendar
FirstDate   |  LastDate
------------+-----------
2020-05-01     2020-05-03
2020-05-02     2020-05-04

ProfileRate
ID |    Date    | Rate | Product
---+------------+------+----------
1    2020-05-01   100    Prod1
2    2020-05-02   200    Prod1
3    2020-05-03   300    Prod1
4    2020-05-04   400    Prod1
5    2020-05-01   150    Prod2
6    2020-05-02   250    Prod2
7    2020-05-03   350    Prod2
8    2020-05-04   450    Prod2

I want to calculate SUM. Something like this
FirstDate   | LastDate    | Prod1  | Prod2
------------+-------------+--------+-------
2020-05-01    2020-05-03    600      750
2020-05-02    2020-05-04    900      1050

What I've tried:
SELECT [Date], SUM([Rate])
FROM [ProfileRate]
WHERE [Date] BETWEEN '2020-05-01' AND '2020-05-04'
GROUP BY [Date]

Please help me. Thanks

A: I think this is a JOIN and conditional aggregation:
SELECT c.FirstDate, c.LastDate,
       SUM(CASE WHEN pr.prod = 'Prod1' THEN pr.Rate END) as prod1,
       SUM(CASE WHEN pr.prod = 'Prod2' THEN pr.Rate END) as prod2
FROM Calender c LEFT JOIN
     ProfileRate pr
     ON pr.Date >= c.FirstDate AND pr.Date <= c.LastDate
GROUP BY c.FirstDate, c.LastDate;

A: Do the join & conditional aggregation :
select c.fisrtdate, c.lastdate,
       sum(case when pr.product = 'prod1' then rate else 0 end) as prod1,
       sum(case when pr.product = 'prod2' then rate else 0 end) as prod2
from calendar c join
     ProfileRate pr
     on pr.date >= c.fisrtdate and pr.date <= c.lastdate
group by c.fisrtdate, c.lastdate;

If you want all calendar dates then use left join instead.

A: you have to do several steps to solve the problem:

*

*combine calendar records with profiles

*establish which profiles meet the calendar range

*total the value for each profile and date range

*finally establish the detailed information of the calendar

this query meets the conditions
with DataForCalendar as
(
  SELECT IdCalendar,FirstDate,LastDate,Id,DateRate,Rate,Product
  FROM
  Calendar CROSS JOIN ProfileRate
  where DateRate  between '2020-05-01' and '2020-05-05'
),
DetailForCalendar as
(
  select IdCalendar,Rate,Product
  from DataForCalendar
  where   DateRate between FirstDate and LastDate
),
TotalForCalendar as
(
  select IdCalendar,Product,sum(Rate)As Total from DetailForCalendar
  GROUP BY IdCalendar,Product
)
select   Calendar.IdCalendar,Calendar.FirstDate,Calendar.LastDate,
TotalForCalendar.Product,TotalForCalendar.Total
from TotalForCalendar inner join
Calendar on TotalForCalendar.IdCalendar=Calendar.IdCalendar;

in this example you can find step by step how it work
in this example there is one more product and one more calendar.


text:
Q: Scientific Reporting in Python I am working on a scientific python project performing a bunch of computations generating a lot of data.
The problem comes when reports have to be generated from these data, with images embedded (mostly computed with matplotlib). I'd like to use a python module or tool to be able to describe the reports and "build" HTML pages for these reports (or any format supported by a browser).
I was thinking about generating an ipython notebook but I was unable to find if there is a way to do so (except creating the json but I'm doubtful about this approach).
The other way is using Sphinx a bit like the matplotlib but I am not sure how I could really fine-tune the layouts of my various pages.
The last option is to use jinja2 templates (or django-templates or any template engine working) and embed matplotlib code inside.
I know it's vague but was unable to find any kind of reference.

A: nbconvert has been merged into IPython itself, so please do not use the standalone version anymore. It is now fully template base so you can change things from just tweeking the css, fully re-wrote your templates, or just overwrite the current part of templates you want.
Notebook format is a pure json file, is takes ~20 lines to write a program that loop through it and re-run the codecell. That plus command line argument it is not hard to write a notebook, make it a 'template' notebook and run it on multiple dataset without opening a browser.
Some resources :
programatically run nbconvert, and run a notebook headless (first link)

A: I think you want to work in ipython notebook and then use nbconvert
Currently, this is it's own utility, that already works (albeit with some installation hurdles, but working) but it is currently being implemented directly into the ipython notebook machinery, which I believe should be released in autumn, or so.
The goal is (and Fernando Perez has demonstrated that this works), that a notebook becomes a fully documented, image containing pdf-document after the conversion.

A: Using the inline-modus of ipython notebook,

ipython notebook --pylab inline

you can execute your matplotlib-scripts in a browser interactively (thus generating your plots). Then go to

File -> Print View (in the notebook-menu, NOT the browser menu)

and save the generated html-File (via the browser menu). This will include all the plots you generated before as well as the python code. Of course, you cannot modify these html-Files anymore without the notebook-server in the background.
Is this what you mean?

A: I just found this old question and want to add PWeave to the list, which is perfectly suited to generate reports from python code / jupyter notebooks. I use it to share my work with colleagues that aren't invested with programming alot.
It also integrates into Spyder, THE scientific IDE for python, using the spyder-reports module.


text:
Q: Caused by: java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "modifyThreadGroup") error while using javax.mail I am getting exception Caused by:

java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "modifyThreadGroup") when I used javax.mail package...

I am running my web application using Google app engine maven build...When any request hits server which wants to send email to specified mail using javax.mail, it is showing the above exception..
[INFO] org.glassfish.jersey.server.ContainerException: java.lang.ExceptionInInitializerError
[INFO]  at org.glassfish.jersey.servlet.internal.ResponseWriter.rethrow(ResponseWriter.java:230)
[INFO]  at org.glassfish.jersey.servlet.internal.ResponseWriter.failure(ResponseWriter.java:212)
[INFO]  at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:360)
[INFO]  at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:230)
[INFO]  at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
[INFO]  at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
[INFO]  at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
[INFO]  at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
[INFO]  at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
[INFO]  at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
[INFO]  at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:198)
[INFO]  at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:946)
[INFO]  at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:323)
[INFO]  at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
[INFO]  at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
[INFO]  at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
[INFO]  at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
[INFO]  at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
[INFO]  at com.googlecode.objectify.ObjectifyFilter.doFilter(ObjectifyFilter.java:48)
[INFO]  at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
[INFO]  at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
[INFO]  at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
[INFO]  at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:127)
[INFO]  at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
[INFO]  at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
[INFO]  at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
[INFO]  at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
[INFO]  at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
[INFO]  at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
[INFO]  at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
[INFO]  at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
[INFO]  at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
[INFO]  at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
[INFO]  at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
[INFO]  at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
[INFO]  at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
[INFO]  at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
[INFO]  at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
[INFO]  at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
[INFO]  at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
[INFO]  at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
[INFO]  at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:98)
[INFO]  at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
[INFO]  at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:491)
[INFO]  at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
[INFO]  at org.mortbay.jetty.Server.handle(Server.java:326)
[INFO]  at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
[INFO]  at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:938)
[INFO]  at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:755)
[INFO]  at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
[INFO]  at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
[INFO]  at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
[INFO]  at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
[INFO] Caused by: java.lang.ExceptionInInitializerError
[INFO]  at java.lang.Class.forName0(Native Method)
[INFO]  at java.lang.Class.forName(Unknown Source)
[INFO]  at com.google.appengine.tools.development.agent.runtime.RuntimeHelper.checkRestricted(RuntimeHelper.java:70)
[INFO]  at com.google.appengine.tools.development.agent.runtime.Runtime.checkRestricted(Runtime.java:64)
[INFO]  at com.we.tinklez.manager.UserManager.processValidateRequestObj(UserManager.java:222)
[INFO]  at com.we.tinklez.manager.UserManager.userRegister(UserManager.java:91)
[INFO]  at com.we.tinklez.api.RestClient.validateMessage(RestClient.java:48)
[INFO]  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[INFO]  at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
[INFO]  at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
[INFO]  at java.lang.reflect.Method.invoke(Unknown Source)
[INFO]  at com.google.appengine.tools.development.agent.runtime.Runtime.invoke(Runtime.java:115)
[INFO]  at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
[INFO]  at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:125)
[INFO]  at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152)
[INFO]  at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:91)
[INFO]  at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:346)
[INFO]  at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:341)
[INFO]  at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:101)
[INFO]  at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:224)
[INFO]  ... 49 more
[INFO] Caused by: java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "modifyThreadGroup")
[INFO]  at java.security.AccessControlContext.checkPermission(Unknown Source)
[INFO]  at java.security.AccessController.checkPermission(Unknown Source)
[INFO]  at java.lang.SecurityManager.checkPermission(Unknown Source)
[INFO]  at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkPermission(DevAppServerFactory.java:429)
[INFO]  at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkAccess(DevAppServerFactory.java:454)
[INFO]  at java.lang.ThreadGroup.checkAccess(Unknown Source)
[INFO]  at java.lang.Thread.init(Unknown Source)
[INFO]  at java.lang.Thread.init(Unknown Source)
[INFO]  at java.lang.Thread.<init>(Unknown Source)
[INFO]  at com.we.tinklez.Email.EmailSender.<init>(EmailSender.java:45)
[INFO]  at com.we.tinklez.Email.EmailSender.startInstance(EmailSender.java:51)
[INFO]  at com.we.tinklez.Email.EmailSender.<clinit>(EmailSender.java:57)
[INFO]  ... 69 more

And in the web, I got like:

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 500 java.lang.ExceptionInInitializerError</title>

HTTP ERROR 500

Problem accessing /tinklez/user/validate. Reason:

    java.lang.ExceptionInInitializerError

Caused by:

org.glassfish.jersey.server.ContainerException: java.lang.ExceptionInInitializerError
    at org.glassfish.jersey.servlet.internal.ResponseWriter.rethrow(ResponseWriter.java:230)
    at org.glassfish.jersey.servlet.internal.ResponseWriter.failure(ResponseWriter.java:212)
    at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:360)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:230)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:198)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:946)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:323)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
    at com.googlecode.objectify.ObjectifyFilter.doFilter(ObjectifyFilter.java:48)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:127)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
    at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:98)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:491)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:938)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:755)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Caused by: java.lang.ExceptionInInitializerError
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at com.google.appengine.tools.development.agent.runtime.RuntimeHelper.checkRestricted(RuntimeHelper.java:70)
    at com.google.appengine.tools.development.agent.runtime.Runtime.checkRestricted(Runtime.java:64)
    at com.we.tinklez.manager.UserManager.processValidateRequestObj(UserManager.java:222)
    at com.we.tinklez.manager.UserManager.userRegister(UserManager.java:91)
    at com.we.tinklez.api.RestClient.validateMessage(RestClient.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.google.appengine.tools.development.agent.runtime.Runtime.invoke(Runtime.java:115)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:125)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:91)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:346)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:341)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:101)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:224)
    ... 49 more
Caused by: java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "modifyThreadGroup")
    at java.security.AccessControlContext.checkPermission(Unknown Source)
    at java.security.AccessController.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPermission(Unknown Source)
    at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkPermission(DevAppServerFactory.java:429)
    at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkAccess(DevAppServerFactory.java:454)
    at java.lang.ThreadGroup.checkAccess(Unknown Source)
    at java.lang.Thread.init(Unknown Source)
    at java.lang.Thread.init(Unknown Source)
    at java.lang.Thread.<init>(Unknown Source)
    at com.we.tinklez.Email.EmailSender.<init>(EmailSender.java:45)
    at com.we.tinklez.Email.EmailSender.startInstance(EmailSender.java:51)
    at com.we.tinklez.Email.EmailSender.<clinit>(EmailSender.java:57)
    ... 69 more

Caused by:

java.lang.ExceptionInInitializerError
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at com.google.appengine.tools.development.agent.runtime.RuntimeHelper.checkRestricted(RuntimeHelper.java:70)
    at com.google.appengine.tools.development.agent.runtime.Runtime.checkRestricted(Runtime.java:64)
    at com.we.tinklez.manager.UserManager.processValidateRequestObj(UserManager.java:222)
    at com.we.tinklez.manager.UserManager.userRegister(UserManager.java:91)
    at com.we.tinklez.api.RestClient.validateMessage(RestClient.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.google.appengine.tools.development.agent.runtime.Runtime.invoke(Runtime.java:115)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:125)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:91)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:346)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:341)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:101)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:224)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:198)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:946)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:323)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
    at com.googlecode.objectify.ObjectifyFilter.doFilter(ObjectifyFilter.java:48)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:127)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
    at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:98)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:491)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:938)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:755)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Caused by: java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "modifyThreadGroup")
    at java.security.AccessControlContext.checkPermission(Unknown Source)
    at java.security.AccessController.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPermission(Unknown Source)
    at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkPermission(DevAppServerFactory.java:429)
    at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkAccess(DevAppServerFactory.java:454)
    at java.lang.ThreadGroup.checkAccess(Unknown Source)
    at java.lang.Thread.init(Unknown Source)
    at java.lang.Thread.init(Unknown Source)
    at java.lang.Thread.<init>(Unknown Source)
    at com.we.tinklez.Email.EmailSender.<init>(EmailSender.java:45)
    at com.we.tinklez.Email.EmailSender.startInstance(EmailSender.java:51)
    at com.we.tinklez.Email.EmailSender.<clinit>(EmailSender.java:57)
    ... 69 more

Caused by:

java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "modifyThreadGroup")
    at java.security.AccessControlContext.checkPermission(Unknown Source)
    at java.security.AccessController.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPermission(Unknown Source)
    at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkPermission(DevAppServerFactory.java:429)
    at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkAccess(DevAppServerFactory.java:454)
    at java.lang.ThreadGroup.checkAccess(Unknown Source)
    at java.lang.Thread.init(Unknown Source)
    at java.lang.Thread.init(Unknown Source)
    at java.lang.Thread.<init>(Unknown Source)
    at com.we.tinklez.Email.EmailSender.<init>(EmailSender.java:45)
    at com.we.tinklez.Email.EmailSender.startInstance(EmailSender.java:51)
    at com.we.tinklez.Email.EmailSender.<clinit>(EmailSender.java:57)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at com.google.appengine.tools.development.agent.runtime.RuntimeHelper.checkRestricted(RuntimeHelper.java:70)
    at com.google.appengine.tools.development.agent.runtime.Runtime.checkRestricted(Runtime.java:64)
    at com.we.tinklez.manager.UserManager.processValidateRequestObj(UserManager.java:222)
    at com.we.tinklez.manager.UserManager.userRegister(UserManager.java:91)
    at com.we.tinklez.api.RestClient.validateMessage(RestClient.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.google.appengine.tools.development.agent.runtime.Runtime.invoke(Runtime.java:115)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:125)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:91)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:346)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:341)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:101)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:224)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:198)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:946)

Please any one knows the issue?

I am using jerysey 2.6 version

A: The GAE sandbox will not allow you to create new Thread objects which is what is happening in your com.we.tinklez.Email.EmailSender class.
To create threads in GAE, you have to use the com.google.appengine.api.ThreadManager.


text:
Q: How can I rewrite jQuery without guard clause? How can I rewrite this jQuery to be more terse and without the guard clause?
var myTextBox = $('#myTextBox');

if (myTextBox )
    myTextBox.val("");

The guard clause is there simply to ensure that the element exists on the page before trying to set it's value but the code seems bloated and most of it unnecessary.
What's the preferred solution to this?

A: $('#myTextBox').val("") will do nothing if the jQuery object has a length of 0, so simply use it.

A: Unless you need to cache the selector for future operations, I would do this:
$('#myTextBox').val("")

If there are none selected, nothing will get enumerated, so jQuery will not run the val() routine.

A: It'll work just as $('#myTextBox').val("");, if it finds no object then it will just be an empty jQuery object and the .val() routine will do nothing.

A: I believe that if #mytextbox doesn't exist, mytextbox will not be undefined anyway, it will be an empty jQuery object. So the check is redundant.
I also think that if you perform an operation on an empty jQuery object nothing will happen anyway, so you're safe.


text:
Q: Prove that a function is subharmonic I am trying to prove the following conjecture (or find a counterexample):
Claim: Let $f(z)$ and $g(z)$ be holomorphic functions defined on a simply connected bounded domain  $\Omega \subset \mathbb C$ in the complex plane.
We know that at any point in the domain the following inequality holds
$$ |f(z)| > |g(z)|, $$
then the function  $\zeta(z) = \frac{1}{|f(z)|-|g(z)|}$ is subharmonic in $\Omega$.
Some properties that (might) be useful:
1) From the above inequality we also know that $f$ does not vanish in the domain, i.e. $\forall z\in \Omega$,  $f(z)\neq 0$.
2) $log|f(z)|$ and $log|g(z)|$ are subharmonic and since $f$ does not vanish in the domain $log|f(z)|$ is also harmonic.
3) The function $\zeta(z)$ is strictly positive.
4) The modulus of a holomorphic function is subharmonic. In particular, $|f(z)|$ and $|g(z)|$ are subharmonic.
5) Linear combinations of subharmonic functions with positive weights is subharmonic. In particular the sum of two subharmonic functions is subharmonic (but the difference of two subharmonic functions is not in general subharmonic).

A: It is correct. First, note that
$$\frac{1}{|f(z)|-|g(z)|}=\frac{1}{|f(z)|}\frac{1}{1-\frac{|g(z)|}{|f(z)|}}=\frac{1}{|f(z)|}\sum_{k=0}^{\infty}\frac{|g(z)|^k}{|f(z)|^k}=\sum_{k=0}^{\infty}\frac{|g(z)|^k}{|f(z)|^{k+1}}.$$
For any $k\in\mathbb N$, since $f$ does not vanish and $\Omega$ is simply connected, there exists a holomorphic branch $F_k(z)=f^{-\frac{k+1}{k}}(z)$. Then, write
$$\frac{|g(z)|^k}{|f(z)|^{k+1}}=|g(z)F_k(z)|^k,$$
and since $gF_k$ is holomorphic, we obtain that the summands are subharmonic functions.
Edit: To show subharmonicity of the sum, consider a ball $B$ in the domain and let $u$ be a harmonic function in $B$, with $\frac{1}{|f|-|g|}\leq u$ on $\partial B$. Set $$v_n(z)=\sum_{k=0}^n\frac{|g(z)|^k}{|f(z)|^{k+1}},$$ then  $v_n\to\frac{1}{|f|-|g|}$ pointwise, as $n\to\infty$, and $v_n\leq\frac{1}{|f|-|g|}$ for all $n$. Therefore, $v_n\leq u$ on $\partial B$, and since $v_n$ is subharmonic, we obtain that $v_n\leq u$ in $B$. By letting $n\to\infty$ we get that $\frac{1}{|f|-|g|}\leq u$, therefore $\frac{1}{|f|-|g|}$ is subharmonic in $B$.


text:
Q: How to set a DataGridView column to a DataGridViewComboBoxColumn? Here is my code:
DataSet data = new DataSet();
data.ReadXml("data.xml");

DataGridView grid = new DataGridView();

var genreCboBoxItems = data.Tables[0].AsEnumerable().Select(genre => genre.Field<string>("genre")).Distinct().ToArray();

// TODO: Make is so the 'genre' column in grid is a combo box?

grid.DataSource = data.Tables[0];
grid.Dock = DockStyle.Fill;
this.Controls.Add(grid);

*edit: genreCboBoxItems

A: Try this:  (not tested)
var column = new DataGridViewComboBoxColumn();

column.DataSource = data.Tables[0].AsEnumerable().
      Select(genre => new { genre = genre.Field<string>("genre") }).Distinct();
column.DataPropertyName = "genre";
column.DisplayMember = "genre";
column.ValueMember = "genre";
grid.DataSource = data.Tables[0];
// Instead of the below line, You could use grid.Columns["genre"].Visible = false;
grid.Columns.Remove("genre");
grid.Columns.Add(column);

A: This might help you cast DataGridViewColumn to DataGridViewComboBox.

A: First create DataGridViewComboBoxColumn using designer with proper name. Then say you have a list of String list and other string values to bind to that datagridview then use this code:
Below code will bind a list to two DataGridViewTextBoxCell  and a DataGridViewComboBoxCell. Note AllCriterias is a list with two string values and a list of string. DGVEligibilityCriteria is the grid name.
for (int i = 0; i < AllCriterias.Count; i++)
            {
                DataGridViewTextBoxCell Cmb1 = (DataGridViewTextBoxCell)DGVEligibilityCriteria.Rows[i].Cells[0];
                Cmb1.Value = AllCriterias[i].Name;
                DataGridViewTextBoxCell Cmb2 = (DataGridViewTextBoxCell)DGVEligibilityCriteria.Rows[i].Cells[1];
                Cmb2.Value = AllCriterias[i].Type;
                DataGridViewComboBoxCell Cmb = (DataGridViewComboBoxCell)DGVEligibilityCriteria.Rows[i].Cells[2];
                foreach (var filtervalue in AllCriterias[i].FilterValues)
                {
                    Cmb.Items.Add(filtervalue);
                }
             }

Need to display the fist index as default by setting selectindex property.
Use this code : Here "filterValues" is the name of the DataGridViewComboBoxCell which u created in the datagridview designer.
foreach (DataGridViewRow  row in DGVEligibilityCriteria.Rows)
            {
                row.Cells["filterValues"].Value = (row.Cells["filterValues"] as DataGridViewComboBoxCell).Items[0];
            }


text:
Q: Delegating to a property of a property in Kotlin Let's consider the following code :
data class Location(var x:Int,var y:Int)
data class Player(val location:Location)

var Player.x: Int
    get() = location.x
    set(value) { location.x = value}

Is there a way to shorten this declaration using property delegates, in the style of var Player.x by  instead of of the last three lines ?

A: The obvious way works, using a property reference:
data class Location(var x: Int, var y: Int)

data class Player(val location: Location) {
    var x by location::x
}


text:
Q: Powershell command to replace AD user's title in title field not working? I have created a script for a project with some code which I was given fused with my own. Most of the commands which are great, but unfortunately two commands are not working.
These commands are:
Set-ADUser $UserName -replace @{title="Former Employee" + $title}

Move-ADObject -Identity $UserName -TargetPath "OU=Former Employee,OU=Users,OU=Contoso,DC=Contoso,DC=local"

Any ideas? I appreciate the help!
Here is the full script:
$UserName = Read-Host "Please enter username to be disabled"

if ($UserName) {
    ''
} Else {
    'User not Found'
}
Disable-ADAccount $UserName
Get-ADUser $UserName -Properties MemberOf | ForEach-Object {
$_.MemberOf | Remove-ADGroupMember -Members $_.DistinguishedName -Confirm:$false }

$title = get-aduser $UserName -properties title
$title = $title.title
$old=Get-ADuser $UserName -properties Description
$old = $old.description
$new = "DISABLED " + $old
set-aduser $UserName -description $new
set-aduser $UserName -clear "manager"
set-aduser $UserName -clear "telephonenumber"

# these two:
set-aduser $UserName -replace @{title="Former Employee" + $title}
Move-ADObject -Identity $UserName -TargetPath "OU=Former Employee,OU=Users,OU=Contoso,DC=Contoso,DC=local"

A: I think it's better to clear up a bit of your code. Have a look at this:
$SamAccountName = Read-Host 'Please enter the SamAccountName of the user you want to disable'

$VerbosePreference = 'SilentlyContinue'
$VerbosePreference = 'Continue'

Try {
    $ADUser = Get-ADUser -Identity $SamAccountName -Properties MemberOf, Title, Description
    Write-Verbose  "User '$($ADUser.Name)' found in AD"
}
Catch {
    throw "No user found in AD with SamAccountName '$SamAccountName'"
}

Write-Verbose 'Disable user'
Disable-ADAccount $ADUser

foreach ($Group in $ADUser.MemberOf) {
    Write-Verbose "Remove user from group '$Group'"
    Remove-ADGroupMember -Identity $Group -Members $ADUser -Confirm:$false
}

$NewTitle = "Former Employee {0}" -f $ADUser.Title
Write-Verbose "Set 'Title' to '$NewTitle'"
Set-ADUser -Identity $ADUser -Title $NewTitle

$NewDescription = "DISABLED {0}" -f $ADUser.Description
Write-Verbose "Set 'Description' to '$NewDescription'"
Set-ADUser -Identity $ADUser -Description $NewDescription

foreach ($Property in @('Manager', 'telephonenumber')) {
    Write-Verbose "Clear property '$_'"
    Set-ADUser -Identity $ADUser -Clear $Property
}

$NewTargetPath = "OU=Former Employee,OU=Users,OU=Contoso,DC=Contoso,DC=local"
Write-Verbose "Move AD User to '$NewTargetPath'"
Move-ADObject -Identity $ADUser -TargetPath $NewTargetPath

Some tips:

*

*Use Write-Verbose to show what is happening in the script. Yuo can disable/enable this by commenting out the VerbosePreference.

*Always start with retrieving an object instead of working with text strings ($UserName vs $ADUser). See Get-ADUser as the very first action.

*Work with Try/Catch in case things fail.

*Always use the parameter names. It makes it more clear on what you're trying to do.


text:
Q: How to display in a View a returned value from a completion handler in Swift? I have a class that has these two methods:
private func send(method: String, path: String, code: Array<Int>, headers: HTTPHeaders, completionHandler: @escaping (Int) -> Void) {
        let url: String = "\(self.credentials.url)/\(path)"

        AF.request(url, method: HTTPMethod(rawValue: method), headers: headers)
            .authenticate(with: self.request_credentials)
            .response { response in
                let status_code: Int = response.response!.statusCode

                completionHandler(status_code as Int)
            }
}

And
func list_files(path: String) {
        let headers: HTTPHeaders = [
            "Depth": "1"
        ]

        send(method: "PROPFIND", path: path, code: [207, 301], headers: headers) { status_code in
            self.status_code = String(status_code)
        }
}

So both of these functions use completion handlers because of the fact that Alamofire uses them in its process of making HTTP requests.
I understood that I have to use completion handlers this way to handle this async data.
My current issue is that now I have to display this data (let's say self.status_code) in a view but I have no idea how to do this. When I display it like this :
struct ContentView: View {
    var body: some View {

        let auth = Authentication(username: "****",
                                  domain: "****",
                                  password: "****",
                                  port: ****,
                                  proto: "****",
                                  path:"****")

        let commands = Commands(credentials: auth.get_credentials())

        let _ = commands.list_files(path: "/")

        Text(commands.status_code)
            .padding()
    }
}

It will display the initialization value of status_code (which is 0) instead of the updated value by list_files method. I know this is because of the asynchronous behavior of these completion handlers and the value is not yet updated when I display it.
But here's the question: how can I manage to properly display this updated value to the user?
I'm probably doing lots of things wrong here and I don't mind receiving a completely different solution since I'm willing to follow the best practices.
Thank you.

A: Below is a Playground with a complete example.  I'll walk through some of the important things to note.
First I simplified the "send" method since I don't have all the types and things from your original example.  This send will wait 3 seconds then call the completion handler with whatever message you give it.
Inside the view, when the button is pushed, we call "send".  Then, in the completion handler you'll notice:
DispatchQueue.main.async {
    message = msg
}

I don't know what thread the Timer in send is going to use to call my completion handler.  But UI updates need to happen on the main thread, so the DispatchQueue.main... construct will ensure that the UI update (setting message to msg) will happen on the main thread.
import UIKit
import SwiftUI
import PlaygroundSupport

func send(message: String, completionHandler: @escaping (String) -> Void) {
    Timer.scheduledTimer(withTimeInterval: 3.0, repeats: false) { timer in
        completionHandler(message)
        timer.invalidate()
    }
}

struct ContentView: View {
    @State var message : String = ""

    var body: some View {
        print("Building view")
        return VStack {
            TextField("blah", text: $message)
            Button("Push Me", action: {
                send(message: "Message Received") { msg in
                    DispatchQueue.main.async {
                        message = msg
                    }
                }
            })
        }.frame(width: 320, height: 480, alignment: .center)
    }
}

let myView = ContentView()
let host = UIHostingController(rootView: myView)
PlaygroundSupport.PlaygroundPage.current.liveView = host


text:
Q: Can I use a local repository as a git remote I have two repositories locally, A and B. Can I use the local copy of A, as a remote in B?
Something like
git remote add A file:///path/to/repo/

A: Yep, works like a charm.
git remote add A file:///path/to/repo/


text:
Q: Weird issue with multiple Python installations on Windows I have 3 versions of Python (2.5, 2.7, 3.2) installed on a Windows machine, 2.5 being the default one (first in PATH and default for open action).
Now the weird thing appear when I run a python script with filename.py (without specifying the interpreter) or by clicking the file in Explorer: Python 2.5 is running the script (expected) BUT Python 2.7 PATH being inserted before the original system PATH.
Still if I look at the command line, it seems that Python 2.5 was executed.
Where is the first record in PATH (C:\Ptyhon27\) comming from, I can assure you this is added when the scripts runs, but by whom?

As you already observed I do have several versions of Python in PATH, this is not something anormal, because they can also have versioned executables instead and because Windows always picks the first one it the PATH.

A: Looking closely, it seems you have various versions of Python in your PATH environment variable.
The standard Python installer for Windows doesn't add itself to the PATH; I always do this manually for the version of Python I want to use by default. If you're using a different Python installer (such as ActiveState or Enthought) that may be the cause, but I haven't tried those.
In any case, you can edit your PATH environment variable manually and clean it up, leaving only the path to the version of Python you wish to be the default, as described here (scroll down a bit to get to the relevant section).

A: You might be interested in the Python Launcher for Windows project, a.k.a. PEP 397. Install it, and remove all Python dirs from PATH, leaving only the launcher one, and use py/pyw instead of python/pythonw.

A: Ahh, I think I have it! You didn't mention exactly how you're running Python...
Python adds the directory from which the command is run to the PATH! If you run it from the command line, this will be the directory in which the Python file you execute is located, or the directory you ran Python from if you just opened an interpreter. However, various tools, interpreters and development environments start up differently, and some of them will use a certain Python interpreter (depends on their configuration) and add its location to PATH.
If you want more help, please give a detailed description of how you're running Python when this happens.


text:
Q: Why does my Odoo 9 custom Qweb report with CSS is not working? I'm creating a new report on Odoo 9 which uses css styles in order to position text over a background image. The image is in background and occupies the full A4 page without any margins.
In html, it's working fine. However, when I print the report to PDF, I have blank margins at left and right, and the text goes below the background image. It seems that the CSS rules are not applied. Do you find any solution for making it working in PDF?
Here is my report:
<template id="sub_proposal">

<t t-call="report.html_container">
    <t t-foreach="docs" t-as="o">

    </t>
</t>

A: The style tag and contents must be set within the
 element.
I don't have any documentation, only from experience.
Link to same question on Odoo forum

A: This will print image with text on pdf
<template id="account_report_id" inherit_id="account.report_invoice_document">

        Customer Sign

 </template>


text:
Q: How can I compare two version in C#? I am using C# language for compare two version. How can I compare two version? I had used below code but I am confused how it's working. When I had tried below code :
 var tem = "3.10.1".CompareTo("3.9.0"); // returns -1

var tem1 = "4.0.1".CompareTo("3.9.0"); // returns 1

I need 1 result for the tem variable also. Can anyone guide me on this?

A: You should compare Versions, not Strings:
 var tem = Version.Parse("3.10.1").CompareTo(Version.Parse("3.9.0"));

 var tem1 = Version.Parse("4.0.1").CompareTo(Version.Parse("3.9.0"));


text:
Q: Not found UnitySetup-Android-Support-for-Editor 5.3.4f1

*

*Open Download page click.

*Not found.
need android build module.

A: You should install the module from the unity installer. I have the same for iOS but that is because I decided do not install that module.
Note: you don't need to reinstall unity, just check the module you need in the dialog

A: Could not found UnitySetup-Android-Support-for-Editor
EDIT 1:

If Unity fails to install the Android package:
Kindly do check, that the name for the folder in which Unity3D is installed is "Unity" and nothing else. Then try to install the Android package again, via installer.

[Unity Download Archive][1]
If you still have problem after installation, you need to follow these steps:

*

*In the Application folder(For Mac) - Unity -> PlaybackEngines ->
Copy AndroidPlayer folder.

*After that Right click on Unity Package(Icon) -> Select "Show
Package  Contents" -> Contents -> Select PlaybackEngines -> You Just
Paste here(AndroidPlayer folder).

*Restart Unity


text:
Q: How to simulate an Appearance ("dark mode") change in React Native using Jest? I am writing a puzzle app in React Native where the user can solve a puzzle by changing their device's Appearance to dark mode. I'm using React Native's Appearance module to accomplish this, by calling Appearance.getColorScheme() to get the initial color scheme, and registering an event listener for when the color scheme changes using Appearance.addChangeListener() within the useEffect hook:
useEffect(() => {
      const originalColorScheme = Appearance.getColorScheme();

      Appearance.addChangeListener((event) => {
        if (Appearance.getColorScheme() !== originalColorScheme) {
          setSolved(true);
        }
      });
    }, []);

This is working fine, but I'd like to be able to unit test my component by simulating a change to dark mode in Jest and/or React Native Testing Library (or similar), after which I can check for changes to the content of the page (a "congratulations" message, in this case).
In my mind, it could look something like:
const text = await screen.findByText("good luck!");
// fireEvent("changeColorScheme", { colorScheme: "dark" });
const text2 = await screen.findByText("congratulations!");

Is anything like this possible? I'm guessing it has something to do with mocks, but it's a little over my head at the moment. Thanks for any help you can provide!


text:
Q: Collectors.groupingBy doesn't accept null keys In Java 8, this works:
Stream<Class> stream = Stream.of(ArrayList.class);
HashMap<Class, List<Class>> map = (HashMap)stream.collect(Collectors.groupingBy(Class::getSuperclass));

But this doesn't:
Stream<Class> stream = Stream.of(List.class);
HashMap<Class, List<Class>> map = (HashMap)stream.collect(Collectors.groupingBy(Class::getSuperclass));

Maps allows a null key, and List.class.getSuperclass() returns null. But Collectors.groupingBy emits a NPE, at Collectors.java, line 907:
K key = Objects.requireNonNull(classifier.apply(t), "element cannot be mapped to a null key");

It works if I create my own collector, with this line changed to:
K key = classifier.apply(t);

My questions are:
1) The Javadoc of Collectors.groupingBy doesn't say it shouldn't map a null key. Is this behavior necessary for some reason?
2) Is there another, easier way, to accept a null key, without having to create my own collector?

A: Use filter before groupingBy##
Filter out the null instances before groupingBy.
Here is an example
MyObjectlist.stream()
  .filter(p -> p.getSomeInstance() != null)
  .collect(Collectors.groupingBy(MyObject::getSomeInstance));

A: I had the same kind of problem.
This failed, because groupingBy performs Objects.requireNonNull on the value returned from the classifier:
    Map<Long, List<ClaimEvent>> map = events.stream()
      .filter(event -> eventTypeIds.contains(event.getClaimEventTypeId()))
      .collect(groupingBy(ClaimEvent::getSubprocessId));

Using Optional, this works:
    Map<Optional<Long>, List<ClaimEvent>> map = events.stream()
      .filter(event -> eventTypeIds.contains(event.getClaimEventTypeId()))
      .collect(groupingBy(event -> Optional.ofNullable(event.getSubprocessId())));

A: To your 1st question, from the docs:

There are no guarantees on the type, mutability, serializability, or thread-safety of the Map or List objects returned.

Because not all Map implementations allow null keys they probably added this to reduce to the most common allowable definition of a map to get maximum flexibility when choosing a type.
To your 2nd question, you just need a supplier, wouldn't a lambda work? I'm still getting acquainted with Java 8, maybe a smarter person can add a better answer.

A: I figured I would take a moment and try to digest this issue you have. I put together a SSCE for what I would expect if I did it manually, and what the groupingBy implementation actually does.
I don't think this is an answer, but it is a 'wonder why it is a problem' thing. Also, if you want, feel free to hack this code to have a null-friendly collector.
Edit: A generic-friendly implementation:
/** groupingByNF - NullFriendly - allows you to specify your own Map and List supplier. */
private static final <T,K> Collector<T,?,Map<K,List<T>>> groupingByNF (
        final Supplier<Map<K,List<T>>> mapsupplier,
        final Supplier<List<T>> listsupplier,
        final Function<? super T,? extends K> classifier) {

    BiConsumer<Map<K,List<T>>, T> combiner = (m, v) -> {
        K key = classifier.apply(v);
        List<T> store = m.get(key);
        if (store == null) {
            store = listsupplier.get();
            m.put(key, store);
        }
        store.add(v);
    };

    BinaryOperator<Map<K, List<T>>> finalizer = (left, right) -> {
        for (Map.Entry<K, List<T>> me : right.entrySet()) {
            List<T> target = left.get(me.getKey());
            if (target == null) {
                left.put(me.getKey(), me.getValue());
            } else {
                target.addAll(me.getValue());
            }
        }
        return left;
    };

    return Collector.of(mapsupplier, combiner, finalizer);

}

/** groupingByNF - NullFriendly - otherwise similar to Java8 Collections.groupingBy */
private static final <T,K> Collector<T,?,Map<K,List<T>>> groupingByNF (Function<? super T,? extends K> classifier) {
    return groupingByNF(HashMap::new, ArrayList::new, classifier);
}

Consider this code (the code groups String values based on the String.length(), (or null if the input String is null)):
public static void main(String[] args) {

    String[] input = {"a", "a", "", null, "b", "ab"};

    // How we group the Strings
    final Function<String, Integer> classifier = (a) -> {return a != null ? Integer.valueOf(a.length()) : null;};

    // Manual implementation of a combiner that accumulates a string value based on the classifier.
    // no special handling of null key values.
    BiConsumer<Map<Integer,List<String>>, String> combiner = (m, v) -> {
        Integer key = classifier.apply(v);
        List<String> store = m.get(key);
        if (store == null) {
            store = new ArrayList<String>();
            m.put(key, store);
        }
        store.add(v);
    };

    // The finalizer merges two maps together (right into left)
    // no special handling of null key values.
    BinaryOperator<Map<Integer, List<String>>> finalizer = (left, right) -> {
        for (Map.Entry<Integer, List<String>> me : right.entrySet()) {
            List<String> target = left.get(me.getKey());
            if (target == null) {
                left.put(me.getKey(), me.getValue());
            } else {
                target.addAll(me.getValue());
            }
        }
        return left;
    };

    // Using a manual collector
    Map<Integer, List<String>> manual = Arrays.stream(input).collect(Collector.of(HashMap::new, combiner, finalizer));

    System.out.println(manual);

    // using the groupingBy collector.
    Collector<String, ?, Map<Integer, List<String>>> collector = Collectors.groupingBy(classifier);

    Map<Integer, List<String>> result = Arrays.stream(input).collect(collector);

    System.out.println(result);
}

The above code produces the output:

{0=[], null=[null], 1=[a, a, b], 2=[ab]}
Exception in thread "main" java.lang.NullPointerException: element cannot be mapped to a null key
  at java.util.Objects.requireNonNull(Objects.java:228)
  at java.util.stream.Collectors.lambda$groupingBy$135(Collectors.java:907)
  at java.util.stream.Collectors$$Lambda$10/258952499.accept(Unknown Source)
  at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
  at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
  at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
  at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
  at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
  at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
  at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
  at CollectGroupByNull.main(CollectGroupByNull.java:49)

A: First of all, you are using lots of raw objects. This is not a good idea at all, first convert the following:

*

*Class to Class<?>, ie. instead of a raw type, a parametrized type with an unknown class.

*Instead of forcefully casting to a HashMap, you should supply a HashMap to the collector.

First the correctly typed code, without caring about a NPE yet:
Stream<Class<?>> stream = Stream.of(ArrayList.class);
HashMap<Class<?>, List<Class<?>>> hashMap = (HashMap<Class<?>, List<Class<?>>>)stream
        .collect(Collectors.groupingBy(Class::getSuperclass));

Now we get rid of the forceful cast there, and instead do it correctly:
Stream<Class<?>> stream = Stream.of(ArrayList.class);
HashMap<Class<?>, List<Class<?>>> hashMap = stream
        .collect(Collectors.groupingBy(
                Class::getSuperclass,
                HashMap::new,
                Collectors.toList()
        ));

Here we replace the groupingBy which just takes a classifier, to one that takes a classifier, a supplier and a collector. Essentially this is the same as what there was before, but now it is correctly typed.
You are indeed correct that in the javadoc it is not stated that it will throw a NPE, and I do not think it should be throwing one, as I am allowed to supply whatever map I want, and if my map allows null keys, then it should be allowed.
I do not see any other way to do it simpler as of now, I'll try to look more into it.

A: For the first question, I agree with skiwi that it shouldn't be throwing a NPE.  I hope they will change that (or else at least add it to the javadoc). Meanwhile, to answer the second question I decided to use Collectors.toMap instead of Collectors.groupingBy:
Stream<Class<?>> stream = Stream.of(ArrayList.class);

Map<Class<?>, List<Class<?>>> map = stream.collect(
    Collectors.toMap(
        Class::getSuperclass,
        Collections::singletonList,
        (List<Class<?>> oldList, List<Class<?>> newEl) -> {
        List<Class<?>> newList = new ArrayList<>(oldList.size() + 1);
        newList.addAll(oldList);
        newList.addAll(newEl);
        return newList;
        }));

Or, encapsulating it:
/** Like Collectors.groupingBy, but accepts null keys. */
public static <T, A> Collector<T, ?, Map<A, List<T>>>
groupingBy_WithNullKeys(Function<? super T, ? extends A> classifier) {
    return Collectors.toMap(
        classifier,
        Collections::singletonList,
        (List<T> oldList, List<T> newEl) -> {
            List<T> newList = new ArrayList<>(oldList.size() + 1);
            newList.addAll(oldList);
            newList.addAll(newEl);
            return newList;
            });
    }

And use it like this:
Stream<Class<?>> stream = Stream.of(ArrayList.class);
Map<Class<?>, List<Class<?>>> map = stream.collect(groupingBy_WithNullKeys(Class::getSuperclass));

Please note rolfl gave another, more complicated answer, which allows you to specify your own Map and List supplier. I haven't tested it.

A: You can use Stream#collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner) instead.
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#collect-java.util.function.Supplier-java.util.function.BiConsumer-java.util.function.BiConsumer-

When you have a list of objects of a self-defined POJO type:
package code;

import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static lombok.AccessLevel.PRIVATE;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

import lombok.Data;
import lombok.experimental.Accessors;
import lombok.experimental.FieldDefaults;

public class MainGroupListIntoMap {

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

        final List<Item> items = Arrays.asList(
            new Item().setName("One").setType("1"),
            new Item().setName("Two").setType("1"),
            new Item().setName("Three").setType("1"),
            new Item().setName("Four").setType("2"),
            new Item().setName("Same").setType(null),
            new Item().setName("Same").setType(null),
            new Item().setName(null).setType(null)
        );

        final Map<String, List<Item>> grouped = items
                .stream()
                .collect(HashMap::new,
                         (m, v) -> m.merge(v.getType(),
                                           asList(v),
                                           (oldList, newList) -> Stream.concat(oldList.stream(),
                                                                               newList.stream())
                                                                       .collect(toList())),
                         HashMap::putAll);

        grouped.entrySet().forEach(System.out::println);
    }
}

@Data
@Accessors(chain = true)
@FieldDefaults(level = PRIVATE)
class Item {
    String name;
    String type;
}

Output:
null=[Item(name=Same, type=null), Item(name=Same, type=null), Item(name=null, type=null)]
1=[Item(name=One, type=1), Item(name=Two, type=1), Item(name=Three, type=1)]
2=[Item(name=Four, type=2)]

In your case:
package code;

import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

public class MainGroupListIntoMap2 {

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

        group(asList(ArrayList.class, List.class))
            .entrySet()
            .forEach(System.out::println);
    }

    private static Map<Class<?>, List<Class<?>>> group(List<Class<?>> classes) {
        final Map<Class<?>, List<Class<?>>> grouped = classes
                .stream()
                .collect(HashMap::new,
                         (m, v) -> m.merge(v.getSuperclass(),
                                           asList(v),
                                           (oldList, newList) -> Stream.concat(oldList.stream(),
                                                                               newList.stream())
                                                                       .collect(toList())),
                         HashMap::putAll);

        return grouped;
    }
}

Output:
null=[interface java.util.List]
class java.util.AbstractList=[class java.util.ArrayList]


text:
Q: Total number of likes from list I have the following piece of code that gives the following output.
I wanted to know if there was any way to get the TOTAL number of likes instead of just individual likes.
Using: jInstagram and Vaadin
Thanks!
Code:
    MediaFeed mediaFeed = instagram.getRecentMediaFeed(userID); //Get recent images
    List<MediaFeedData> mediafeed = mediaFeed.getData(); // Store info from mediaFeed into this list

    for (MediaFeedData mediaData : mediafeed) { //For loop

    int likes = mediaData.getLikes().getCount(); //Number of likes for each picture
    System.out.println("Likes: " + likes); //Print likes

Output:
Likes: 1
Likes: 0
Likes: 0

A: int totalLikes = 0;
for (MediaFeedData mediaData : mediafeed) { //For loop
    totalLikes += mediaData.getLikes().getCount();
}
System.out.println("Likes: " + totalLikes); //Print likes


text:
Q: Vitest integration with Quasar I have been trying to integrate Vitest with a project that implements Quasar but I have not succeed doing so. The main problem that I am facing when testing is that quasar components are not rendering in HTML elements, so when I try to set a text on an element vitest does not identify it as an HTML element and I get the next error:
Error: wrapper.setValue() cannot be called on Q-INPUT
 ❯ DOMWrapper.setValue node_modules/@vue/test-utils/dist/vue-test-utils.cjs.js:7417:19
 ❯ src/modules/Auth/LoginView.spec.ts:8:60
      6|   const wrapper = mount(LoginView)
      7|   test('should render correctly', async() => {
      8|     const inputEmail = await wrapper.get('[label="Email"]').setValue('andres@correo.com')
       |

I tried a console.log(wrapper.get('[label="Email"]').html()) and I got the follow:
<q-input type="text" filled="" label="Email" placeholder="correo@correo.com" lazy-rules="" modelvalue="" rules="(val) => val && val.length > 0 || "El correo es obligatorio",(val) => {
  const emailPattern = /^(?=[a-zA-Z0-9@._%+-]{6,254}$)[a-zA-Z0-9._%+-]{1,64}@(?:[a-zA-Z0-9-]{1,63}\.){1,8}[a-zA-Z]{2,63}$/;
  return emailPattern.test(val) || "No es un correo valido";
}" data-v-5d16ad28=""></q-input>

As you can see the element is not being "transformed" to an HTML tag. Is it possible an integration of quasar with vitest? If it is, could you please let me know how it should be ?
TIA

A: The OP found their answer on this GitHub discussion on Quasar's repository. I am linking it here for future wanderers.

For anyone facing the same issue, I just made it work with
@yusufkandemir recommendation but with a different approach than the
one I showed before. I'll let my code below: vite.config.ts:
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
import { quasar, transformAssetUrls } from '@quasar/vite-plugin'

// https://vitejs.dev/config/
export default defineConfig({
  test: {
    environment: 'jsdom'
  },
  plugins: [
    vue({
      template: { transformAssetUrls }
    }),
    quasar({
      sassVariables: 'src/quasar-variables.sass'
    })
  ],
})

Implementation of quasar plugin in test:
import { test, expect, describe } from 'vitest'
import { mount } from '@vue/test-utils'
import { Quasar } from 'quasar'

import HelloWorld from "../components/HelloWorld.vue"

const wrapperFactory = () => mount(HelloWorld, {
  global: {
    plugins: [Quasar]
  },
})

test('mount component', () => {
  expect(HelloWorld).toBeTruthy();
  const wrapper = wrapperFactory();

  console.log(wrapper.html());
})

Now, when it prints the html from the wrapper, Quasar elements are being shown as simple HTML
elements.


text:
Q: Golang: Как передать по ссылке переменную interface{} вместо *string Вопрос: как это сделать?
пример:
package main

import (
    "fmt"
    "strings"
)

func MakeUpper(s *string) {
    *s = strings.ToUpper(*s)
}

func main() {
    x := "qwe"
    fmt.Println(x) // qwe
    MakeUpper(&x)
    fmt.Println(x) // QWE
    y := interface{}("asd")
    fmt.Println(y) // asd
    // MakeUpper(y) // cannot use y (type interface {}) as type *string in argument to MakeUpper: need type assertion
    // MakeUpper(&y) // cannot use &y (type *interface {}) as type *string in argument to MakeUpper

    // MakeUpper(&string(y)) // cannot convert y (type interface {}) to type string: need type assertion
    // MakeUpper(*string(&y)) // cannot convert &y (type *interface {}) to type string

    // ok, using type assertion:
    // MakeUpper(&y.(string)) // cannot take the address of y.(string)
    // MakeUpper((&y).(*string)) // invalid type assertion: (&y).(string) (non-interface type *interface {} on left)
    // MakeUpper(y.(*string)) // panic: interface conversion: interface {} is string, not *string

    // Works:
    fmt.Println(strings.ToUpper(y.(string))) // ASD

}

зачем нужно?
хочу сделать структуру (user type), содержащую поле типа interface{}, и использовать это поле в библиотечных функциях, принимающих аргумент по ссылке.
раньше прогал на python - подобных проблем в принципе не существовало)
даже в java можно сделать тип Object и (String)x потом, к примеру.
возможно ли вообще это сделать в golang, и как?)
самым логичным и правильным с точки зрения синтаксиса кажется
MakeUpper(&y.(string)) // cannot take the address of y.(string)

Невозможно получить адрес - связано с тем, что string и interface{}, содержащий string, выглядят в памяти по разному?
как тогда быть? хранить в структуре универсальный указатель *interface{} ?
var z *interface{}
z = &x // cannot use &x (type *string) as type *interface {} in assignment:
       // *interface {} is pointer to interface, not interface

так тоже не работает. как создать аналог void*?

A: // test
package main

import (
    "fmt"
    "strings"
)

func MakeUpper(s *string) {
    *s = strings.ToUpper(*s)
}

func main() {
    x := "qwe"
    var y interface{}
    y = &x
    MakeUpper(y.(*string))
    fmt.Println(*y.(*string))

}

вот так заработало... (внезапно)


text:
Q: Need to detect programatically which version of MS Office is installed without false positives/negatives I need a way that works all the time, not just most of the times.
So far I've been using the method of checking if "HKLM\Software\Microsoft\Office\14.0\Word\InstallRoot" registry key exists (14.0 is for Word 2010 here).
However I recently had a false negative, a user who had Word 2010 installed but didn't have the key. His registry had HKLM\Software\Microsoft\Office\14.0\Word, but not HKLM\Software\Microsoft\Office\14.0\Word\InstallRoot. This caused my program to install an old version of my toolbar which isn't optimized for the ribbon interface.
And I've had a false positive, too, a user who had installed Word 2007 previously, but then uninstalled it, and replaced it with Word 2003. But there were registry keys from Office 2007 lying around, which fooled my installer and it installed a toolbar that is optimized for ribbons but which can't be loaded at all in Word 2003.
So is there a better way to detect the version of Office?

A: One way to fetch the "active" version of Word irrespective of prior/fragmentary installs is to request the version of the currently registered automation server;
[Code]
function WordVer(dummy: String): String;
var
  Obj: Variant;
begin
  try
    Obj := CreateOleObject('Word.Application');
    Result := Obj.Version;
    Obj.Quit(False);
  except
    RaiseException('not installed');
  end;
end;

and using the scripted constant {code:WordVer} to get the version string (12.0 etc).