问:
valgrind for Android devices (Crystax). configure: error: C compiler cannot create executables
Using and adapting the script(https://gist.github.com/smits/27060b310546ca6f76568f24838118c3) I get and error " C compiler cannot create executables":

```<code>#!/usr/bin/env bash

#set -x

function extract()
{
     if [ -f "$1" ] ; then
         case "$1" in
             *.tar.bz2)   tar xvjf "$1"     ;;
             *.tar.gz)    tar xvzf "$1"     ;;
             *.bz2)       bunzip2 "$1"      ;;
             *.rar)       unrar x "$1"      ;;
             *.gz)        gunzip "$1"       ;;
             *.tar)       tar xvf "$1"      ;;
             *.tbz2)      tar xvjf "$1"     ;;
             *.tgz)       tar xvzf "$1"     ;;
             *.zip)       unzip "$1"        ;;
             *.Z)         uncompress "$1"   ;;
             *.7z)        7z x "$1"         ;;
             *)           echo "$1 cannot be extracted via >extract<" ;;
         esac
     else
         echo "'$1' is not a valid file"
     fi
}

VALGRIND_VERSION="3.15.0"
VALGRIND_EXTENSION=".tar.bz2"
VALGRIND_DIRECTORY="valgrind-${VALGRIND_VERSION}"
VALGRIND_TARBALL="valgrind-${VALGRIND_VERSION}${VALGRIND_EXTENSION}"

# Only download Valgrind tarball again if not already downloaded
if [[ ! -f "${VALGRIND_TARBALL}" ]]; then
  wget -v -nc "https://sourceware.org/pub/valgrind/${VALGRIND_TARBALL}"
fi

# Only extract Valgrind tarball again if not already extracted
if [[ ! -d "$VALGRIND_DIRECTORY" ]]; then
  extract "$VALGRIND_TARBALL"
fi

# Ensure ANDROID_NDK is set
#if [[ ! -z "$ANDROID_NDK" ]]; then
  export ANDROID_NDK="/home/userhome/src/crystax-ndk-10.3.1"
#fi

# Ensure ANDOID_SDK_HOME is set
#if [[ ! -z "$ANDROID_SDK" ]]; then
  #export ANDROID_SDK="/opt/android-sdk-linux/"
#fi

if [[ ! -d "$VALGRIND_DIRECTORY" ]];
then
  echo "Problem with extracting Valgrind from $VALGRIND_TARBALL into $VALGRIND_DIRECTORY!!!"
  exit -1
fi

# Move to extracted directory
cd "$VALGRIND_DIRECTORY"

# ARM Toolchain
export PATH=$ANDROID_NDK/toolchains/${ARCH_ABI}/prebuilt/linux-x86_64/bin:$PATH
ARCH_ABI="arm-linux-androideabi-6"
export AR="$ANDROID_NDK/toolchains/${ARCH_ABI}/prebuilt/linux-x86_64/bin/arm-linux-androideabi-ar"
export LD="$ANDROID_NDK/toolchains/${ARCH_ABI}/prebuilt/linux-x86_64/bin/arm-linux-androideabi-ld"
export CC="$ANDROID_NDK/toolchains/${ARCH_ABI}/prebuilt/linux-x86_64/bin/arm-linux-androideabi-gcc"
export CXX="$ANDROID_NDK/toolchains/${ARCH_ABI}/prebuilt/linux-x86_64/bin/arm-linux-androideabi-g++"
export RANLIB="$ANDROID_NDK/toolchains/${ARCH_ABI}/prebuilt/linux-x86_64/bin/arm-linux-androideabi-ranlib"
export AS="$ANDROID_NDK/toolchains/${ARCH_ABI}/prebuilt/linux-x86_64/bin/arm-linux-androideabi-as"
export CPP="$ANDROID_NDK/toolchains/${ARCH_ABI}/prebuilt/linux-x86_64/bin/arm-linux-androideabi-cpp"

echo $ANDROID_NDK
echo $AR
echo $LD
echo $CC
echo $CXX

[[ ! -d "$ANDROID_NDK" || ! -f "$AR" || ! -f "$LD" || ! -f "$CC" || ! -f "$CXX" ]] && echo "Make sure AR, LD, CC, CXX variables are defined correctly. Ensure ANDROID_NDK is defined also" && exit -1

# Configure build
export HWKIND="generic"
ANDROID_PLATFORM=android-21
export CPPFLAGS="--sysroot=$ANDROID_NDK/platforms/${ANDROID_PLATFORM}/arch-arm -DANDROID_HARDWARE_$HWKIND"
export CFLAGS="--sysroot=$ANDROID_NDK/platforms/${ANDROID_PLATFORM}/arch-arm"

# BUG: For some reason file command is unable to detect if the file does not exist with ! -f , it says it doesn't exist even when it does!!!
BUILD=true
if [[ "${VALGRIND_DIRECTORY}/Inst/data/local/Inst/bin/valgrind" = *"No such file or directory"* ]]; then
  BUILD=true
fi

if [[ "$BUILD" = true ]];
then
  ./configure --prefix="/data/local/Inst" \
  --host="armv7-unknown-linux" \
  --target="armv7-unknown-linux" \
  --with-tmpdir="/sdcard"

  [[ $? -ne 0 ]] && echo "Can't configure!" && exit -1

  # Determine the number of jobs (commands) to be run simultaneously by GNU Make
  NO_CPU_CORES=$(grep -c ^processor /proc/cpuinfo)

  if [ $NO_CPU_CORES -le 8 ]; then
    JOBS=$(($NO_CPU_CORES+1))
  else
    JOBS=${NO_CPU_CORES}
  fi

  # Compile Valgrind
  make -j "${JOBS}"

  [[ $? -ne 0 ]] && echo "Can't compile!" && exit -1

  # Install Valgrind locally
  make -j "${JOBS}" install DESTDIR="$(pwd)/Inst"
  [[ $? -ne 0 ]] && echo "Can't install!" && exit -1
fi

# Push local Valgrind installtion to the phone
if [[ $(adb shell ls -ld /data/local/Inst/bin/valgrind) = *"No such file or directory"* ]];
then
  adb root
  adb remount
  adb shell "[ ! -d /data/local/Inst ] && mkdir /data/local/Inst"
  adb push Inst /
  adb shell "ls -l /data/local/Inst"

  # Ensure Valgrind on the phone is running
  adb shell "/data/local/Inst/bin/valgrind --version"

  # Add Valgrind executable to PATH (this might fail)
  adb shell "export PATH=$PATH:/data/local/Inst/bin/"
fi
</code>```

I got the following error ( C compiler cannot create executables):

```<code>checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for armv7-unknown-linux-strip... no
checking for strip... strip
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking whether to enable maintainer-specific portions of Makefiles... no
checking whether ln -s works... yes
checking for armv7-unknown-linux-gcc... /home/rubvacalz/src/crystax-ndk-10.3.1/toolchains/arm-linux-androideabi-6/prebuilt/linux-x86_64/bin/arm-linux-androideabi-gcc
checking whether the C compiler works... no
configure: error: in `/home/rubvacalz/src/valgrind-3.15.0':
configure: error: C compiler cannot create executables
See `config.log' for more details
Can't configure!
</code>```

And config.log says "error: cannot find -lcrystax":

```<code>configure:3723: checking whether the C compiler works
configure:3745: /home/rubvacalz/src/crystax-ndk-10.3.1/toolchains/arm-linux-androideabi-6/prebuilt/linux-x86_64/bin/arm-linux-androideabi-gcc --sysroot=/home/rubvacalz/src/crystax-ndk-10.3.1/platforms/android-21/arch-arm --sysroot=/home/rubvacalz/src/crystax-ndk-10.3.1/platforms/android-21/arch-arm -DANDROID_HARDWARE_yellowstone  conftest.c  >&5
/home/rubvacalz/src/crystax-ndk-10.3.1/toolchains/arm-linux-androideabi-6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/6.1/../../../../arm-linux-androideabi/bin/ld: **error: cannot find -lcrystax**
collect2: error: ld returned 1 exit status
configure:3749: $? = 1
configure:3787: result: no
configure: failed program was:
</code>```

I don't know if the following includes are required and I don't know if it is included in the script process.

```<code>-I/home/userhome/src/crystax-ndk-10.3.1/sources/crystax/include -I/home/userhome/src/crystax-ndk-10.3.1/platforms/android-21/arch-arm/usr/include -I/home/userhome/src/crystax-ndk-10.3.1/sources/cxx-stl/gnu-libstdc++/6/include -I/home/userhome/src/crystax-ndk-10.3.1/sources/cxx-stl/gnu-libstdc++/6/libs/armeabi-v7a/include -I/home/userhome/src/crystax-ndk-10.3.1/sources/cxx-stl/gnu-libstdc++/6/include/backward
</code>```

答:
I fix the problem. It just add in the script the lines:

export LDFLAGS="-L/home/userhome/src/crystax-ndk-10.3.1/sources/crystax/libs/armeabi-v7a/thumb"

export LIBS="-lcrystax"

Body:
Using and adapting the script(https://gist.github.com/smits/27060b310546ca6f76568f24838118c3) I get and error " C compiler cannot create executables":

#!/usr/bin/env bash

#set -x

function extract()
{
     if [ -f "$1" ] ; then
         case "$1" in
             *.tar.bz2)   tar xvjf "$1"     ;;
             *.tar.gz)    tar xvzf "$1"     ;;
             *.bz2)       bunzip2 "$1"      ;;
             *.rar)       unrar x "$1"      ;;
             *.gz)        gunzip "$1"       ;;
             *.tar)       tar xvf "$1"      ;;
             *.tbz2)      tar xvjf "$1"     ;;
             *.tgz)       tar xvzf "$1"     ;;
             *.zip)       unzip "$1"        ;;
             *.Z)         uncompress "$1"   ;;
             *.7z)        7z x "$1"         ;;
             *)           echo "$1 cannot be extracted via >extract<" ;;
         esac
     else
         echo "'$1' is not a valid file"
     fi
}

VALGRIND_VERSION="3.15.0"
VALGRIND_EXTENSION=".tar.bz2"
VALGRIND_DIRECTORY="valgrind-${VALGRIND_VERSION}"
VALGRIND_TARBALL="valgrind-${VALGRIND_VERSION}${VALGRIND_EXTENSION}"

# Only download Valgrind tarball again if not already downloaded
if [[ ! -f "${VALGRIND_TARBALL}" ]]; then
  wget -v -nc "https://sourceware.org/pub/valgrind/${VALGRIND_TARBALL}"
fi

# Only extract Valgrind tarball again if not already extracted
if [[ ! -d "$VALGRIND_DIRECTORY" ]]; then
  extract "$VALGRIND_TARBALL"
fi

# Ensure ANDROID_NDK is set
#if [[ ! -z "$ANDROID_NDK" ]]; then
  export ANDROID_NDK="/home/userhome/src/crystax-ndk-10.3.1"
#fi

# Ensure ANDOID_SDK_HOME is set
#if [[ ! -z "$ANDROID_SDK" ]]; then
  #export ANDROID_SDK="/opt/android-sdk-linux/"
#fi

if [[ ! -d "$VALGRIND_DIRECTORY" ]];
then
  echo "Problem with extracting Valgrind from $VALGRIND_TARBALL into $VALGRIND_DIRECTORY!!!"
  exit -1
fi

# Move to extracted directory
cd "$VALGRIND_DIRECTORY"

# ARM Toolchain
export PATH=$ANDROID_NDK/toolchains/${ARCH_ABI}/prebuilt/linux-x86_64/bin:$PATH
ARCH_ABI="arm-linux-androideabi-6"
export AR="$ANDROID_NDK/toolchains/${ARCH_ABI}/prebuilt/linux-x86_64/bin/arm-linux-androideabi-ar"
export LD="$ANDROID_NDK/toolchains/${ARCH_ABI}/prebuilt/linux-x86_64/bin/arm-linux-androideabi-ld"
export CC="$ANDROID_NDK/toolchains/${ARCH_ABI}/prebuilt/linux-x86_64/bin/arm-linux-androideabi-gcc"
export CXX="$ANDROID_NDK/toolchains/${ARCH_ABI}/prebuilt/linux-x86_64/bin/arm-linux-androideabi-g++"
export RANLIB="$ANDROID_NDK/toolchains/${ARCH_ABI}/prebuilt/linux-x86_64/bin/arm-linux-androideabi-ranlib"
export AS="$ANDROID_NDK/toolchains/${ARCH_ABI}/prebuilt/linux-x86_64/bin/arm-linux-androideabi-as"
export CPP="$ANDROID_NDK/toolchains/${ARCH_ABI}/prebuilt/linux-x86_64/bin/arm-linux-androideabi-cpp"

