text:
Q: Why does "diskutil eraseVolume ..." add an extra "Apple_Free" partition My question is about why "diskutil eraseVolume" adds an extra partition to an APM partition table.
A little history will help understand the situation better I think -- had a 240GB APM style disk on an old PowerBook system that I wanted to upgrade to a larger disk. The PowerBook has some heat related problems and the video goes bad after about 1-2 hours, so wanted to do all this work on another Mac that runs High Sierra, in case the video went bad during the reconstruction on the old PowerBook.
So, basically used "dd" command to clone the entire old 240GB disk to the new 500GB disk, then modified the partition table to correct the total size of disk and size of last partition to compensate for the larger disk, knowing that would need to erase that last HFS+ partition as it's no longer valid. But first, wanted to use "diskutil verifyVolume ..." command to check all the various filesystems and discovered that besides the last MacOS volume the xxxxx volume was also no longer correct.
So, no problem I think -- will erase the last two volumes and restore from a backup image and all should be fine. Here is what the partition table started out as on the 500GB disk:
==================================pdisk "p" command output============
Partition map (with 512 byte blocks) on '/dev/rdisk6'
 #:                type name               length   base      ( size )
 1: Apple_partition_map Apple                  63 @ 1
 2:      Apple_Driver43*Macintosh              56 @ 64
 3:      Apple_Driver43*Macintosh              56 @ 120
 4:    Apple_Driver_ATA*Macintosh              56 @ 176
 5:    Apple_Driver_ATA*Macintosh              56 @ 232
 6:      Apple_FWDriver Macintosh             512 @ 288
 7:  Apple_Driver_IOKit Macintosh             512 @ 800
 8:       Apple_Patches Patch Partition       512 @ 1312
 9:           Apple_HFS MacOS 10.0       64039712 @ 1824      ( 30.5G)
10:           Apple_HFS MacOS 10.1       64039712 @ 64041536  ( 30.5G)
11:           Apple_HFS MacOS 10.2       64039712 @ 128081248 ( 30.5G)
12:           Apple_HFS MacOS 10.3       64039712 @ 192120960 ( 30.5G)
13:           Apple_HFS MacOS 10.4       64039712 @ 256160672 ( 30.5G)
14:           Apple_HFS xxxxx            64039712 @ 320200384 ( 30.5G)
15:           Apple_HFS MacOS           592532992 @ 384240096 (282.5G)
16:          Apple_Free Extra                  80 @ 976773088

Device block size=512, Number of Blocks=976773168 (465.8G)
DeviceType=0x0, DeviceId=0x0
Drivers-
1:  23 @ 64, type=0x1
2:  36 @ 120, type=0xffff
3:  21 @ 176, type=0x701
4:  34 @ 232, type=0xf8ff
======================================================================

I used the command "diskutil eraseVolume HFS+ xxxxx /dev/rdisk6s14" (can't use the GUI Disk Utility program to erase an HFS+, non-journaled, filesystem as that is apparently no longer supported on High Sierra version of Disk Utility.app GUI application) and the partition table had been modified to include a new "Apple_Free" partition right before the "xxxxx" partition:
==================================pdisk "p" command output===========================
Partition map (with 512 byte blocks) on '/dev/disk6'
 #:                type name               length   base      ( size )
 1: Apple_partition_map Apple                  63 @ 1
 2:      Apple_Driver43*Macintosh              56 @ 64
 3:      Apple_Driver43*Macintosh              56 @ 120
 4:    Apple_Driver_ATA*Macintosh              56 @ 176
 5:    Apple_Driver_ATA*Macintosh              56 @ 232
 6:      Apple_FWDriver Macintosh             512 @ 288
 7:  Apple_Driver_IOKit Macintosh             512 @ 800
 8:       Apple_Patches Patch Partition       512 @ 1312
 9:           Apple_HFS MacOS 10.0       64039712 @ 1824      ( 30.5G)
10:           Apple_HFS MacOS 10.1       64039712 @ 64041536  ( 30.5G)
11:           Apple_HFS MacOS 10.2       64039712 @ 128081248 ( 30.5G)
12:           Apple_HFS MacOS 10.3       64039712 @ 192120960 ( 30.5G)
13:           Apple_HFS MacOS 10.4       64039712 @ 256160672 ( 30.5G)
14:          Apple_Free                    262144 @ 320200384 (128.0M)
15:           Apple_HFS xxxxx            63777568 @ 320462528 ( 30.4G)
16:           Apple_HFS MacOS           592532992 @ 384240096 (282.5G)
17:          Apple_Free                        80 @ 976773088

Device block size=512, Number of Blocks=976773168 (465.8G)
DeviceType=0x0, DeviceId=0x0
Drivers-
1:  23 @ 64, type=0x1
2:  36 @ 120, type=0xffff
3:  21 @ 176, type=0x701
4:  34 @ 232, type=0xf8ff
===============================================================================

So, why the new "Apple_Free" partition right before the real "xxxxx" HFS+ partition? I did the "diskutil eraseVolume" once more for the MacOS partition and it again created a new "Apple_Free" partition of same size (262144 blocks) before the real HFS+ partition. So that after these two "eraseVolume" commands the partition table now looks like this:
==========================pdisk "p" command output=====================
Partition map (with 512 byte blocks) on '/dev/disk6'
 #:                type name               length   base      ( size )
 1: Apple_partition_map Apple                  63 @ 1
 2:      Apple_Driver43*Macintosh              56 @ 64
 3:      Apple_Driver43*Macintosh              56 @ 120
 4:    Apple_Driver_ATA*Macintosh              56 @ 176
 5:    Apple_Driver_ATA*Macintosh              56 @ 232
 6:      Apple_FWDriver Macintosh             512 @ 288
 7:  Apple_Driver_IOKit Macintosh             512 @ 800
 8:       Apple_Patches Patch Partition       512 @ 1312
 9:           Apple_HFS MacOS 10.0       64039712 @ 1824      ( 30.5G)
10:           Apple_HFS MacOS 10.1       64039712 @ 64041536  ( 30.5G)
11:           Apple_HFS MacOS 10.2       64039712 @ 128081248 ( 30.5G)
12:           Apple_HFS MacOS 10.3       64039712 @ 192120960 ( 30.5G)
13:           Apple_HFS MacOS 10.4       64039712 @ 256160672 ( 30.5G)
14:          Apple_Free                    262144 @ 320200384 (128.0M)
15:           Apple_HFS Titoonium        63777568 @ 320462528 ( 30.4G)
16:          Apple_Free                    262144 @ 384240096 (128.0M)
17:           Apple_HFS MacOS           592270848 @ 384502240 (282.4G)
18:          Apple_Free                        80 @ 976773088

Device block size=512, Number of Blocks=976773168 (465.8G)
DeviceType=0x0, DeviceId=0x0
Drivers-
1:  23 @ 64, type=0x1
2:  36 @ 120, type=0xffff
3:  21 @ 176, type=0x701
4:  34 @ 232, type=0xf8ff
=======================================================================

Any idea why these "Apple_Free" partitions get created, or even better how to keep it from happening? Thanks...

A: Instead of diskutil, try using newfs_hfs to create the filesystems.  I don't know what happens in Mac OS, but in my experience, the newfs_* commands in BSD create a filesystem in a partition without changing the partition map.
I don't know why Apple likes to reserve 128 megabytes of free space before an HFS partition.  I saw this in my PowerBook G4, when I used the Disk Utility from Mac OS X 10.4 to format my internal hard disk, and it put 128M of Apple_Free (partition 2) between the Apple_partition_map (partition 1) and my Apple_HFS (partition 3).  I guess that one can use part of the 128M to add Mac OS 9 drivers for the disk.
Your disk already has Mac OS 9 drivers (Apple_*Driver* and Apple_Patches), so I don't know why it would need 128M of Apple_Free.  I speculate that your disk might have IDE drivers but not FireWire drivers.  If you would boot your PowerBook in FireWire disk mode, and connect it to some Mac OS 9 machine, then you might need some Apple_Free space to add more drivers; but I never had FireWire hard disks, so I don't know.


text:
Q: .env keyError in django project I'm having a hard time because my django project.
Who can help?
I'd like to thank you for your help.
set .env in proeject Root path
SECRET_KEY=exampleKey
DEBUG=False

DB_ENGINE=django.db.backends.mysql
DB_NAME=example
DB_USER=admin

...Blah Blah

project settings.py
import os
import environ

env = environ.Env(DEBUG=(bool, False), )
environ.Env.read_env()

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = env('SECRET_KEY')

DEBUG = env('DEBUG')

...Blah Blah

And when run the project
I get an this error message.
Django_workspace/asone/asone/.env doesn't exist - if you're not configuring your environment separately, create one.
  "environment separately, create one." % env_file)

    raise KeyError(key) from None
KeyError: 'SECRET_KEY'

During handling of the above exception, another exception occurred:

/Django_workspace/asone/venv/lib/python3.7/site-packages/environ/environ.py", line 277, in get_value
    raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable

I have a hard time because I'm a django beginner.
Who can help? I'd like to thank you for your help.

.P.S
Thank you so much for your answer.
I'm sorry. I'm telling you, there's something I missed out on.
I set up a django-environ package to use the .env in the project.
pip install django-environ

Is there something I'm missing?
What more information will be needed to solve this problem?

.P.S
set up python-dotenv package
pip install python-dotenv.

Change settings.py
import os
from dotenv import load_dotenv

load_dotenv()

...

SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG=os.getenv('DEBUG')

DATABASES = {
    'default': {
        # 'ENGINE': env('DB_ENGINE'),
        # 'NAME': env('DB_NAME'),
        # 'USER': env('DB_USER'),
        # 'PASSWORD': env('DB_PASSWORD'),
        # 'HOST': env('DB_HOST'),
        # 'PORT': env('DB_PORT'),
        'ENGINE': os.getenv('DB_ENGINE'),
        'NAME': os.getenv('DB_NAME'),
        'USER': os.getenv('DB_USER'),
        'PASSWORD': os.getenv('DB_PASSWORD'),
        'HOST': os.getenv('DB_HOST'),
        'PORT': os.getenv('DB_PORT'),
    }
}
...

and then I met this error message.
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/config.py", line 562, in configure
    handler = self.configure_handler(handlers[name])
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/config.py", line 735, in configure_handler
    result = factory(**kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py", line 148, in __init__
    BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py", line 55, in __init__
    logging.FileHandler.__init__(self, filename, mode, encoding, delay)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py", line 1087, in __init__
    StreamHandler.__init__(self, self._open())
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py", line 1116, in _open
    return open(self.baseFilename, self.mode, encoding=self.encoding)
FileNotFoundError: [Errno 2] No such file or directory: '/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/logs/logfile'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run
    autoreload.raise_last_exception()
  File "/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception
    raise _exception[1]
  File "/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute
    autoreload.check_errors(django.setup)()
  File "/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/venv/lib/python3.7/site-packages/django/__init__.py", line 19, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/venv/lib/python3.7/site-packages/django/utils/log.py", line 75, in configure_logging
    logging_config_func(logging_settings)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/config.py", line 799, in dictConfig
    dictConfigClass(config).configure()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/config.py", line 570, in configure
    '%r' % name) from e
