问:
Material-ui drawer width issue
I'm facing an issue with material-ui drawer. I've changed the width of the drawer container which causes a a problem . The drawer remains a little inside the page and visible but I don't want to make it visible on the page while I haven't clicked the button. It might be having an issue with the transform attribute now.

So I changed it to transform: translate(350px, 0px) but then I'm getting another issue, that is if I am clicking the button the drawer is not showing up. Any help on this thing ??

I have got the solution and edited the code.

I've created a Demo here => Have a look

Also shared the code below:

index.js

```<code>import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import Drawer from 'material-ui/Drawer';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

class App extends Component {
  constructor() {
    super();
    this.state = {
      openDrawer: false
    };
  }

  toggleDrawer() {
    this.setState({
      openDrawer: !this.state.openDrawer
    });
  }

  render() {
    return (
      <MuiThemeProvider>
      <div>
        <button onClick={this.toggleDrawer.bind(this)}> Toggle Drawer</button>
        <Drawer
                  open={this.state.openDrawer}
                  containerClassName={!this.state.openDrawer? "hide-drawer": "show-drawer" }
                  openSecondary={true}
                  docked={true}
                >
                    <div className="drawer-title-div">
                        <h4 className="drawer-title-text">It's my drawer</h4>
                    </div>
                </Drawer>
      </div>
      </MuiThemeProvider>
    );
  }
}

render(<App />, document.getElementById('root'));
</code>```

style.css

```<code>h1, p {

font-family: Lato;
}

.show-drawer {
  top: 47px !important;
  text-align: left !important;
  width: 80% !important;
  transform: translate(0%, 0px) !important;
}

.hide-drawer {
  top: 47px !important;
  text-align: left !important;
  width: 80% !important;
  transform: translate(100%, 0px) !important;
}

/* .drawer-side-drawer:focus {
  top: 47px !important;
  text-align: left !important;
  width: 350px !important;
  transform: translate(0px, 0px) !important;
} */

.drawer-title-div {
  display: inline-block;
  width: 100%;
  background: #F2F8FB;
  box-shadow: 0 1px 3px 0 rgba(0,0,0,0.24);
}

.drawer-title-text {
  display: inline-block;
  margin-left: 16px;
  margin-top: 16px;
  margin-bottom: 16px;
  color: #484848;
  font-family: Muli;
  font-size: 16px;
  font-weight: 600;
}
</code>```

答:
You can use window.innerWidth as width: 100%:

```<code>    <Drawer ...>
        <div style={{width: window.innerWidth * 0.25}}>
            ...
        </div>
    </Drawer>
</code>```

Title: Material-ui drawer width issue

Body:
I'm facing an issue with material-ui drawer. I've changed the width of the drawer container which causes a a problem . The drawer remains a little inside the page and visible but I don't want to make it visible on the page while I haven't clicked the button. It might be having an issue with the transform attribute now.

So I changed it to transform: translate(350px, 0px) but then I'm getting another issue, that is if I am clicking the button the drawer is not showing up. Any help on this thing ??

I have got the solution and edited the code.

I've created a Demo here => Have a look

Also shared the code below:

index.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import Drawer from 'material-ui/Drawer';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

class App extends Component {
  constructor() {
    super();
    this.state = {
      openDrawer: false
    };
  }

  toggleDrawer() {
    this.setState({
      openDrawer: !this.state.openDrawer
    });
  }

  render() {
    return (
      <MuiThemeProvider>

        <button onClick={this.toggleDrawer.bind(this)}> Toggle Drawer</button>
        <Drawer
                  open={this.state.openDrawer}
                  containerClassName={!this.state.openDrawer? "hide-drawer": "show-drawer" }
                  openSecondary={true}
                  docked={true}
                >

It's my drawer

                </Drawer>

      </MuiThemeProvider>
    );
  }
}

render(<App />, document.getElementById('root'));

style.css

h1, p {

font-family: Lato;
}

.show-drawer {
  top: 47px !important;
  text-align: left !important;
  width: 80% !important;
  transform: translate(0%, 0px) !important;
}

.hide-drawer {
  top: 47px !important;
  text-align: left !important;
  width: 80% !important;
  transform: translate(100%, 0px) !important;
}

/* .drawer-side-drawer:focus {
  top: 47px !important;
  text-align: left !important;
  width: 350px !important;
  transform: translate(0px, 0px) !important;
} */

.drawer-title-div {
  display: inline-block;
  width: 100%;
  background: #F2F8FB;
  box-shadow: 0 1px 3px 0 rgba(0,0,0,0.24);
}

.drawer-title-text {
  display: inline-block;
  margin-left: 16px;
  margin-top: 16px;
  margin-bottom: 16px;
  color: #484848;
  font-family: Muli;
  font-size: 16px;
  font-weight: 600;
}

Body:
You can use window.innerWidth as width: 100%:

    <Drawer ...>
        <div style={{width: window.innerWidth * 0.25}}>
            ...
        </div>
    </Drawer>


来源: stackexchange

问:
Call variable inside class from function inside class without $this
I recently needed to change my function to static and now $this does not work, and i need to get variable in the same class is there way to do it without $this?</p>

答:
Prefix it with:

```<code>self::$VariableName
</code>```

or

```<code>MyClassName::$VariableName
</code>```

(For more info: http://php.net/manual/en/language.oop5.static.php)

ContentLicense: CC BY-SA 3.0

Body:
Prefix it with:

self::$VariableName

or

MyClassName::$VariableName

(For more info: http://php.net/manual/en/language.oop5.static.php)


问:
Serviceworker.js code being shown on page (only in Google) each time i open root site directory and being replaced with index.html after ctrl+f5
I guess, it is something about django-pwa. This problem appears only in google chrome (in local mode it even works fine on 127.0.0.1:8000 but doesnt work on localhost:8000).

My project structure:

```<code>D:.
├───api
│   └───migrations
├───core
│   └───__pycache__
├───games
│   └───migrations
├───main
│   ├───migrations
│   └───__pycache__
├───static
│   ├───images
│   └───js
├───staticfiles
└───templates
</code>```

it appears, that chrome browser requests the empty path for pwa.urls firstly, but other browsers requesting main urls. i dont really how to make chrome request my urls from main app on first place.

this is my urls.py:

```<code>from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import TemplateView
from rest_framework.schemas import get_schema_view
import debug_toolbar

schema_url_patterns = [
    path('api/v1/', include('api.urls')),
]

urlpatterns = [
    path(r'', include('main.urls')),
    path('openapi', get_schema_view(
        title="Gamers Gazette",
        description="API!",
        version="1.0.0",
        patterns=schema_url_patterns,
        ), name='openapi-schema'),

    path('swagger-ui/', TemplateView.as_view(
        template_name='swagger-ui.html',
        extra_context={'schema_url':'openapi-schema'}
    ), name='swagger-ui'),

    path('redoc/', TemplateView.as_view(
        template_name='redoc.html',
        extra_context={'schema_url':'openapi-schema'}
    ), name='redoc'),

    path('admin/', admin.site.urls),
    path('games/', include('games.urls')),
    path('api/v1/', include('api.urls')),
    path("", include("pwa.urls")),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        path('__debug__/', include('debug_toolbar.urls')),
    ] + urlpatterns
</code>```

this is my serviceworker.js:

```<code>var staticCacheName = 'djangopwa-v1';

self.addEventListener("install", event => {
    this.skipWaiting();
    event.waitUntil(
        caches.open(staticCacheName)
            .then(cache => {
                return cache.addAll(filesToCache);
            })
    )
});

// Clear cache on activate
self.addEventListener('activate', event => {
    event.waitUntil(
        caches.keys().then(cacheNames => {
            return Promise.all(
                cacheNames
                    .filter(cacheName => (cacheName.startsWith("django-pwa-")))
                    .filter(cacheName => (cacheName !== staticCacheName))
                    .map(cacheName => caches.delete(cacheName))
            );
        })
    );
});

// Serve from Cache
self.addEventListener("fetch", event => {
    event.respondWith(
        caches.match(event.request)
            .then(response => {
                return response || fetch(event.request);
            })
            .catch(() => {
                return caches.match('offline');
            })
    )
});
</code>```

the settings.py:

```<code>from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
PWA_SERVICE_WORKER_PATH = os.path.join(BASE_DIR, 'static/js', 'serviceworker.js')

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-fl61624yl*s1hbc9lt@9ipbmyytdrurqo@dc%$3pdz9g8haof3'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
SESSIONS_ENGINE='django.contrib.sessions.backends.cache'
ALLOWED_HOSTS = []

INSTALLED_APPS = [
    #apps
    'main',
    'api',
    'games',
    #django staff
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #drf staff
    'rest_framework',
    #debugging
    "debug_toolbar",
    #third_party
    "pwa"
]

MIDDLEWARE = [
    #django staff
    "debug_toolbar.middleware.DebugToolbarMiddleware",
    'debug_toolbar_force.middleware.ForceDebugToolbarMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

]

ROOT_URLCONF = 'core.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'core.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'main_db',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': 'db',
        'PORT': '5432'
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

if DEBUG:
    import socket  # only if you haven't already imported this
    hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
    INTERNAL_IPS = [ip[:-1] + '1' for ip in ips] + ['127.0.0.1', '10.0.2.2']

# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static/"),
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
        'LOCATION': 'cache:11211',
    }
}

#PWA STAFF
PWA_APP_NAME = 'test app'
PWA_APP_DESCRIPTION = "test app PWA"
PWA_APP_THEME_COLOR = '#000000'
PWA_APP_BACKGROUND_COLOR = '#ffffff'
PWA_APP_DISPLAY = 'standalone'
PWA_APP_SCOPE = '/'
PWA_APP_ORIENTATION = 'any'
PWA_APP_START_URL = '/'
PWA_APP_STATUS_BAR_COLOR = 'default'
PWA_APP_ICONS = [
    {
        'src': 'static/images/icon.png',
        'sizes': '160x160'
    }
]
PWA_APP_ICONS_APPLE = [
    {
        'src': 'static/images/icon.png',
        'sizes': '160x160'
    }
]
PWA_APP_SPLASH_SCREEN = [
    {
        'src': 'static/images/icon.png',
        'media': '(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)'
    }
]
PWA_APP_DIR = 'ltr'
PWA_APP_LANG = 'ru-RU'

import django_heroku
django_heroku.settings(locals())
</code>```

ask eweryting You need

答: Sorry for iterrupting, the problew was in Google. It cached a wrong version of script, after cleaning cache ewerything was fine.</p>

ContentLicense: CC BY-SA 4.0

Body:
I guess, it is something about django-pwa. This problem appears only in google chrome (in local mode it even works fine on 127.0.0.1:8000 but doesnt work on localhost:8000).

My project structure:

D:.
├───api
│   └───migrations
├───core
│   └───__pycache__
├───games
│   └───migrations
├───main
│   ├───migrations
│   └───__pycache__
├───static
│   ├───images
│   └───js
├───staticfiles
└───templates

it appears, that chrome browser requests the empty path for pwa.urls firstly, but other browsers requesting main urls. i dont really how to make chrome request my urls from main app on first place.

this is my urls.py:

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import TemplateView
from rest_framework.schemas import get_schema_view
import debug_toolbar

schema_url_patterns = [
    path('api/v1/', include('api.urls')),
]

urlpatterns = [
    path(r'', include('main.urls')),
    path('openapi', get_schema_view(
        title="Gamers Gazette",
        description="API!",
        version="1.0.0",
        patterns=schema_url_patterns,
        ), name='openapi-schema'),

    path('swagger-ui/', TemplateView.as_view(
        template_name='swagger-ui.html',
        extra_context={'schema_url':'openapi-schema'}
    ), name='swagger-ui'),

    path('redoc/', TemplateView.as_view(
        template_name='redoc.html',
        extra_context={'schema_url':'openapi-schema'}
    ), name='redoc'),

    path('admin/', admin.site.urls),
    path('games/', include('games.urls')),
    path('api/v1/', include('api.urls')),
    path("", include("pwa.urls")),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        path('__debug__/', include('debug_toolbar.urls')),
    ] + urlpatterns

this is my serviceworker.js:

var staticCacheName = 'djangopwa-v1';

self.addEventListener("install", event => {
    this.skipWaiting();
    event.waitUntil(
        caches.open(staticCacheName)
            .then(cache => {
                return cache.addAll(filesToCache);
            })
    )
});

// Clear cache on activate
self.addEventListener('activate', event => {
    event.waitUntil(
        caches.keys().then(cacheNames => {
            return Promise.all(
                cacheNames
                    .filter(cacheName => (cacheName.startsWith("django-pwa-")))
                    .filter(cacheName => (cacheName !== staticCacheName))
                    .map(cacheName => caches.delete(cacheName))
            );
        })
    );
});

// Serve from Cache
self.addEventListener("fetch", event => {
    event.respondWith(
        caches.match(event.request)
            .then(response => {
                return response || fetch(event.request);
            })
            .catch(() => {
                return caches.match('offline');
            })
    )
});

the settings.py:

from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
PWA_SERVICE_WORKER_PATH = os.path.join(BASE_DIR, 'static/js', 'serviceworker.js')

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-fl61624yl*s1hbc9lt@9ipbmyytdrurqo@dc%$3pdz9g8haof3'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
SESSIONS_ENGINE='django.contrib.sessions.backends.cache'
ALLOWED_HOSTS = []

INSTALLED_APPS = [
    #apps
    'main',
    'api',
    'games',
    #django staff
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #drf staff
    'rest_framework',
    #debugging
    "debug_toolbar",
    #third_party
    "pwa"
]

MIDDLEWARE = [
    #django staff
    "debug_toolbar.middleware.DebugToolbarMiddleware",
    'debug_toolbar_force.middleware.ForceDebugToolbarMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

]

ROOT_URLCONF = 'core.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'core.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'main_db',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': 'db',
        'PORT': '5432'
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

if DEBUG:
    import socket  # only if you haven't already imported this
    hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
    INTERNAL_IPS = [ip[:-1] + '1' for ip in ips] + ['127.0.0.1', '10.0.2.2']

# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static/"),
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
        'LOCATION': 'cache:11211',
    }
}