echo $ANDROID_NDK
echo $AR
echo $LD
echo $CC
echo $CXX

[[ ! -d "$ANDROID_NDK" || ! -f "$AR" || ! -f "$LD" || ! -f "$CC" || ! -f "$CXX" ]] && echo "Make sure AR, LD, CC, CXX variables are defined correctly. Ensure ANDROID_NDK is defined also" && exit -1

# Configure build
export HWKIND="generic"
ANDROID_PLATFORM=android-21
export CPPFLAGS="--sysroot=$ANDROID_NDK/platforms/${ANDROID_PLATFORM}/arch-arm -DANDROID_HARDWARE_$HWKIND"
export CFLAGS="--sysroot=$ANDROID_NDK/platforms/${ANDROID_PLATFORM}/arch-arm"

# BUG: For some reason file command is unable to detect if the file does not exist with ! -f , it says it doesn't exist even when it does!!!
BUILD=true
if [[ "${VALGRIND_DIRECTORY}/Inst/data/local/Inst/bin/valgrind" = *"No such file or directory"* ]]; then
  BUILD=true
fi

if [[ "$BUILD" = true ]];
then
  ./configure --prefix="/data/local/Inst" \
  --host="armv7-unknown-linux" \
  --target="armv7-unknown-linux" \
  --with-tmpdir="/sdcard"

  [[ $? -ne 0 ]] && echo "Can't configure!" && exit -1

  # Determine the number of jobs (commands) to be run simultaneously by GNU Make
  NO_CPU_CORES=$(grep -c ^processor /proc/cpuinfo)

  if [ $NO_CPU_CORES -le 8 ]; then
    JOBS=$(($NO_CPU_CORES+1))
  else
    JOBS=${NO_CPU_CORES}
  fi

  # Compile Valgrind
  make -j "${JOBS}"

  [[ $? -ne 0 ]] && echo "Can't compile!" && exit -1

  # Install Valgrind locally
  make -j "${JOBS}" install DESTDIR="$(pwd)/Inst"
  [[ $? -ne 0 ]] && echo "Can't install!" && exit -1
fi

# Push local Valgrind installtion to the phone
if [[ $(adb shell ls -ld /data/local/Inst/bin/valgrind) = *"No such file or directory"* ]];
then
  adb root
  adb remount
  adb shell "[ ! -d /data/local/Inst ] && mkdir /data/local/Inst"
  adb push Inst /
  adb shell "ls -l /data/local/Inst"

  # Ensure Valgrind on the phone is running
  adb shell "/data/local/Inst/bin/valgrind --version"

  # Add Valgrind executable to PATH (this might fail)
  adb shell "export PATH=$PATH:/data/local/Inst/bin/"
fi

I got the following error ( C compiler cannot create executables):

checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for armv7-unknown-linux-strip... no
checking for strip... strip
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking whether to enable maintainer-specific portions of Makefiles... no
checking whether ln -s works... yes
checking for armv7-unknown-linux-gcc... /home/rubvacalz/src/crystax-ndk-10.3.1/toolchains/arm-linux-androideabi-6/prebuilt/linux-x86_64/bin/arm-linux-androideabi-gcc
checking whether the C compiler works... no
configure: error: in `/home/rubvacalz/src/valgrind-3.15.0':
configure: error: C compiler cannot create executables
See `config.log' for more details
Can't configure!

And config.log says "error: cannot find -lcrystax":

configure:3723: checking whether the C compiler works
configure:3745: /home/rubvacalz/src/crystax-ndk-10.3.1/toolchains/arm-linux-androideabi-6/prebuilt/linux-x86_64/bin/arm-linux-androideabi-gcc --sysroot=/home/rubvacalz/src/crystax-ndk-10.3.1/platforms/android-21/arch-arm --sysroot=/home/rubvacalz/src/crystax-ndk-10.3.1/platforms/android-21/arch-arm -DANDROID_HARDWARE_yellowstone  conftest.c  >&5
/home/rubvacalz/src/crystax-ndk-10.3.1/toolchains/arm-linux-androideabi-6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/6.1/../../../../arm-linux-androideabi/bin/ld: **error: cannot find -lcrystax**
collect2: error: ld returned 1 exit status
configure:3749: $? = 1
configure:3787: result: no
configure: failed program was:

I don't know if the following includes are required and I don't know if it is included in the script process.

-I/home/userhome/src/crystax-ndk-10.3.1/sources/crystax/include -I/home/userhome/src/crystax-ndk-10.3.1/platforms/android-21/arch-arm/usr/include -I/home/userhome/src/crystax-ndk-10.3.1/sources/cxx-stl/gnu-libstdc++/6/include -I/home/userhome/src/crystax-ndk-10.3.1/sources/cxx-stl/gnu-libstdc++/6/libs/armeabi-v7a/include -I/home/userhome/src/crystax-ndk-10.3.1/sources/cxx-stl/gnu-libstdc++/6/include/backward


来源: stackexchange

问:
How can I create columns out of a nested dictionary in python pandas
I'm trying to filter my data frame by making separate columns to increase readability and usability.

Problem statement:
Column "Editables" has a nested dictionary as the value I'm trying to create separate columns as per the key. For instance 'photo_repace' 'text_remove', 'text_add' has different columns.

The nested dictionary:

```<code>{
'photo': {
    'photo_replace': None,
    'photo_remove': None,
    'photo_add': None,
    'photo_effect': None,
    'photo_brightness': None,
    'background_color': None,
    'photo_resize': None,
    'photo_rotate': None,
    'photo_mirror': None,
    'photo_layer_rearrange': None,
    'photo_move': None
},
'text': {
    'text_remove': None,
    'text_add': None,
    'text_edit': None,
    'font_select': None,
    'text_color': None,
    'text_style': None,
    'background_color': None,
    'text_align': None,
    'text_resize': None,
    'text_rotate': None,
    'text_move': None,
    'text_layer_rearrange': None
}
}

</code>```

Output

Code I've been using:

```<code>df["editables"] = df["editables"].apply(lambda x : dict(eval(x)))
df_edit = df["editables"].apply(pd.Series )
</code>```

Output:

答:
Use json.json_normalize per rows and concat, last remove values before first . in columns names:

```<code>from pandas.io.json import json_normalize

c = ['photo.photo_replace', 'photo.photo_remove', 'text.text_remove']
df = pd.concat([json_normalize(x)[c] for x in df['editables']], ignore_index=True)
df.columns = df.columns.str.split('.').str[1]
print (df)
  photo_replace photo_remove text_remove
0          None         None        None
1          None         None        None
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to filter my data frame by making separate columns to increase readability and usability.

Problem statement:
Column "Editables" has a nested dictionary as the value I'm trying to create separate columns as per the key. For instance 'photo_repace' 'text_remove', 'text_add' has different columns.

The nested dictionary:

{
'photo': {
    'photo_replace': None,
    'photo_remove': None,
    'photo_add': None,
    'photo_effect': None,
    'photo_brightness': None,
    'background_color': None,
    'photo_resize': None,
    'photo_rotate': None,
    'photo_mirror': None,
    'photo_layer_rearrange': None,
    'photo_move': None
},
'text': {
    'text_remove': None,
    'text_add': None,
    'text_edit': None,
    'font_select': None,
    'text_color': None,
    'text_style': None,
    'background_color': None,
    'text_align': None,
    'text_resize': None,
    'text_rotate': None,
    'text_move': None,
    'text_layer_rearrange': None
}
}

Output

Code I've been using:

df["editables"] = df["editables"].apply(lambda x : dict(eval(x)))
df_edit = df["editables"].apply(pd.Series )

Output:

Body:
Use json.json_normalize per rows and concat, last remove values before first . in columns names:

from pandas.io.json import json_normalize

c = ['photo.photo_replace', 'photo.photo_remove', 'text.text_remove']
df = pd.concat([json_normalize(x)[c] for x in df['editables']], ignore_index=True)
df.columns = df.columns.str.split('.').str[1]
print (df)
  photo_replace photo_remove text_remove
0          None         None        None
1          None         None        None


问:
Suggest good UI framework for react-native app. I used expo to create project
i need some good ui components library for react-native like react material ui for react web applications

Please suggest a library that you have used in you projects

答:
React Native Elements

As a cross-platform UI Toolkit, you can now use RNE on the web & share your codebase between your React Native + React web apps.

View

Nativebase

Essential cross-platform UI components for React Native & Vue Native

View

React Native Material UI

Highly customizable material design components for React Native.

View

UI Kitten

React Native framework for creating stunning cross-platform mobile applications. Design system based brings your product from MVP to enterprise. Forever Open Source and free.

View

React Native UI Lib

View


问:
Related to user object ain't beeing created Django
thanks for your time:

i've been having a problem on my POST request its getting me de code 302.0

it should create a object that is related to the user that did the request:

views.py:

```<code>@login_required
@transaction.atomic
def parceiros_create(request):
    if request.method == 'POST':
        form = ParceirosForm(request.POST, instance=request.user.parceiros)
        if form.is_valid():
            form.save()
            messages.success(request, ('Parceiro criado'))
            return redirect('home2')
        else:
            messages.error(request, ('Please correct the error below.'))
    else:
        form = ParceirosForm(instance=request.user)
    context = {
        'form': form,
    }
    return render (request, 'parceiroform.html', context)

</code>```

forms.py:

```<code>class ParceirosForm(forms.ModelForm):
    nome = forms.CharField(max_length=200)
    endereco = forms.TextInput()
    responsavel = forms.CharField(max_length=100)
    tel = PhoneField(max_length=12)

    class Meta:
        prefix = 'parceiro'
        model = Parceiros
        fields = ['nome', 'endereco', 'responsavel', 'tel']

</code>```

models.py:

```<code>get_user_model = User