ValueError: Unable to configure handler 'file'

Is there something I'm missing?

A: There is no environ module in stdlib(standard library of python). So I checked if there is third party module called 'environ' by running pip install environ, which installed it, but when I checked at pypi website, I can't see any valid explanation. I think it's not maintained well.
So I concluded that your environ configuration went a bit odd.
Here's my suggestion

*

*Install python-dotenv module by running pip install python-dotenv. There are many .env module, but this is one of the most popular, well maintained one in my opinion.

*Ensure your .env file is in the directory where settings.py is. setting.py will load .env file in the same directory unless specified otherwise

*Change your code from this
import os
import environ

env = environ.Env(DEBUG=(bool, False), )
environ.Env.read_env()

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = env('SECRET_KEY')

DEBUG = env('DEBUG')

to this
import os
from dotenv import load_dotenv

load_dotenv()

...

SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG=os.getenv('DEBUG')

...

Change your db setting similar way
DATABASES = {
    'default': {
        'ENGINE': os.getenv('DB_ENGINE'),
        'NAME': os.getenv('DB_NAME'),
        'USER': os.getenv('DB_USER'),
        # and so on ...
        }
    }
}

A: You are running into a KeyError because either:

*

*You aren't putting a SECRET_KEY variable in your .env file.

*It can't find your .env file.
From what I can see from your answer, try moving your .env file from your root directory to where it will sit alongside settings.py.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Desenvolvimento multi-camadas e regra de negócios Trabalho com uma equipe desenvolvendo um ERP e estou responsável por emissão de relatórios, da qual um deles executa um select no banco que em testes chegou a levar mais de 2h rodando, o que acarretou erros e uma grande duvida: "quem estava processando toda a informação?" E foi aí que começou o problema pois o processamento não é feito pela aplicação servidora (web server) mas pelo banco de dados (neste caso o PostgreSQL).
O correto é realizar todos os possíveis cálculos diretamente na consulta do SQL (vendo que todas as funções para cálculos se encontram no próprio banco de dados) ou apenas buscar os dados primitivos do banco e realizar toda a operação via código pela camada servidora?
Se tiverem referências é de suma importância.

A: Depende. Se os dados estão todos no banco de dados e faz sentido executar lá para dar resultados menores, é relativamente simples fazê-los, então deve fazer lá, caso contrário, se o mais importante for pegar os dados brutos onde todos serão necessários no relatório, os cálculos são secundários então deve fazer na aplicação.
Não tem mágica, não tem receita de bolo. Eu sei que hoje em dia muitas pessoas que trabalham em TI acham que é só decorar algumas regras, algumas soluções e tudo se resolve. Se isso fosse verdade estaríamos começando a ficar sem empregos em breve. Para saber a resposta certa disto depende de muita experiência, conhecimento profundo da computação e entender todos os detalhes do contexto para dar uma resposta definitiva. Na verdade nem tão definitiva, apenas enquanto durarem os mesmos critérios e volumes.
Não é questão de onde se faz, mas como se faz. É quase certo que não deveria levar 21 horas, muito provavelmente está sendo feito de forma errada e a solução correta não é decidir em que lugar fazer, é fazer levar menos tempo. Aí tem uma série de técnicas para reduzir este tempo, precisa analisar a(s) consulta(s) para descobrir onde estão ocorrendo gargalos, e aí entendendo o funcionamento do banco de dados, mudar as consultas, as configurações para atender a demanda deste caso, sem atrapalhar outros casos. É simples? Claro que não, por isso temos empregos e ganhamos bem.
Pelo que está dizendo parece que nem fará diferença onde está rodando, mas pode ser uma especulação errada minha pela falta de informações da pergunta.
Só lembrando que cálculo em si costuma ser uma ínfima parte do processamento, o padrão de acesso aos dados costuma ser bem pior, especialmente me relatórios.
Em alguns casos o hardware disponível não é adequado e causa extrema lentidão.
Existem métodos científicos de observar as ocorrências para isolar o problema, eliminar as interferências, focar no problema específica e achar a causa raiz, mas isso é um escopo geral e não de desenvolvimento ou operação de infraestrutura.
Em alguns casos é culpa da modelagem existente. O que mais ocorre é as pessoas não entenderem o poder do índice (em outros o problema é o abuso deles).


text:
Q: how to insert an specific line before another line, into a text file with python and without inserting any empty lines between any lines? I want to extract the element stiffness matrix from Abaqus input file.
the contents of the last lines of the file are as follows:
**
** OUTPUT REQUESTS
**
*Restart, write, frequency=0
**
** FIELD OUTPUT: F-Output-1
**
*Output, field, variable=PRESELECT
*End Step

in order to extract the element stiffness matrix from an input file, we should the following line into the input file, i.e. the line before the ((*End Step)) line:
*ELEMENT MATRIX OUTPUT,ELSET=m,STIFFNESS=YES,MASS=NO,OUTPUTFILE=USER

I want to add this line into my input file through python language which is the scripting language of Abaqus software.
I try the following code to another text file to test this code, but after executing these lines, between each of two lines, it inserts an empty line which I don't want these empty line:(in the following code, I just want to show that, other codes create empty lines)
import fileinput

processing_foo1s = False

for line in fileinput.input('Input8.inp', inplace=1):
  if line.startswith('*Output,'):
    processing_foo1s = True
  else:
    if processing_foo1s:
      print ('foo bar')
    processing_foo1s = False
  print (line,)

A: This code will do exactly what you need:
with open('Input8.inp', 'r+') as f:
    _text = ''
    for line in f:
        if line.startswith('*End Step'):
            _text += '*ELEMENT MATRIX OUTPUT,ELSET=m,STIFFNESS=YES,MASS=NO,OUTPUTFILE=USER\n'

        _text += line

    f.seek(0)
    f.write(_text)
    f.truncate()

Explanation:

*

*Open file in read-write mode.

*Create temp variable

*Iterate file line by line

*If found line which starts with '*End Step' - add your custom line to temp variable

*Add iterated line to temp variable

*Go to start of file

*Write temp variable to it

*Delete the remaining lines in file ( which should not be present, but in case they somehow where not iterated - delete them )


text:
Q: Failed to load CSS file in elementore inside wordpress Hello Stackowerflow comunity.
I am suffering from the issue which is "Failed To Load Resource" inside wordpress.
When I close the elementore, all the contents of my website goes break and when i reopen it the website looks great.
In this period what happen is, inside my wordpress directory wp-plugings/upload/elementore/css it contain all css files of elemetore all css files removed auotomaticaly and
when i reopen the elementore all file comes up
What to do ?

A: I'm assuming your site is breaking down when you deactivate the Elementor plugin. It is common for plugins to remove codes/files generated by them when they're deactivated.
If you need to deactivate the Elementor plugin, yet keep the styling:
What you can do is:
copy all the codes from the css files in wp-content/uploads/elementor/css and paste them in one of the css files in your child theme, or in the theme settings or customizer. (Make sure that all the css code has proper selectors instead of pseudo selectors).


text:
Q: Why the execution result does not meet expectations when inheriting an abstract class class C {
    public static void main(String[] args){
        B test = new B(1);
    }
}

abstract class A {
    int i = 1;

    abstract void test();

    public A(){
        System.out.println("before test()");
        test();
        System.out.println("after test");
    }
}

class B extends A {
    int i = 1;
    @Override
    void test(){
        System.out.println("test()" + i);
    }
    public B(int i) {
        System.out.println("before test()");
        test();
        System.out.println("after test");
    }
}

When I run this code, the output is
before test()
test()0
after test
before test()
test()1
after test

I know the first set of output results comes from the construction method of A, and I don't know
why the variable i is 0 for the first time, but in second time is right.

A: You are creating an instance of B using the constructor B(int i).
That constructor starts by executing the super class constructor public A(). This constructor calls test(), which is overridden in the B class and prints the i variable of class B.
That variable is not yet initialized, since the constructor of the super class is executed before the instance variables of B are initialized. Therefore, it still contains the default value 0.
After the constructor public A() is done, B's instance variables are initialized (so i is initialized to 1), and B's constructor  body is executed. It calls test(), which now prints 1.


text:
Q: how to avoid logging multiple number of times while using python threads In a single thread.run() i am finding  a couple of strings in their corresponding webpages
if found, I am logging a text to a log file.
lets say 4 strings in their corresponding 4 webpages.
when i run the a single thread, the log file shows 4 logs for each string in corresponding webpage
altogether i am getting 16 logs in a single thread, whereas i am expecting only 4 logs for 4 string searches.
i am not sure where its going wrong ..
https://github.com/sumankumar/websitemonitor
Any pointers to this design, or where i am doing mistake
(I use global logger to all my files and just import the logger when necessary )
myLogFile = logging.FileHandler("./example.log")

i guess the fault is with logger object which i have created since
myLogFile = logging.FileHandler("./example.log",'w')

behaves a bit differently
(finally .. please point any other suggestions on my code :-) )

A: you can use a Queue, and have all threads write data to the queue instance.  Then read from that queue from another thread and log there.  The queue takes care of locking/synchronization. (multi-producer/single-consumer model)


text:
Q: Inconsistent Rendering of Google Profile Picture     import * as React from 'react';
import { Text, View, Image, TouchableWithoutFeedback, TouchableOpacity, Alert } from 'react-native';

import Colors from '../constants/Colors';

import { Side, GlobalContext } from '../Context';
import { GetTintColor, Icon, IconButton } from '../components/Common';
import { PostList } from '../components/Lists';

import { useNavigation, DrawerActions } from '@react-navigation/native';
import { FontAwesome } from '@expo/vector-icons';

import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { FriendRequestInternal, Profile, ProfileType, RootStackParamList } from '../types';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { dbURI } from '../App';

import { LinearGradient } from 'expo-linear-gradient';

// import logo from "../assets/images/logo";