#PWA STAFF
PWA_APP_NAME = 'test app'
PWA_APP_DESCRIPTION = "test app PWA"
PWA_APP_THEME_COLOR = '#000000'
PWA_APP_BACKGROUND_COLOR = '#ffffff'
PWA_APP_DISPLAY = 'standalone'
PWA_APP_SCOPE = '/'
PWA_APP_ORIENTATION = 'any'
PWA_APP_START_URL = '/'
PWA_APP_STATUS_BAR_COLOR = 'default'
PWA_APP_ICONS = [
    {
        'src': 'static/images/icon.png',
        'sizes': '160x160'
    }
]
PWA_APP_ICONS_APPLE = [
    {
        'src': 'static/images/icon.png',
        'sizes': '160x160'
    }
]
PWA_APP_SPLASH_SCREEN = [
    {
        'src': 'static/images/icon.png',
        'media': '(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)'
    }
]
PWA_APP_DIR = 'ltr'
PWA_APP_LANG = 'ru-RU'

import django_heroku
django_heroku.settings(locals())

ask eweryting You need


问:
Unlist gives me a longer vector than expected
I am performing an RNA-seq analysis and I need a logical vector, however I am starting from a SimpleLogicalList called hk with 58037 elements, that I obtained from hk <- features.info$symbol %in% house_keeping_genes where features.info is a dataframe and house_keeping_genes is a vector.