class Parceiros (models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    nome = models.CharField(max_length=200)
    endereco = models.TextField(max_length=400, blank=True)
    responsavel = models.CharField(max_length=100)
    tel = PhoneField(max_length=12)
    created_at = models.DateTimeField(auto_now=True)
    updated_at = models.DateTimeField(auto_now_add=True, blank=True)
    ativo = models.BooleanField(default=False)

    def __str__(self):
        return '%s %s' % (self.user, self.nome)

</code>```

parceiroform.html:

```<code>{% extends 'base.html' %}

{% block content %}

<h1>ok</h1>
<h1>OK</h1>
<h1>ok</h1>

<form method="POST">
    {% csrf_token %}
    {{form.as_p}}
    <button type="submit">Save</button>
</form>
{% endblock %}
</code>```

i'm getting the message (parceiro criado) on my admin although ain't creating any object(Parceiros).

答:
You are not handling the user so change it like this</p>

```<code>if form.is_valid():
      obj = form.save(commit=False)
      obj.user = request.user
      obj.save()
      ....
</code>```

Body:
thanks for your time:

i've been having a problem on my POST request its getting me de code 302.0

it should create a object that is related to the user that did the request:

views.py:

@login_required
@transaction.atomic
def parceiros_create(request):
    if request.method == 'POST':
        form = ParceirosForm(request.POST, instance=request.user.parceiros)
        if form.is_valid():
            form.save()
            messages.success(request, ('Parceiro criado'))
            return redirect('home2')
        else:
            messages.error(request, ('Please correct the error below.'))
    else:
        form = ParceirosForm(instance=request.user)
    context = {
        'form': form,
    }
    return render (request, 'parceiroform.html', context)

forms.py:

class ParceirosForm(forms.ModelForm):
    nome = forms.CharField(max_length=200)
    endereco = forms.TextInput()
    responsavel = forms.CharField(max_length=100)
    tel = PhoneField(max_length=12)

    class Meta:
        prefix = 'parceiro'
        model = Parceiros
        fields = ['nome', 'endereco', 'responsavel', 'tel']

models.py:

get_user_model = User

class Parceiros (models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    nome = models.CharField(max_length=200)
    endereco = models.TextField(max_length=400, blank=True)
    responsavel = models.CharField(max_length=100)
    tel = PhoneField(max_length=12)
    created_at = models.DateTimeField(auto_now=True)
    updated_at = models.DateTimeField(auto_now_add=True, blank=True)
    ativo = models.BooleanField(default=False)

    def __str__(self):
        return '%s %s' % (self.user, self.nome)

parceiroform.html:

{% extends 'base.html' %}

{% block content %}

ok

OK

ok

<form method="POST">
    {% csrf_token %}
    {{form.as_p}}
    <button type="submit">Save</button>
</form>
{% endblock %}

i'm getting the message (parceiro criado) on my admin although ain't creating any object(Parceiros).

Body:
You are not handling the user so change it like this

if form.is_valid():
      obj = form.save(commit=False)
      obj.user = request.user
      obj.save()
      ....


问:
TypeError: AutoProxy object is not iterable - multiprocessing
consider the following server code :

```<code>from multiprocessing.managers import BaseManager, BaseProxy

def baz(aa) :
    print "aaa"
    l = []
    for i in range(3) :
      l.append(aa)
    return l

class SolverManager(BaseManager): pass

manager = SolverManager(address=('127.0.0.1', 50000), authkey='mpm')
manager.register('solver', baz)

server = manager.get_server()
server.serve_forever()
</code>```

and the associated client :

```<code>import sys
from multiprocessing.managers import BaseManager, BaseProxy

class SolverManager(BaseManager): pass

def main(args) :
    SolverManager.register('solver')
    m = SolverManager(address=('127.0.0.1', 50000), authkey='mpm')
    m.connect()

    for i in m.solver(args[1]):
        print i

if __name__ == '__main__':
    sys.exit(main(sys.argv))
</code>```

I think I'm missing something important here. My guess is that I have to subclass the BaseProxy class to provide an iterable object, but so far I haven't managed to get it right.

when I run the client I get this error :

```<code>Traceback (most recent call last):
  File "mpmproxy.py", line 17, in <module>
    sys.exit(main(sys.argv))
  File "mpmproxy.py", line 13, in main
    for i in m.solver(args[1]):
TypeError: 'AutoProxy[solver]' object is not iterable
</code>```

however if I try to print it, the list is there ... Maybe it has also something to do with the way data is serialized between client and server ...

in the documentation there is a similar case (with a generator) and they use the following class to access the data :

```<code>class GeneratorProxy(BaseProxy):
    _exposed_ = ('next', '__next__')
    def __iter__(self):
        return self
    def next(self):
        return self._callmethod('next')
    def __next__(self):
        return self._callmethod('__next__')
</code>```

shall I do something similar ? Can anybody give me an example and explain to me how this works ?

update

To clarify : suppose I add the class :

```<code>class IteratorProxy(BaseProxy):
    def __iter__(self):
        print self
        return self
</code>```

and in the client I register the function as

```<code>SolverManager.register('solver', proxytype=IteratorProxy)
</code>```

the error I get is :

```<code>$python mpmproxy.py test
['test', 'test', 'test']
Traceback (most recent call last):
  File "mpmproxy.py", line 22, in <module>
    sys.exit(main(sys.argv))
  File "mpmproxy.py", line 18, in main
    for i in m.solver(args[1]):
TypeError: iter() returned non-iterator of type 'IteratorProxy'
</code>```

I have the impression I'm missing something stupid here ...

update 2

I think I solved this problem:

The point was to get the real value :

```<code>for i in m.solver(args[1])._getvalue():
    print i
</code>```

gosh !!! I'm not sure if this is the correct answer or just a workaround ...

答: Indeed, to be iterable your class needs to define the __iter__ method that BaseProxy defines, so I guess inheritance is the right way to go !

ContentLicense: CC BY-SA 3.0

Body:
consider the following server code :

from multiprocessing.managers import BaseManager, BaseProxy

def baz(aa) :
    print "aaa"
    l = []
    for i in range(3) :
      l.append(aa)
    return l

class SolverManager(BaseManager): pass

manager = SolverManager(address=('127.0.0.1', 50000), authkey='mpm')
manager.register('solver', baz)

server = manager.get_server()
server.serve_forever()

and the associated client :

import sys
from multiprocessing.managers import BaseManager, BaseProxy

class SolverManager(BaseManager): pass

def main(args) :
    SolverManager.register('solver')
    m = SolverManager(address=('127.0.0.1', 50000), authkey='mpm')
    m.connect()

    for i in m.solver(args[1]):
        print i

if __name__ == '__main__':
    sys.exit(main(sys.argv))

I think I'm missing something important here. My guess is that I have to subclass the BaseProxy class to provide an iterable object, but so far I haven't managed to get it right.

when I run the client I get this error :

Traceback (most recent call last):
  File "mpmproxy.py", line 17, in <module>
    sys.exit(main(sys.argv))
  File "mpmproxy.py", line 13, in main
    for i in m.solver(args[1]):
TypeError: 'AutoProxy[solver]' object is not iterable

however if I try to print it, the list is there ... Maybe it has also something to do with the way data is serialized between client and server ...

in the documentation there is a similar case (with a generator) and they use the following class to access the data :

class GeneratorProxy(BaseProxy):
    _exposed_ = ('next', '__next__')
    def __iter__(self):
        return self
    def next(self):
        return self._callmethod('next')
    def __next__(self):
        return self._callmethod('__next__')

shall I do something similar ? Can anybody give me an example and explain to me how this works ?

update

To clarify : suppose I add the class :

class IteratorProxy(BaseProxy):
    def __iter__(self):
        print self
        return self

and in the client I register the function as

SolverManager.register('solver', proxytype=IteratorProxy)

the error I get is :

$python mpmproxy.py test
['test', 'test', 'test']
Traceback (most recent call last):
  File "mpmproxy.py", line 22, in <module>
    sys.exit(main(sys.argv))
  File "mpmproxy.py", line 18, in main
    for i in m.solver(args[1]):
TypeError: iter() returned non-iterator of type 'IteratorProxy'

I have the impression I'm missing something stupid here ...

update 2

I think I solved this problem:

The point was to get the real value :

for i in m.solver(args[1])._getvalue():
    print i

gosh !!! I'm not sure if this is the correct answer or just a workaround ...


问:
MIPS Counting Number of 1's given a user input (B instruction doesn't jump in MARS)
I wrote a code in MIPS that I thought would take in a users input (decimal number), AND it with 1 and increment this by 1 and shifting the bit position left by 1 until the number reached 0, then display the number of 1s in the decimal number in its binary representation. I am not sure where I went wrong.</p>

```<code># Count number of 1s in a 32 Bit Number
#$t0 = user input
#$t1 = counter
.data
prompt: .asciiz "Enter Number: "
result: .asciiz "Number of 1s counted: "
n:  .word   0
counter:.word   0
    .text

#Prompt User for Number
    li $v0, 4       #load text stored in v0
        la $a0, prompt  #print prompt
        syscall     #call prompt string

#Get user Input
        li $v0, 5   #load number stored in v0
        la $t0, n   #load int into $t0
        syscall     #display integer

#Store user input in $t0 to do function
        move $t0, $v0   #Move value from $v0 to $t0 to modify
        la $t1, counter #load address of counter
        lw $t1, 0($t1)  #load counter to t1

AND:
    andi $t2, $t0, 1 #and user input($t0) with 1 and store in $t2
    beq  $t2, 1, loop #if t2 equals 0 branch
    srl  $t0, $t0, 1 #shift user input($t0) to right 1 position logically
    b AND       #branch this function

loop:
    add $t1, $t1, 1 #add 1 to the counter
    srl $t0, $t0, 1 #shift $to to the right 1 position logically with counter
    beqz $t0, display #If $t0 equals 0 send to display function
    b AND       #send back to AND function if not

display:
       li $v0, 4    #load text stored in v0
       la $a0, result   #print text from address a0
       syscall
       la $a0, ($t1)    #load the address of the counter to a0
       li $v0, 1      #load integer stored in v0
       syscall        #print final integer

</code>```

答:
Stepping through this code with MARS 4.5 MIPS emulator reveals that for some yet unknown reason for me b AND just does not work as should. If you write j AND instead everything will work correctly.

EDIT: As @Peter Cordes pointed out it is most likely an assembler bug.

NOTE: You could remove the whole loop part and do this in the AND section:

```<code>and:
    andi $t2, $t0, 1 #and user input($t0) with 1 and store in $t2
    add $t1, $t1, $t2 #add the result it is either 0 or 1
    srl  $t0, $t0, 1 #shift user input($t0) to right 1 position logically
    beqz $t0, display #If $t0 equals 0 send to display function
    j and       #send back to AND function if not
</code>```

Body:
I wrote a code in MIPS that I thought would take in a users input (decimal number), AND it with 1 and increment this by 1 and shifting the bit position left by 1 until the number reached 0, then display the number of 1s in the decimal number in its binary representation. I am not sure where I went wrong.

# Count number of 1s in a 32 Bit Number
#$t0 = user input
#$t1 = counter
.data
prompt: .asciiz "Enter Number: "
result: .asciiz "Number of 1s counted: "
n:  .word   0
counter:.word   0
    .text

#Prompt User for Number
    li $v0, 4       #load text stored in v0
        la $a0, prompt  #print prompt
        syscall     #call prompt string

#Get user Input
        li $v0, 5   #load number stored in v0
        la $t0, n   #load int into $t0
        syscall     #display integer

#Store user input in $t0 to do function
        move $t0, $v0   #Move value from $v0 to $t0 to modify
        la $t1, counter #load address of counter
        lw $t1, 0($t1)  #load counter to t1

AND:
    andi $t2, $t0, 1 #and user input($t0) with 1 and store in $t2
    beq  $t2, 1, loop #if t2 equals 0 branch
    srl  $t0, $t0, 1 #shift user input($t0) to right 1 position logically
    b AND       #branch this function

loop:
    add $t1, $t1, 1 #add 1 to the counter
    srl $t0, $t0, 1 #shift $to to the right 1 position logically with counter
    beqz $t0, display #If $t0 equals 0 send to display function
    b AND       #send back to AND function if not

display:
       li $v0, 4    #load text stored in v0
       la $a0, result   #print text from address a0
       syscall
       la $a0, ($t1)    #load the address of the counter to a0
       li $v0, 1      #load integer stored in v0
       syscall        #print final integer

Body:
Stepping through this code with MARS 4.5 MIPS emulator reveals that for some yet unknown reason for me b AND just does not work as should. If you write j AND instead everything will work correctly.

EDIT: As @Peter Cordes pointed out it is most likely an assembler bug.

NOTE: You could remove the whole loop part and do this in the AND section:

and:
    andi $t2, $t0, 1 #and user input($t0) with 1 and store in $t2
    add $t1, $t1, $t2 #add the result it is either 0 or 1
    srl  $t0, $t0, 1 #shift user input($t0) to right 1 position logically
    beqz $t0, display #If $t0 equals 0 send to display function
    j and       #send back to AND function if not


问:
Modal width (increase)
I want a modal to be 80% or so of a screen width. modal-lg isn't large enough. This:

```<code>.modal .modal-dialog {
  width: 80%;
}
</code>```

Doesn't work with Bootstrap 4.

答:
Try this, This was the solution that worked for me:</p>

```<code><div class="modal-dialog" style="min-width: 1500px" role="document">
</code>```

Title: Modal width (increase)

Body:
I want a modal to be 80% or so of a screen width. modal-lg isn't large enough. This:

.modal .modal-dialog {
  width: 80%;
}

Doesn't work with Bootstrap 4.

Body:
Try this, This was the solution that worked for me:

<div class="modal-dialog" style="min-width: 1500px" role="document">


问:
Why doesn't update repaint a scene?
I am making a marching cubes project in python using PyQt5 and PyOpenGL. I am trying to hide the wireframe cube which marches across the screen, referenced as mainWindow.marchingCube to disappear after cycling through. I managed to get the disappearing cycle to occur, but the cube does not actually disappear. I called the QOpenGLWidget's update function, but the cube still did not disappear.

import sys
from PyQt5.QtWidgets import (
                             QApplication, QMainWindow, QSlider,
                             QOpenGLWidget, QLabel, QPushButton
                            )
from PyQt5.QtCore import Qt
from OpenGL.GL import (
                       glLoadIdentity, glTranslatef, glRotatef,
                       glClear, glBegin, glEnd,
                       glColor3fv, glVertex3fv,
                       GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT,
                       GL_QUADS, GL_LINES
                      )
from OpenGL.GLU import gluPerspective
from numerics import sin, cos, tan, avg, rnd    #Numerics is my custom math library.
import random, time

class mainWindow(QMainWindow):    #Main class.
    shapes = []    #this will hold instances of the following classes: cube
    dataPoints = []
    zoomLevel = -10
    rotateDegreeV = -90
    rotateDegreeH = 0
    marchActive = False
    limit = -1
    meshPoints = []

    class cube():
        render = True
        solid = False
        color = (1, 1, 1)

        def config(self, x, y, z, size = 0.1, solid = False, color = (1, 1, 1)):
            self.solid = solid
            self.color = color
            self.size = size / 2
            s = self.size
            self.vertices = [
                    (-s + x, s + y, -s + z),
                    (s + x, s + y, -s + z),
                    (s + x, -s + y, -s + z),
                    (-s + x, -s + y, -s + z),
                    (-s + x, s + y, s + z),
                    (s + x, s + y, s + z),
                    (s + x, -s + y, s + z),
                    (-s + x, -s + y, s + z)
                   ]
            self.edges = [
                          (0,1), (0,3), (0,4), (2,1),
                          (2,3), (2,6), (7,3), (7,4),
                          (7,6), (5,1), (5,4), (5,6)
                         ]
            self.facets = [
                           (0, 1, 2, 3), (0, 1, 6, 5),
                           (0, 3, 7, 4), (6, 5, 1, 2),
                           (6, 7, 4, 5), (6, 7, 3, 2)
                          ]
        def show(self):
            self.render = True
        def hide(self):
            self.render = False

    class dataPoint():
        location = (0, 0, 0)
        value = 0
        shape = None
        def place(self, x, y, z):
            self.location = (x, y, z)
        def set(self, val):
            self.value = val
        def setShape(self, shape):
            self.shape = shape

    class meshPoint():
        location = (0, 0, 0)
        shape = None
        def place(self, x, y, z):
            self.location = (x, y, z)
        def setShape(self, shape):
            self.shape = shape

    def keyPressEvent(self, event):    #This is the keypress detector. I use this to determine input to edit grids.
        try:
            key = event.key()
            #print(key)
            if key == 87:
                self.rotateV(5)
            elif key == 65:
                self.rotateH(5)
            elif key == 83:
                self.rotateV(-5)
            elif key == 68:
                self.rotateH(-5)
            elif key == 67:
                self.zoom(1)
            elif key == 88:
                self.zoom(-1)
            elif key == 77:
                self.marchStep()
        except:
            pass

    def __init__(self):
        super(mainWindow, self).__init__()
        self.currentStep = 0
        self.width = 700    #Variables used for the setting of the size of everything
        self.height = 600
        self.setGeometry(0, 0, self.width + 50, self.height)    #Set the window size
        self.initData(3, 3, 3)
    def setupUI(self):
        self.openGLWidget = QOpenGLWidget(self)    #Create the GLWidget
        self.openGLWidget.setGeometry(0, 0, self.width, self.height)
        self.openGLWidget.initializeGL()
        self.openGLWidget.resizeGL(self.width, self.height)    #Resize GL's knowledge of the window to match the physical size?
        self.openGLWidget.paintGL = self.paintGL    #override the default function with my own?

        self.filterSlider = QSlider(Qt.Vertical, self)
        self.filterSlider.setGeometry(self.width + 10, int(self.height / 2) - 100, 30, 200)
        self.filterSlider.valueChanged[int].connect(self.filter)

        self.limitDisplay = QLabel(self)
        self.limitDisplay.setGeometry(self.width, int(self.height / 2) - 130, 50, 30)
        self.limitDisplay.setAlignment(Qt.AlignCenter)
        self.limitDisplay.setText('-1')

        self.marchButton = QPushButton(self)
        self.marchButton.setGeometry(self.width, int(self.height / 2) - 160, 50, 30)
        self.marchButton.setText('March!')
        self.marchButton.clicked.connect(self.marchStep)

    def marchStep(self):
        if not self.marchActive:
            marchAddr = len(self.shapes)
            self.shapes.append(self.cube())
            self.marchingCube = self.shapes[marchAddr]
            self.marchActive = True
            self.currentStep = 0
        if self.currentStep == len(self.marchPoints):
            self.currentStep = 0
            #print('meshPoints: {}'.format(self.meshPoints))
            for mp in self.meshPoints:
                #print(mp.shape)
                self.shapes.remove(mp.shape)
            self.meshPoints.clear()
            self.marchingCube.hide()
            return

        if self.currentStep == 0:
            self.marchingCube.show()

        p = self.marchPoints[self.currentStep]
        x, y, z = p
        self.marchingCube.config(x, y, z, size = 1)
        points = []
        for i in range(8):
            point = self.getDataPointByLocation(self.marchingCube.vertices[i])
            points.append(point)
        self.openGLWidget.update()
        #print('step: {}  x: {}  y: {}  z: {}'.format(self.currentStep, x, y, z))
        #for point in points:
        #    print(point.location, end = ' ')
        #print()
        for pair in self.marchingCube.edges:
            pointA = points[pair[0]]
            pointB = points[pair[1]]
            #print('pointA.value: {}  pointB.value: {}  limit: {}'.formatpointA.value, pointB.value, self.limit)
            if (pointA.value < self.limit and pointB.value > self.limit) or (pointA.value > self.limit and pointB.value < self.limit):
                xA, yA, zA = pointA.location
                xB, yB, zB = pointB.location
                valA = (pointA.value + 1) / 2
                valB = (pointB.value + 1) / 2
                xC = float(avg([xA, xB]))
                yC = float(avg([yA, yB]))
                zC = float(avg([zA, zB]))

                mp = self.meshPoint()
                mp.place(xC, yC, zC)
                mp.setShape(self.cube())
                mp.shape.config(xC, yC, zC, size = 0.05, solid = True, color = (1, 0, 0))
                self.shapes.append(mp.shape)
                self.meshPoints.append(mp)
        self.currentStep += 1
        self.openGLWidget.update()

    def zoom(self, value):
        self.zoomLevel += value
        self.openGLWidget.update()

    def rotateV(self, value):
        self.rotateDegreeV += value
        self.openGLWidget.update()

    def rotateH(self, value):
        self.rotateDegreeH += value
        self.openGLWidget.update()

    def filter(self, value):
        self.limit = rnd((value / 49.5) -1, -2)
        for d in self.dataPoints:
            if d.value < self.limit:
                d.shape.hide()
            else:
                d.shape.show()
        self.limitDisplay.setText(str(self.limit))
        self.openGLWidget.update()

    def getDataPointByLocation(self, coord):
        x, y, z = coord
        for dp in self.dataPoints:
            if dp.location == (x, y, z):
                return dp
        return False

    def paintGL(self):
        glLoadIdentity()
        gluPerspective(45, self.width / self.height, 0.1, 110.0)    #set perspective?
        glTranslatef(0, 0, self.zoomLevel)    #I used -10 instead of -2 in the PyGame version.
        glRotatef(self.rotateDegreeV, 1, 0, 0)    #I used 2 instead of 1 in the PyGame version.
        glRotatef(self.rotateDegreeH, 0, 0, 1)
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        if len(self.shapes) != 0:
            glBegin(GL_LINES)
            for s in self.shapes:
                glColor3fv(s.color)
                if s.render and not s.solid:
                    for e in s.edges:
                        for v in e:
                            glVertex3fv(s.vertices[v])
            glEnd()

            glBegin(GL_QUADS)
            for s in self.shapes:
                glColor3fv(s.color)
                if s.render and s.solid:
                    for f in s.facets:
                        for v in f:
                            glVertex3fv(s.vertices[v])
            glEnd()

    def initData(self, sizeX, sizeY, sizeZ):
        marchSizeX = sizeX - 1
        marchSizeY = sizeY - 1
        marchSizeZ = sizeZ - 1
        xOff = -(sizeX / 2) + 0.5
        yOff = -(sizeY / 2) + 0.5
        zOff = -(sizeZ / 2) + 0.5
        xMarchOff = -(marchSizeX / 2) + 0.5
        yMarchOff = -(marchSizeY / 2) + 0.5
        zMarchOff = -(marchSizeZ / 2) + 0.5
        vals = []
        self.marchPoints = []
        for z in range(marchSizeZ):
            for y in range(marchSizeY):
                for x in range(marchSizeX):
                    self.marchPoints.append((x + xMarchOff, y + yMarchOff ,z + zMarchOff))

        for z in range(sizeZ):
            for y in range(sizeY):
                for x in range(sizeX):
                    loc = len(self.dataPoints)
                    val = self.generate(x + xOff, y + yOff, z + zOff)
                    self.dataPoints.append(self.dataPoint())
                    self.dataPoints[loc].place(x + xOff, y + yOff, z + zOff)
                    self.dataPoints[loc].set(val)
                    loc2 = len(self.shapes)
                    self.shapes.append(self.cube())
                    self.shapes[loc2].config(x + xOff, y + yOff, z + zOff, solid = True, color = (0, (val + 1) / 2, (val + 1) / -2 + 1))
                    self.dataPoints[loc].setShape(self.shapes[loc2])
                    vals.append(val)
        print(avg(vals))

    def generate(self, xIn, yIn, zIn):    #Function which produces semi-random values based on the supplied coordinates.
        i = -(xIn * yIn * (10 + zIn))
        j = xIn * yIn * (10 + zIn)
        if i < j:
            mixer = random.randint(i, j)
        else:
            mixer = random.randint(j, i + 1)
        a = avg([sin(cos(xIn)), tan(tan(yIn)), cos(tan(zIn))])
        out = mixer * a
        while out > 10:
            out -= 5
        while out < -10:
            out += 5
        return float(out / 10)

app = QApplication([])
window = mainWindow()
window.setupUI()
window.show()
sys.exit(app.exec_())
```

<p>Why doesn't the cube disappear? I have caught wind during my web searches on the subject that update does not always work as expected. Directly calling <code>self.openGLWidget.paintGL()</code> does not work either. What must I do to make the cube disappear?</p>

<p>EDIT:
If I make a call to rotate, rotate, or zoom, the screen refreshes and the meshpoints as well as the marching cube all disappear. I think I may end up making a workaround by calling one of those with a zero value.</p>

<p>To test, save the following code in a file named <code>numerics.py</code> in the same directory as the rest of the code.</p>

<pre class="lang-py prettyprint-override"><code>from decimal import Decimal as dec

degrad = 'deg'
pi = 3.14159265358979323846
terms = dec(9)    #number of terms used for the trig calculations

def version():
    print('numerics.py version 1.0.0')
    print('Packaged with the cubes project')
def mode(modeinput = ''):    #switch between degrees and radians or check the current mode
    global degrad
    if modeinput == 'deg':
        degrad = 'deg'
        return 'deg'
    if modeinput == 'rad':
        degrad = 'rad'
        return 'rad'
    if modeinput == '':
        return degrad
    else:
        return False

def accuracy(accinput = ''):
    global terms
    global pi
    if accinput == '':
        return terms
    terms = dec(accinput)
    PI = calculatePi(accinput)
    print('Pi is: {}'.format(PI))
    return terms

def calculatePi(placeIn = terms):
    if placeIn > 15:
        if input("Warning: You have chosen to calculate more than 20 digits of pi. This may take a LONG TIME and may be inacurate. Enter 'yes' if you wish to proceed. If you enter anything else, this function will revert to 10 digits.") == 'yes':
            place = placeIn
        else:
            place = 10
    else:
        place = placeIn
    print('Calculating Pi...\nPlease wait, as this may take a while.')
    PI = dec(3)
    addSub = True
    for i in range(2, 2 * (int(place) ** 6) + 1, 2):
        if addSub:
            PI += dec(4) / (dec(i) * dec(i + 1) * dec(i + 2))
        elif not addSub:
            PI -= dec(4) / (dec(i) * dec(i + 1) * dec(i + 2))
        addSub = not addSub
    return rnd(PI, -(place), mode = 'cutoff')

def radToDeg(radin):
    return (dec(radin) * dec(180 / pi))

def degToRad(degin):
    return (dec(degin) * dec(pi / 180))

def avg(numsIn):    #return the average of two numbers, specified as an integer or float
    num1 = dec(0)
    for i in numsIn:
        num1 += dec(i)
    return rnd(dec(num1 / dec(len(numsIn))))

def sin(anglein, dr = degrad):    #return sine of the supplied angle using the predetermined mode or the supplied mode
    if dr == 'deg':
        while anglein > 180:
            anglein -= 360
        while anglein < -180:
            anglein += 360
        angle = degToRad(anglein)
    if dr == 'rad':
        while anglein > pi:
            anglein -= (2 * pi)
        while anglein < -pi:
            anglein += (2 * pi)
        angle = anglein
    return rnd(rawsin(dec(angle)), -terms)

def arcsin(ratioin, dr = degrad):    #return arcsine of the supplied ratio using the predetermined mode or the supplied mode
    if ratioin > 1 or ratioin < -1:    #if the input is illegal
        return False
    attempt = dec(0)    #start at 0
    target = rnd(dec(ratioin), -terms)    #identify the target value
    #print('target is: {}'.format(target))
    for i in range(-1, int(terms) + 1):    #for each place from 10s to terms decimal place (use -i, not i)
        #print('Editing place {0}'.format(10 ** -i))    #debugging
        for j in range(10):    #for 10 steps
            #print('current attempt: {}'.format(attempt), end = ' ')
            if rnd(sin(attempt, dr), -terms) == target:
                if attempt < 0:
                    final = (attempt * dec(-1))
                else:
                    final = attempt
                #print('attempt: {0} final: {1}'.format(attempt, final))
                return final
            if rnd(sin(attempt, dr), -terms) < target:
                #add some
                attempt += (dec(10) ** -i)
                #print('attempt: {}'.format(attempt), end = ' ')
            if rnd(sin(attempt, dr), -terms) > target:
                #subtract some
                attempt -= (dec(10) ** -i)
                #print('attempt: {}'.format(attempt), end = ' ')
            #print('')
    if attempt < 0:
        final = (attempt * dec(-1))
    else:
        final = attempt
    #print('attempt: {0} final: {1}'.format(attempt, final))
    return (final)

def cos(anglein, dr = degrad):    #return cosine of the supplied angle
    if dr == 'deg':
        return rawsin(degToRad(90 - anglein))
    else:
        angle = anglein
        return rnd(rawsin(90 - angle), -terms)

def arccos(ratioin, dr = degrad):    #return arccosine of the supplied ratio
    if ratioin > 1 or ratioin < -1:
        return False
    attempt = dec(0)    #start at 0
    target = rnd(dec(ratioin), -terms)    #identify the target value
    #print('target is: {}'.format(target))
    for i in range(-1, int(terms) + 1):    #for each place from 10s to terms decimal place (use -i, not i)
        #print('Editing place {0}'.format(10 ** -i))    #debugging
        for j in range(10):    #for 10 steps
            #print('current attempt: {}'.format(attempt), end = ' ')
            if rnd(cos(attempt, dr), -terms) == target:
                if attempt < 0:
                    final = (attempt * dec(-1))
                else:
                    final = attempt
                #print('attempt: {0} final: {1}'.format(attempt, final))
                return final
            if rnd(cos(attempt, dr), -terms) < target:
                #add some
                attempt += (dec(10) ** -i)
                #print('attempt: {}'.format(attempt), end = ' ')
            if rnd(cos(attempt, dr), -terms) > target:
                #subtract some
                attempt -= (dec(10) ** -i)
                #print('attempt: {}'.format(attempt), end = ' ')
            #print('')
    if attempt < 0:
        final = (attempt * dec(-1))
    else:
        final = attempt
    #print('attempt: {0} final: {1}'.format(attempt, final))
    return (final)

def tan(anglein, dr = degrad):    #return tangent of the supplied angle
    a = sin(anglein, dr)
    b = cos(anglein, dr)
    if (not a == 0) and (not b == 0):
        return rnd((a / b), -terms)
    else:
        return False

def arctan(ratioin, dr = degrad):    #return arctangent of the supplied ratio
    if ratioin > 1 or ratioin < -1:
        return False
    attempt = dec(0)    #start at 0
    target = rnd(dec(ratioin), -terms)    #identify the target value
    #print('target is: {}'.format(target))
    for i in range(-1, int(terms) + 1):    #for each place from 10s to terms decimal place (use -i, not i)
        #print('Editing place {0}'.format(10 ** -i))    #debugging
        for j in range(10):    #for 10 steps
            #print('current attempt: {}'.format(attempt), end = ' ')
            if rnd(tan(attempt, dr), -terms) == target:
                if attempt < 0:
                    final = (attempt * dec(-1))
                else:
                    final = attempt
                #print('attempt: {0} final: {1}'.format(attempt, final))
                return final
            if rnd(tan(attempt, dr), -terms) < target:
                #add some
                attempt += (dec(10) ** -i)
                #print('attempt: {}'.format(attempt), end = ' ')
            if rnd(tan(attempt, dr), -terms) > target:
                #subtract some
                attempt -= (dec(10) ** -i)
                #print('attempt: {}'.format(attempt), end = ' ')
            #print('')
    if attempt < 0:
        final = (attempt * dec(-1))
    else:
        final = attempt
    #print('attempt: {0} final: {1}'.format(attempt, final))
    return (final)

def rawsin(anglein):    #return the result of sine of the supplied angle, using radians
#This is the taylor series used.
#final = x - (x^3 / 3!) + (x^5 / 5!) - (x^7 / 7!) + (x^9 / 9!) - (x^11 / 11!)...
    angle = dec(anglein)
    final = angle
    add = False
    for i in range(3, int(terms) * 3, 2):
        if add:
            final += dec(angle ** i) / fact(i)
        elif not add:
            final -= dec(angle ** i) / fact(i)
        add = not add
    return final

def fact(intin):    #return the factorial of the given integer, return False if not given an int
    if intin == int(intin):
        intout = 1
        for i in range(1, intin + 1):
            intout *= i
        return intout
    else:
        return False

def rnd(numIn, decPlcIn = -terms, mode = 'fiveHigher'):    #return the given number, rounded to the given decimal place.
#use 1 to indicate 10s, 0 to indicate 1s, -2 to indicate 100ths, etc.
    num1 = dec(numIn)
    decPlc = dec(decPlcIn)
    if mode == 'fiveHigher':
        return dec(str(dec(round(num1 * (dec(10) ** -decPlc))) * (dec(10) ** decPlc)).rstrip('0'))
    elif mode == 'cutoff':
        return dec(str(dec(int(num1 * (dec(10) ** -decPlc))) * (dec(10) ** decPlc)).rstrip('0'))

def root(numIn, rootVal):
    num = dec(numIn)
    rt = dec(dec(1) / rootVal)
    num1 = num ** rt
    return rnd(num1, -terms)

def quad(aIn, bIn, cIn):    #Plugin for the quadratic formula. Provide a, b, and c.
    a = dec(aIn)
    b = dec(bIn)
    c = dec(cIn)
    try:
        posResult = (-b + root((b ** dec(2)) - (dec(4) * a * c), 2)) / (dec(2) * a)
    except:
        posResult = False
    try:
        negResult = (-b - root((b ** dec(2)) - (dec(4) * a * c), 2)) / (dec(2) * a)
    except:
        negResult = False
    return (posResult, negResult)
</code>```

答:
You are missing 1 call to self.openGLWidget.update(). There is a return statement in the instruction block of the if. The function is terminated at this point and the self.openGLWidget.update() instruction at the end of the code is never executed.

Add self.openGLWidget.update() right before return, to solve the issue:

class mainWindow(QMainWindow):
    # [...]

    def marchStep(self):
        if not self.marchActive:
            # [...]
            self.currentStep = 0
        if self.currentStep == len(self.marchPoints):
            # [...]
            self.meshPoints.clear()
            self.marchingCube.hide()

            self.openGLWidget.update() # <--------- ADD
            return

        if self.currentStep == 0:
            self.marchingCube.show()

        # [...]
```

Title: Why doesn't update repaint a scene?

Body:
I am making a marching cubes project in python using PyQt5 and PyOpenGL. I am trying to hide the wireframe cube which marches across the screen, referenced as mainWindow.marchingCube to disappear after cycling through. I managed to get the disappearing cycle to occur, but the cube does not actually disappear. I called the QOpenGLWidget's update function, but the cube still did not disappear.

import sys
from PyQt5.QtWidgets import (
                             QApplication, QMainWindow, QSlider,
                             QOpenGLWidget, QLabel, QPushButton
                            )
from PyQt5.QtCore import Qt
from OpenGL.GL import (
                       glLoadIdentity, glTranslatef, glRotatef,
                       glClear, glBegin, glEnd,
                       glColor3fv, glVertex3fv,
                       GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT,
                       GL_QUADS, GL_LINES
                      )
from OpenGL.GLU import gluPerspective
from numerics import sin, cos, tan, avg, rnd    #Numerics is my custom math library.
import random, time

class mainWindow(QMainWindow):    #Main class.
    shapes = []    #this will hold instances of the following classes: cube
    dataPoints = []
    zoomLevel = -10
    rotateDegreeV = -90
    rotateDegreeH = 0
    marchActive = False
    limit = -1
    meshPoints = []

    class cube():
        render = True
        solid = False
        color = (1, 1, 1)

        def config(self, x, y, z, size = 0.1, solid = False, color = (1, 1, 1)):
            self.solid = solid
            self.color = color
            self.size = size / 2
            s = self.size
            self.vertices = [
                    (-s + x, s + y, -s + z),
                    (s + x, s + y, -s + z),
                    (s + x, -s + y, -s + z),
                    (-s + x, -s + y, -s + z),
                    (-s + x, s + y, s + z),
                    (s + x, s + y, s + z),
                    (s + x, -s + y, s + z),
                    (-s + x, -s + y, s + z)
                   ]
            self.edges = [
                          (0,1), (0,3), (0,4), (2,1),
                          (2,3), (2,6), (7,3), (7,4),
                          (7,6), (5,1), (5,4), (5,6)
                         ]
            self.facets = [
                           (0, 1, 2, 3), (0, 1, 6, 5),
                           (0, 3, 7, 4), (6, 5, 1, 2),
                           (6, 7, 4, 5), (6, 7, 3, 2)
                          ]
        def show(self):
            self.render = True
        def hide(self):
            self.render = False

    class dataPoint():
        location = (0, 0, 0)
        value = 0
        shape = None
        def place(self, x, y, z):
            self.location = (x, y, z)
        def set(self, val):
            self.value = val
        def setShape(self, shape):
            self.shape = shape

    class meshPoint():
        location = (0, 0, 0)
        shape = None
        def place(self, x, y, z):
            self.location = (x, y, z)
        def setShape(self, shape):
            self.shape = shape

    def keyPressEvent(self, event):    #This is the keypress detector. I use this to determine input to edit grids.
        try:
            key = event.key()
            #print(key)
            if key == 87:
                self.rotateV(5)
            elif key == 65:
                self.rotateH(5)
            elif key == 83:
                self.rotateV(-5)
            elif key == 68:
                self.rotateH(-5)
            elif key == 67:
                self.zoom(1)
            elif key == 88:
                self.zoom(-1)
            elif key == 77:
                self.marchStep()
        except:
            pass

    def __init__(self):
        super(mainWindow, self).__init__()
        self.currentStep = 0
        self.width = 700    #Variables used for the setting of the size of everything
        self.height = 600
        self.setGeometry(0, 0, self.width + 50, self.height)    #Set the window size
        self.initData(3, 3, 3)
    def setupUI(self):
        self.openGLWidget = QOpenGLWidget(self)    #Create the GLWidget
        self.openGLWidget.setGeometry(0, 0, self.width, self.height)
        self.openGLWidget.initializeGL()
        self.openGLWidget.resizeGL(self.width, self.height)    #Resize GL's knowledge of the window to match the physical size?
        self.openGLWidget.paintGL = self.paintGL    #override the default function with my own?

        self.filterSlider = QSlider(Qt.Vertical, self)
        self.filterSlider.setGeometry(self.width + 10, int(self.height / 2) - 100, 30, 200)
        self.filterSlider.valueChanged[int].connect(self.filter)

        self.limitDisplay = QLabel(self)
        self.limitDisplay.setGeometry(self.width, int(self.height / 2) - 130, 50, 30)
        self.limitDisplay.setAlignment(Qt.AlignCenter)
        self.limitDisplay.setText('-1')

        self.marchButton = QPushButton(self)
        self.marchButton.setGeometry(self.width, int(self.height / 2) - 160, 50, 30)
        self.marchButton.setText('March!')
        self.marchButton.clicked.connect(self.marchStep)

    def marchStep(self):
        if not self.marchActive:
            marchAddr = len(self.shapes)
            self.shapes.append(self.cube())
            self.marchingCube = self.shapes[marchAddr]
            self.marchActive = True
            self.currentStep = 0
        if self.currentStep == len(self.marchPoints):
            self.currentStep = 0
            #print('meshPoints: {}'.format(self.meshPoints))
            for mp in self.meshPoints:
                #print(mp.shape)
                self.shapes.remove(mp.shape)
            self.meshPoints.clear()
            self.marchingCube.hide()
            return

        if self.currentStep == 0:
            self.marchingCube.show()

        p = self.marchPoints[self.currentStep]
        x, y, z = p
        self.marchingCube.config(x, y, z, size = 1)
        points = []
        for i in range(8):
            point = self.getDataPointByLocation(self.marchingCube.vertices[i])
            points.append(point)
        self.openGLWidget.update()
        #print('step: {}  x: {}  y: {}  z: {}'.format(self.currentStep, x, y, z))
        #for point in points:
        #    print(point.location, end = ' ')
        #print()
        for pair in self.marchingCube.edges:
            pointA = points[pair[0]]
            pointB = points[pair[1]]
            #print('pointA.value: {}  pointB.value: {}  limit: {}'.formatpointA.value, pointB.value, self.limit)
            if (pointA.value < self.limit and pointB.value > self.limit) or (pointA.value > self.limit and pointB.value < self.limit):
                xA, yA, zA = pointA.location
                xB, yB, zB = pointB.location
                valA = (pointA.value + 1) / 2
                valB = (pointB.value + 1) / 2
                xC = float(avg([xA, xB]))
                yC = float(avg([yA, yB]))
                zC = float(avg([zA, zB]))

                mp = self.meshPoint()
                mp.place(xC, yC, zC)
                mp.setShape(self.cube())
                mp.shape.config(xC, yC, zC, size = 0.05, solid = True, color = (1, 0, 0))
                self.shapes.append(mp.shape)
                self.meshPoints.append(mp)
        self.currentStep += 1
        self.openGLWidget.update()

    def zoom(self, value):
        self.zoomLevel += value
        self.openGLWidget.update()

    def rotateV(self, value):
        self.rotateDegreeV += value
        self.openGLWidget.update()

    def rotateH(self, value):
        self.rotateDegreeH += value
        self.openGLWidget.update()

    def filter(self, value):
        self.limit = rnd((value / 49.5) -1, -2)
        for d in self.dataPoints:
            if d.value < self.limit:
                d.shape.hide()
            else:
                d.shape.show()
        self.limitDisplay.setText(str(self.limit))
        self.openGLWidget.update()

    def getDataPointByLocation(self, coord):
        x, y, z = coord
        for dp in self.dataPoints:
            if dp.location == (x, y, z):
                return dp
        return False

    def paintGL(self):
        glLoadIdentity()
        gluPerspective(45, self.width / self.height, 0.1, 110.0)    #set perspective?
        glTranslatef(0, 0, self.zoomLevel)    #I used -10 instead of -2 in the PyGame version.
        glRotatef(self.rotateDegreeV, 1, 0, 0)    #I used 2 instead of 1 in the PyGame version.
        glRotatef(self.rotateDegreeH, 0, 0, 1)
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        if len(self.shapes) != 0:
            glBegin(GL_LINES)
            for s in self.shapes:
                glColor3fv(s.color)
                if s.render and not s.solid:
                    for e in s.edges:
                        for v in e:
                            glVertex3fv(s.vertices[v])
            glEnd()

            glBegin(GL_QUADS)
            for s in self.shapes:
                glColor3fv(s.color)
                if s.render and s.solid:
                    for f in s.facets:
                        for v in f:
                            glVertex3fv(s.vertices[v])
            glEnd()

    def initData(self, sizeX, sizeY, sizeZ):
        marchSizeX = sizeX - 1
        marchSizeY = sizeY - 1
        marchSizeZ = sizeZ - 1
        xOff = -(sizeX / 2) + 0.5
        yOff = -(sizeY / 2) + 0.5
        zOff = -(sizeZ / 2) + 0.5
        xMarchOff = -(marchSizeX / 2) + 0.5
        yMarchOff = -(marchSizeY / 2) + 0.5
        zMarchOff = -(marchSizeZ / 2) + 0.5
        vals = []
        self.marchPoints = []
        for z in range(marchSizeZ):
            for y in range(marchSizeY):
                for x in range(marchSizeX):
                    self.marchPoints.append((x + xMarchOff, y + yMarchOff ,z + zMarchOff))

        for z in range(sizeZ):
            for y in range(sizeY):
                for x in range(sizeX):
                    loc = len(self.dataPoints)
                    val = self.generate(x + xOff, y + yOff, z + zOff)
                    self.dataPoints.append(self.dataPoint())
                    self.dataPoints[loc].place(x + xOff, y + yOff, z + zOff)
                    self.dataPoints[loc].set(val)
                    loc2 = len(self.shapes)
                    self.shapes.append(self.cube())
                    self.shapes[loc2].config(x + xOff, y + yOff, z + zOff, solid = True, color = (0, (val + 1) / 2, (val + 1) / -2 + 1))
                    self.dataPoints[loc].setShape(self.shapes[loc2])
                    vals.append(val)
        print(avg(vals))

    def generate(self, xIn, yIn, zIn):    #Function which produces semi-random values based on the supplied coordinates.
        i = -(xIn * yIn * (10 + zIn))
        j = xIn * yIn * (10 + zIn)
        if i < j:
            mixer = random.randint(i, j)
        else:
            mixer = random.randint(j, i + 1)
        a = avg([sin(cos(xIn)), tan(tan(yIn)), cos(tan(zIn))])
        out = mixer * a
        while out > 10:
            out -= 5
        while out < -10:
            out += 5
        return float(out / 10)

app = QApplication([])
window = mainWindow()
window.setupUI()
window.show()
sys.exit(app.exec_())

Why doesn't the cube disappear? I have caught wind during my web searches on the subject that update does not always work as expected. Directly calling self.openGLWidget.paintGL() does not work either. What must I do to make the cube disappear?

EDIT:
If I make a call to rotate, rotate, or zoom, the screen refreshes and the meshpoints as well as the marching cube all disappear. I think I may end up making a workaround by calling one of those with a zero value.

To test, save the following code in a file named numerics.py in the same directory as the rest of the code.

from decimal import Decimal as dec

degrad = 'deg'
pi = 3.14159265358979323846
terms = dec(9)    #number of terms used for the trig calculations

def version():
    print('numerics.py version 1.0.0')
    print('Packaged with the cubes project')
def mode(modeinput = ''):    #switch between degrees and radians or check the current mode
    global degrad
    if modeinput == 'deg':
        degrad = 'deg'
        return 'deg'
    if modeinput == 'rad':
        degrad = 'rad'
        return 'rad'
    if modeinput == '':
        return degrad
    else:
        return False

def accuracy(accinput = ''):
    global terms
    global pi
    if accinput == '':
        return terms
    terms = dec(accinput)
    PI = calculatePi(accinput)
    print('Pi is: {}'.format(PI))
    return terms

def calculatePi(placeIn = terms):
    if placeIn > 15:
        if input("Warning: You have chosen to calculate more than 20 digits of pi. This may take a LONG TIME and may be inacurate. Enter 'yes' if you wish to proceed. If you enter anything else, this function will revert to 10 digits.") == 'yes':
            place = placeIn
        else:
            place = 10
    else:
        place = placeIn
    print('Calculating Pi...\nPlease wait, as this may take a while.')
    PI = dec(3)
    addSub = True
    for i in range(2, 2 * (int(place) ** 6) + 1, 2):
        if addSub:
            PI += dec(4) / (dec(i) * dec(i + 1) * dec(i + 2))
        elif not addSub:
            PI -= dec(4) / (dec(i) * dec(i + 1) * dec(i + 2))
        addSub = not addSub
    return rnd(PI, -(place), mode = 'cutoff')

def radToDeg(radin):
    return (dec(radin) * dec(180 / pi))

def degToRad(degin):
    return (dec(degin) * dec(pi / 180))

def avg(numsIn):    #return the average of two numbers, specified as an integer or float
    num1 = dec(0)
    for i in numsIn:
        num1 += dec(i)
    return rnd(dec(num1 / dec(len(numsIn))))

def sin(anglein, dr = degrad):    #return sine of the supplied angle using the predetermined mode or the supplied mode
    if dr == 'deg':
        while anglein > 180:
            anglein -= 360
        while anglein < -180:
            anglein += 360
        angle = degToRad(anglein)
    if dr == 'rad':
        while anglein > pi:
            anglein -= (2 * pi)
        while anglein < -pi:
            anglein += (2 * pi)
        angle = anglein
    return rnd(rawsin(dec(angle)), -terms)

def arcsin(ratioin, dr = degrad):    #return arcsine of the supplied ratio using the predetermined mode or the supplied mode
    if ratioin > 1 or ratioin < -1:    #if the input is illegal
        return False
    attempt = dec(0)    #start at 0
    target = rnd(dec(ratioin), -terms)    #identify the target value
    #print('target is: {}'.format(target))
    for i in range(-1, int(terms) + 1):    #for each place from 10s to terms decimal place (use -i, not i)
        #print('Editing place {0}'.format(10 ** -i))    #debugging
        for j in range(10):    #for 10 steps
            #print('current attempt: {}'.format(attempt), end = ' ')
            if rnd(sin(attempt, dr), -terms) == target:
                if attempt < 0:
                    final = (attempt * dec(-1))
                else:
                    final = attempt
                #print('attempt: {0} final: {1}'.format(attempt, final))
                return final
            if rnd(sin(attempt, dr), -terms) < target:
                #add some
                attempt += (dec(10) ** -i)
                #print('attempt: {}'.format(attempt), end = ' ')
            if rnd(sin(attempt, dr), -terms) > target:
                #subtract some
                attempt -= (dec(10) ** -i)
                #print('attempt: {}'.format(attempt), end = ' ')
            #print('')
    if attempt < 0:
        final = (attempt * dec(-1))
    else:
        final = attempt
    #print('attempt: {0} final: {1}'.format(attempt, final))
    return (final)

def cos(anglein, dr = degrad):    #return cosine of the supplied angle
    if dr == 'deg':
        return rawsin(degToRad(90 - anglein))
    else:
        angle = anglein
        return rnd(rawsin(90 - angle), -terms)

def arccos(ratioin, dr = degrad):    #return arccosine of the supplied ratio
    if ratioin > 1 or ratioin < -1:
        return False
    attempt = dec(0)    #start at 0
    target = rnd(dec(ratioin), -terms)    #identify the target value
    #print('target is: {}'.format(target))
    for i in range(-1, int(terms) + 1):    #for each place from 10s to terms decimal place (use -i, not i)
        #print('Editing place {0}'.format(10 ** -i))    #debugging
        for j in range(10):    #for 10 steps
            #print('current attempt: {}'.format(attempt), end = ' ')
            if rnd(cos(attempt, dr), -terms) == target:
                if attempt < 0:
                    final = (attempt * dec(-1))
                else:
                    final = attempt
                #print('attempt: {0} final: {1}'.format(attempt, final))
                return final
            if rnd(cos(attempt, dr), -terms) < target:
                #add some
                attempt += (dec(10) ** -i)
                #print('attempt: {}'.format(attempt), end = ' ')
            if rnd(cos(attempt, dr), -terms) > target:
                #subtract some
                attempt -= (dec(10) ** -i)
                #print('attempt: {}'.format(attempt), end = ' ')
            #print('')
    if attempt < 0:
        final = (attempt * dec(-1))
    else:
        final = attempt
    #print('attempt: {0} final: {1}'.format(attempt, final))
    return (final)

def tan(anglein, dr = degrad):    #return tangent of the supplied angle
    a = sin(anglein, dr)
    b = cos(anglein, dr)
    if (not a == 0) and (not b == 0):
        return rnd((a / b), -terms)
    else:
        return False

def arctan(ratioin, dr = degrad):    #return arctangent of the supplied ratio
    if ratioin > 1 or ratioin < -1:
        return False
    attempt = dec(0)    #start at 0
    target = rnd(dec(ratioin), -terms)    #identify the target value
    #print('target is: {}'.format(target))
    for i in range(-1, int(terms) + 1):    #for each place from 10s to terms decimal place (use -i, not i)
        #print('Editing place {0}'.format(10 ** -i))    #debugging
        for j in range(10):    #for 10 steps
            #print('current attempt: {}'.format(attempt), end = ' ')
            if rnd(tan(attempt, dr), -terms) == target:
                if attempt < 0:
                    final = (attempt * dec(-1))
                else:
                    final = attempt
                #print('attempt: {0} final: {1}'.format(attempt, final))
                return final
            if rnd(tan(attempt, dr), -terms) < target:
                #add some
                attempt += (dec(10) ** -i)
                #print('attempt: {}'.format(attempt), end = ' ')
            if rnd(tan(attempt, dr), -terms) > target:
                #subtract some
                attempt -= (dec(10) ** -i)
                #print('attempt: {}'.format(attempt), end = ' ')
            #print('')
    if attempt < 0:
        final = (attempt * dec(-1))
    else:
        final = attempt
    #print('attempt: {0} final: {1}'.format(attempt, final))
    return (final)

def rawsin(anglein):    #return the result of sine of the supplied angle, using radians
#This is the taylor series used.
#final = x - (x^3 / 3!) + (x^5 / 5!) - (x^7 / 7!) + (x^9 / 9!) - (x^11 / 11!)...
    angle = dec(anglein)
    final = angle
    add = False
    for i in range(3, int(terms) * 3, 2):
        if add:
            final += dec(angle ** i) / fact(i)
        elif not add:
            final -= dec(angle ** i) / fact(i)
        add = not add
    return final

def fact(intin):    #return the factorial of the given integer, return False if not given an int
    if intin == int(intin):
        intout = 1
        for i in range(1, intin + 1):
            intout *= i
        return intout
    else:
        return False

def rnd(numIn, decPlcIn = -terms, mode = 'fiveHigher'):    #return the given number, rounded to the given decimal place.
#use 1 to indicate 10s, 0 to indicate 1s, -2 to indicate 100ths, etc.
    num1 = dec(numIn)
    decPlc = dec(decPlcIn)
    if mode == 'fiveHigher':
        return dec(str(dec(round(num1 * (dec(10) ** -decPlc))) * (dec(10) ** decPlc)).rstrip('0'))
    elif mode == 'cutoff':
        return dec(str(dec(int(num1 * (dec(10) ** -decPlc))) * (dec(10) ** decPlc)).rstrip('0'))

def root(numIn, rootVal):
    num = dec(numIn)
    rt = dec(dec(1) / rootVal)
    num1 = num ** rt
    return rnd(num1, -terms)

def quad(aIn, bIn, cIn):    #Plugin for the quadratic formula. Provide a, b, and c.
    a = dec(aIn)
    b = dec(bIn)
    c = dec(cIn)
    try:
        posResult = (-b + root((b ** dec(2)) - (dec(4) * a * c), 2)) / (dec(2) * a)
    except:
        posResult = False
    try:
        negResult = (-b - root((b ** dec(2)) - (dec(4) * a * c), 2)) / (dec(2) * a)
    except:
        negResult = False
    return (posResult, negResult)


问:
How you pass CLI arguments in php while booting up the server through terminal?
I am getting little trouble in passing arguments and options while booting up the server through php -S localhost:5000 like this.

The documentation shows passing -- and then right arguments after this like :

php -S localhost:5000 -- foo=bar.

But this above thing is giving me errors like foo=bar not found in C:\xampp\Pear\.

I want to pass two CLI arguments which I can read from stdin or  from options but its not taking arguments. Apart from this how would we even pass options eg --testing when we boot up server in specific directory as mentioned above.

like eg php -S localhost:5000 --testing How can we pass this testing flag. Same error I am getting when trying to pass flags like these.

答:
Why won't you use ENV variables instead? It's dead simple solution that should work everywhere.

```<code>$ FOO=bar php -S localhost:5000
</code>```

In your PHP file then just use then $_ENV['FOO']. Done.

Body:
Why won't you use ENV variables instead? It's dead simple solution that should work everywhere.

$ FOO=bar php -S localhost:5000

In your PHP file then just use then $_ENV['FOO']. Done.


问:
When I use the apple to log in, the selection box will pop up. I choose to use the password to continue and the prompt is not complete
iOS13 (beta) Apple Login error

```<code>@available(iOS 13.0, *)
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        // Handle error.
        crprint(error.localizedDescription)
    }
</code>```

Failed to complete operation. (com.apple.AuthenticationServices.AuthorizationError error 1000.)

答: Simply Add +  "Sign In with Apple" from Capability.</p>

Body:
iOS13 (beta) Apple Login error

@available(iOS 13.0, *)
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        // Handle error.
        crprint(error.localizedDescription)
    }