// TODO: move this elsewhere
export function PersonalProfessionalToggle() {
    const {setSide, currentProfile, setCurrentProfile, personalProfile, professionalProfile} = React.useContext(GlobalContext)
    const [profileImage, setProfileImage] = React.useState(currentProfile.profileImage)
    const [idRecorder, setIdRecorder] = React.useState('')
    const nav = useNavigation<NativeStackNavigationProp<RootStackParamList>>() // TODO: optimize: don't nest flatlist inside scrollview (use sectionlist?)

    React.useEffect(() => {
        if (currentProfile?._id) {
            let isMounted = true;

            if(isMounted){setProfileImage(currentProfile.profileImage);}
            console.log("HERE IS THE IMAGE :" + profileImage)
            console.log("HERE IS THE profileIMAGE :" + currentProfile.profileImage)

            return () => { isMounted = false}
        }
    },[])

    const handleToggleMessageDisplay = (side : Side) => {
        return Alert.alert(
            "Switching Account",
            "You are about to switch to your "
                + (side === Side.Personal ? "Private " : "Public ")
                + "account. All unsaved changes will be lost.",
            [
                {
                    text: "Yes",
                    onPress: () => {
                        setSide(side);
                        if(side === Side.Personal){ setCurrentProfile({...personalProfile}) }
                        else{ setCurrentProfile({...professionalProfile}) }
                        nav.navigate("Home")
                    }
                },
                {
                    text: "No",
                },
            ]
        )
    }
    const color1 = "#343336";
    const color2 = "#B408A4";
    return (
        <View style={{left: 0}}>
            <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
                <TouchableWithoutFeedback
                    onPress={() => {
                        if(currentProfile.type !== ProfileType.Personal) {
                            handleToggleMessageDisplay(Side.Personal)
                        }
                    }}>
                    <View style={{
                        width: '50%', height: 30}}>
                            <LinearGradient style={{
                                width: '100%', height: 30}}
                                colors={[Colors.personal.primary, "#3e5898", "#8e4d73"]}
                                start={{x: 0, y: 0.5}}
                                end={{x: 1, y: 0.5}}
                                locations={[0.4, 0.6, 0]}>
                            </LinearGradient>
                    </View>
                </TouchableWithoutFeedback>

                <TouchableWithoutFeedback
                    onPress={() => {
                        if(currentProfile.type !== ProfileType.Professional) {
                            handleToggleMessageDisplay(Side.Professional)
                    }
                }}>
                    <View style={{
                        width: '52%', height: 30}}>
                        <LinearGradient style={{
                                width: '100%', height: 30}}
                                colors={["#6d5674", "#e12424", Colors.professional.primary]}
                                start={{x: 0, y: 0.5}}
                                end={{x: 1, y: 0.5}}
                                locations={[0, 0.4, 0.6]}>
                            </LinearGradient>
                    </View>
                </TouchableWithoutFeedback>
            </View>

            <View style= {{ position: 'absolute', top: 0, left: 0, width: '100%', alignItems: 'center' }} pointerEvents='box-none'>
                <TouchableWithoutFeedback
                    onPress={() => {
                        nav.navigate('Profile', {pid: currentProfile._id})
                    }}
                >
                    <Image
                        style={{ width: 60, height: 60, borderRadius: 100, marginTop: -15 }}
                        source={{ uri: profileImage }}
                        key={profileImage}
                    />
                </TouchableWithoutFeedback>
            </View>
        </View>
    )
}

export function TopBar(props: {
    handleNavigate: (path: string, params?: any) => void,
    push: (path: string) => void
}) {
    const [incomingRequests, setIncomingRequests] = React.useState<FriendRequestInternal[]>([]);
    const [unreadMessageCount, setUnreadMessageCount] = React. useState(0);
    const { user, currentProfile } = React.useContext(GlobalContext)

    const nav = useNavigation<NativeStackNavigationProp<RootStackParamList>>()

    React.useEffect(() => {
        if (user._id) {
            let isMounted = true;
            if(currentProfile.type === ProfileType.Personal){
                // Fetch number of incoming requests; need to display the count for button
                fetch(
                    dbURI + '/profile/getIncomingRequests/' + currentProfile._id
                    ,{method: 'GET'})
                .then(response => response.json())
                .then((json) => { if (isMounted) setIncomingRequests(json.data.incomingRequests) })
                .catch(error => alert(`getIncomingRequests\n${error}`));
            } else {
                setIncomingRequests([])
            }

            // Fetch number of unread messages; need to display the count for button
            // this has been commented out because this api call does not exist
            // fetch(
            //     dbURI + '/profile/getUnreadMessageCount/' + currentProfile._id
            //     ,{method: 'GET'})
            //     .then(response => response.json())
            //     .then((json) => { if (isMounted) setUnreadMessageCount(json.data.unreadCount) })
            //     .catch(error => alert(`getUnreadMessageCount\n${error}`));

            return () => { isMounted = false }
        } else {
            props.handleNavigate('Login')
        }
    }, [user._id, currentProfile])

    return (
        user ?
            <View style={{
                alignItems: 'center',
                justifyContent: 'center'
            }}
            >
                <View style={{
                    width: '100%',
                    paddingBottom: 15,
                    marginTop: 30,
                    flexDirection: 'row'}}
                >
                    <View style={{justifyContent:'center', left: 17}}>
                        <TouchableOpacity onPress={() => nav.dispatch(DrawerActions.toggleDrawer())}>
                            <Icon name='bars' size={30} color='black'/>
                        </TouchableOpacity>
                    </View>
                    <Image style={{
                            width: '35%',
                            resizeMode: 'contain',
                            marginLeft: '20%'
                    }} source={require('../assets/images/logo.png')}/>
                    <View style={{justifyContent:'center', left: '6%'}}>
                            <TouchableOpacity onPress={() => nav.navigate('Notifications')}>
                                <FontAwesome name="bell" size={25} color="black"/>
                                {
                                    //Only display count if > 0
                                    (incomingRequests.length > 0)
                                        ?
                                            <View style={{
                                                    position: 'absolute',
                                                    right: -8,
                                                    top: -5,
                                                    width: 20,
                                                    height: 20,
                                                    borderRadius: 100,
                                                    justifyContent:'center',
                                                    alignItems:'center',
                                                    backgroundColor: currentProfile.type === ProfileType.Personal ? Colors.personal.primary : Colors.professional.primary}}
                                            >
                                                <Text style={{color:'white', fontSize: 10}}>
                                                {
                                                    //Display count limit is 99. Anything over still displays 99
                                                    incomingRequests.length > 99
                                                    ? 99
                                                    : incomingRequests.length
                                                }
                                                </Text>
                                            </View>
                                        :
                                            <></>
                                }
                            </TouchableOpacity>
                        </View>
                    <View style={{justifyContent:'center', left: '11%'}}>
                            <TouchableOpacity onPress={() => nav.navigate('Connection')}>
                                <FontAwesome name="users" size={25} color="black"/>
                                {
                                    //Only display count if > 0
                                    (incomingRequests.length > 0)
                                        ?
                                            <View style={{
                                                    position: 'absolute',
                                                    right: -8,
                                                    top: -5,
                                                    width: 20,
                                                    height: 20,
                                                    borderRadius: 100,
                                                    justifyContent:'center',
                                                    alignItems:'center',
                                                    backgroundColor: currentProfile.type === ProfileType.Personal ? Colors.personal.primary : Colors.professional.primary}}
                                            >
                                                <Text style={{color:'white', fontSize: 10}}>
                                                {
                                                    //Display count limit is 99. Anything over still displays 99
                                                    incomingRequests.length > 99
                                                    ? 99
                                                    : incomingRequests.length
                                                }
                                                </Text>
                                            </View>
                                        :
                                            <></>
                                }
                            </TouchableOpacity>
                        </View>
                        <View style={{justifyContent:'center', left: '16%'}}>
                            <TouchableOpacity onPress={() => nav.navigate('Inbox')}>
                                <FontAwesome name="envelope" size={25} color="black"/>
                                {
                                    //Only display count if > 0
                                    (unreadMessageCount > 0)
                                        ?
                                            <View style={{
                                                position: 'absolute',
                                                right: -8,
                                                top: -5,
                                                width: 20,
                                                height: 20,
                                                borderRadius: 100,
                                                justifyContent:'center',
                                                alignItems:'center',
                                                backgroundColor: currentProfile.type === ProfileType.Personal ? Colors.personal.primary : Colors.professional.primary}}>
                                                <Text style={{color:'white', fontSize: 10}}>
                                                    {unreadMessageCount > 99 ? 99 : unreadMessageCount}
                                                </Text>
                                            </View>
                                        :
                                            <></>
                                }
                            </TouchableOpacity>
                        </View>
                </View>

                <View style={{
                    width: '100%',
                    paddingBottom: 15,
                    flexDirection: 'row'}}
                >
                    <View style={{flex: 9, left: -5}}>
                    <PersonalProfessionalToggle/>
                    </View>
                </View>
            </View>
            : <></>
    )
}

enum HomeTab { Top, Recent, Popular, Search }

function HomeTabs({ navigation, tab, setTab }: any) {
    return (
        <GlobalContext.Consumer>
            {({ side, setSide }) => (
            <View style={{ flexDirection: 'row', justifyContent: 'space-evenly' }}>
                <TouchableOpacity onPress={() => {
                    setTab(HomeTab.Popular)
                    navigation.navigate('Popular')
                }}>
                    <Text style={{ color: GetTintColor(side, tab == HomeTab.Popular) }}>Popular</Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => {
                    setTab(HomeTab.Top)
                    navigation.navigate('Top')
                }}>
                    <Text style={{ color: GetTintColor(side, tab == HomeTab.Top) }}>Top</Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => {
                    setTab(HomeTab.Recent)
                    navigation.navigate('Recent')
                }}>
                    <Text style={{ color: GetTintColor(side, tab == HomeTab.Recent) }}>Recent</Text>
                </TouchableOpacity>
                <IconButton name='search' size={16} color={GetTintColor(side, tab == HomeTab.Search)} onPress={() => {
                    navigation.navigate('Search')
                }}/>
            </View>
        )}</GlobalContext.Consumer>)
}

function TopFeed() {
    const { currentProfile } = React.useContext(GlobalContext)
    console.log('topfeed')
    console.log(currentProfile._id)
    // return (currentProfile._id
    //     ? <PostList query={dbURI + '/post/getTopPosts/' + currentProfile._id} emptyMessage={'Go follow your friends!'} /> : <></>)

    return (currentProfile._id
        ? <PostList query={dbURI + '/post/getTopPosts/' + currentProfile._id} emptyMessage={'Go follow your friends!'} /> : <></>)
}

function RecentFeed() {
    const { currentProfile } = React.useContext(GlobalContext)
    console.log('recentfeed')
    console.log(currentProfile._id)
    return (currentProfile._id
        ? <PostList query={dbURI + '/post/getRecentPosts/' + currentProfile._id} emptyMessage={'Go follow your friends!'} /> : <></>)
}

function PopularFeed() {
    const { currentProfile } = React.useContext(GlobalContext)
    console.log('popularfeed')
    console.log(currentProfile._id)
    return (currentProfile._id
        ? <PostList query={dbURI + '/post/getPopularPosts/' + currentProfile._id} emptyMessage={'Go follow your friends!'} /> : <></>)
}

//const Tab = createMaterialTopTabNavigator();
const Tab = createNativeStackNavigator()