After using unlist(hk) 58731 elements are retrieved. Then I realized that there were parts of the list that contained more than two elements (in stead of just FALSE, it contained FALSE FALSE FALSE, thus increasing the length of the result.

Then I just used a unlist(unique(hk)) and most of the unexpected variables were dropped, however there were still 58041 elements in stead of 58037 and I have no idea where are they coming from. I checked and there are no NA being generated.

What could I do to find where those 4 extra elements are coming from?

```<code>> dput(hk[60:70])
new("SimpleLogicalList", elementType = "logical", elementMetadata = NULL,
    metadata = list(), listData = list(ENSG00000004777 = FALSE,
        ENSG00000004779 = FALSE, ENSG00000004799 = FALSE, ENSG00000004809 = FALSE,
        ENSG00000004838 = FALSE, ENSG00000004846 = FALSE, ENSG00000004848 = FALSE,
        ENSG00000004864 = FALSE, ENSG00000004866 = c(FALSE, FALSE,
        FALSE), ENSG00000004897 = TRUE, ENSG00000004939 = FALSE))

> dput(features.info$symbol[1:5])
new("SimpleCharacterList", elementType = "character", elementMetadata = NULL,
    metadata = list(), listData = list(ENSG00000000003 = "TSPAN6",
        ENSG00000000005 = "TNMD", ENSG00000000419 = "DPM1", ENSG00000000457 = "SCYL3",
        ENSG00000000460 = "C1orf112"))

> dput(house_keeping_genes[1:5])
c("DPM1", "SCYL3", "GCLC", "BAD", "LAP3")
</code>```

Edit:  I need the logical vector to use it as an argument for RUVg()
function and if I write hk an error is retrieved: > Error in Ycenter[, cIdx] : invalid subscript type 'S4'.

Packages:

```<code>other attached packages:
 [1] NCmisc_1.1.6                RUVSeq_1.28.0               EDASeq_2.28.0               ShortRead_1.52.0
 [5] GenomicAlignments_1.30.0    Rsamtools_2.10.0            Biostrings_2.62.0           XVector_0.34.0
 [9] snpStats_1.44.0             Matrix_1.4-0                survival_3.2-13             sva_3.42.0
[13] BiocParallel_1.28.3         genefilter_1.76.0           mgcv_1.8-38                 nlme_3.1-153
[17] pheatmap_1.0.12             ggfortify_0.4.14            ggplot2_3.3.5               edgeR_3.36.0
[21] limma_3.50.0                dplyr_1.0.7                 SummarizedExperiment_1.24.0 GenomicRanges_1.46.1
[25] GenomeInfoDb_1.30.0         IRanges_2.28.0              S4Vectors_0.32.3            MatrixGenerics_1.6.0
[29] matrixStats_0.61.0          tweeDEseqCountData_1.32.0   Biobase_2.54.0              BiocGenerics_0.40.0
</code>```

答:
The issue would be that some of the symbol (which is a SimpleLogicalList) contains more than one element, so we loop over the list with sapply, and wrap with any which returns a single TRUE/FALSE if any of the elements in the list element are present %in% 'house_keeping_genes.  The \(x) is a concise way to represent lambda function (function(x)) in the recent versions of R

```<code>hk1 <- sapply(features.info$symbol, \(x)
         any(x %in% house_keeping_genes, na.rm = TRUE))
</code>```

Body:
I am performing an RNA-seq analysis and I need a logical vector, however I am starting from a SimpleLogicalList called hk with 58037 elements, that I obtained from hk <- features.info$symbol %in% house_keeping_genes where features.info is a dataframe and house_keeping_genes is a vector.

After using unlist(hk) 58731 elements are retrieved. Then I realized that there were parts of the list that contained more than two elements (in stead of just FALSE, it contained FALSE FALSE FALSE, thus increasing the length of the result.

Then I just used a unlist(unique(hk)) and most of the unexpected variables were dropped, however there were still 58041 elements in stead of 58037 and I have no idea where are they coming from. I checked and there are no NA being generated.

What could I do to find where those 4 extra elements are coming from?

> dput(hk[60:70])
new("SimpleLogicalList", elementType = "logical", elementMetadata = NULL,
    metadata = list(), listData = list(ENSG00000004777 = FALSE,
        ENSG00000004779 = FALSE, ENSG00000004799 = FALSE, ENSG00000004809 = FALSE,
        ENSG00000004838 = FALSE, ENSG00000004846 = FALSE, ENSG00000004848 = FALSE,
        ENSG00000004864 = FALSE, ENSG00000004866 = c(FALSE, FALSE,
        FALSE), ENSG00000004897 = TRUE, ENSG00000004939 = FALSE))

> dput(features.info$symbol[1:5])
new("SimpleCharacterList", elementType = "character", elementMetadata = NULL,
    metadata = list(), listData = list(ENSG00000000003 = "TSPAN6",
        ENSG00000000005 = "TNMD", ENSG00000000419 = "DPM1", ENSG00000000457 = "SCYL3",
        ENSG00000000460 = "C1orf112"))

> dput(house_keeping_genes[1:5])
c("DPM1", "SCYL3", "GCLC", "BAD", "LAP3")

Edit:  I need the logical vector to use it as an argument for RUVg()
function and if I write hk an error is retrieved: > Error in Ycenter[, cIdx] : invalid subscript type 'S4'.

Packages:

other attached packages:
 [1] NCmisc_1.1.6                RUVSeq_1.28.0               EDASeq_2.28.0               ShortRead_1.52.0
 [5] GenomicAlignments_1.30.0    Rsamtools_2.10.0            Biostrings_2.62.0           XVector_0.34.0
 [9] snpStats_1.44.0             Matrix_1.4-0                survival_3.2-13             sva_3.42.0
[13] BiocParallel_1.28.3         genefilter_1.76.0           mgcv_1.8-38                 nlme_3.1-153
[17] pheatmap_1.0.12             ggfortify_0.4.14            ggplot2_3.3.5               edgeR_3.36.0
[21] limma_3.50.0                dplyr_1.0.7                 SummarizedExperiment_1.24.0 GenomicRanges_1.46.1
[25] GenomeInfoDb_1.30.0         IRanges_2.28.0              S4Vectors_0.32.3            MatrixGenerics_1.6.0
[29] matrixStats_0.61.0          tweeDEseqCountData_1.32.0   Biobase_2.54.0              BiocGenerics_0.40.0

Body:
The issue would be that some of the symbol (which is a SimpleLogicalList) contains more than one element, so we loop over the list with sapply, and wrap with any which returns a single TRUE/FALSE if any of the elements in the list element are present %in% 'house_keeping_genes.  The \(x) is a concise way to represent lambda function (function(x)) in the recent versions of R

hk1 <- sapply(features.info$symbol, \(x)
         any(x %in% house_keeping_genes, na.rm = TRUE))


问:
How can I automatically toggle showinfo in jQuery Galleria plugin?
I can't seem to find this documented anywhere. Basically I just want to have the caption automatically be displayed throughout the slideshow...

Thanks in advance...

答:
To show the caption automatically, try triggering a click event in jQuery:

$(".galleria-info-link").click()


问:
Get rid of ID (category and article) from URL (Joomla 3.3 / 3.4 / 3.5)
I have a Joomla 3.3.6 (edited: 3.5.) site organized in only 3 levels:

Four big categories (i, ii, iii, iiii)

Each one divided in some intermediate categories (A, B, C, ...)

And finally articles

Two languages (en, pt)

The URL after setting Search Engine Friendly URLs, Use URL rewriting, Adds Suffix to URL and multilanguage support, should be in the form:

http://www.example.com/en/bigcatiii/intercatA/articlex.html

But as many others that have Joomla installed and ask for a solution since Joomla-Baby-Version, I got:

http://www.example.com/en/bigcatiii/666-intercatA/articlex.html

where 666 is a number from hell indicating for no purpose a category ID

Now browsing for an answer, I found this answer:

```<code> Edit “components/com_content/router.php“
 (You’ll probably have to re-do this step every time you update Joomla.)
 Replace the lines 38 and 290 with:
 $advanced = $params->get('sef_advanced_link', 1);

 and Replace line 426 with
 ->where($db->quoteName(‘alias’) . ‘ = ‘ . $db->quote($segment));
</code>```

Well, first of all, line 426 is already like that in the original. Second, this does not do the trick. It do works with:

http://www.example.com/en/bigcatiii/intercatA/articlex.html

But it breaks wit a 404 error if you browse to:

http://www.example.com/en/bigcatiii/intercatA.html

Also, I noticed that the ID numbers are different. While the whole URL is

http://www.example.com/en/bigcatiii/666-intercatA/articlex.html

The same category description page is

http://www.example.com/en/bigcatiii/333-intercatA.html

There is also another solution that sound better, but also do not work, based on .htaccess

```<code>RewriteEngine on
RewriteBase /
RewriteRule (\d+)-([^/]*) $2 [R=301,L]
</code>```

The URLs appear ok, but the pages are not found. It would be so much better if we can provide a solution using .htaccess instead of changing Joomla core.

Still, changing the Joomla core would just fine, if this other googled suggestion was valid.

```<code> Copy “components/com_content/router.php” to “/templates/your-template/html”
</code>```

Meaning that once you moved router.php to your "local", you wouldn't need to redo all the stuff after an upgrade. (Unless, of course, router.php is updated, in case you would better mirror it again.)

Thanks for your time to solve this puzzle!

References

1- Change/ Remove Article ID in URL?

2- Removing the Article ID number

3- How to remove article id in url?

4- Remove article id from url for joomla 3.0

5- Enabling SEF

6- Remove article id from joomla 3 URL

7- Remove article id from joomla 3 URL

8- .htaccess redirect rule

9- Test .htaccess

Edited (2016/May/02): NEW Bounty for Joomla last version 3.5

答:
Joomla 3.7(?) to 3.10.5 Legacy router issue fix

Here is the solution that worked for me, on Joomla 3.10.5, but it might be the same from 3.7 up (If not fixed in 4.0).

Legacy router - path: @www/components/com_content/helpers/legacyrouter.php

Hacking the legacy router, and deactivate appending the category id to the segments array by commenting out line 199 in the legacy router and replacing it like this:

//if (!$advanced && count($array))
if (false)
```

Tried these solutions

Defaulting $advanced to 1 and more, and other solutions here and in this link: https://vincentping.com/en/remove-category-article-id-from-url-in-joomla-3.html did not work for me:

And more: The site article urls only needed the category id to be removed, not the article id, as removing  both causes a 404

Hoping this helps someone not have to spend the large amount of time I have trying .htaccess routing, other solutions and plugins before resorting to this hack.

You can see the result here: https://new.ac-news.org (under construction)

Body:
I have a Joomla 3.3.6 (edited: 3.5.) site organized in only 3 levels:

Four big categories (i, ii, iii, iiii)

Each one divided in some intermediate categories (A, B, C, ...)

And finally articles

Two languages (en, pt)

The URL after setting Search Engine Friendly URLs, Use URL rewriting, Adds Suffix to URL and multilanguage support, should be in the form:

http://www.example.com/en/bigcatiii/intercatA/articlex.html

But as many others that have Joomla installed and ask for a solution since Joomla-Baby-Version, I got:

http://www.example.com/en/bigcatiii/666-intercatA/articlex.html

where 666 is a number from hell indicating for no purpose a category ID

Now browsing for an answer, I found this answer:

 Edit “components/com_content/router.php“
 (You’ll probably have to re-do this step every time you update Joomla.)
 Replace the lines 38 and 290 with:
 $advanced = $params->get('sef_advanced_link', 1);

 and Replace line 426 with
 ->where($db->quoteName(‘alias’) . ‘ = ‘ . $db->quote($segment));

Well, first of all, line 426 is already like that in the original. Second, this does not do the trick. It do works with:

http://www.example.com/en/bigcatiii/intercatA/articlex.html

But it breaks wit a 404 error if you browse to:

http://www.example.com/en/bigcatiii/intercatA.html

Also, I noticed that the ID numbers are different. While the whole URL is

http://www.example.com/en/bigcatiii/666-intercatA/articlex.html

The same category description page is

http://www.example.com/en/bigcatiii/333-intercatA.html

There is also another solution that sound better, but also do not work, based on .htaccess

RewriteEngine on
RewriteBase /
RewriteRule (\d+)-([^/]*) $2 [R=301,L]

The URLs appear ok, but the pages are not found. It would be so much better if we can provide a solution using .htaccess instead of changing Joomla core.

Still, changing the Joomla core would just fine, if this other googled suggestion was valid.

 Copy “components/com_content/router.php” to “/templates/your-template/html”

Meaning that once you moved router.php to your "local", you wouldn't need to redo all the stuff after an upgrade. (Unless, of course, router.php is updated, in case you would better mirror it again.)

Thanks for your time to solve this puzzle!

References

1- Change/ Remove Article ID in URL?

2- Removing the Article ID number

3- How to remove article id in url?

4- Remove article id from url for joomla 3.0

5- Enabling SEF

6- Remove article id from joomla 3 URL

7- Remove article id from joomla 3 URL

8- .htaccess redirect rule

9- Test .htaccess

Edited (2016/May/02): NEW Bounty for Joomla last version 3.5

Body:
Joomla 3.7(?) to 3.10.5 Legacy router issue fix

Here is the solution that worked for me, on Joomla 3.10.5, but it might be the same from 3.7 up (If not fixed in 4.0).

Legacy router - path: @www/components/com_content/helpers/legacyrouter.php

Hacking the legacy router, and deactivate appending the category id to the segments array by commenting out line 199 in the legacy router and replacing it like this:

//if (!$advanced && count($array))
if (false)

Tried these solutions

Defaulting $advanced to 1 and more, and other solutions here and in this link: https://vincentping.com/en/remove-category-article-id-from-url-in-joomla-3.html did not work for me:

And more: The site article urls only needed the category id to be removed, not the article id, as removing  both causes a 404

Hoping this helps someone not have to spend the large amount of time I have trying .htaccess routing, other solutions and plugins before resorting to this hack.

You can see the result here: https://new.ac-news.org (under construction)


问:
Extracting rows from file based on another file using awk
I have two files.

File 1:

```<code>SNP Allele1 Allele2 Effect  StdErr  PVAL    Direction   HetISq  HetChiSHetDf    HetPVal
rs12266638  t   g   0.4259  0.0838  3.776e-07   +?  0.0 0.000   0   1
rs7995014   t   c   2.2910  0.5012  4.853e-06   +?  0.0 0.000   0   1
</code>```

File 2:

```<code>Chromosome Position SNP EA NEA EAF BETA SE P Direction
10 108627406 rs12266638 t g 0.991 -0.2649 0.0578 4.608e-06 -
11 116365828 rs112127824 a t 0.0327 0.4569 0.0994 4.327e-06 +
</code>```

I would like to print a file 3, based on the "SNP" column. If the SNP exists in file 2, I would like to print the whole row with all columns of file 1.

Output:

```<code>rs12266638  t   g   0.4259  0.0838  3.776e-07   +?  0.0 0.000   0   1
</code>```

I tried the following:

```<code>awk 'FNR==NR{a[$1]=$0; if(NR==1) print $0} ($1 in a) {print a[$1]}' file 1 file 2 > file 3
</code>```

But it prints different SNPs than those present in file 2.

Body:
I have two files.

File 1:

SNP Allele1 Allele2 Effect  StdErr  PVAL    Direction   HetISq  HetChiSHetDf    HetPVal
rs12266638  t   g   0.4259  0.0838  3.776e-07   +?  0.0 0.000   0   1
rs7995014   t   c   2.2910  0.5012  4.853e-06   +?  0.0 0.000   0   1

File 2:

Chromosome Position SNP EA NEA EAF BETA SE P Direction
10 108627406 rs12266638 t g 0.991 -0.2649 0.0578 4.608e-06 -
11 116365828 rs112127824 a t 0.0327 0.4569 0.0994 4.327e-06 +

I would like to print a file 3, based on the "SNP" column. If the SNP exists in file 2, I would like to print the whole row with all columns of file 1.

Output:

rs12266638  t   g   0.4259  0.0838  3.776e-07   +?  0.0 0.000   0   1

I tried the following:

awk 'FNR==NR{a[$1]=$0; if(NR==1) print $0} ($1 in a) {print a[$1]}' file 1 file 2 > file 3

But it prints different SNPs than those present in file 2.

Body:
You may use this awk:

awk 'FNR==NR {a[$3]; next} FNR> 1 && $1 in a' file2 file1

rs12266638  t   g   0.4259  0.0838  3.776e-07   +?  0.0 0.000   0   1


问:
Error: module declaration must occur at the start of the translation unit export module occupati
I am a beginner to C ++ and I am practicing with structures. Every time I try to compile the program the compiler gives me this error:

```<code>FAILED: CMakeFiles/jacoProject.dir/main.cpp.o
/Library/Developer/CommandLineTools/usr/bin/c++   -g -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk -std=gnu++2a -MD -MT CMakeFiles/jacoProject.dir/main.cpp.o -MF CMakeFiles/jacoProject.dir/main.cpp.o.d -o CMakeFiles/jacoProject.dir/main.cpp.o -c /Users/jacopodosio/CLionProjects/jacoProject/main.cpp
In file included from /Users/jacopodosio/CLionProjects/jacoProject/main.cpp:3:
/Users/jacopodosio/CLionProjects/jacoProject/occupati.ixx:1:8: error: module declaration must occur at the start of the translation unit
export module occupati;
</code>```

The code in the files is shown below.
main.cpp

```<code>#include <iostream>
#include "occupati.ixx"
#include "test.h"
using std::cout;
using std::endl;
using std::cin;

int main()
{
    Employes employeesCompany;
    employeesCompany.initialEmployee = 'f';
}
</code>```

occupati.ixx

```<code>export module employes;

export struct Employes
{
    char initialEmployee {};
    char ultimaLetteraDipendente {};
    int occupatiTotali {};
    int stipendio {};
};
</code>```

答:
You do not #include modules. #include means to copy-and-paste a file into this one. That's not how C++ modules work.

You import modules. Assuming your build is set up to handle C++ modules, you should import employes; at the top.

Body:
I am a beginner to C ++ and I am practicing with structures. Every time I try to compile the program the compiler gives me this error:

FAILED: CMakeFiles/jacoProject.dir/main.cpp.o
/Library/Developer/CommandLineTools/usr/bin/c++   -g -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk -std=gnu++2a -MD -MT CMakeFiles/jacoProject.dir/main.cpp.o -MF CMakeFiles/jacoProject.dir/main.cpp.o.d -o CMakeFiles/jacoProject.dir/main.cpp.o -c /Users/jacopodosio/CLionProjects/jacoProject/main.cpp
In file included from /Users/jacopodosio/CLionProjects/jacoProject/main.cpp:3:
/Users/jacopodosio/CLionProjects/jacoProject/occupati.ixx:1:8: error: module declaration must occur at the start of the translation unit
export module occupati;

The code in the files is shown below.
main.cpp

#include <iostream>
#include "occupati.ixx"
#include "test.h"
using std::cout;
using std::endl;
using std::cin;

int main()
{
    Employes employeesCompany;
    employeesCompany.initialEmployee = 'f';
}

occupati.ixx

export module employes;

export struct Employes
{
    char initialEmployee {};
    char ultimaLetteraDipendente {};
    int occupatiTotali {};
    int stipendio {};
};


问:
How to define attribute aliased name to a c++ function?
in my cpp file i have the following:

```<code>int A()
{
}
void B_A() __attribute__((alias ("A")));
</code>```

and i am getting the error:
B_A() aliased to undefined symbol A;
however, as u can notice, A is being defined just before that.

so whats the problem!?

答:
From the docs:

In C++, the mangled name for the target must be used.

So, you need the mangled name of A, or you need to give A C linkage so its name doesn't get mangled in the first place.

Body:
in my cpp file i have the following:

int A()
{
}
void B_A() __attribute__((alias ("A")));

and i am getting the error:
B_A() aliased to undefined symbol A;
however, as u can notice, A is being defined just before that.

so whats the problem!?


问:
Outlook Add-In: how to simulate automatic reply with external service?

Background

I previously asked this question: Outlook Add-In: how to automatically reply based on custom logic?

As the answerers @EugeneAstafiev and @OutlookAdd-insTeam-MSFT noted, Outlook web add-ins can only run on a currently selected item. This does not work for an automatic reply use case, since automatic replies should send on receiving a new email, regardless of whether the user has selected it.

Question

Despite this, I know add-ins can categorize incoming mail, e.g. move/copy them to different folders. Would it be possible to detect incoming mail in that sense and then have the add-in call out to an external service to send an automatic reply in that way?

Example

For example:

Add-in copies incoming email to folder.

Add-in hits external API endpoint.

External service sends auto reply email (perhaps using SMTP or similar?).

Clarifications

I'm not looking to use the built-in automatic replies feature in Outlook, since that has very limited options. (Roughly speaking, it can only send one message to all senders or one to contacts and another to non-contacts.) I want this simulated automatic reply to be sent based on custom logic, e.g. whether the external service has verified the sender's email.

Is this possible? If so, any recommendations on how best to implement it?

Thank you!

答:
Yes, it is possible with COM based add-ins (VSTO based ones).

The Application.NewMailEx event fires once for every received item that is processed by Microsoft Outlook. The item can be one of several different item types, for example, MailItem, MeetingItem, or SharingItem. The EntryIDsCollection string contains the Entry ID that corresponds to that item. Use the Entry ID specified in the EntryIDCollection string to call the NameSpace.GetItemFromID method and process the item.

If you need to handle any specific folder in Outlook and process only items dropped to the folder you may use the Items.ItemAdd event which is fired when one or more items are added to the specified collection. Note, this event does not run when a large number of items are added to the folder at once (more than sixteen).

You may consider your VSTO add-in as a regular windows .net application. So, standard mechanisms can be used to make a web call. For example, you may find the Calling Web Services with HttpWebRequest, WebClient and HttpClient article helpful.


问:
Is it possible to pull out a list of particular field values from a collection of generic objects in C#?
I have the following method in a class I am using for pagination in my app:

```<code>public static PagedList<T> ToPagedList(IEnumerable<T> source, int pageNumber, int pageSize)
        {
            var count = source.Count();
            var items = source
              .Skip((pageNumber - 1) * pageSize)
              .Take(pageSize).ToList();

            return new PagedList<T>(items, count, pageNumber, pageSize);
        }
</code>```

In this method I am passing in a collection of generic objects as IEnumerable<T> source which regardless of type will always have an Id field. What I'd like to do is pull out all of the Ids for these objects and store them in a list to be passed into my PagedList constructor. Is this possible?

答:
the best way would be create an interface

```<code>public interface IBaseClass{
  public int Id {get; set;}
}
</code>```

in this case you could change method header

```<code>static PagedList<T> ToPagedList<T>(IEnumerable<T> source, int pageNumber, int pageSize)
                    where T : IBaseClass
</code>```

and ids

```<code>var ids=items.Select(i => i.Id ).ToList();
</code>```

Body:
I have the following method in a class I am using for pagination in my app:

public static PagedList<T> ToPagedList(IEnumerable<T> source, int pageNumber, int pageSize)
        {
            var count = source.Count();
            var items = source
              .Skip((pageNumber - 1) * pageSize)
              .Take(pageSize).ToList();

            return new PagedList<T>(items, count, pageNumber, pageSize);
        }

In this method I am passing in a collection of generic objects as IEnumerable<T> source which regardless of type will always have an Id field. What I'd like to do is pull out all of the Ids for these objects and store them in a list to be passed into my PagedList constructor. Is this possible?

Body:
the best way would be create an interface

public interface IBaseClass{
  public int Id {get; set;}
}

in this case you could change method header

static PagedList<T> ToPagedList<T>(IEnumerable<T> source, int pageNumber, int pageSize)
                    where T : IBaseClass

and ids

var ids=items.Select(i => i.Id ).ToList();


问:
How to Split screen height in half in Jetpack Compose?
I want to split my screen in half horizontally in Jetpack Compose like this:

```<code>    @Composable
fun Splash(alpha: Float) {
    val configuration = LocalConfiguration.current
    val screenHeight = configuration.screenHeightDp.dp
    val screenWidth = configuration.screenWidthDp.dp
    val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.cat2))
    Box(
        modifier = Modifier
            .background(Blue)
            .height(screenHeight /  2)
            .padding(8.dp),
        contentAlignment = Alignment.TopCenter
    ) {
        Column() {
            Text(text = "Example", fontSize = 44.sp)
        }
    }
    Box(
        modifier = Modifier
            .background(Red)
            .height(screenHeight /  2)
            .padding(8.dp),
        contentAlignment = Alignment.BottomCenter
    ){
        Column {

            Text(text = "Example", textAlign = TextAlign.End, color = Grey, fontSize = 12.sp)
        }
    }
}
</code>```

I can get screen height with LocalConfiguration.current in dp and I set my top box and bottom box alignments as Alignment.TopCenter and Alignment.BottomCenter respectively but it didn't work. Second box(Red one) stays on top of the blue one.

答:
You can wrap your Boxes with a Column and set Modifier.weight(1f) for each box to set both of them at same height with

```<code>@Composable
fun Splash() {

    Column(modifier =Modifier.fillMaxSize()) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(Blue)
                .weight(1f)
                .padding(8.dp),
            contentAlignment = Alignment.TopCenter
        ) {
            Column() {
                Text(text = "Example", fontSize = 44.sp)
            }
        }
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(Red)
                .weight(1f)
                .padding(8.dp),
            contentAlignment = Alignment.Center
        ){
            Column {

                Text(text = "Example", textAlign = TextAlign.End, color = DarkGray, fontSize = 12.sp)
            }
        }
    }
}
</code>```

or wrap with a BoxWithConstraints which returns Contraints, maxWidth, maxHeight and use Modifier.align to one Box to top and other one to Bottom. BoxWithConstraints is useful for getting measurement parameters and set them as children Modifiers.

```<code>@Composable
fun Splash2() {
    BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(Blue)
                .height(maxHeight/2)
                .align(Alignment.TopStart)
                .padding(8.dp),
            contentAlignment = Alignment.TopCenter
        ) {
            Column() {
                Text(text = "Example", fontSize = 44.sp)
            }
        }
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(Red)
                .align(Alignment.BottomStart)
                .height(maxHeight/2)
                .padding(8.dp),
            contentAlignment = Alignment.Center
        ){
            Column {

                Text(text = "Example", textAlign = TextAlign.End, color = DarkGray, fontSize = 12.sp)
            }
        }
    }
}
</code>```

Body:
I want to split my screen in half horizontally in Jetpack Compose like this:

    @Composable
fun Splash(alpha: Float) {
    val configuration = LocalConfiguration.current
    val screenHeight = configuration.screenHeightDp.dp
    val screenWidth = configuration.screenWidthDp.dp
    val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.cat2))
    Box(
        modifier = Modifier
            .background(Blue)
            .height(screenHeight /  2)
            .padding(8.dp),
        contentAlignment = Alignment.TopCenter
    ) {
        Column() {
            Text(text = "Example", fontSize = 44.sp)
        }
    }
    Box(
        modifier = Modifier
            .background(Red)
            .height(screenHeight /  2)
            .padding(8.dp),
        contentAlignment = Alignment.BottomCenter
    ){
        Column {

            Text(text = "Example", textAlign = TextAlign.End, color = Grey, fontSize = 12.sp)
        }
    }
}

I can get screen height with LocalConfiguration.current in dp and I set my top box and bottom box alignments as Alignment.TopCenter and Alignment.BottomCenter respectively but it didn't work. Second box(Red one) stays on top of the blue one.

Body:
You can wrap your Boxes with a Column and set Modifier.weight(1f) for each box to set both of them at same height with

@Composable
fun Splash() {

    Column(modifier =Modifier.fillMaxSize()) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(Blue)
                .weight(1f)
                .padding(8.dp),
            contentAlignment = Alignment.TopCenter
        ) {
            Column() {
                Text(text = "Example", fontSize = 44.sp)
            }
        }
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(Red)
                .weight(1f)
                .padding(8.dp),
            contentAlignment = Alignment.Center
        ){
            Column {

                Text(text = "Example", textAlign = TextAlign.End, color = DarkGray, fontSize = 12.sp)
            }
        }
    }
}

or wrap with a BoxWithConstraints which returns Contraints, maxWidth, maxHeight and use Modifier.align to one Box to top and other one to Bottom. BoxWithConstraints is useful for getting measurement parameters and set them as children Modifiers.

@Composable
fun Splash2() {
    BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(Blue)
                .height(maxHeight/2)
                .align(Alignment.TopStart)
                .padding(8.dp),
            contentAlignment = Alignment.TopCenter
        ) {
            Column() {
                Text(text = "Example", fontSize = 44.sp)
            }
        }
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(Red)
                .align(Alignment.BottomStart)
                .height(maxHeight/2)
                .padding(8.dp),
            contentAlignment = Alignment.Center
        ){
            Column {

                Text(text = "Example", textAlign = TextAlign.End, color = DarkGray, fontSize = 12.sp)
            }
        }
    }
}


问:
Recalculate ngx-datatable on Click Event from another Directive
I have a Side Navigation with a docking feature and a data table in Main View. Upon un-docking the side navigation, the data table in Main View does not recalculate (this will leave some empty space that the Side Navigation came from) so I need to recalculate manually upon click. However, problem lies in the fact that the Side Navigation and Data Table are two different directives.

PS. I have multiple modules with different data table names

Same Problem here:
https://github.com/swimlane/ngx-datatable/issues/193#issuecomment-334809144

答:
I made it using MutationObserver which tracks style change for left menu and sets DatatableComponent width.

```<code>@Directive({ selector: '[sidePanelToggle]' })
export class SidePanelToggleDirective implements OnDestroy {
  private changes: MutationObserver;
  wasVisible: boolean | undefined;