Failed to complete operation. (com.apple.AuthenticationServices.AuthorizationError error 1000.)


问:
Jquery remove form tag, not content
Hello i need to remove a form tag but non the content:</p>

```<code><form id="form">
<div> not remove this only the form tag</div>

</form>
</code>```

答:
```<code>$('.element').replaceWith(function() {
</code>```

return $(this).html();
});

This is wrong....

```<code>$form = $('#form');
</code>```

$form.replaceWith($form.html());

This one is correct...

ContentLicense: CC BY-SA 2.5

Title: Jquery remove form tag, not content

Body:
Hello i need to remove a form tag but non the content:

<form id="form">

 not remove this only the form tag

</form>

Body:
$('.element').replaceWith(function() {

return $(this).html();
});

This is wrong....

$form = $('#form');

$form.replaceWith($form.html());

This one is correct...


问:
How to get the max number and key
I have has like this

var hash = {};
hash['a'] = ["a", "b", "c", "d", "e"];
hash['b'] = ["a", "b", "c"];
hash['k'] = ["q", "b"];

Math.max(Object.keys(hash)
    .map(function(key) {
      return hash[key].length;
    })
  )```

It returns 5 but, I want to get the hash key 'a' at the same time.

Is it possible??

答:
Combine Object.entries() and Array.prototype.reduce() to get the key and the elements behind that key (and their length)

var hash = {
   a: ["a", "b", "c", "d", "e"]
  ,b: ["a", "b", "c"]
  ,k: ["q", "b"]
};

var result = Object.entries(hash)
                   .reduce((r, c) => r[1].length > c[1].length ? r : c);

console.log(result);```