export default function HomeScreen({ navigation }: any) { // TODO: type
    let [tab, setTab] = React.useState(HomeTab.Popular)

    return (
        <View style={{ flex: 1}}>
            <Tab.Navigator screenOptions={({ navigation, route }) => ({
                animation: 'fade',
                header: (props) => <HomeTabs {...props} tab={tab} setTab={setTab} />
            })}>
                <Tab.Screen name="Top" component={TopFeed} />
                {/* <Tab.Screen name="Recent" component={RecentFeed} />
                <Tab.Screen name="Popular" component={PopularFeed} /> */}
            </Tab.Navigator>

            <GlobalContext.Consumer>
                {({ side }) => (
                <View style={{
                    alignItems: 'center',
                    justifyContent: 'center',
                    width: 80,
                    position: 'absolute',
                    bottom: 32,
                    right: 32,
                    height: 80,
                    backgroundColor: side == Side.Personal ? Colors.personal.primary : Colors.professional.primary,
                    borderRadius: 100,
                    shadowColor: 'gray',
                    shadowOpacity: 10,
                    shadowOffset: { width: 0, height: 4 } }}>
                    <IconButton name='pencil' color='white' onPress={() => navigation.push('NewPost')} />
                </View>)}
            </GlobalContext.Consumer>
        </View>
    );
}

enter image description here
In the middle of this gradient app bar, my google profile icon should show. However, I'm getting inconsistent behavior that points to a problem in my HomeScreen.tsx file (above). Specifically, I get a "State: ERRORED" for the Image that gets the image uri from the currentProfile.profileImage being set for the profileImage. I was thinking that it might be a problem with global context or google permissions but wasn't sure. Any thoughts or possibilities on what could be causing this? Occasionally, the profile icons are back, and they stay but then they'll disappear along with the capital G google logo from the sign in button.


text:
Q: bundle install error I'm trying to install this gem: https://github.com/jongilbraith/simple-private-messages with bundle install.
And I'm getting the following error message:

Updating git://github.com/professionalnerd/simple-private-messages.git
Fetching source index for http://rubygems.org/
Could not find gem 'simple-private-messages (>= 0, runtime)' in git://github.com/professionalnerd/simple-private-messages.git (at master).
Source does not contain any versions of 'simple-private-messages (>= 0, runtime)'

entry in Gemfile:
gem "simple-private-messages",:git =>"git://github.com/professionalnerd/simple-private-messages.git"
Any ideas?

A: As per @bjeanes answer, ideally the Git repository should have a .gemspec file for each gem the Git repository represents.
However, if the repository is only missing the .gemspec file and would otherwise be a valid Git gem source, you can specify a version number in your gem call to have Bundler generate a .gemspec for you:
gem 'simple-private-messages', '0.0.0', :git => 'git://github.com/jongilbraith/simple-private-messages.git'

A: The git repo needs to have a .gemspec file in it in order to be a valid gem.


text:
Q: Is it possible to configure a GPIO as both input and output? I am planning to implement a GPIO based I2C in atmega16.
Since it should have two pins SCL, SDA. The SDA pin should be bi directional but what i know is that either we can set a pin as input or output at a time.
By what way we can implement it?

A:
The SDA pin should be bi directional but what i know is that either we can set a pin as input or output at a time.

This is true, but the I2C master "knows" when to expect incoming data. Since this is a synchronous bus, the master can switch between driving the output or switching to tri-state/input right before clocking data in/out.
This application note from Atmel may be useful to you: Atmel AVR156: TWI Master Bit Bang Driver
The example from Atmel uses a polling-approach, which limits speed. If one of your GPIOs has pin change interrupt support, you could probably utilize that to get more speed if required.


text:
Q: VB.NET 4.0 DataContractJsonSerializer with changed properties i have some Objects serialized with the System.Runtime.Serialization.Json.DataContractJsonSerializer and written to my Database:
Dim serializer = New DataContractJsonSerializer(obj.GetType)
Using ms = New MemoryStream()
    serializer.WriteObject(ms, obj)
    ms.Position = 0
    Using sr = New StreamReader(ms)
        Dim json = sr.ReadToEnd()
        sr.Close()
        Return json
    End Using
End Using

Now i have to change the Classes and add some new Properties.
Then i want to deserialize the "old" strings to the new classes:
Using ms = New MemoryStream(Encoding.UTF8.GetBytes(serialized))
    Dim ser = New DataContractJsonSerializer(GetType(T))
    Return DirectCast(ser.ReadObject(ms), T)
End Using

How can i now deserialize the "old" Strings to the new class? (The new Properties can stay empty)
thank you!

A: We found a solution for this issue:
We switched from the DataContractJsonSerializer to JSON.Net.
The Problem now was, that the JSON.Net serializes with a different naming conventions, so the old serializes Data in the Database could not be Deserialized.
the DataContractJsonSerializer uses "_propertyname", ans the JSON.Net uses "propertyname".
But fortunalety the JSON.Net Serializer allowed us to overwrite the Naming Generation with a small class:
 Public Class UnderscorePropertyNamesContractResolver
    Inherits Newtonsoft.Json.Serialization.DefaultContractResolver

    Protected Overrides Function ResolvePropertyName(propertyName As String) As String
        Return MyBase.ResolvePropertyName("_" + propertyName)
    End Function
End Class

Which could be then used this was with the old JSON Data:
 Dim Setting = New JsonSerializerSettings
 Setting.ContractResolver = New UnderscorePropertyNamesContractResolver
 return JsonConvert.DeserializeObject(Of T)(serialized, Setting)

and do the Seralisation with this:
Dim Setting = New JsonSerializerSettings
Setting.ContractResolver = New UnderscorePropertyNamesContractResolver
return JsonConvert.SerializeObject(obj, Formatting.Indented, Setting)

Now we have a more fault tollerant JSON Serialisation and can add Properties to our classes with the old JSON Data.


text:
Q: Prove that for any $n\times n$ complex matrix $B$, $e^B$ exists and is invertible Prove that for any $n\times n$ complex matrix $B$, $e^B$ exists and is invertible.
Here we have $e^B= \sum_{k=0}^\infty \frac{1}{k!} B^k$.
Using the Jordan canonical form we have $B=QJQ^{-1}$, and for each Jordan block $J_i$ we have $J_i= \lambda_i I + N_i$ for some nilpotent matrix $N$.
So $e^B= Qe^JQ^{-1}$ will always exists.
$e^{-B}e^B=e^{B-B}=e^0=I$. So $e^B$ is invertible.
Could someone check if my proof is correct?
Thank you!


text:
Q: Транслятор выражений в ассемблер проблема IO и архитектура Хочу создать небольшой транслятор выражений в ассемблер. Написал такой код, который работает для выражений типа 2+2:
io_error.h:
#ifndef IO_ERROR_H
#define IO_ERROR_H

#include <string>

namespace io
{
    // Read new character from input stream
    void getch();

    // Return current character
    char look();

    // Output a string with tab
    void __emit(std::string const& s);

    // Output a string with tab and CRLF
    void emitln(std::string const& s);

    // Get a number from input stream
    char getnum();

    // Report error
    void error(std::string const& s);

    // Report error and quit
    void abort(std::string const& s);

    // Report what was expected
    void expected(std::string const& s);

    //Match a specific input character
    bool match(char c);
}

#endif // IO_ERROR_H

io_error.cpp:
#include "io_error.h"
#include <iostream>
#include <cstdlib>
#include <cctype>

namespace io
{
    static char symbol = 0;

    // Read new character from input stream
    void getch()
    {
        std::cin >> symbol;
    }

    // Return current character
    char look()
    {
        return symbol;
    }

    // Report error
    void error(std::string const& s)
    {
        std::cout << "Error: " << s << std::endl;
    }

    // Report error and quit
    void abort(std::string const& s)
    {
        error(s);
        std::exit(0);
    }

    // Report what was expected
    void expected(std::string const& s)
    {
        abort(s);
    }

    //Match a specific input character
    bool match(char c)
    {
        if (symbol != c)
        {
            expected("" + c);
        }
        return symbol == c;
    }

    // Output a string with tab
    void __emit(std::string const& s)
    {
        std::cout << "\t" << s;
    }

    // Output a string with tab and CRLF
    void emitln(std::string const& s)
    {
        __emit(s);
        std::cout << std::endl;
    }

    char getnum()
    {
        if (!std::isdigit(symbol)) expected("Integer");
        return symbol;
    }
}

translator.h:
#ifndef TRANSLATOR_H
#define TRANSLATOR_H

void term();
void expression();

#endif // TRANSLATOR_H

translator.cpp:
#include "io_error.h"
#include "translator.h"

void term()
{
    io::emitln(std::string("mov eax, ") + io:: getnum());
}

// Recognize and translate an Add
void add()
{
    io::match('+');
    io::getch();
    term();
    io::emitln("add eax, ebx");
}

// Recognize and translate a Subtract
void subtract()
{
    io::match('-');
    term();
    io::emitln("sub eax, ebx");
}

void expression()
{
    term();
    io::emitln("mov ebx, eax");
    io::getch();
    switch (io::look())
    {
        case '+': add(); break;
        case '-': subtract(); break;
    }
}

main:
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    io::getch();
    expression();

    return a.exec();
}

У меня много проблем с этим кодом.
1) Реализация ввода/вывода и ошибок: операции, которые должны быть простыми, на деле выполняют больше, чем обещает название: например, читают следующий символ. Это вносит путаницу при отладке
2) Код процедурный. Не знаю, плохо ли это, но обычно даже системный софт пишут в парадигме ООП. Какие здесь можно выделить сущности? Абстрагировать ввод/вывод, сделать обработку ошибок через исключения, создать класс транслятора?
3) Вообще, система ввода/вывода здесь очень грязная. Как лучше реализовать чтение выражений с консоли, чтобы операции ввода/вывода были простыми, выполняли одно действие, позволяли парсить выражение транслятором и делать другие вещи, которые я еще не пробовал реализовать?


text:
Q: Unable to get curl response from codeigniter paypal library I have checked the answer to this post
paypal codeigniter library
but i am getting this error cURL Error: Operation timed out after 30000 milliseconds with 0 bytes received.
can someone help me to resolve this issue?

A: Try to set the timeout manually
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 500); // timeout in seconds


text:
Q: multiple boxplots, side by side, using matplotlib from a dataframe I'm trying to plot 60+ boxplots side by side from a dataframe and I was wondering if someone could suggest some possible solutions.
At the moment I have df_new, a dataframe with 66 columns, which I'm using to plot boxplots. The easiest way I found to plot the boxplots was to use the boxplot package inside pandas:
boxplot = df_new.boxplot(column=x, figsize = (100,50))
This gives me a very very tiny chart with illegible axis which I cannot seem to change the font size for, so I'm trying to do this natively in matplotlib but I cannot think of an efficient way of doing it. I'm trying to avoid creating 66 separate boxplots using something like:
fig, ax = plt.subplots(nrows = 1,
                       ncols = 66,
                       figsize = (10,5),
                       sharex = True)