  constructor(
    private elementRef: ElementRef,
    @Host() @Self() private tableComponent: DatatableComponent
  ) {
    this.changes = new MutationObserver((mutations: MutationRecord[]) => {
        mutations.forEach((mutation: MutationRecord) => {
            const sideNavElement = mutation.target as HTMLElement;
            const tableElement = this.elementRef.nativeElement as HTMLElement;
            const isVisible = sideNavElement?.style.visibility === 'visible';
            if (this.wasVisible === undefined || this.wasVisible && !isVisible || !this.wasVisible && isVisible) {
              if (tableElement.style.width) {
                tableElement.style.width = `${SidePanelToggleDirective.floatOrZero(tableElement.style.width) + (isVisible ? -sideNavElement.offsetWidth : sideNavElement.offsetWidth)}px`;
                console.log('Already set before, now will be ', tableElement.style.width);
              }
              else {
                tableElement.style.width = `${tableElement.offsetWidth + (isVisible ? -sideNavElement.offsetWidth : sideNavElement.offsetWidth)}px`;
                console.log('Setting first time as ', tableElement.style.width);
              }
              this.tableComponent.recalculate();
            }
            this.wasVisible = isVisible;
        });
    });

    document.querySelectorAll('mat-sidenav[position="start"]').forEach(element => {
      this.changes.observe(element, { attributeFilter: ['style'] });
    });
  }