Title: How to get the max number and key

Body:
I have has like this

var hash = {};
hash['a'] = ["a", "b", "c", "d", "e"];
hash['b'] = ["a", "b", "c"];
hash['k'] = ["q", "b"];

Math.max(Object.keys(hash)
    .map(function(key) {
      return hash[key].length;
    })
  )

It returns 5 but, I want to get the hash key 'a' at the same time.

Is it possible??


问:
Combine sizeof string and chararcter
The last 2 cout statements have the same size. why?

```<code>int main()
{
char ch=127;
cout<<sizeof(ch)<<endl;    //Size=1
cout<<sizeof("Hello")<<endl;    //Size=6
cout<<sizeof("Hello"+ch)<<endl;    //Size=8
cout<<sizeof("HelloWorld"+ch)<<endl;    //Size=8
return 0;
}
</code>```

Please explain.
Thanks

答:
When you do "Hello"+ch the array containing the string "Hello" decays to a pointer to its first element, and you add ch to this pointer.

The result of pointer arithmetic is a pointer, which is what you get the size of.

Equivalent code would be something like

```<code>char const hello[] = "Hello";
char const* phello = hello;  // equivalent to &hello[0]
char const* result = phello + ch;
cout << sizeof(result) << endl;
</code>```

Title: Combine sizeof string and chararcter