ax[0,0].boxplot(#insert parameters here)

I actually do not not how to get the data from df_new.describe() into the boxplot function, so any tips on this would be greatly appreciated! The documentation is confusing. Not sure what x vectors should be.
Ideally I'd like to just give the boxplot function the dataframe and for it to automatically create all the boxplots by working out all the quartiles, column separations etc on the fly - is this even possible?
Thanks!

A: I tried to replace the boxplot with a ridge plot, which takes up less space because:

*

*it requires half of the width

*you can partially overlap the ridges

*it develops vertically, so you can scroll down all the plot

I took the code from the seaborn documentation and adapted it a little bit in order to have 60 different ridges, normally distributed; here the code:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import itertools
sns.set(style="white", rc={"axes.facecolor": (0, 0, 0, 0)})

# # Create the data
n = 20
x = list(np.random.randn(1, 60)[0])
g = [item[0] + item[1] for item in list(itertools.product(list('ABCDEFGHIJ'), list('123456')))]
df = pd.DataFrame({'x': n*x,
                   'g': n*g})

# Initialize the FacetGrid object
pal = sns.cubehelix_palette(10, rot=-.25, light=.7)
g = sns.FacetGrid(df, row="g", hue="g", aspect=15, height=.5, palette=pal)

# Draw the densities in a few steps
g.map(sns.kdeplot, "x", clip_on=False, shade=True, alpha=1, lw=1.5, bw=.2)
g.map(sns.kdeplot, "x", clip_on=False, color="w", lw=2, bw=.2)
g.map(plt.axhline, y=0, lw=2, clip_on=False)

# Define and use a simple function to label the plot in axes coordinates
def label(x, color, label):
    ax = plt.gca()
    ax.text(0, .2, label, fontweight="bold", color=color,
            ha="left", va="center", transform=ax.transAxes)

g.map(label, "x")

# Set the subplots to overlap
g.fig.subplots_adjust(hspace=-.25)

# Remove axes details that don't play well with overlap
g.set_titles("")
g.set(yticks=[])
g.despine(bottom=True, left=True)

plt.show()

This is the result I get:

I don't know if it will be good for your needs, in any case keep in mind that keeping so many distributions next to each other will always require a lot of space (and a very big screen).
Maybe you could try dividing the distrubutions into smaller groups and plotting them a little at a time?


text:
Q: powerpivot 2010 pivot table new measure for percentage difference I'm a newbie with PowerPivot 2010.  I've created a few reports, but I'm having difficulty with a report that I want to create that requires a new measure.  In my volume table I have 2 columns in my volume table (tblPilot_Volume) - Current Wk Vol This and Current Wk Vol Last.  I want to display in the pivot the percentage difference between these two values.
I tried the calculation below but it doesn't work.  I'm not sure what I'm doing wrong.
=sum(tblPilot_Volume[Current Wk Vol This]-(tblPilot_Volume[Current Wk Vol Last])/(tblPilot_Volume[Current Wk Vol Last])

Prior to this I tried to just add a column to the PowerPivot table with the formula.  The calculations works in the table, but when I create the pivot table it doesn't work.
I also need to eliminate any rows where there is a zero in the Current wk Vol Last column.

A: ME Miller, I would try this:
=(sum(tblPilot_Volume[Current Wk Vol This])-sum(tblPilot_Volume[Current Wk Vol Last])) / sum(tblPilot_Volume[Current Wk Vol Last])

When creating measures, make sure you always use one of the aggregation functions (like sum, avg, min, max etc.).
Hope this helps.


text:
Q: ComponentWillReceiveProps method does not invoke automatically unless there is some API which triggers this through mapStateToProps function Suppose I have a React class based component named as "ComponentA". Now I have called the action creator (getCategories) inside componentDidMount hook of this component and get its response inside componentWillReceiveProps through mapStateToProps setting up and carrying state inside redux. Now if I switch to "componentB" and trying to get this already setted up state inside componentWillReceiveProps through mapStateToProps of "ComponentB", the componentWillReceiveProps never invoked unless there is an API call which forcing this to invoke. I want to invoke this method of "ComponentB" everytime I switch to this component without API call. Please let me know the correct solution of this problem. Thanks

A: As per you description, It is hard to resolve your issue, but this is my try.
As you are switching the component, assuming you click some link, you will never get data in componentWillReceiveProps because whenever you are switching the component, that component only go through below process as a newly mounted component.
componentWillMount() -> Render -> componentDidMount().
This is the process for newly mounted component.
The data you want in componentWillReceiveProps will only come when you pass data from parent to child and not when you switch the component.
As you are using redux, and changing some state in one component (ComponentA), you can access the changed state the another component's (ComponentB) ComponentDidMount().


text:
Q: How do I recognize the extension that has taken over markdown editing I suddenly find that my markdown files are being opened by a wysiwyg editor with chinese menus. No language is detected and searching through my extensions gave no hint. How do I figure out which extension is active?

A: In general, there is a command called "Developer: Show Running Extensions" that you can activate from the command palette.
In this case, I see a weird spelling in that screenshot: "Vditor".
Searching for that word finds a few pages, including one whose title is "vditor VS vscode-markdown-editor". From that page, I found Vanessa219/vditor.
That project claims to be

An In-browser Markdown editor, support WYSIWYG (Rich Text), Instant Rendering (Typora-like) and Split View modes

but not a Visual Studio Code plugin.
However, the extension vscode all markdown says it is "powered by" Vditor. I suspect you'll find that's the plugin to disable.
There is also something called vscode-office. It uses Vditor for Markdown out of the box, but this can be disabled:

It change markdown editor as vditor, it's WYSIWYG editor for markdown...
if you want using vscode editor, insert below json to vscode config.
"workbench.editorAssociations": [{
  "viewType": "default",
  "filenamePattern": "*.md"
}]


text:
Q: Syntax sql server I have a problem in syntax sql, i have 3 tables like this
Table : Stock
StockCode | StockName  | BeginStock
0001      | Mouse      | 5
0002      | Keyboard   | 1
0003      | MousePad   | 4

Table : Purchase
NoDoc  | StockCode | PurchaseDate | Qty
P-0001 | 0001      | 06/12/2019   | 1
P-0002 | 0002      | 06/20/2019   | 5
P-0003 | 0002      | 06/21/2019   | 2
P-0004 | 0003      | 06/22/2019   | 1
P-0005 | 0001      | 07/01/2019   | 2

Table : Sales
NoDoc  | StockCode | PurchaseDate | Qty
S-0001 | 0001      | 06/30/2019   | 1
S-0002 | 0002      | 06/30/2019   | 1
S-0003 | 0002      | 06/30/2019   | 1
S-0004 | 0003      | 06/30/2019   | 1
S-0005 | 0003      | 07/01/2019   | 1

I want if i query for date  >= '07/01/2019' and date <='07/07/2019' the stock will be
StockCode | StockName  | BeginStock | Purchase | Sales | Actual
0001      | Mouse      | 5          | 1        | 0     | 6
0002      | Keyboard   | 6          | 0        | 0     | 6
0003      | MousePad   | 4          | 0        | 1     | 3

i want to know the beginstock in before month and after month, please help me how the query in sql. Sorry i'm the newbie. Thank's for helping

A: Assuming all stock codes are present in the Stock table, you can use CROSS APPLY like this:
SELECT  St.StockCode, St.StockName, St.BeginStock,
        ISNULL(X.Purchase,0) AS Purchase, ISNULL(Y.Sales,0) AS Sales,
        St.BeginStock+ISNULL(X.Purchase,0)-ISNULL(Y.Sales,0) AS Actual
FROM Stock St
CROSS APPLY (
    SELECT SUM(P.Qty) AS Purchase
    FROM Purchase P
    WHERE P.StockCode=St.StockCode
    AND P.PurchaseDate BETWEEN '20190701' AND '20190707'
) X
CROSS APPLY (
    SELECT SUM(Sa.Qty) AS Sales
    FROM Sales Sa
    WHERE Sa.StockCode=St.StockCode
    AND Sa.PurchaseDate BETWEEN '20190701' AND '20190707'
) Y

Alternatively, you can use LEFT JOIN with GROUP BY in the derived tables, like this:
SELECT  St.StockCode, St.StockName, St.BeginStock,
        ISNULL(X.Purchase,0) AS Purchase, ISNULL(Y.Sales,0) AS Sales,
        St.BeginStock+ISNULL(X.Purchase,0)-ISNULL(Y.Sales,0) AS Actual
FROM Stock St
LEFT JOIN (
    SELECT P.StockCode, SUM(P.Qty) AS Purchase
    FROM Purchase P
    WHERE P.PurchaseDate BETWEEN '20190701' AND '20190707'
    GROUP BY P.StockCode
) X ON St.StockCode=X.StockCode
LEFT JOIN (
    SELECT Sa.StockCode, SUM(Sa.Qty) AS Purchase
    FROM Sales Sa
    WHERE Sa.PurchaseDate BETWEEN '20190701' AND '20190707'
    GROUP BY Sa.StockCode
) Y ON St.StockCode=Y.StockCode


text:
Q: captureStream() on dynamically created video element I am trying to capture stream from dynamically created video element. when I get the video element and try to videoElement.captureStream() Firefox returns videoElement.captureStream is not a function but the same code works on Chrome. Problem seems like Firefox has an issue with dynamically created video element. I tried mutation observer to detect the newly added video element and access the captureStream method with no luck I am posting the code sample below (I am using adapter.js for WebRTC https://webrtc.github.io/adapter/adapter-latest.js)
(function (win) {

    var listeners = [],
        doc = win.document,
        MutationObserver = win.MutationObserver || win.WebKitMutationObserver,
        observer;

    function ready(selector, fn) {
        listeners.push({
        selector: selector,
        fn: fn
        });
        if (!observer) {
        observer = new MutationObserver(check);
        observer.observe(doc.documentElement, {
            childList: true,
            subtree: true
        });
        }
        check();
    }

    function check() {
        for (var i = 0, len = listeners.length, listener, elements; i < len; i++) {
        listener = listeners[i];
        elements = doc.querySelectorAll(listener.selector);
        for (var j = 0, jLen = elements.length, element; j < jLen; j++) {
            element = elements[j];
            if (!element.ready) {
            element.ready = true;
            listener.fn.call(element, element);
            }
        }
        }
    }

    win.ready = ready;

})(this);

ready('.jw-video',function(element){
    var stream = null;
    element.addEventListener('play',function(e){
    //with firefox here e.target.captureStream or element.captureStream returns error
    stream = e.target.captureStream();

    var mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.onerror = function(error){
        console.log("media recorder error:",error);
    }
    mediaRecorder.start();
    mediaRecorder.ondataavailable = function(evt){
        console.log("mediaRecorderData");
        var blob = evt.data;

        var fileReader = new FileReader();
        var arraybuffer;
        fileReader.onload = function(){
            arraybuffer = fileReader.result;
            console.log("arraybuffer");
            console.log(arraybuffer);
            chunks.push(arraybuffer);
            sendChunks(chunks);
        };
        fileReader.readAsArrayBuffer(blob);
    }
    window.setInterval(function(){
        mediaRecorder.requestData();
    },3000);

    });
});

does anyone know how to access captureStream method of a newly added video  element which both works on Chrome and Firefox or another approach to capture stream and convert it to arraybuffer from JWPlayer?

A: No, the problem is simply that Firefox still prefixes HTMLMediaElement#captureStream.
So you need to call video.mozCaptureStream(), and this even for inlined video elements.

console.log(`In document :
captureStream : ${inDoc.captureStream}
mozCaptureStream : ${inDoc.mozCaptureStream}
`)

var dyn = document.createElement('video');
console.log(`Dynamic :
captureStream : ${dyn.captureStream}
mozCaptureStream : ${dyn.mozCaptureStream}
`)
<video id="inDoc">

So in order to support both chrome and FF :
let stream = video.mozCaptureStream ? video.mozCaptureStream() : video.captureStream();


text:
Q: BST Insert function giving issues I am working on practicing python but I am stuck here. I got my Binary Search Tree to work as it relates to the search function but I am having some issues with my insert function. I keep getting the error TypeError: insert() missing 1 required positional argument: 'key' I cannot seem to see what I am missing:
class Node:

def __init__(self, key, parent = None):
    self.key = key
    self.parent = parent
    self.left = None
    self.right = None
    # Make sure that the parent's left/right pointer
    # will point to the newly created node.
    if parent != None:
        if key < parent.key:
            assert(parent.left == None),
            parent.left = self
        else:
            assert key > parent.key,
            assert(parent.right == None ),
            parent.right = self

# Utility function that keeps traversing left until it finds
# the leftmost descendant
def get_leftmost_descendant(self):
    if self.left != None:
        return self.left.get_leftmost_descendant()
    else:
        return self

def search(self, key):
    if self.key == key:
        return (True, self)
    else:
        if key > self.key and self.right != None:
            return self.right.search(key)
        if key < self.key and self.left != None:
            return self.left.search(key)
        else:
            return (False, self)

def insert(self, parent, key):
    if parent is None:
        parent = Node(key)
        return parent
    else:
        if parent.data <= key:
            parent.right = self.insert(parent.right, key)
        else:
            parent.left = self.insert(parent.left, key)
        return parent

These are the conditions it tests against. It seems to pass the search with no isuues but I am not entirely sure as to why the insert errors out.
print('-- Testing search -- ')
(b, found_node) = t1.search(18)
assert b and found_node.key == 18, 'test 8 failed'
(b, found_node) = t1.search(25)
assert b and found_node.key == 25,
(b, found_node) = t1.search(26)
assert(not b), 'test 10 failed'
assert(found_node.key == 40),

print('-- Testing insert -- ')
ins_node = t1.insert(26)
assert ins_node.key == 26, ' test 12 failed '
assert ins_node.parent == t4, ' test 13 failed '
assert t4.left == ins_node, ' test 14 failed '
ins_node2 = t1.insert(33)
assert ins_node2.key == 33, 'test 15 failed'
assert ins_node2.parent == ins_node, 'test 16 failed'
assert ins_node.right == ins_node2, 'test 17 failed'

A: That's because the insert signature defined in Node is
def insert(self: Node, parent: Optional[Node], key: int):

and in your tests you're calling
ins_node = t1.insert(26)

which has the signature
def insert(self: Node, key: int):

Since the signatures don't match, the error appears. You can refactor to something like this:
def insert(self, key):
    if self.parent is None:
        self.parent = Node(key)
        return parent

    if self.parent.data <= key:
        self.parent.right = self.parent.right.insert(key)
    else:
        self.parent.left = self.parent.left.insert(key)
    return self.parent


text:
Q: Use mapBox tile as osmdroid tileSource I am new on map in android and I want to create simple map application with osmdroid.
I added
implementation 'org.osmdroid:osmdroid-android:6.0.3'

to my gradle and i use in this way in ma class:
final ITileSource tileSource = TileSourceFactory.HIKEBIKEMAP;
mapView.setTileSource(tileSource);
mapView.setTilesScaledToDpi(true);
mapView.setMultiTouchControls(true);
mapView.setVisibility(View.VISIBLE);

Now i am using TileSourceFactory.HIKEBIKEMAP as a tile source. According this page I want to use mapbox tile so in order i registered in mapbox site and i created Access tokens now i can not find to create MAPBOX_MAPID where is it?
After create ID how can i use mapbox.mapbox-streets-v8?

A: The important fact to note: The mapbox.mapbox-streets-v8 is a vector tileset. Vector tiles are not directly supported by Osmdroid, only bitmap are. Fortunately, Mapbox is still provides bitmap tiles for their tilesets.
Use mapbox.mapbox-streets-v8 ( you can also try mapbox.streets for example) as MAPBOX_MAPID and use MapBoxTileSource as described in the osmdroid documentation.
final MapBoxTileSource tileSource = new MapBoxTileSource();
//option 1, load your settings from the manifest
tileSource.retrieveAccessToken(context);
tileSource.retrieveMapBoxMapId(context);
//option 2, provide them programmatically
tileSource.setAccessToken(context);
tileSource.setMapBoxMapId(context);
mMapView.setTileSource(tileSource);

It should work.


text:
Q: How can I access a directory shared by macOS 10.14 from Windows 98 SE? On macOS I have enabled "File Sharing" in the "Sharing" section of the "System Preferences" application. It says "File Sharing: On" and "Other users can access shared folders on this computer, and administrators all volumes, at smb://192.168.1.100".
Under "Options..." I have enabled "Share files and folders using SMB", and I have enabled "Windows Sharing" for my account.
One folder is listed under "Shared Folders": my account's "Public" folder. When selected, these users and permissions are listed under "Users":

*

*Me: Read & Writer

*Staff: Read Only

*Everyone: Read Only

In the "Network" settings, under "WINS", the "NetBIOS Name" setting is set to "MACBOOKPRO-0A79" and the "Workgroup" settings is set to "WORKGROUP".
Finally, the "Firewall" under "Security & Privacy" is "Off".
(On Windows 10 Professional I can access the shared folder and volumes, by browsing to \\macbookpro-0a97, and entering credentials that match the credentials of my account on my Mac.)
On Windows 98 SE, when starting the computer, in the "Enter Network Password", I enter credentials that match the credentials of my account on my Mac. The "Network" configuration (found in the "Control Panel"), lists the following installed components (among others):

*

*Client for Microsoft Networks

*Intel 8255x-based PCI Ethernet Adapter (10/100)

*TCP/IP (bound to the ethernet adapter)

*File and printer sharing for Microsoft Networks

"TCP/IP" is configured to "obtain an IP address automatically", and the computer is connected physically to the same router that the Mac is connected to wirelessly. They are in the same subnet, and can ping each other.
For "File and printer sharing for Microsoft Networks", I have set "Browse Master" to "Enabled".
Under the "Identification" tab of the "Network" configuration, the "Workgroup" setting is set to "WORKGROUP".
Typing net view on the "MS-DOS Prompt" gives the following output:
Servers available in workgroup WORKGROUP
Server name            Remark
----------------------------------------
\\INTELLISTATION       IBM IntelliStation E Pro 6893-810
\\MACBOOKPRO-0A79      Michiel's MacBook Pro
The command was completed successfully.

The Mac is visible in the "Network Neighbourhood", but when I double-click it, I get the following error:

\Macbookpro-0a97 is not accessible.
  The computer or share name could not be found. Make sure you typed it correctly, and try again.

Also, when I use the "Find: Computer" option from the Start menu ("Start", "Find", "Computer...") and I type "MacBookPro-0a79" in the "Named:" field, the following record is displayed:

*

*Name: MacBook Pro-0a79

*Location: Network Neighbourhood

*Comment: Michiel's MacBook Pro

Double-clicking this record gives the exact same error as double-clicking the computer in Network Neighbourhood.
Right-clicking it and selecting "Properties", gives the following warning:

The server \Macbookpro-0a97 could not be found on the network.

After that, the properties applet opens, but it shows no meaningful information.
How can I actually access data on the Mac from Windows 98 SE?

A: The security methods of Windows 98 (SMBv1 only, Master browsing to list all devices) have been displaced by more secure methods. Windows 98 cannot be secured (basically a DOS system with a GUI attached to it) and so you will not be able to connect it to any modern system.

A: According this forum post, Samba on Windows 98 will automatically send your login username as the username to connect to the network. Have you tried renaming the Windows 98 SE account to match the username on your MacOS?


text:
Q: Excel VBA - Unable to remove extra spaces between words using Trim and similar functions I am trying to remove unnecessary white space in a string using VBA but the trim funciton doesn't seem to work for me. I want to remove the extra space between 'End' and 'Time' in this hypothetical example.
Public Sub RemoveSpaces()

    Dim s As String: s = "START TIME: N/A END     TIME: N/A "

    s = Trim(s)

    Debug.Print s

    End Sub

A: Simplest (and probably the best performing) way of doing this is with a regular expression:
'Requires reference to Microsoft VBScript Regular expressions
Private Function RemoveExtraSpace(inVal As String) As String
    With New RegExp
        .Pattern = "\s+"
        .Global = True
        RemoveExtraSpace = .Replace(inVal, " ")
    End With
End Function

Sub Example()
    Dim s As String
    s = "START TIME: N/A END     TIME: N/A "

    Debug.Print RemoveExtraSpace(s)
End Sub

Late bound version:
Private Function RemoveExtraSpace(inVal As String) As String
    With CreateObject("VBScript.RegExp")
        .Pattern = "\s+"
        .Global = True
        RemoveExtraSpace = .Replace(inVal, " ")
    End With
End Function

EDIT: If per comments you need multiline, just added the additional parameter:
With New RegExp
    .Pattern = "\s+"
    .Global = True
    .MultiLine = True
    RemoveExtraSpace = .Replace(inVal, " ")
End With

If you want the line breaks to remain, change the pattern to .Pattern = "[ ]+" (brackets for readability).

A: Maybe app.Worksheetfunction.Trim?
Public Sub RemoveSpaces()

    Dim s As String: s = "START TIME: N/A END     TIME: N/A "

    s = Application.WorksheetFunction.Trim(s)

    Debug.Print s

End Sub

Oh, I see @Alexis Olson was first with this.

A: Off the top of my head, I'd use the split function and then join the pieces back together.
Dim s As String: s = "START TIME: N/A END     TIME: N/A "
sParts = Split(s, " ")
s_wo_xtra_space = ""
for i = lbound(sParts) to ubound(sParts)
    if sParts(i) <> "" then
        s_wo_xtra_space = s_wo_xtra_space & sParts(i) & " "
    end if
next i
s_wo_xtra_space = trim(s_wo_xtra_space)

This assumes you still want one space between words.

A: You can use split() to split on the spaces then loop through and skip all the empty items in the resultant array:
Public Sub RemoveSpaces()

Dim s As String: s = "START TIME: N/A END     TIME: N/A "
Dim str() As String
Dim str1

str = Split(s)
s = ""
For Each str1 In str
    If str1 <> "" Then
        s = s & str1 & " "
    End If
Next str1

s = Trim(s)

Debug.Print s

End Sub

A: do until instr(s, "  ") = 0
s = replace(s, "  ", " ")
loop

Or if you want to do a UDF you can do something like this, then to remove double spaces you can just do s = RmvDblSpc(s)
Function RmvDblSpc(What As String) As String

Do Until InStr(What, "  ") = 0

    What = Replace(What, "  ", " ")

Loop

RmvDblSpc = What

End Function


text:
Q: background image along with background color problem Hey Designers and Developers i have  a problem  in a  project, i want to add a background color  into background image , but not worked, i tried some methods here in community but still didnt worked,  i added snippet for this
Any solution for this ?
Thanks so much who wants to helps me

.background {
  width:100%;
  min-height: 500px;
  background: url(https://images.unsplash.com/photo-1500964757637-c85e8a162699?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60), #651fff;
  background-size: cover;
  background-repeat: no-repeat;
  display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}

1

A: Well you can use a background-image and a background-color at the same time. As soon as the background-image is loaded, it will be rendered above the background color. What youc an do, is to place a pseudo-div spanning the entire width and height and use a background-color on this pesudo-div. Be sure to sue a rgba value as otherwise the background will be non-transpaerent and hide the background-image.
However, ther content will be influenced at the same time, so the content has to be pushed to the front (layer-wise) with the use of z-index (e.g..content { z-index: 1; }).
To span the layer with the background-color the entire width, I gave the parent the attribute: position: relative;.
Next I used for the layer position: absolute;. I gave it a top: 0; bottom: 0; left: 0; right: 0; so it will be spanned the entire parents space.

.background {
  width:100%;
  min-height: 500px;
  background: url(https://images.unsplash.com/photo-1500964757637-c85e8a162699?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60), #651fff;
  background-size: cover;
  background-repeat: no-repeat;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.layer {
  background-color: rgba(255, 0, 0, 0.6);
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

.content {
  z-index: 1;
}

1

A: You can't mix background colours and background images like that, so here is a solution by:
a. making the colours semi-transparent
b. turning it into a linear-gradient
c. putting it before the image so it goes on top

.background {
  width: 100%;
  min-height: 500px;
  background: linear-gradient(#651fffaa,#651fffaa), url(https://images.unsplash.com/photo-1500964757637-c85e8a162699?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60);
  background-size: cover;
  background-repeat: no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

1

A: I'am Using background:before for catch a Background Image.
Into Code, We will got a transparent black with white text

.background {
  position: relative;
  background: #000; /* Change Transparent Color */
  overflow: hidden;
}
.background h1 {
padding: 50px;
position: relative;
z-index: 2;
color: #fff;
}

.background:before {
content: ' ';
display: block;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 1; /* Must z-Index 1 */
opacity: 0.6; /* Set Opacity for Background Transparent */
background-image: url('https://images.unsplash.com/photo-1500964757637-c85e8a162699?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60');
background-repeat: no-repeat;
background-position: 50% 0;
background-size: cover;
}

1. I'am Only Try


text:
Q: how can I add values into a new data table column in the existing rows Here Is my problem. I am trying to take the Full Name field of my data table and split the name into first and last then add those names back into my data table in their correct positions. So far this is what I have.
DataTable DBTable = LoadMailingListContent(Location);

List<string> fullNames = DBTable.Rows.OfType<DataRow>().Select(dr => dr.Field<string>(columnName)).ToList();

DBTable.Columns.Remove(columnName);

DBTable.Columns.Add("First Name");
DBTable.Columns.Add("Last Name");

foreach (string fullname in fullNames)
{
    var names = fullname.Split(' ');
    string firstName = names[0];
    string lastName = names[1];

    //here is where I want to add the new name values into their new fields
}

Could I set a counter inside my foreach loop and add the names back in depending on the index of the row? I need help on how to add the new first and last name values back into my new fields.
thanks

A: Try
DataTable DBTable = LoadMailingListContent(Location);

DataColumn dc = new DataColumn("FirstName");
DBTable.Columns.Add(dc);
dc = new DataColumn("LastName");
DBTable.Columns.Add(dc);
foreach (DataRow d in DBTable.Rows)
{
    var names = d["fullname"].ToString().Split(' ');
    d["FirstName"] = names[0];
    d["LastName"] = names[1];
}

A: Below is simple example to add column and its value to existing datatable.
string status = "ABC";
        DataColumn dc = new DataColumn("Status");
        dt.Columns.Add(dc);
        foreach (DataRow dr in dt.Rows)
        {
            dr["status"]= status;
        }
        return dt;

The resulting datatable will look like
ExistingColumn | Status
ExistingValue  | ABC

A: for (int iter = 0; iter < fullNames.Count; iter++)
{
  var names = fullNames[iter].Split(' ');
  string firstName = names[0];
  string lastName = names[1];
  DBTable.Rows[iter]["First Name"] = firstName;
  DBTable.Rows[iter]["Last Name"] = lastName;
}

A: DBTable["First Name"] = firstName;
DBTable["Last Name"] = lastName;


text:
Q: What kind of memory DIMM for Dell Vostro 3670 I want to add some memory to my Dell Vostro 3670 running an Intel i5-8400. At neither Crucial nor Kingston do I find the Vostro 3670 listed.
What kind of memory should I get?

A:
What kind of memory should I get?

The Dell Vostro 3670 comes with 8 GB DDR4 but there are other configuration possibilities.  You have a Core i5-8400, which is a desktop processor, so you want to purchase DDR4 for a desktop.  The other processor configurations are also desktop processors.  The maximum amount of memory it supports is 32 GB.  It supports 2666 MHz DDR4 Non-ECC modules. The other processors support a different memory frequency, checking the specifications for your particular configuration, is highly recommended
Specifications
Manual

A: Here are the memory specs for your model.
So they are udimm memory modules (you have 2 module slots) at various sizes (GB) and speeds (Mhz)
Your support page

A: You can use a scanner like the one at Crucial to get your current specs (link below).
http://www.crucial.com/usa/en/systemscanner
Alternatively, the instructions at the link below will show your current specs.
https://www.tenforums.com/tutorials/66809-determine-system-memory-size-speed-type-windows-10-a.html
From this info, you'll see that for a laptop, you likely have two banks, each occupied. You'll need to swap them both out for replacement. You likely want a pair of modules in the same form factor as your existing, capacity depending on the maximum the motherboard can handle (need more research there, likely 4Gb or 8Gb each). You'll want a clock speed equal or greater than your current. Remember, the bus sets the speed so you need to support at least that speed or exceed it with your selection. 1) Form factor 2) Capacity 3) Speed. Physically swapping them will be something for the Dell website, keep all contact surfaces clean and untouched by grubby fingers, and make sure the modules are firmly 'seated' in the bays before replacing the cover. Good luck


text:
Q: ArcGis 10 interpolate Z between polyline's vertices (IZ.InterpolateZsBetween ?) Here's what's happening:
I want to create a 3D line using only the height of some GSP points. I need to be able to extrapolate the vertice's height between where it's known to the one where it's unkonwn.
What I have tried:

*

*Creating a TIN from GPS points: where the line meanders and there is no GPS points, the height is not correct.

*Linear Referencing tools: but as originally the Polyline Z has no value interpolated between each vertex, it doesn't seem to do what is needed

*Conversion of Point to raster at a 1 m cell (Nodata outside the cell where the GPS points lay) and extraction of the Z value to the vertex where they overlap the cell with value, leaving the not-overlapping vertices without Z value.

Is this what I need?:
I think I should use something like "IZ.InterpolateZsBetween" but I am useless at coding.
Could someone please explain me how to implement this fonction?
Many thanks

A: IZ.InterpolateZsBetween interpolates between vertices with Z value. Use it if your polyline has some Z values.
Otherwise you can use Extract Values to points or
Interpolate Shape. These both require surface that you may get your values. Not sure if TIN would be ok, but always you can convert TIN To Raster.
Also you could construct polyline ZM and Calibrate Route M with your GPS points. It should do what IZ.InterpolateZsBetween, only for M. Than you could use M as Z. though as far as I remember year back there was a bug in this algorithm. Still worth a try.


text:
Q: Split dataframe by row at first instance I am trying to split a dataframe into two pieces by rows at the first instance of a certain value i.e., not splitting by groups. For example, if my data is:
patid disease
3     Z
99    B
4     A
1002  B
43    A
745   C
399   Z
545   A
8     A

I would like two dataframes from this, the first dataframe to contain the first two patid rows and the second to contain all of the others i.e., I am splitting from the first instances of disease A. Ultimately I will discard everything that came before A, i.e., the first two occurrences of diseases B and Z.
Please note, I cannot order the rows in any way as these are time-course (medical history) records.
I can do this in a loop, easy! However, I know that R does not favour loops.

A: If your ultimate goal is to subset the data, you can do this directly:
subset(df, cumsum(disease == "A") >= 1)
#  patid disease
#3     4       A
#4  1002       B
#5    43       A
#6   745       C
#7   399       Z
#8   545       A
#9     8       A

But if you want to split the data, you can do it similarly:
split(df, cumsum(df$disease == "A") >= 1)
# $`FALSE`
# patid disease
# 1     3       Z
# 2    99       B
#
# $`TRUE`
# patid disease
# 3     4       A
# 4  1002       B
# 5    43       A
# 6   745       C
# 7   399       Z
# 8   545       A
# 9     8       A

A: Another way is using which.max to get the index of first occurrence of "A" in disease column and get all the rows after that.
df[which.max(df$disease == "A"):nrow(df), ]

#  patid disease
#3     4       A
#4  1002       B
#5    43       A
#6   745       C
#7   399       Z
#8   545       A
#9     8       A

and the same thing could also be achieved with match
df[match("A", df$disease):nrow(df), ]

A: You could use which.min and grepl function altogether:
df[which.min(!grepl("A", df[,"disease"])):nrow(df),]

Obtaining
  patid disease
3     4       A
4  1002       B
5    43       A
6   745       C
7   399       Z
8   545       A
9     8       A


text:
Q: Searching in array returns only the first result I'm trying to search in an array and find specific objects based on their category.
But when I run my code, I only get one result. but in the example below, I should have two results because the cat 2 exists in two of the objects!
This is what I have:

var storedArray = [{
 "title": "test title 1",
 "date_added": "2018-09-26",
 "url": "someurl.com",
 "filename": "file 1",
 "category": "cat 1"
}, {
 "title": "test title 2",
 "date_added": "2018-10-25",
 "url": "someurl.com",
 "filename": "file 2",
 "category": "cat 2"
},{
 "title": "test title 3",
 "date_added": "2018-10-25",
 "url": "someurl.com",
 "filename": "file 3",
 "category": "cat 2"
}];

var result = storedArray.find( audio => audio.category === 'cat 2' );

console.log(result);

Could someone please advice on this issue?

A: Array.prototype.find() returns the first element found. You are looking for Array.prototype.filter()

A: You want to use filter function.

A: Array.prototype.find()

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

From the above, you have to use filter() to get the expected result:

var storedArray = [{
 "title": "test title 1",
 "date_added": "2018-09-26",
 "url": "someurl.com",
 "filename": "file 1",
 "category": "cat 1"
}, {
 "title": "test title 2",
 "date_added": "2018-10-25",
 "url": "someurl.com",
 "filename": "file 2",
 "category": "cat 2"
},{
 "title": "test title 3",
 "date_added": "2018-10-25",
 "url": "someurl.com",
 "filename": "file 3",
 "category": "cat 2"
}];

var result = storedArray.filter( audio => audio.category === 'cat 2' );

console.log(result);

A: From the MDN documentation on find...

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

Key word: first.

A: The method you are using .find() is returning only the first record that matches the condition, this is why you are getting only 1 result.


text:
Q: How to make an effect plot for GLM model with ggplot? I have a generalized linear model (family - gamma) with interaction, and need to plot it specifically in ggplot2 (on a response scale).
The model was constructed with following code:
fit1mult = glm(SIZE_OOCYTE ~ TREATMENT * CASTE,
               family = Gamma(link = "log"), data=data1)

I made a plot using the lattice package, and it looks like this:

How can I make a similar one in ggplot? I know that the geom_smooth has an option glm, but don't know how to apply it.
Thanks in advance for suggestions!
UPD. Solution:
library(ggeffects)

 mydf1 <- ggpredict(fit1mult, terms = c("CASTE", "TREATMENT"))

 plot(mydf1)

Result:
new plot


text:
Q: How to check loop.php is called from which file or code? I want to check in loop.php file from which code it is called
Like i call it as <?php get_template_part('loop','index'); ?>
and secondly i call it as <?php get_template_part('loop', 'category'); ?>
i want to give different <div> structure & style according to differentiation.
like if loop.php is called from category.php page then font-color of title should be red otherwise blue.
Any IDEA...?

A: If you wish to make this yourself by modifying code, then I think you are looking for the
$_SERVER['SCRIPT_FILENAME'] variable in order to be able to figure out if loop.php is called from category.php or index.php


text:
Q: stringContains argument matching within Laravel Log facade shouldReceive I saw in the Laravel docs that it's possible to set a test expectation like this:
Cache::shouldReceive('get')
                ->once()
                ->with('key')
                ->andReturn('value');

Then I saw in the PHPunit docs that flexible argument matching is possible like this: $this->stringContains('Something').
But when I edit my test to have this:
Log::shouldReceive('error')
            ->once();
            ->with($this->stringContains('Contact does not exist'));

...then I get the following error:
Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_1_Illuminate_Log_Writer::error("Contact does not exist blah blah etc").
Either the method was unexpected or its arguments matched no expected argument list for this method

How can I accomplish my goal (with flexible argument matching within Log::shouldReceive)?
P.S. I've also tried ->with(\PHPUnit\Framework\Assert::stringContains('Contact does not exist')).

A: The mocking functionality of facades uses Mockery to generate mock objects. stringContains() is functionality provided by PHPUnit mock objects. These two are not compatible.
You will need to use argument validation methods provided by Mockery.
My first attempt would be to use the \Mockery::pattern() matcher which uses regular expressions:
Log::shouldReceive('error')
    ->once()
    ->with(\Mockery::pattern('/Contact does not exist/'));

Another option would be to use the \Mockery::on() matcher, which allows you to use a Closure to provide complex argument matching logic.
Log::shouldReceive('error')
    ->once()
    ->with(\Mockery::on(function ($arg) {
        return stripos($arg, 'Contact does not exist') !== false;
    }));


text:
Q: How to set variables in While Loop in Sql Server I am trying to use while loop instead of CURSOR in SQL SERVER. I am trying to select TOP 1 in while and set them to the variables like below. It doesnt let me set the variables in while loop. What am I doing wrong?
WHILE (
        SELECT TOP 1 @WAOR_CODE = WAOR_.WAOR_CODE
                   , @WAOD_INVENTORYITEMID = WAOD_.WAOD_INVENTORYITEMID
        FROM #wmsorder
    )
BEGIN
    SELECT @WAOR_CODE
         , @WAOD_INVENTORYITEMID

    DELETE TOP (1) #wmsorder
END

A: Another option:
WHILE EXISTS(select 1 FROM #wmsorder)
BEGIN
    DELETE TOP (1)
    FROM #wmsorder
END

However, deleting all records from a table one by one might be a performance hell. You might want to consider using TRUNCATE TABLE instead:
TRUNCATE TABLE #wmsorder

Also, note that each delete is written to the database log, while truncate table doesn't get written to the log at all.
Testing with a temporary table containing 100,000 rows, deleting the rows one by one took me 9 seconds, while truncate table completed immediately:
-- create and populate sample table
SELECT TOP 100000 IDENTITY(int,1,1) AS Number
    INTO #wmsorder
    FROM sys.objects s1
    CROSS JOIN sys.objects s2

    -- delete rows one by one
    WHILE EXISTS(select 1 FROM #wmsorder)
    BEGIN
        DELETE TOP (1)
        FROM #wmsorder
    END

-- clean up
DROP TABLE #wmsorder

-- create and populate sample table
SELECT TOP 100000 IDENTITY(int,1,1) AS Number
    INTO #wmsorder
    FROM sys.objects s1
    CROSS JOIN sys.objects s2

-- truncate the table
TRUNCATE TABLE #wmsorder

-- clean up
DROP TABLE #wmsorder

A: DECLARE @t TABLE (a INT PRIMARY KEY)
INSERT INTO @t
VALUES (1), (2), (3)

Variant #1:
label:
    DELETE TOP(1)
    FROM @t
    OUTPUT DELETED.a
IF @@ROWCOUNT > 0
    GOTO label

Variant #2:
WHILE @@ROWCOUNT != 0
    DELETE TOP(1)
    FROM @t
    OUTPUT DELETED.a

Variant #3:
DECLARE @a TABLE(a INT)

WHILE @@ROWCOUNT != 0 BEGIN

    DELETE FROM @a

    DELETE TOP(1)
    FROM @t
    OUTPUT DELETED.a INTO @a

    SELECT * FROM @a

END

A:
See the below code. I just corrected the SQL statements shared by you

WHILE 1=1
BEGIN
        IF NOT EXISTS (SELECT 1 FROM #wmsorder)
            BREAK
        SELECT TOP 1 @WAOR_CODE = WAOR_.WAOR_CODE
            ,@WAOD_INVENTORYITEMID = WAOD_.WAOD_INVENTORYITEMID
        FROM #wmsorder WAOR_

        SELECT @WAOR_CODE
        ,@WAOD_INVENTORYITEMID

        DELETE #wmsorder WHERE WAOR_CODE = @WAOR_CODE AND WAOD_INVENTORYITEMID = @WAOD_INVENTORYITEMID
END

But as Zohar Peled mentioned, it will be a pain to the engine if you are deleting the records one by one from a table. So below I have shared another query, through this even you can track the records before deleting from the table

DECLARE @TableVar AS TABLE (WAOR_CODE VARCHAR(100), WAOD_INVENTORYITEMID VARCHAR(100))
    WHILE 1=1
    BEGIN
            SELECT TOP 1 @WAOR_CODE = WAOR_.WAOR_CODE
                ,@WAOD_INVENTORYITEMID = WAOD_.WAOD_INVENTORYITEMID
            FROM #wmsorder WAOR_
            WHERE NOT EXISTS (SELECT 1 FROM @TableVar t WHERE t.WAOR_CODE = WAOR_.WAOR_CODE AND t.WAOD_INVENTORYITEMID = WAOR_.WAOD_INVENTORYITEMID)
            IF @WAOR_CODE IS NULL AND @WAOD_INVENTORYITEMID IS NULL
                BREAK

            INSERT INTO @TableVar
            (WAOR_CODE, WAOD_INVENTORYITEMID)
            SELECT @WAOR_CODE
            ,@WAOD_INVENTORYITEMID
    END
DELETE #wmsorder WHERE EXISTS (SELECT 1 FROM @TableVar t WHERE t.WAOR_CODE = #wmsorder.WAOR_CODE AND t.WAOD_INVENTORYITEMID = #wmsorder.WAOD_INVENTORYITEMID)

Sorry I did not test the second code. Please forgive me if it breaks something. But I am pretty sure it may require a small repair to make this query functional. All the best.


text:
Q: Can I test Exchange Web Services off Office 365 I am looking to get involved with Exchange Web services. Is Office 365 a good place to do this.  I don't have the time and infrastructure to install exchange in the office to test everything.  So is office 365 a good test bed?
Rico

A: You can use Office 365 to test the WebService. It's very easy to use once it is set up and you get a 30 day test account.
Limitation: To get AutoDiscover to work, you either need to fiddle around with your DNS settings, or follow Glens advice on this page: http://social.technet.microsoft.com/Forums/en/exchangesvrdevelopment/thread/03e5e902-1de1-43b9-a86d-13e3d826c920


text:
Q: Ceilometer or Healthnmon for measuring VM stats in OpenStack I am looking to measure stats for VMs running in OpenStack environment. Stats would be like Uptime, CPU or RAM consumption just by that VM.
My understanding from reading the documentation is that Ceilometer and Healthnmon are for measuring the stats of the resources used on individual OpenStack nodes.
Is this true or can Ceilometer or Healthnmon be extended to capture monitoring stats from VMs as well?

A: Ceilometer meters can be used to monitor the vm vital stats. In hea templates this is been used to monitor vm cpu utilizations and memory consumptions.


text:
Q: Copy From Previous Button Hi I  have a basic question related to C Sharp.
I have a windows application, with some text fields, dropwown's and radio buttons.Now user fills in information in these fields and saves the information, which is stored in backend db. Once this task is done i reset all the fields.
Now what i want is when user has to save information for the next time, there should be a button like "Copy From Previous", when user clicks on it, the details in the box should be copied from previous task, instead of user having to fill in details again.
I would like to know what is the best approach to implement this in C Sharp. I was thinking of using dictionary in C Sharp.
Like
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("txtKeyToSucess", "Pray to One God Alone");
d.Add("txtAdvise", "Dont associate any partners with God");
d.Add("txtResult", "You will be judged for your actions");

if (d.ContainsKey("txtKeyToSucess"))
    {
        String v = d["txtKeyToSucess"];
        txtKeyToSucess.text = v;
    }

Still not sure. Can you kindly advise how to do this with best possible approach. Recommended section of code if possible.
Thanks.

A: Why don't you store a reference to the fields in the database? So once you store it, retain the ID to the data, and then the copy button could just query the database, fill the fields, and you're all good.

A: Since you have a well known set of fields you could just create a class for this:
public class Settings
{
   public string KeyToSucces {get;set;}
   public string Advise {get;set;}
   public string Result {get;set;}
}

Now you can just copy the settings from your Settings instance. In general you should not mix presentation ( i.e. txtKeyToSucess) with your model (Settings in this case) if not neccessary.