  private static floatOrZero(value: any) {
    const result = parseFloat(value);
    return isNaN(result) ? 0 : result;
  }

  ngOnDestroy(): void {
    this.changes.disconnect();
  }
}
</code>```

Change in markup is minimal:

```<code><ngx-datatable sidePanelToggle ...
</code>```

Body:
I made it using MutationObserver which tracks style change for left menu and sets DatatableComponent width.

@Directive({ selector: '[sidePanelToggle]' })
export class SidePanelToggleDirective implements OnDestroy {
  private changes: MutationObserver;
  wasVisible: boolean | undefined;

  constructor(
    private elementRef: ElementRef,
    @Host() @Self() private tableComponent: DatatableComponent
  ) {
    this.changes = new MutationObserver((mutations: MutationRecord[]) => {
        mutations.forEach((mutation: MutationRecord) => {
            const sideNavElement = mutation.target as HTMLElement;
            const tableElement = this.elementRef.nativeElement as HTMLElement;
            const isVisible = sideNavElement?.style.visibility === 'visible';
            if (this.wasVisible === undefined || this.wasVisible && !isVisible || !this.wasVisible && isVisible) {
              if (tableElement.style.width) {
                tableElement.style.width = `${SidePanelToggleDirective.floatOrZero(tableElement.style.width) + (isVisible ? -sideNavElement.offsetWidth : sideNavElement.offsetWidth)}px`;
                console.log('Already set before, now will be ', tableElement.style.width);
              }
              else {
                tableElement.style.width = `${tableElement.offsetWidth + (isVisible ? -sideNavElement.offsetWidth : sideNavElement.offsetWidth)}px`;
                console.log('Setting first time as ', tableElement.style.width);
              }
              this.tableComponent.recalculate();
            }
            this.wasVisible = isVisible;
        });
    });

    document.querySelectorAll('mat-sidenav[position="start"]').forEach(element => {
      this.changes.observe(element, { attributeFilter: ['style'] });
    });
  }

  private static floatOrZero(value: any) {
    const result = parseFloat(value);
    return isNaN(result) ? 0 : result;
  }

  ngOnDestroy(): void {
    this.changes.disconnect();
  }
}

Change in markup is minimal:

<ngx-datatable sidePanelToggle ...


问:
how do i send html file to slack using curl command
I have file in directory as

```<code>cgi-bin   test.html   var
</code>```

And i want to send test.html file to slack

my workspace is

```<code>https://hooks.slack.com/services/TJJFXMD0E/BNKRQTZAPDEEDXSEED
</code>```

and i tried using curl cmd

```<code> curl -X POST file=@/test.html https://hooks.slack.com/services/TJJFXMD0E/BNKRQTZAPDEEDXSEED
</code>```

but it doesnot work

答:
```<code>curl -F file=@example.txt -F "initial_comment=Example file" -F channels=<CHANNEL_ID>, <ANOTHER_CHANNEL_ID_IF_NEEDED> -H "Authorization: Bearer <BOT_USER_OAUTH_ACCESS_TOKEN>" https://slack.com/api/files.upload
</code>```

read here for more details and see if it's help you:
https://dev.to/hakobyansen/upload-and-publish-a-file-on-slack-channel-with-bash-i2e

Body:
I have file in directory as

cgi-bin   test.html   var

And i want to send test.html file to slack

my workspace is

https://hooks.slack.com/services/TJJFXMD0E/BNKRQTZAPDEEDXSEED

and i tried using curl cmd

 curl -X POST file=@/test.html https://hooks.slack.com/services/TJJFXMD0E/BNKRQTZAPDEEDXSEED

but it doesnot work

Body:
curl -F file=@example.txt -F "initial_comment=Example file" -F channels=<CHANNEL_ID>, <ANOTHER_CHANNEL_ID_IF_NEEDED> -H "Authorization: Bearer <BOT_USER_OAUTH_ACCESS_TOKEN>" https://slack.com/api/files.upload

read here for more details and see if it's help you:
https://dev.to/hakobyansen/upload-and-publish-a-file-on-slack-channel-with-bash-i2e


问:
How to create an automatic mapping of possible JSON data options to be collected?
I've never heard of or found an option for what I'm looking for, but maybe someone knows a way:

To collect the data from a JSON I need to map manually it like this:

```<code>events = response['events']
for event in events:
    tournament_name = event['tournament']['name']
    tournament_slug = event['tournament']['slug']
    tournament_category_name = event['tournament']['category']['name']
    tournament_category_slug = event['tournament']['category']['slug']
    tournament_category_sport_name = event['tournament']['category']['sport']['name']
    tournament_category_sport_slug = event['tournament']['category']['sport']['slug']
    tournament_category_sport_id = event['tournament']['category']['sport']['id']
</code>```

The complete model is this:

```<code>{
    "events": [
      {
        "tournament": {
          "name": "Serie A",
          "slug": "serie-a",
          "category": {
            "name": "Italy",
            "slug": "italy",
            "sport": {
              "name": "Football",
              "slug": "football",
              "id": 1
            },
            "id": 31,
            "flag": "italy",
            "alpha2": "IT"
          },
          "uniqueTournament": {
            "name": "Serie A",
            "slug": "serie-a",
            "category": {
              "name": "Italy",
              "slug": "italy",
              "sport": {
                "name": "Football",
                "slug": "football",
                "id": 1
              },
              "id": 31,
              "flag": "italy",
              "alpha2": "IT"
            },
            "userCount": 586563,
            "id": 23,
            "hasEventPlayerStatistics": true
          },
          "priority": 254,
          "id": 33
        },
        "roundInfo": {
          "round": 24
        },
        "customId": "Kdbsfeb",
        "status": {
          "code": 7,
          "description": "2nd half",
          "type": "inprogress"
        },
        "winnerCode": 0,
        "homeTeam": {
          "name": "Bologna",
          "slug": "bologna",
          "shortName": "Bologna",
          "gender": "M",
          "userCount": 39429,
          "nameCode": "BOL",
          "national": false,
          "type": 0,
          "id": 2685,
          "subTeams": [

          ],
          "teamColors": {
            "primary": "#003366",
            "secondary": "#cc0000",
            "text": "#cc0000"
          }
        },
        "awayTeam": {
          "name": "Empoli",
          "slug": "empoli",
          "shortName": "Empoli",
          "gender": "M",
          "userCount": 31469,
          "nameCode": "EMP",
          "national": false,
          "type": 0,
          "id": 2705,
          "subTeams": [

          ],
          "teamColors": {
            "primary": "#0d5696",
            "secondary": "#ffffff",
            "text": "#ffffff"
          }
        },
        "homeScore": {
          "current": 0,
          "display": 0,
          "period1": 0
        },
        "awayScore": {
          "current": 0,
          "display": 0,
          "period1": 0
        },
        "coverage": 1,
        "time": {
          "initial": 2700,
          "max": 5400,
          "extra": 540,
          "currentPeriodStartTimestamp": 1644159735
        },
        "changes": {
          "changes": [
            "status.code",
            "status.description",
            "time.currentPeriodStart"
          ],
          "changeTimestamp": 1644159743
        },
        "hasGlobalHighlights": false,
        "hasEventPlayerStatistics": true,
        "hasEventPlayerHeatMap": true,
        "id": 9645399,
        "statusTime": {
          "prefix": "",
          "initial": 2700,
          "max": 5400,
          "timestamp": 1644159735,
          "extra": 540
        },
        "startTimestamp": 1644156000,
        "slug": "empoli-bologna",
        "lastPeriod": "period2",
        "finalResultOnly": false
      }
    ]
  }