Body:
The last 2 cout statements have the same size. why?

int main()
{
char ch=127;
cout<<sizeof(ch)<<endl;    //Size=1
cout<<sizeof("Hello")<<endl;    //Size=6
cout<<sizeof("Hello"+ch)<<endl;    //Size=8
cout<<sizeof("HelloWorld"+ch)<<endl;    //Size=8
return 0;
}

Please explain.
Thanks

Body:
When you do "Hello"+ch the array containing the string "Hello" decays to a pointer to its first element, and you add ch to this pointer.

The result of pointer arithmetic is a pointer, which is what you get the size of.

Equivalent code would be something like

char const hello[] = "Hello";
char const* phello = hello;  // equivalent to &hello[0]
char const* result = phello + ch;
cout << sizeof(result) << endl;


问:
Reducing the number of reads firestore
I have a dating kind of app (without chat support) in which I am showing list of all the profiles that matches certain criteria to user. I have used realtime snapshot listener for this.

```<code> query.addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot snapshot,
                                @Nullable FirebaseFirestoreException e) {
                if (e != null) {
                    return;
                }
                if (snapshot != null && !snapshot.isEmpty()) {
                    List<FeedDetails> feedDetailsList = new ArrayList<>();
                    for (DocumentSnapshot document : snapshot.getDocuments()) {
                        FeedDetails feedDetails = document.toObject(FeedDetails.class);
                        feedDetailsList.add(feedDetails);
                    }
                    feedItemAdapter.updateData(feedDetailsList);
                }

            }
        });
</code>```