</code>```

In my example I am collecting 7 values.

But there are 83 possible values to be collected.

In case I want to get all the values options that exist in this JSON, is there any way to make this map sequence automatically to print so I can copy it to the code?

Because manually it takes too long to do and it's very tiring.

And the results of texts like print() in terminal would be something like:

```<code>tournament_name = event['tournament']['name']
tournament_slug = event['tournament']['slug']
...
...
...
And so on until delivering the 83 object paths with values to collect...
</code>```

Then I could copy all the prints and paste into my Python file to retrieve the values or any other way to make the work easier.

答:
If the elements in the events arrays are the same, this code works without errors.

```<code>def get_prints(recode: dict):
    for key in recode.keys():
        if type(recode[key]) == dict:
            for sub_print in get_prints(recode[key]):
                yield [key] + sub_print
        else:
            yield [key]

class Automater:
    def __init__(self,name: str):
        """
        Params:
            name: name of json
        """
        self.name = name

    def get_print(self,*args):
        """
        Params:
            *args: keys json
        """
        return '_'.join(args) + ' = ' + self.name + ''.join([f"['{arg}']" for arg in args])
</code>```

For example, this code:

```<code>dicts = {
    'tournament':{
        'name':"any name",
        'slug':'somthing else',
        'sport':{
            'name':'sport',
            'anotherdict':{
                'yes':True
            }
        }
    }
}
list_names = get_prints(dicts)
for name in list_names:
    print(auto.get_print(*name))
</code>```

Gives this output:

```<code>tournament_name = event['tournament']['name']
tournament_slug = event['tournament']['slug']
tournament_sport_name = event['tournament']['sport']['name']
tournament_sport_anotherdict_yes = event['tournament']['sport']['anotherdict']['yes']
</code>```

Body:
I've never heard of or found an option for what I'm looking for, but maybe someone knows a way:

To collect the data from a JSON I need to map manually it like this:

events = response['events']
for event in events:
    tournament_name = event['tournament']['name']
    tournament_slug = event['tournament']['slug']
    tournament_category_name = event['tournament']['category']['name']
    tournament_category_slug = event['tournament']['category']['slug']
    tournament_category_sport_name = event['tournament']['category']['sport']['name']
    tournament_category_sport_slug = event['tournament']['category']['sport']['slug']
    tournament_category_sport_id = event['tournament']['category']['sport']['id']

The complete model is this:

{
    "events": [
      {
        "tournament": {
          "name": "Serie A",
          "slug": "serie-a",
          "category": {
            "name": "Italy",
            "slug": "italy",
            "sport": {
              "name": "Football",
              "slug": "football",
              "id": 1
            },
            "id": 31,
            "flag": "italy",
            "alpha2": "IT"
          },
          "uniqueTournament": {
            "name": "Serie A",
            "slug": "serie-a",
            "category": {
              "name": "Italy",
              "slug": "italy",
              "sport": {
                "name": "Football",
                "slug": "football",
                "id": 1
              },
              "id": 31,
              "flag": "italy",
              "alpha2": "IT"
            },
            "userCount": 586563,
            "id": 23,
            "hasEventPlayerStatistics": true
          },
          "priority": 254,
          "id": 33
        },
        "roundInfo": {
          "round": 24
        },
        "customId": "Kdbsfeb",
        "status": {
          "code": 7,
          "description": "2nd half",
          "type": "inprogress"
        },
        "winnerCode": 0,
        "homeTeam": {
          "name": "Bologna",
          "slug": "bologna",
          "shortName": "Bologna",
          "gender": "M",
          "userCount": 39429,
          "nameCode": "BOL",
          "national": false,
          "type": 0,
          "id": 2685,
          "subTeams": [

          ],
          "teamColors": {
            "primary": "#003366",
            "secondary": "#cc0000",
            "text": "#cc0000"
          }
        },
        "awayTeam": {
          "name": "Empoli",
          "slug": "empoli",
          "shortName": "Empoli",
          "gender": "M",
          "userCount": 31469,
          "nameCode": "EMP",
          "national": false,
          "type": 0,
          "id": 2705,
          "subTeams": [

          ],
          "teamColors": {
            "primary": "#0d5696",
            "secondary": "#ffffff",
            "text": "#ffffff"
          }
        },
        "homeScore": {
          "current": 0,
          "display": 0,
          "period1": 0
        },
        "awayScore": {
          "current": 0,
          "display": 0,
          "period1": 0
        },
        "coverage": 1,
        "time": {
          "initial": 2700,
          "max": 5400,
          "extra": 540,
          "currentPeriodStartTimestamp": 1644159735
        },
        "changes": {
          "changes": [
            "status.code",
            "status.description",
            "time.currentPeriodStart"
          ],
          "changeTimestamp": 1644159743
        },
        "hasGlobalHighlights": false,
        "hasEventPlayerStatistics": true,
        "hasEventPlayerHeatMap": true,
        "id": 9645399,
        "statusTime": {
          "prefix": "",
          "initial": 2700,
          "max": 5400,
          "timestamp": 1644159735,
          "extra": 540
        },
        "startTimestamp": 1644156000,
        "slug": "empoli-bologna",
        "lastPeriod": "period2",
        "finalResultOnly": false
      }
    ]
  }

In my example I am collecting 7 values.

But there are 83 possible values to be collected.

In case I want to get all the values options that exist in this JSON, is there any way to make this map sequence automatically to print so I can copy it to the code?

Because manually it takes too long to do and it's very tiring.

And the results of texts like print() in terminal would be something like:

tournament_name = event['tournament']['name']
tournament_slug = event['tournament']['slug']
...
...
...
And so on until delivering the 83 object paths with values to collect...

Then I could copy all the prints and paste into my Python file to retrieve the values or any other way to make the work easier.

Body:
If the elements in the events arrays are the same, this code works without errors.

def get_prints(recode: dict):
    for key in recode.keys():
        if type(recode[key]) == dict:
            for sub_print in get_prints(recode[key]):
                yield [key] + sub_print
        else:
            yield [key]

class Automater:
    def __init__(self,name: str):
        """
        Params:
            name: name of json
        """
        self.name = name

    def get_print(self,*args):
        """
        Params:
            *args: keys json
        """
        return '_'.join(args) + ' = ' + self.name + ''.join([f"['{arg}']" for arg in args])

For example, this code:

dicts = {
    'tournament':{
        'name':"any name",
        'slug':'somthing else',
        'sport':{
            'name':'sport',
            'anotherdict':{
                'yes':True
            }
        }
    }
}
list_names = get_prints(dicts)
for name in list_names:
    print(auto.get_print(*name))

Gives this output:

tournament_name = event['tournament']['name']
tournament_slug = event['tournament']['slug']
tournament_sport_name = event['tournament']['sport']['name']
tournament_sport_anotherdict_yes = event['tournament']['sport']['anotherdict']['yes']


问:
Add multiple Kafka users to clickhouse
I'm trying to use Apache Kafka with Clickhouse. I have a kafka username and password which I added to config.xml file in clickhouse files liked this:

```<code><kafka>
    <sasl_mechanisms>SCRAM-SHA-256</sasl_mechanisms>
    <sasl_username>some_user</sasl_username>
    <sasl_password>some_pass</sasl_password>
</kafka>
</code>```

This way I can use Kafka topics which is available for that one user. How can I use multiple user and use different topics available for different users while using a Kafka Engine in Clickhouse?

Is there a way to configure Kafka user settings while writing Kafka table with SQL in Clickhouse?

答:
https://clickhouse.com/docs/en/engines/table-engines/integrations/kafka/#configuration

each topic can have own settings

<kafka_mytopic>
    <sasl_mechanisms>SCRAM-SHA-256</sasl_mechanisms>
    <sasl_username>yyyy</sasl_username>
    <sasl_password>xxxx</sasl_password>
</kafka_mytopic>
<kafka_mytopic2>
    <sasl_mechanisms>SCRAM-SHA-256</sasl_mechanisms>
    <sasl_username>ddd</sasl_username>
    <sasl_password>zzz</sasl_password>
</kafka_mytopic2>
```

Title: Add multiple Kafka users to clickhouse

Body:
I'm trying to use Apache Kafka with Clickhouse. I have a kafka username and password which I added to config.xml file in clickhouse files liked this:

<kafka>
    <sasl_mechanisms>SCRAM-SHA-256</sasl_mechanisms>
    <sasl_username>some_user</sasl_username>
    <sasl_password>some_pass</sasl_password>
</kafka>

This way I can use Kafka topics which is available for that one user. How can I use multiple user and use different topics available for different users while using a Kafka Engine in Clickhouse?

Is there a way to configure Kafka user settings while writing Kafka table with SQL in Clickhouse?


问:
Call Webapi with Dictionary<String, object> as parameter from ASP .NET MVC Application
I have a WebApi defined as below

```<code>    public ActionResult DoSomeAction([FromForm(Name = "file")] IFormFile dataFile,
                               Dictionary<string,object> collection)
    {
    //do something
    }
</code>```

I am trying to call this from my client as shown below,

```<code>            using (var client = new HttpClient())
            {
                var api_Uri = Environment.GetEnvironmentVariable("API_URL");
                client.BaseAddress = new Uri(api_Uri);
                client.DefaultRequestHeaders.Clear();
                //Define request data format
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                Dictionary<string, object> data = new Dictionary<string, object>();
                data.Add("a", "sasas");
                data.Add("b", "sasas");
                data.Add("", "sasas");

                var inputSerialized = JsonSerializer.Serialize(data);
                var stringContent = new StringContent(inputSerialized , Encoding.UTF8, "application/json");

                var requestString = string.Format("api/DoSomeAction?selectedRule={0}", stringContent);

                HttpResponseMessage Res = await client.PostAsync(requestString, multipartContent);

            }
</code>```

multipartContent is MultipartFormDataContent which contains File information.
The above code is not working. Some guidance would be appreciated.

答:
I was able to solve this my implementing a custom IModelBinder.
I moved IFormFile and Dictionary to a class.
While creating the request as below ,

```<code>    internal MultipartFormDataContent GetRequestParams(IFormFile FilePath)
    {
        MultipartFormDataContent multipartContent = GetFileContent(FilePath);
        var dataExtractor = new DataExtractor();
        var dictionaryData = dataExtractor.GetDictionary(); //This return  Dictionary<string,object>
        var serialisedData = JsonSerializer.Serialize(dictionaryData);
        var stringContent = new StringContent(serialisedData, Encoding.UTF8, "application/json");

        multipartContent.Add(stringContent, "MyCollection");
        return multipartContent;
    }

    private MultipartFormDataContent GetFileContent(IFormFile FilePath)
    {
        byte[] data;
        using (var br = new BinaryReader(FilePath.OpenReadStream()))
        {
            data = br.ReadBytes((int) FilePath.OpenReadStream().Length);
        }
        ByteArrayContent bytes = new ByteArrayContent(data);
        MultipartFormDataContent multiContent = new MultipartFormDataContent();
        multiContent.Add(bytes, "File", FilePath.FileName);
        //Key is "File", bcos my property name in class is File. This should match
        return multiContent;
     }

</code>```

Custom class containing the data

```<code>  public class Input
  {
    public IFormFile File { get; set; }

    [ModelBinder(BinderType = typeof(FormDataJsonBinder))]
    public Dictionary<string,object> MyCollection{ get; set; }

 }
</code>```

Custom IModelBinder implementation

```<code> public class FormDataJsonBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        var modelName = bindingContext.ModelName;

        var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);

        if (valueProviderResult == ValueProviderResult.None)
        {
            return Task.CompletedTask;
        }

        bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);

        var value = valueProviderResult.FirstValue;

        if (string.IsNullOrEmpty(value))
        {
            return Task.CompletedTask;
        }

        try
        {
            var result = JsonSerializer.Deserialize(value, bindingContext.ModelType);
            bindingContext.Result = ModelBindingResult.Success(result);
        }
        catch (Exception ex)
        {
            bindingContext.Result = ModelBindingResult.Failed();
        }

        return Task.CompletedTask;
    }
}
</code>```

}

Web Api Signature

```<code> public IActionResult ExecuteRule([FromForm] Input inputdata)
 {
 // Do something
 }
</code>```

Body:
I have a WebApi defined as below

    public ActionResult DoSomeAction([FromForm(Name = "file")] IFormFile dataFile,
                               Dictionary<string,object> collection)
    {
    //do something
    }

I am trying to call this from my client as shown below,

            using (var client = new HttpClient())
            {
                var api_Uri = Environment.GetEnvironmentVariable("API_URL");
                client.BaseAddress = new Uri(api_Uri);
                client.DefaultRequestHeaders.Clear();
                //Define request data format
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                Dictionary<string, object> data = new Dictionary<string, object>();
                data.Add("a", "sasas");
                data.Add("b", "sasas");
                data.Add("", "sasas");

                var inputSerialized = JsonSerializer.Serialize(data);
                var stringContent = new StringContent(inputSerialized , Encoding.UTF8, "application/json");

                var requestString = string.Format("api/DoSomeAction?selectedRule={0}", stringContent);

                HttpResponseMessage Res = await client.PostAsync(requestString, multipartContent);

            }

multipartContent is MultipartFormDataContent which contains File information.
The above code is not working. Some guidance would be appreciated.

Body:
I was able to solve this my implementing a custom IModelBinder.
I moved IFormFile and Dictionary to a class.
While creating the request as below ,

    internal MultipartFormDataContent GetRequestParams(IFormFile FilePath)
    {
        MultipartFormDataContent multipartContent = GetFileContent(FilePath);
        var dataExtractor = new DataExtractor();
        var dictionaryData = dataExtractor.GetDictionary(); //This return  Dictionary<string,object>
        var serialisedData = JsonSerializer.Serialize(dictionaryData);
        var stringContent = new StringContent(serialisedData, Encoding.UTF8, "application/json");

        multipartContent.Add(stringContent, "MyCollection");
        return multipartContent;
    }

    private MultipartFormDataContent GetFileContent(IFormFile FilePath)
    {
        byte[] data;
        using (var br = new BinaryReader(FilePath.OpenReadStream()))
        {
            data = br.ReadBytes((int) FilePath.OpenReadStream().Length);
        }
        ByteArrayContent bytes = new ByteArrayContent(data);
        MultipartFormDataContent multiContent = new MultipartFormDataContent();
        multiContent.Add(bytes, "File", FilePath.FileName);
        //Key is "File", bcos my property name in class is File. This should match
        return multiContent;
     }

Custom class containing the data

  public class Input
  {
    public IFormFile File { get; set; }

    [ModelBinder(BinderType = typeof(FormDataJsonBinder))]
    public Dictionary<string,object> MyCollection{ get; set; }

 }

Custom IModelBinder implementation

 public class FormDataJsonBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        var modelName = bindingContext.ModelName;

        var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);

        if (valueProviderResult == ValueProviderResult.None)
        {
            return Task.CompletedTask;
        }

        bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);

        var value = valueProviderResult.FirstValue;

        if (string.IsNullOrEmpty(value))
        {
            return Task.CompletedTask;
        }

        try
        {
            var result = JsonSerializer.Deserialize(value, bindingContext.ModelType);
            bindingContext.Result = ModelBindingResult.Success(result);
        }
        catch (Exception ex)
        {
            bindingContext.Result = ModelBindingResult.Failed();
        }

        return Task.CompletedTask;
    }
}

}

Web Api Signature

 public IActionResult ExecuteRule([FromForm] Input inputdata)
 {
 // Do something
 }


答:
Modules (in *.ixx files) aren't something you #include in other source files. Rather, you import the components that are exported by those module files.

So, try this for your "main.cpp":

#include <iostream>
import employes; // Imports from "occupati.ixx"
#include "test.h"
using std::cout;
using std::endl;
using std::cin;

int main()
{
    Employes employeesCompany;
    employeesCompany.initialEmployee = 'f';
}
```

Note that the "occupati.ixx" file should be part of the project/build.

Note: You have said, in comments, that you use CLion as your IDE/build-system. I don't use this, but this blog may offer some advice and/or remedies for how to use C++20 Modules in that environment.

Title: Error: module declaration must occur at the start of the translation unit export module occupati

Body:
Modules (in *.ixx files) aren't something you #include in other source files. Rather, you import the components that are exported by those module files.

So, try this for your "main.cpp":

#include <iostream>
import employes; // Imports from "occupati.ixx"
#include "test.h"
using std::cout;
using std::endl;
using std::cin;

int main()
{
    Employes employeesCompany;
    employeesCompany.initialEmployee = 'f';
}

Note that the "occupati.ixx" file should be part of the project/build.

Note: You have said, in comments, that you use CLion as your IDE/build-system. I don't use this, but this blog may offer some advice and/or remedies for how to use C++20 Modules in that environment.


问:
dynamical sql, then pivot them, anything better?
through dynamically SQL, I managed to got the result like this:

```<code>product   name
milk     AAA
tea      BBB
cake     CCC
milk     ABA
tea      BDB
cake     CAA
milk     xxx
tea     ...
</code>```

I want to result like this

```<code>milk   AAA   ABA XXX ....   ...... (16 columns)
tea    BBB   BDB ...
</code>```

looking at pivot example, it appears the column name already known, but I have
16 columns, and not know the exact column name, any way can solve it. thanks

答:
Since the dynamic column names aren't defined, they need to be generated.

Row_number can be used to add a sequencial number.

Sample data

```<code>create table your_table
(
 id int identity primary key,
 product varchar(30) not null,
 name varchar(30) not null
);

insert into your_table (product, name) values
('milk', 'AAA'),
('tea',  'BBB'),
('cake', 'CCC'),
('milk', 'ABA'),
('tea',  'BDB'),
('cake', 'CAA'),
('milk', 'ABC');
</code>```

T-Sql:

```<code>DECLARE @Cols AS NVARCHAR(MAX);
DECLARE @DynSql AS NVARCHAR(MAX);

SELECT @Cols = CONCAT(@Cols+',', char(10), QUOTENAME(COL))
FROM (
   SELECT
   COL = CONCAT('Name_', ROW_NUMBER() OVER (PARTITION BY product ORDER BY name))
   FROM your_table
   GROUP BY product, name
) q
GROUP BY col
ORDER BY col;
-- SELECT @Cols as Cols;

SET @DynSql = 'SELECT *' +char(10)
  + 'FROM (' +char(10)
  + '  SELECT product, name' +char(10)
  + '  , COL = CONCAT(''Name_'', ROW_NUMBER() OVER (PARTITION BY product ORDER BY name))' +char(10)
  + '  FROM your_table' +char(10)
  + '  GROUP BY product, name' +char(10)
  + ') Src' +char(10)
  + 'PIVOT (' +char(10)
  + '  MAX(name) FOR COL IN ('+ @Cols +')' +char(10)
  + ') Pvt';

-- SELECT @DynSql as DynSql;
EXECUTE sp_executesql @DynSql;
</code>```

product
Name_1
Name_2
Name_3

cake
CAA
CCC
null

milk
AAA
ABA
ABC

tea
BBB
BDB
null

Demo on db<>fiddle here

Body:
through dynamically SQL, I managed to got the result like this:

product   name
milk     AAA
tea      BBB
cake     CCC
milk     ABA
tea      BDB
cake     CAA
milk     xxx
tea     ...

I want to result like this

milk   AAA   ABA XXX ....   ...... (16 columns)
tea    BBB   BDB ...

looking at pivot example, it appears the column name already known, but I have
16 columns, and not know the exact column name, any way can solve it. thanks

Body:
Since the dynamic column names aren't defined, they need to be generated.

Row_number can be used to add a sequencial number.

Sample data

create table your_table
(
 id int identity primary key,
 product varchar(30) not null,
 name varchar(30) not null
);

insert into your_table (product, name) values
('milk', 'AAA'),
('tea',  'BBB'),
('cake', 'CCC'),
('milk', 'ABA'),
('tea',  'BDB'),
('cake', 'CAA'),
('milk', 'ABC');

T-Sql:

DECLARE @Cols AS NVARCHAR(MAX);
DECLARE @DynSql AS NVARCHAR(MAX);

SELECT @Cols = CONCAT(@Cols+',', char(10), QUOTENAME(COL))
FROM (
   SELECT
   COL = CONCAT('Name_', ROW_NUMBER() OVER (PARTITION BY product ORDER BY name))
   FROM your_table
   GROUP BY product, name
) q
GROUP BY col
ORDER BY col;
-- SELECT @Cols as Cols;

SET @DynSql = 'SELECT *' +char(10)
  + 'FROM (' +char(10)
  + '  SELECT product, name' +char(10)
  + '  , COL = CONCAT(''Name_'', ROW_NUMBER() OVER (PARTITION BY product ORDER BY name))' +char(10)
  + '  FROM your_table' +char(10)
  + '  GROUP BY product, name' +char(10)
  + ') Src' +char(10)
  + 'PIVOT (' +char(10)
  + '  MAX(name) FOR COL IN ('+ @Cols +')' +char(10)
  + ') Pvt';

-- SELECT @DynSql as DynSql;
EXECUTE sp_executesql @DynSql;

product
Name_1
Name_2
Name_3

cake
CAA
CCC
null

milk
AAA
ABA
ABC

tea
BBB
BDB
null

Demo on db<>fiddle here


问:
creating a large bytearray that does not take up space in RAM
I need to create a very large (~30 GB) bytearray, but when I create it, I get a Memory Error because there is not enough RAM to store it. Question: is it possible to create such an object in python that will have the same properties (mutability and the ability to access an arbitrary offset), but will not take up space in memory while it is empty? I need to fill it in arbitrary places with only a small amount of data</p>

答:
You probably want to use Numpy's Memmap. This will let you reference a numpy object (any data type, any number of dimensions, a byte array is just a 1D array with bytes dtype). You can read and write subsections of the array which are backed by disk.

Note that when you read or write data from a Memmap array that section will stay in memory as long as you keep the object open. If memory becomes an issue you can always close/delete and reopen the object at an appropriate interval. The Numpy API doesn't provide a way to flush the objects in-memory cache (any segment you read or write).

You use the numpy Memmap object in the same way you would with a normal numpy object, e.g. slicing, numpy functions, etc.

https://numpy.org/doc/stable/reference/generated/numpy.memmap.html

Examples from the docs copied here, there are more examples in the docs referenced above.

```<code>import numpy as np