In individual profile doc, I have 10-12 field with one online/offline info field. So lets say if no other field changed but online/offline status changed for some profiles then listener is going to read that document again. Is there any way to cut down those reads?

答:
I have a 10-12 field with one online/offline info field. So let's say if no other field changed but online/offline status changed for some profiles then the listener is going to read that document again.

There is no way in Cloud Firestore in which you can listen only to a set of properties of a document and exclude others. It's the entire document or nothing. So if this field online=true is changed into online=false, then you will get the entire document.

Cloud Firestore listeners fire on the document level and always return complete documents. Unfortunately, there is no way to request only a part of the document with the client-side SDK, although this option does exist in the server-side SDK's select() method.

If you don't want to get notified for specific fields, consider adding an extra collection with documents that will contain only those fields. So create that additional collection where each document just contains the data you don't need. In this way, you won't be notified for online/offline changes.

Title: Reducing the number of reads firestore

Body:
I have a dating kind of app (without chat support) in which I am showing list of all the profiles that matches certain criteria to user. I have used realtime snapshot listener for this.

 query.addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot snapshot,
                                @Nullable FirebaseFirestoreException e) {
                if (e != null) {
                    return;
                }
                if (snapshot != null && !snapshot.isEmpty()) {
                    List<FeedDetails> feedDetailsList = new ArrayList<>();
                    for (DocumentSnapshot document : snapshot.getDocuments()) {
                        FeedDetails feedDetails = document.toObject(FeedDetails.class);
                        feedDetailsList.add(feedDetails);
                    }
                    feedItemAdapter.updateData(feedDetailsList);
                }

            }
        });