data = np.arange(12, dtype='float32')
data.resize((3,4))

# This example uses a temporary file so that doctest doesn’t write files to your directory. You would use a ‘normal’ filename.

from tempfile import mkdtemp
import os.path as path

filename = path.join(mkdtemp(), 'newfile.dat')

# Create a memmap with dtype and shape that matches our data:

fp = np.memmap(filename, dtype='float32', mode='w+', shape=(3,4))

fp
memmap([[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]], dtype=float32)

# Write data to memmap array:

fp[:] = data[:]

fp
memmap([[  0.,   1.,   2.,   3.],
        [  4.,   5.,   6.,   7.],
        [  8.,   9.,  10.,  11.]], dtype=float32)
</code>```

Body:
You probably want to use Numpy's Memmap. This will let you reference a numpy object (any data type, any number of dimensions, a byte array is just a 1D array with bytes dtype). You can read and write subsections of the array which are backed by disk.

Note that when you read or write data from a Memmap array that section will stay in memory as long as you keep the object open. If memory becomes an issue you can always close/delete and reopen the object at an appropriate interval. The Numpy API doesn't provide a way to flush the objects in-memory cache (any segment you read or write).

You use the numpy Memmap object in the same way you would with a normal numpy object, e.g. slicing, numpy functions, etc.

https://numpy.org/doc/stable/reference/generated/numpy.memmap.html

Examples from the docs copied here, there are more examples in the docs referenced above.

import numpy as np

data = np.arange(12, dtype='float32')
data.resize((3,4))

# This example uses a temporary file so that doctest doesn’t write files to your directory. You would use a ‘normal’ filename.

from tempfile import mkdtemp
import os.path as path

filename = path.join(mkdtemp(), 'newfile.dat')

# Create a memmap with dtype and shape that matches our data:

fp = np.memmap(filename, dtype='float32', mode='w+', shape=(3,4))

fp
memmap([[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]], dtype=float32)

# Write data to memmap array:

fp[:] = data[:]

fp
memmap([[  0.,   1.,   2.,   3.],
        [  4.,   5.,   6.,   7.],
        [  8.,   9.,  10.,  11.]], dtype=float32)


问:
Clojurescript compiler options in leiningen
An error message in my browser has informed me that:

```<code>ClojureScript could not load :main, did you forget to specify :asset-path?
</code>```

According to the documentation, :asset-path is a compiler option. What is the correct place in my leiningen configuration file for a compiler option such as :asset-path? It doesn't seem to work at the top level.

The project is freshly generated using this command:

```<code>lein new figwheel-main <name> -- --reagent
</code>```

I'm hosting the website on my own server, with the output files hosted at /static/cljs-out, hence the need for the :asset-path option.

Leiningen version is 2.9.1, figwheel-main version is 0.2.16

答:
The :asset-path option can be placed in the build specific configuration file, dev.cljs.edn in my case. This file is found in the project's root folder.

```<code>^{:watch-dirs ["test" "src"]
  :css-dirs ["resources/public/css"]
  :auto-testing true
   }
{:main flaglib2.core
 :asset-path "/static/cljs-out/dev"}
</code>```

This answer is possibly specific to figwheel-main projects. The rules seem to be different for cljs-build projects, as per cfrick's comment above.

Body:
An error message in my browser has informed me that:

ClojureScript could not load :main, did you forget to specify :asset-path?

According to the documentation, :asset-path is a compiler option. What is the correct place in my leiningen configuration file for a compiler option such as :asset-path? It doesn't seem to work at the top level.

The project is freshly generated using this command:

lein new figwheel-main <name> -- --reagent

I'm hosting the website on my own server, with the output files hosted at /static/cljs-out, hence the need for the :asset-path option.

Leiningen version is 2.9.1, figwheel-main version is 0.2.16

Body:
The :asset-path option can be placed in the build specific configuration file, dev.cljs.edn in my case. This file is found in the project's root folder.

^{:watch-dirs ["test" "src"]
  :css-dirs ["resources/public/css"]
  :auto-testing true
   }
{:main flaglib2.core
 :asset-path "/static/cljs-out/dev"}

This answer is possibly specific to figwheel-main projects. The rules seem to be different for cljs-build projects, as per cfrick's comment above.


问:
Delete from main table records that apear in cte
I have a main table from which I need to delete rows that are returned in CTE
Preferably I would like to do something  like that:

```<code>with users_to_exclude as (
select uid, date, location_id
from some_previous_ctes_with_logic
)
delete from main_table mt
inner join
users_to_exclude ux
 on ux.uid = mt.uid
 and ux.date = mt.date
 and ux.location_id = mt.location_id
</code>```

But I have not idea how to approach this in GBQ.
If I had only one key by which I would delete, it would be simpler as I would use all the CTE with a final select field in the where clause.
But where (f1,f2,f3) in (select f1,f2,f3 from..) is not possible in GBQ to my understanding.

So not sure how to do that.

Thanks

答:
Consider below approach

```<code>delete from main_table mt
where exists (
  with users_to_exclude as (
    select uid, date, location_id
    from some_previous_ctes_with_logic
  )
  select 1 from users_to_exclude ux
  where ux.uid = mt.uid
  and ux.date = mt.date
  and ux.location_id = mt.location_id
);
</code>```

why do I have to attach it to the main table in the where clause?

If for some reason you want to go this direction - use below

```<code>delete from main_table mt
where (uid, date, location_id) in (
  with users_to_exclude as (
    select uid, date, location_id
    from some_previous_ctes_with_logic
  )
  select as struct  * from users_to_exclude
);
</code>```

Body:
I have a main table from which I need to delete rows that are returned in CTE
Preferably I would like to do something  like that:

with users_to_exclude as (
select uid, date, location_id
from some_previous_ctes_with_logic
)
delete from main_table mt
inner join
users_to_exclude ux
 on ux.uid = mt.uid
 and ux.date = mt.date
 and ux.location_id = mt.location_id

But I have not idea how to approach this in GBQ.
If I had only one key by which I would delete, it would be simpler as I would use all the CTE with a final select field in the where clause.
But where (f1,f2,f3) in (select f1,f2,f3 from..) is not possible in GBQ to my understanding.

So not sure how to do that.

Thanks

Body:
Consider below approach

delete from main_table mt
where exists (
  with users_to_exclude as (
    select uid, date, location_id
    from some_previous_ctes_with_logic
  )
  select 1 from users_to_exclude ux
  where ux.uid = mt.uid
  and ux.date = mt.date
  and ux.location_id = mt.location_id
);

why do I have to attach it to the main table in the where clause?

If for some reason you want to go this direction - use below

delete from main_table mt
where (uid, date, location_id) in (
  with users_to_exclude as (
    select uid, date, location_id
    from some_previous_ctes_with_logic
  )
  select as struct  * from users_to_exclude
);


问:
Changes in the column values for machine learning
Below shown is the engine column that I have taken from a data set

engine

2150 cc

2240 cc

2150 cc

2230 cc

2050 cc

2280 cc

I want my column engine to be like as shown below:

engine

2150

2240

2150

2230

2050

2280

答:
You can use a lambda to change the values of the column

```<code>import pandas as pd

data = {'engine' : ["2150 cc", "2240 cc", "2150 cc", "2230 cc", "2050 cc", "2280 cc"]}

df = pd.DataFrame(data)
df['engine'] = df['engine'].map(lambda x: x.rstrip(' c'))
</code>```

Also you can replace non digit characters

```<code>df['engine'] = df['engine'].astype(str).str.replace('\D+', '', regex=True)
</code>```

Body:
You can use a lambda to change the values of the column

import pandas as pd

data = {'engine' : ["2150 cc", "2240 cc", "2150 cc", "2230 cc", "2050 cc", "2280 cc"]}

df = pd.DataFrame(data)
df['engine'] = df['engine'].map(lambda x: x.rstrip(' c'))

Also you can replace non digit characters

df['engine'] = df['engine'].astype(str).str.replace('\D+', '', regex=True)


问:
'The file name must end with .xml' when i try to read the value from text file(.txt) inside the assets folder
I'm trying to read the value from the text file(.txt), which is inside the assets folder, when I try to rebuild the project, I'm getting this error, how to solve this?

```<code>The file name must end with .xml
</code>```

this is the java code, I'm trying to read the value from the text file,

```<code>         try {

            InputStream is=getAssets().open("english.text");
            int size=is.available();

            byte[] buffer=new byte[size];
            is.read(buffer);
            is.close();
            line=new String(buffer);

        } catch (IOException e) {
            e.printStackTrace();
        }
</code>```

答: You have the assets/ directory in the wrong place. It needs to directly under main/, as a peer of java/ and res/.

Body:
I'm trying to read the value from the text file(.txt), which is inside the assets folder, when I try to rebuild the project, I'm getting this error, how to solve this?

The file name must end with .xml

this is the java code, I'm trying to read the value from the text file,

         try {

            InputStream is=getAssets().open("english.text");
            int size=is.available();

            byte[] buffer=new byte[size];
            is.read(buffer);
            is.close();
            line=new String(buffer);

        } catch (IOException e) {
            e.printStackTrace();
        }


问:
Call variable inside class from function inside class without $this
I recently needed to change my function to static and now $this does not work, and i need to get variable in the same class is there way to do it without $this?</p>

答: In a static class, you could access it by self::