In individual profile doc, I have 10-12 field with one online/offline info field. So lets say if no other field changed but online/offline status changed for some profiles then listener is going to read that document again. Is there any way to cut down those reads?


问:
Image viewer - standard gui controls, bottom-up or what?
I need to make a basic image viewer.
The main concern is how to implement (in terms of gui components and image manipulation) such features as: zoom in-out, scroll and 'hand tool'.

There seems to be several options for achieving this goal, differing mainly in degree of putting responsibilities on the graphical interface framework as opposed to manually implementing things.

Two solutions that are obvious to me are:

1) Resizing and cropping the visible part of the image is crafted on its own using functionality of some image manipulation library. The image (or it's part) is then drawn on some window/control in an overridden onPaint() method. Scrollbars updating (when 'hand tool' used) and operation (when used directly) code needs to be written.

2) An oversized control (StaticBitmap or whatever) containing the image is put inside a window with automatic scrolling. Then one needs to figure out how to convert image coordinates to scrolling coordinates.

Both ways look awkward. Any ideas how to do it in a neat way? Or is what I feel as being ugly just the only way to go?

I'm using Python with wxPython/wxWidgets and PIL, but the question is to a large extent language- and platform- independent.

Sample code and links to sources (of something that is not too bloated) are welcome.

答:
Here's a tutorial that might help.  Build a wxPython Image Viewer

I didn't actually watch all the videos, so I can't speak to how well it address's your specific problems.

Also, here's a blog post by Jeff Atwood on Coding Horror that could apply. Programming Is Hard, Let's Go Shopping!  It speaks to when you should take the time to write your own code and when to just use a third party solution.

LastEditorDisplayName: Maleev

OwnerDisplayName: tgray


问:
Why do I need the interface(decorated with [ServiceContract])?
I have a Service.svc class. In it I have:

```<code>public class CommentsWCFService : Objects.ISessionIDCommentWCFContract
    {
        public List<Comment> GetComments(string SessionId)
        {
            //dummy data first
            List<Comment> dummyData = new List<Comment>();

            if (SessionId == "123")
            {
                dummyData.Add(new Comment("Comment 1", DateTime.Now));
                dummyData.Add(new Comment("Comment 2", DateTime.Now));
                dummyData.Add(new Comment("Comment 3", DateTime.Now));
            }

            return dummyData;
        }
    }
</code>```

I have implemented the interface because I was told to do so. What im wondering is why I need to inherit an interface that is decorated with the [ServiceContract] attribute?

Would .net know? Could I still call the service if I removed this interface all together?

答:
This attribute tells WCF that the interface defines a contract and should be exposed.

See the documentation or an arbitrary tutorial about WCF.

Body:
I have a Service.svc class. In it I have:

public class CommentsWCFService : Objects.ISessionIDCommentWCFContract
    {
        public List<Comment> GetComments(string SessionId)
        {
            //dummy data first
            List<Comment> dummyData = new List<Comment>();

            if (SessionId == "123")
            {
                dummyData.Add(new Comment("Comment 1", DateTime.Now));
                dummyData.Add(new Comment("Comment 2", DateTime.Now));
                dummyData.Add(new Comment("Comment 3", DateTime.Now));
            }

            return dummyData;
        }
    }

I have implemented the interface because I was told to do so. What im wondering is why I need to inherit an interface that is decorated with the [ServiceContract] attribute?

Would .net know? Could I still call the service if I removed this interface all together?


问:
Automatic indentation of arguments list on multiple lines in Visual Studio
When the list of arguments to a method grows to the point where they do not fit comfortably on one line, I like to format code such that each argument is on a separate line (following the StyleCop suggestion), like this:

```<code>public void MyMethod(
   int someArgument,
   double someOtherArgument,
   int someMoreArguments)
</code>```

The problem I run into is that this formatting is "fragile" and does not get automatically reformatted when using Ctrl + K + D. For instance, if I happen to insert some spaces in front of one of the arguments, it doesn't get removed, and I end up doing some tedious manual reformatting.

If I copy a method (say, to provide an overloaded signature), the argument indentation in the copy gets totally messy.
I have a similar issue with LINQ statements, which I also like to format on multiple lines, like:

```<code>myEnumerable.
   .Where(this and that)
   .Where(this and that)
   .FirstOrDefault();
</code>```

I realize this is complete obsessive-compulsive formatting, and a very minor issue, but is there a way to make Visual Studio 2010 automatically reindent multi-line arguments following that pattern when it gets misaligned?

答:
For anyone searching this problem for later versions, in Visual Studio 2017 I found an option to do this (I am not sure if it is available in other versions).

Under menu Tools → Options → Text editor → C/C++ → Formatting → Indentation → "Within parentheses, align new lines when I type them".

Choose the option "Align contents to opening parentheses".

Visual studio 2019 update.

Mostly the same answer but Formatting seems to have moved under Code style:
So:
Under menu Tools → Options → Text editor → C/C++ → Code Style → Formatting → Indentation → "Within parentheses, align new lines when I type them".

Choose the option "Align contents to opening parentheses".

Body:
When the list of arguments to a method grows to the point where they do not fit comfortably on one line, I like to format code such that each argument is on a separate line (following the StyleCop suggestion), like this:

public void MyMethod(
   int someArgument,
   double someOtherArgument,
   int someMoreArguments)

The problem I run into is that this formatting is "fragile" and does not get automatically reformatted when using Ctrl + K + D. For instance, if I happen to insert some spaces in front of one of the arguments, it doesn't get removed, and I end up doing some tedious manual reformatting.

If I copy a method (say, to provide an overloaded signature), the argument indentation in the copy gets totally messy.
I have a similar issue with LINQ statements, which I also like to format on multiple lines, like:

myEnumerable.
   .Where(this and that)
   .Where(this and that)
   .FirstOrDefault();

I realize this is complete obsessive-compulsive formatting, and a very minor issue, but is there a way to make Visual Studio 2010 automatically reindent multi-line arguments following that pattern when it gets misaligned?


问:
Trying To Get a Custom Array With Looping PHP
Good day, i am trying to generate a csv with array below

```<code>array[0] => array(
  ["a"] => 1,
  ["b"] => 1,
  ["c"] => 1, --> the value is only 1 and 2
  ["d"] => user2,
),
array[1] => array(
  ["a"] => 1,
  ["b"] => 1,
  ["c"] => 2,
  ["d"] => user3,
),
array[2] => array(
  ["a"] => 2,
  ["b"] => 2,
  ["c"] => 1,
  ["d"] => user4,
),
array[3] => array(
  ["a"] => 2,
  ["b"] => 2,
  ["c"] => 2,
  ["d"] => user5,
)
</code>```

edit: i want to get the 2 array with same number on "a" and "b" value, but different in "c" value
i tried my code below

```<code>$results = array();

for($i = 1 ; $i <= 10 ; $i++){
    $j = $i+1;

    $response = array(
        array(
            $i, $i, 1, "user".$i
        ),
        array(
            $i, $i, 2, "user".$j
        )
    );
    array_push($results, $response);
}
</code>```

but the array result is not as i wanted like above result. is there any solutions?, sorry for the confusion of this question, i am trying my best to ask. thank you for the help!.

答:
1.You need to use % (modules operator) in your code to set 1 or 2 at third index of each of your child-array.

2.Don't create too many array/variables in your code.Do direct assignments

```<code>$results = array();
$j = 1;
for($i=1; $i<=10; $i++){
    $j++;
    $results[] = array($i, $i, 1, "user".$j);
    $j++;
    $results[] = array($i, $i, 2, "user".$j);
}

print_r($results);
</code>```

Output: https://3v4l.org/GE7MD

Body:
Good day, i am trying to generate a csv with array below

array[0] => array(
  ["a"] => 1,
  ["b"] => 1,
  ["c"] => 1, --> the value is only 1 and 2
  ["d"] => user2,
),
array[1] => array(
  ["a"] => 1,
  ["b"] => 1,
  ["c"] => 2,
  ["d"] => user3,
),
array[2] => array(
  ["a"] => 2,
  ["b"] => 2,
  ["c"] => 1,
  ["d"] => user4,
),
array[3] => array(
  ["a"] => 2,
  ["b"] => 2,
  ["c"] => 2,
  ["d"] => user5,
)

edit: i want to get the 2 array with same number on "a" and "b" value, but different in "c" value
i tried my code below

$results = array();

for($i = 1 ; $i <= 10 ; $i++){
    $j = $i+1;

    $response = array(
        array(
            $i, $i, 1, "user".$i
        ),
        array(
            $i, $i, 2, "user".$j
        )
    );
    array_push($results, $response);
}

but the array result is not as i wanted like above result. is there any solutions?, sorry for the confusion of this question, i am trying my best to ask. thank you for the help!.

Body:
1.You need to use % (modules operator) in your code to set 1 or 2 at third index of each of your child-array.

2.Don't create too many array/variables in your code.Do direct assignments

$results = array();
$j = 1;
for($i=1; $i<=10; $i++){
    $j++;
    $results[] = array($i, $i, 1, "user".$j);
    $j++;
    $results[] = array($i, $i, 2, "user".$j);
}

print_r($results);

Output: https://3v4l.org/GE7MD


问:
Angular 8 : How to do calculation on observable object's two properties and need to save on another property
I need to show sum of two properties of an observable data. here is my code Please advice me how to fix it.

Typescript class

```<code>export class Amount {
Amount1: number;
Amount2: number;
Total:number;
}
</code>```

In typescript service:

I have declared the observable object

```<code>export class AmountService {
 public newmessageService = new BehaviorSubject(new Amount());
  public Model = this.newmessageService.asObservable();
}
</code>```

In Component Class:

subscribed that observable Model in calcuation component

```<code>export class Calculation implements OnInit {
Model$:Amount;
  ngOnInit() {
    this.service.Model.subscribe(temp => this.Model$ = temp)
  }
}
</code>```

In component view :

In the view, Amount1 and Amount2 property are declared for inputs and total is displayed.

```<code>  <form name="calculationform">

  <mat-form-field class="example-full-width">
    <mat-label>Amount1</mat-label>
    <input matInput [(ngModel)]="Model$.Amount1" name="Amount1">
  </mat-form-field>

  <mat-form-field class="example-full-width">
    <mat-label>Amount2</mat-label>
    <input matInput [(ngModel)]="Model$.Amount2" name="Amount2">
  </mat-form-field>

      <mat-label>Total:</mat-label>
      <mat-label>{{Model$.Total}}</mat-label>
</form>
</code>```

I need to show the sum of Amount1 and Amount2 on Total property when ever we change the amount.

Thank you.

答:
You can consider converting Total property to getter.

export class Amount {
  Amount1: number;
  Amount2: number;
  get Total():number {
    return this.Amount1 + this.Amount2;
  };
}
```

Body:
I need to show sum of two properties of an observable data. here is my code Please advice me how to fix it.

Typescript class

export class Amount {
Amount1: number;
Amount2: number;
Total:number;
}

In typescript service:

I have declared the observable object

export class AmountService {
 public newmessageService = new BehaviorSubject(new Amount());
  public Model = this.newmessageService.asObservable();
}

In Component Class:

subscribed that observable Model in calcuation component

export class Calculation implements OnInit {
Model$:Amount;
  ngOnInit() {
    this.service.Model.subscribe(temp => this.Model$ = temp)
  }
}

In component view :

In the view, Amount1 and Amount2 property are declared for inputs and total is displayed.

  <form name="calculationform">

  <mat-form-field class="example-full-width">
    <mat-label>Amount1</mat-label>
    <input matInput [(ngModel)]="Model$.Amount1" name="Amount1">
  </mat-form-field>

  <mat-form-field class="example-full-width">
    <mat-label>Amount2</mat-label>
    <input matInput [(ngModel)]="Model$.Amount2" name="Amount2">
  </mat-form-field>

      <mat-label>Total:</mat-label>
      <mat-label>{{Model$.Total}}</mat-label>
</form>

I need to show the sum of Amount1 and Amount2 on Total property when ever we change the amount.

Thank you.