Explore all Drupal open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Drupal

lando

v3.6.4

drush

11.0.9

CMSeeK

CMSeeK v.1.1.3 - K-RONA

ddev

v1.19.1: more compression options, ddev clean

composer-patches

Composer 2.1 compatibility

Popular Libraries in Drupal

codemod

by facebook doticonpythondoticon

star image 3884 doticonApache-2.0

Codemod is a tool/library to assist you with large-scale codebase refactors that can be partially automated but still require human oversight and occasional intervention. Codemod was developed at Facebook and released as open source.

drupal

by drupal doticonphpdoticon

star image 3568 doticon

Verbatim mirror of the git.drupal.org repository for Drupal core. Please see the https://github.com/drupal/drupal#contributing. PRs are not accepted on GitHub.

lando

by lando doticonshelldoticon

star image 3311 doticonGPL-3.0

A development tool for all your projects that is fast, easy, powerful and liberating

exphub

by zhzyker doticonpythondoticon

star image 2606 doticon

Exphub[漏洞利用脚本库] 包括Webloigc、Struts2、Tomcat、Nexus、Solr、Jboss、Drupal的漏洞利用脚本,最新添加CVE-2020-14882、CVE-2020-11444、CVE-2020-10204、CVE-2020-10199、CVE-2020-1938、CVE-2020-2551、CVE-2020-2555、CVE-2020-2883、CVE-2019-17558、CVE-2019-6340

drush

by drush-ops doticonphpdoticon

star image 2237 doticon

Drush is a command-line shell and scripting interface for Drupal, a veritable Swiss Army knife designed to make life easier for those who spend their working hours hacking away at the command prompt.

OOD-Principles-In-Swift

by ochococo doticonswiftdoticon

star image 1676 doticonGPL-3.0

💎 The Principles of OOD (SOLID) based on Uncle Bob articles.

drupal-project

by drupal-composer doticonphpdoticon

star image 1473 doticonGPL-2.0

:rocket: Composer template for Drupal projects. Quick installation via "composer create-project drupal-composer/drupal-project"

raspberry-pi-dramble

by geerlingguy doticonshelldoticon

star image 1443 doticonMIT

Raspberry Pi Kubernetes cluster that runs HA/HP Drupal 8

CMSeeK

by Tuhinshubhra doticonpythondoticon

star image 1430 doticonGPL-3.0

CMS Detection and Exploitation suite - Scan WordPress, Joomla, Drupal and over 180 other CMSs

Trending New libraries in Drupal

exphub

by zhzyker doticonpythondoticon

star image 2606 doticon

Exphub[漏洞利用脚本库] 包括Webloigc、Struts2、Tomcat、Nexus、Solr、Jboss、Drupal的漏洞利用脚本,最新添加CVE-2020-14882、CVE-2020-11444、CVE-2020-10204、CVE-2020-10199、CVE-2020-1938、CVE-2020-2551、CVE-2020-2555、CVE-2020-2883、CVE-2019-17558、CVE-2019-6340

EverybodyDanceNow

by carolineec doticonpythondoticon

star image 417 doticonNOASSERTION

Motion Retargeting Video Subjects

phpstorm-attributes

by JetBrains doticonphpdoticon

star image 160 doticonApache-2.0

PhpStorm specific attributes

composer-install

by ramsey doticonshelldoticon

star image 130 doticonMIT

A GitHub Action to streamline installation of PHP dependencies with Composer.

DrupalPod

by shaal doticonshelldoticon

star image 86 doticonMIT

Start Drupal contributions with 1 click.

druxt.js

by druxt doticonjavascriptdoticon

star image 74 doticonMIT

The Fully Decoupled Drupal Framework

drupal-rector

by palantirnet doticonphpdoticon

star image 70 doticon

A developer utility for automatically upgrading deprecated code for Drupal 9

gdpr-dump

by Smile-SA doticonphpdoticon

star image 60 doticonGPL-3.0

Utility that creates anonymized database dumps (MySQL only). Provides default config templates for Magento, Drupal and OroCommerce.

ddev-gitpod

by shaal doticonphpdoticon

star image 60 doticonMIT

A full Drupal dev environment in a browser

Top Authors in Drupal

1

phase2

21 Libraries

star icon346

2

geerlingguy

20 Libraries

star icon2105

3

dockerizedrupal

20 Libraries

star icon68

4

drupal

19 Libraries

star icon3843

5

hugowetterberg

18 Libraries

star icon122

6

acquia

17 Libraries

star icon868

7

mglaman

16 Libraries

star icon703

8

morethanthemes

16 Libraries

star icon194

9

Br3nda

16 Libraries

star icon33

10

fourkitchens

14 Libraries

star icon320

1

21 Libraries

star icon346

2

20 Libraries

star icon2105

3

20 Libraries

star icon68

4

19 Libraries

star icon3843

5

18 Libraries

star icon122

6

17 Libraries

star icon868

7

16 Libraries

star icon703

8

16 Libraries

star icon194

9

16 Libraries

star icon33

10

14 Libraries

star icon320

Trending Kits in Drupal

No Trending Kits are available at this moment for Drupal

Trending Discussions on Drupal

Not the required data is displayed for the new user, because the data is taken from the cache of the previous user

Implement "cache tags pattern" in Spring

Gatsby Source Drupal not fetching data when trying to deploy to netlify/heroku

PHP Fatal error: Uncaught Error: Undefined constant "MB_OVERLOAD_STRING"

Condense a Python Dictionary with Similar Keys

React TS variable is undefined

ERROR: the "PHPCompatibility" coding standard is not installed

.htaccess drupal 7 RedirectMatch or RewriteRule nothing seams to work

Does Drupal 7.87 support JQuery 3.6.x

How to programmatically query the translated content of a block in drupal9

QUESTION

Not the required data is displayed for the new user, because the data is taken from the cache of the previous user

Asked 2022-Apr-10 at 10:14

I made a custom module that displays the weather in a particular city.

But I got these comments after the code review:

1. Interesting question, what happens to your cache data, if the site first comes to a person from the city of London, and then Paris?

As I understand it, it means that a person from Paris, when he enters the site, will see the weather in London, because it will be taken from the cache. But I put the data in the cache so that there are not too many requests, I made a request once, put the data in the cache, and the next time I took the data from the cache.

2. In the small function, you are calling the http://ip-api.com/json/ endpoint twice. What happens when the site is visited by a thousand people per minute?

Here, I do not understand what the problem is. If it meant that the connection limit to the resource would be exhausted, then how to solve this problem? In the getCity() function, put the data in the cache in the same way as I do in the build() function? But then the same problem comes up as in the first remark, if a person from another city visits the site, then the data from the cache (name of the city of London) will be taken and not the name of his real city. How then to be?

Can you please tell me what needs to be changed in my code? Below I will write a slightly reduced code for my php file. Full version here: https://phpsandbox.io/n/sweet-forest-1lew-1wmof

1// ....
2use Drupal\Core\Cache\CacheBackendInterface;
3use GuzzleHttp\Client;
4
5//....
6
7  public function getCity() {
8
9    $ip = '193.62.157.66';  // static because for testing
10
11    try {
12      $response_ip = $this->httpClient->get('http://ip-api.com/json/' . $ip);
13      $response_data_ip = $response_ip->getBody();
14      $data_ip = json_decode($response_data_ip);
15
16      if ($data_ip->status == 'success') {
17        return $data_ip->city;
18      }
19      else {
20        return $this->configFactory->get('sydneypro_weather.settings')->get('weather_city');
21      }
22
23    }
24    catch (RequestException $e) {
25      return FALSE;
26    }
27
28  }
29
30  public function build() {
31    $client = $this->httpClient;
32    $api_key = $this->configFactory->get('sydneypro_weather.settings')->get('weather_api_key');
33    $cid = 'sydneypro_weather';
34    $weather_config = $this->configFactory->get('sydneypro_weather.settings');
35
36    if (!$weather_config) {
37      $this->logger->get('sydneypro_weather')->error('Config "sydneypro_weather.settings" is missing4');
38      return [];
39    }
40
41    if (empty($api_key) || empty($this->getCity())) {
42      return [
43        '#type' => 'markup',
44        '#markup' => $this->t('Please enter your API key and City in the Admin panel to see the weather'),
45      ];
46    }
47
48    try {
49      if ($cache = $this->cacheBackend->get($cid)) {
50        $data = $cache->data;
51      }
52      else {
53        $response = $client->get('http://api.openweathermap.org/data/2.5/weather?q=' . $this->getCity() . ',&appid=' . $api_key . '&units=metric');
54        $response_data = $response->getBody();
55        $data = json_decode($response_data);
56        $this->cacheBackend->set($cid, $data, $this->time->getRequestTime() + 21600);
57      }
58
59      $build = [
60        '#theme' => 'weather_block',
61        '#data' => $data,
62        '#attached' => [
63          'library' => [
64            'sydneypro_weather/sydneypro_weather',
65          ],
66        ],
67      ];
68
69      return $build;
70
71    }
72  // ....
73
74

ANSWER

Answered 2022-Apr-10 at 10:14
  1. You need to display some data according to a given city, so you should cache the data on a per-city basis, using a cache id that allows you to retrieve data for a specific city. In other words, $cid must contain a city name or identifier.

1// ....
2use Drupal\Core\Cache\CacheBackendInterface;
3use GuzzleHttp\Client;
4
5//....
6
7  public function getCity() {
8
9    $ip = '193.62.157.66';  // static because for testing
10
11    try {
12      $response_ip = $this->httpClient->get('http://ip-api.com/json/' . $ip);
13      $response_data_ip = $response_ip->getBody();
14      $data_ip = json_decode($response_data_ip);
15
16      if ($data_ip->status == 'success') {
17        return $data_ip->city;
18      }
19      else {
20        return $this->configFactory->get('sydneypro_weather.settings')->get('weather_city');
21      }
22
23    }
24    catch (RequestException $e) {
25      return FALSE;
26    }
27
28  }
29
30  public function build() {
31    $client = $this->httpClient;
32    $api_key = $this->configFactory->get('sydneypro_weather.settings')->get('weather_api_key');
33    $cid = 'sydneypro_weather';
34    $weather_config = $this->configFactory->get('sydneypro_weather.settings');
35
36    if (!$weather_config) {
37      $this->logger->get('sydneypro_weather')->error('Config "sydneypro_weather.settings" is missing4');
38      return [];
39    }
40
41    if (empty($api_key) || empty($this->getCity())) {
42      return [
43        '#type' => 'markup',
44        '#markup' => $this->t('Please enter your API key and City in the Admin panel to see the weather'),
45      ];
46    }
47
48    try {
49      if ($cache = $this->cacheBackend->get($cid)) {
50        $data = $cache->data;
51      }
52      else {
53        $response = $client->get('http://api.openweathermap.org/data/2.5/weather?q=' . $this->getCity() . ',&appid=' . $api_key . '&units=metric');
54        $response_data = $response->getBody();
55        $data = json_decode($response_data);
56        $this->cacheBackend->set($cid, $data, $this->time->getRequestTime() + 21600);
57      }
58
59      $build = [
60        '#theme' => 'weather_block',
61        '#data' => $data,
62        '#attached' => [
63          'library' => [
64            'sydneypro_weather/sydneypro_weather',
65          ],
66        ],
67      ];
68
69      return $build;
70
71    }
72  // ....
73
74$city = $this->getCity();
75$cid = 'sydneypro_weather:' . $city;
76
  • Using a variable for $city prevents getCity() to be called twice. Also you could set a cache that maps IP adresses to their corresponding city but it might not be a good idea as the number of (possible) distinct adresses populating the cache table could be very high.
    Another approach would be to get the region/city of the user from his browser using javascript and/or cookies, and call the api only for those that does not share their location.

  • Source https://stackoverflow.com/questions/71815094

    QUESTION

    Implement "cache tags pattern" in Spring

    Asked 2022-Mar-16 at 01:13

    I have been searching for long time in the Internet, if Spring supports the "cache tag pattern" but seems it doesn't.... How do you implement this cache pattern in Spring???

    An example of this cache pattern can be seen in Drupal cache tag implementation, I will create an example of how would that look

    1@Service
    2@AllArgsConstructor
    3class TicketService {
    4    private final UserRepository userRepository;
    5    private final ProductRepository productRepository;
    6    private final TicketRepository ticketRepository;
    7
    8    @Cacheable(cacheNames = "global-tags-cache", tags = { "ticket:list", "user:#{user.id}", "product:#{product.id}"})
    9    public List<TicketDto> findTicketsForUserThatIncludesProduct(User user, Product product) {
    10           var tickets = ticketRepository.findByUserAndProduct(user, product);
    11    }
    12
    13    @CacheEvict(cacheNames = "global-tags-cache", tags = "ticket:list")
    14    public Ticket saveNewTicket(TicketRequestDto ticketRequestDto) { ... }
    15
    16}
    17
    18@Service
    19@AllArgsConstructor
    20class ProductService {
    21    private final ProductRepository productRepository;
    22
    23    @CacheEvict(cacheNames = "global-tags-cache", tags = "product:#{productRequestDto.id}")
    24    public Product updateProductInformation(ProductRequestDto productRequestDto() { 
    25        ... 
    26    }
    27}
    28
    29@Service
    30class NonTagCacheService() {
    31   @Cacheable(cacheNames = "some-non-global-cache-store")
    32   public Object doStrongComputation() { ... }
    33}
    34

    The idea is to handle the responsability of the "tag eviction" where it belongs to, for example TicketService wants its cache to be break when user is altered, or when any ticket is altered, or when the specified product is altered... TicketService doesn't need to know when or where Product is going to clear its tag

    This pattern is strongly useful in Drupal, and makes its cache very powerfull, this is just an example, but one can implement its own tags for whatever reason he wants, for example a "kafka-process:custom-id"

    ANSWER

    Answered 2022-Mar-16 at 01:13

    As M. Deinum explained, Spring's Cache Abstraction is just that, an "abstraction", or rather an SPI enabling different caching providers to be plugged into the framework in order to offer caching capabilities to managed application services (beans) where needed, not unlike Security, or other cross-cutting concerns.

    Spring's Cache Abstraction only declares fundamental, but essential caching functions that are common across most caching providers. In effect, Spring's Cache Abstraction implements the lowest common denominator of caching capabilities (e.g. put and get). You can think of java.util.Map as the most basic, fundamental cache implementation possible, and is indeed one of the many supported caching providers offered out of the box (see here and here).

    This means advanced caching functions, such as expiration, eviction, compression, serialization, general memory management and configuration, and so on, are left to individual providers since these type of capabilities vary greatly from one cache implementation (provider) to another, as does the configuration of these features. This would be no different in Drupal's case. The framework documentation is definitive on this matter.

    Still, not all is lost, but it usually requires a bit of work on the users part.

    Being that the Cache and CacheManager interfaces are the primary interfaces (SPI) of the Spring Cache Abstraction, it is easy to extend or customize the framework.

    First, and again, as M. Deinum points out, you have the option of custom key generation. But, this offers no relief with respect to (custom) eviction policies based on the key(s) (or tags applied to cache entries).

    Next, you do have the option to get access to the low-level, "native" cache implementation of the provider using the API, Cache.getNativeCache(). Of course, then you must forgo the use of Spring Cache Annotations, or alternatively, the JCAche API Annotations, supported by Spring, which isn't as convenient, particularly if you want to enable/disable caching conditionally.

    Finally, I tested a hypothesis to a question posted in SO not long ago regarding a similar problem... using Regular Expressions (REGEX) to evict entries in a cache where the keys matched the REGEX. I never provided an answer to this question, but I did come up with a "generic" solution, implemented with 3 different caching providers: Redis, Apache Geode, and using the simple ConcurrentMap implementation.

    This involved a significant amount of supporting infrastructure classes, beginning here and declared here. Of course, my goal was to implement support for multiple caching providers via "decoration". Your implementation need not be so complicated, or rather sophisticated, ;-)

    Part of my future work on the Spring team will involve gathering use cases like yours and providing (pluggable) extensions to the core Spring Framework Cache Abstraction that may eventually find its way back into the core framework, or perhaps exist as separate pluggable modules based on application use case and requirements that our many users have expressed over the years.

    At any rate, I hope this offers you some inspiration on how to possibly and more elegantly handle your use case.

    Always keep in mind the Spring Framework is an exceptional example of the Open/Closed principle; it offers many extension points, and when combined with the right design pattern (e.g. Decorator, not unlike AOP itself), it can be quite powerful.

    Good luck!

    Source https://stackoverflow.com/questions/71468094

    QUESTION

    Gatsby Source Drupal not fetching data when trying to deploy to netlify/heroku

    Asked 2022-Mar-09 at 05:33

    I have a site running Gatsby and Gatsby-Source-Drupal7, it is a plugin that uses Graphql to make an axios get request to https://stagingsupply.htm-mbs.com/restws_resource.json and uses the json data to query. I am able to run it just fine on my computer by going to localhost:8000 and it creates over 200k nodes, but when I try to deploy on any cloud service provider like Gatsby Cloud or Netlify it doesn't fetch any nodes or data at all from the site.

    Warning from console
    1Starting to fetch data from Drupal
    2warn The gatsby-source-drupal7 plugin has generated no Gatsby nodes. Do you need
    3 it?
    4
    Code

    code from gatsby config

    1Starting to fetch data from Drupal
    2warn The gatsby-source-drupal7 plugin has generated no Gatsby nodes. Do you need
    3 it?
    4module.exports = {
    5    siteMetadata: {
    6      title: `new`,
    7        siteUrl: `https://www.yourdomain.tld`,
    8    },
    9    plugins: [
    10      {
    11        resolve: `gatsby-source-drupal7`,
    12        options: {
    13          baseUrl: `https://stagingsupply.htm-mbs.com/`,
    14          apiBase: `restws_resource.json`, // optional, defaults to `restws_resource.json`
    15        },
    16      },
    17    ]
    18}
    19

    gatsby-config.js from node_modules/gatsby-source-drupal7

    1Starting to fetch data from Drupal
    2warn The gatsby-source-drupal7 plugin has generated no Gatsby nodes. Do you need
    3 it?
    4module.exports = {
    5    siteMetadata: {
    6      title: `new`,
    7        siteUrl: `https://www.yourdomain.tld`,
    8    },
    9    plugins: [
    10      {
    11        resolve: `gatsby-source-drupal7`,
    12        options: {
    13          baseUrl: `https://stagingsupply.htm-mbs.com/`,
    14          apiBase: `restws_resource.json`, // optional, defaults to `restws_resource.json`
    15        },
    16      },
    17    ]
    18}
    19const createNode = actions.createNode; // Default apiBase to `jsonapi`
    20
    21    apiBase = apiBase || `restws_resource.json`; // Fetch articles.
    22    // console.time(`fetch Drupal data`)
    23
    24    console.log(`Starting to fetch data from Drupal`);
    25    const data = yield axios.get(`${baseUrl}/${apiBase}`, {
    26      auth: basicAuth
    27    });
    28    const allData = yield Promise.all(_.map(data.data.list,
    29

    Link to repo that works on local computer https://github.com/nicholastorr/gatsby-d7

    any and all help will be appreciated

    ANSWER

    Answered 2022-Mar-09 at 05:33

    As you pointed out, you've played around with the Node versions using NODE_ENV and engines workarounds. My guess also relies on a mismatching Node version between environments but as Netlify docs suggests, there are only two ways of customizing Node versions to manage dependencies.

    • Set a NODE_VERSION environment variable.
    • Add a .node-version or .nvmrc file to the site’s base directory in your repository. This will also tell any other developer using the repository which version of Node.js it depends on.

    Without seeing your Netlify build command (to see the NODE_VERSION) there's no .node-version nor .nvmrc in your repository. I'd try creating it at the root of the project with the v14.17.1 in it and trying a fresh install.

    In addition, double-check other server-related conflicts like IP-blocking, etc.

    Source https://stackoverflow.com/questions/71312499

    QUESTION

    PHP Fatal error: Uncaught Error: Undefined constant "MB_OVERLOAD_STRING"

    Asked 2022-Mar-04 at 01:39

    Can someone assist me with this error please. http error 500.

    Somehow, I install a new Drupal on a new subdomain, and I remember changing the time zone and region on cPanel, later both our main official website is down and the same with the new subdomain.

    So far, this is the only log that I can pull out from our cPanel.

    12022-03-03 19:05:38.594912 [NOTICE] [3084980] [T0] [xxx.xxx.xxx.xxx:xxxxx:HTTP2-5#APVH_mise.gov.ki:443] [STDERR] PHP Fatal error:  Uncaught Error: Undefined constant "MB_OVERLOAD_STRING" in /home/misegov/public_html/libraries/vendor/joomla/string/src/phputf8/utf8.php:38
    2  thrown in /home/misegov/public_html/libraries/vendor/joomla/string/src/phputf8/utf8.php on line 38
    3#5 /home/misegov/public_html/index.php(40): require_once('/home/misegov/p...')
    4#4 /home/misegov/public_html/includes/framework.php(18): require_once('/home/misegov/p...')
    5#3 /home/misegov/public_html/libraries/cms.php(36): require('/home/misegov/p...')
    6#2 /home/misegov/public_html/libraries/vendor/autoload.php(7): ComposerAutoloaderInit205c915b9c7d3e718e7c95793ee67ffe::getLoader()
    7#1 /home/misegov/public_html/libraries/vendor/composer/autoload_real.php(56): composerRequire205c915b9c7d3e718e7c95793ee67ffe()
    8#0 /home/misegov/public_html/libraries/vendor/composer/autoload_real.php(66): require()
    9

    Any idea what would be the cause of this please?

    Thank you and looking forward for possible solutions on this.

    Kind regards,

    ANSWER

    Answered 2022-Mar-04 at 01:32

    Go to Extensions - Joomla! Update, click Check for Updates and re-install the Joomla core files from the update package.

    EDIT: If you cannot access to administrator panel try to reset to PHP 7.x, then update the Joomla to >=3.10.1 after making a backup. Update all extensions beforehand. If necessary Test again with PHP8.

    Source https://stackoverflow.com/questions/71345585

    QUESTION

    Condense a Python Dictionary with Similar Keys

    Asked 2022-Feb-26 at 15:42

    I currently have a dictionary that has several keys that are similar but are formatted differently (Visual Studio, Visual studio / JavaScript,Javascript,javascript).

    How would I condense the dictionary so there's only one of a certain key, (Visual Studio, JavaScript, etc.) rather than the above example?

    Note: Elements such as Vue and Vue.js are meant to be separate keys.

    Is there something obvious that I'm missing?

    Code for reference

    1def getVal(keys, data):
    2    techCount = dict()
    3    other = 0
    4    remList = []
    5
    6    # Initialize Dictionary with Keys
    7    for item in keys:
    8        techCount[item] = 0
    9
    10    # Load Values into Dictionary
    11    for item in data:
    12        techCount[item] += 1
    13
    14    # Creates the 'Other' field
    15    for key, val in techCount.items():
    16        if val <= 1:
    17            other += 1
    18            remList.append(key)
    19
    20    techCount['Other'] = other
    21
    22    # Remove Redundant Keys
    23    for item in remList:
    24        techCount.pop(item)
    25
    26    
    27    # Sort the Dictionary
    28    techCount = {key: val for key, val in sorted(
    29        techCount.items(), key=lambda ele: ele[1])}
    30
    31    # Break up the Data
    32    keys = techCount.keys()
    33    techs = techCount.values()
    34
    35    return keys, techs
    36

    Full List:

    1def getVal(keys, data):
    2    techCount = dict()
    3    other = 0
    4    remList = []
    5
    6    # Initialize Dictionary with Keys
    7    for item in keys:
    8        techCount[item] = 0
    9
    10    # Load Values into Dictionary
    11    for item in data:
    12        techCount[item] += 1
    13
    14    # Creates the 'Other' field
    15    for key, val in techCount.items():
    16        if val <= 1:
    17            other += 1
    18            remList.append(key)
    19
    20    techCount['Other'] = other
    21
    22    # Remove Redundant Keys
    23    for item in remList:
    24        techCount.pop(item)
    25
    26    
    27    # Sort the Dictionary
    28    techCount = {key: val for key, val in sorted(
    29        techCount.items(), key=lambda ele: ele[1])}
    30
    31    # Break up the Data
    32    keys = techCount.keys()
    33    techs = techCount.values()
    34
    35    return keys, techs
    36JavaScript: 3
    37C#: 9
    38Visual studio: 2
    39Docker: 4       
    40Azure: 4        
    41AngularJs: 2
    42Java: 3
    43Visual Studio: 5
    44SQL: 4
    45Javascript: 5
    46Typescript: 3
    47AngularJS: 3
    48WordPress: 2
    49Zoho: 3
    50Drupal: 2
    51CSS: 9
    52.NET: 3
    53Python: 6
    54ReactJS: 3
    55HTML: 8
    56ASP.NET: 2
    57PHP: 2
    58Jira: 2
    59Other: 43
    60

    ANSWER

    Answered 2022-Feb-26 at 02:35

    How you solve this really depends on how data is structured-is it a list, a dictionary, or a string? Here I'll assume the data are in a dict() which seems the most likely given the data are like:

    1def getVal(keys, data):
    2    techCount = dict()
    3    other = 0
    4    remList = []
    5
    6    # Initialize Dictionary with Keys
    7    for item in keys:
    8        techCount[item] = 0
    9
    10    # Load Values into Dictionary
    11    for item in data:
    12        techCount[item] += 1
    13
    14    # Creates the 'Other' field
    15    for key, val in techCount.items():
    16        if val <= 1:
    17            other += 1
    18            remList.append(key)
    19
    20    techCount['Other'] = other
    21
    22    # Remove Redundant Keys
    23    for item in remList:
    24        techCount.pop(item)
    25
    26    
    27    # Sort the Dictionary
    28    techCount = {key: val for key, val in sorted(
    29        techCount.items(), key=lambda ele: ele[1])}
    30
    31    # Break up the Data
    32    keys = techCount.keys()
    33    techs = techCount.values()
    34
    35    return keys, techs
    36JavaScript: 3
    37C#: 9
    38Visual studio: 2
    39Docker: 4       
    40Azure: 4        
    41AngularJs: 2
    42Java: 3
    43Visual Studio: 5
    44SQL: 4
    45Javascript: 5
    46Typescript: 3
    47AngularJS: 3
    48WordPress: 2
    49Zoho: 3
    50Drupal: 2
    51CSS: 9
    52.NET: 3
    53Python: 6
    54ReactJS: 3
    55HTML: 8
    56ASP.NET: 2
    57PHP: 2
    58Jira: 2
    59Other: 43
    60JavaScript: 3
    61C#: 9
    62Visual studio: 2
    63Docker: 4       
    64Azure: 4        
    65AngularJs: 2
    66Java: 3
    67Visual Studio: 5
    68

    It seems like the problem is solely one of mixed-case characters. If you convert all to lowercase you'll get some collisions that you want to aggregate. Here is one way:

    1def getVal(keys, data):
    2    techCount = dict()
    3    other = 0
    4    remList = []
    5
    6    # Initialize Dictionary with Keys
    7    for item in keys:
    8        techCount[item] = 0
    9
    10    # Load Values into Dictionary
    11    for item in data:
    12        techCount[item] += 1
    13
    14    # Creates the 'Other' field
    15    for key, val in techCount.items():
    16        if val <= 1:
    17            other += 1
    18            remList.append(key)
    19
    20    techCount['Other'] = other
    21
    22    # Remove Redundant Keys
    23    for item in remList:
    24        techCount.pop(item)
    25
    26    
    27    # Sort the Dictionary
    28    techCount = {key: val for key, val in sorted(
    29        techCount.items(), key=lambda ele: ele[1])}
    30
    31    # Break up the Data
    32    keys = techCount.keys()
    33    techs = techCount.values()
    34
    35    return keys, techs
    36JavaScript: 3
    37C#: 9
    38Visual studio: 2
    39Docker: 4       
    40Azure: 4        
    41AngularJs: 2
    42Java: 3
    43Visual Studio: 5
    44SQL: 4
    45Javascript: 5
    46Typescript: 3
    47AngularJS: 3
    48WordPress: 2
    49Zoho: 3
    50Drupal: 2
    51CSS: 9
    52.NET: 3
    53Python: 6
    54ReactJS: 3
    55HTML: 8
    56ASP.NET: 2
    57PHP: 2
    58Jira: 2
    59Other: 43
    60JavaScript: 3
    61C#: 9
    62Visual studio: 2
    63Docker: 4       
    64Azure: 4        
    65AngularJs: 2
    66Java: 3
    67Visual Studio: 5
    68tech_count = {'JavaScript': 3, 'Visual studio': 2, 'Visual Studio': 5, 'Javascript': 5}
    69
    70consolidated = dict()
    71
    72for item in tech_count.items():
    73    norm_key = item[0].lower()
    74    if norm_key not in consolidated:
    75        consolidated[norm_key] = item[1]
    76    else:
    77        consolidated[norm_key] += item[1]
    78
    79print(consolidated)
    80

    or if you want to do this succinctly as suggested by @juanpa.arrivillaga then you could do it

    1def getVal(keys, data):
    2    techCount = dict()
    3    other = 0
    4    remList = []
    5
    6    # Initialize Dictionary with Keys
    7    for item in keys:
    8        techCount[item] = 0
    9
    10    # Load Values into Dictionary
    11    for item in data:
    12        techCount[item] += 1
    13
    14    # Creates the 'Other' field
    15    for key, val in techCount.items():
    16        if val <= 1:
    17            other += 1
    18            remList.append(key)
    19
    20    techCount['Other'] = other
    21
    22    # Remove Redundant Keys
    23    for item in remList:
    24        techCount.pop(item)
    25
    26    
    27    # Sort the Dictionary
    28    techCount = {key: val for key, val in sorted(
    29        techCount.items(), key=lambda ele: ele[1])}
    30
    31    # Break up the Data
    32    keys = techCount.keys()
    33    techs = techCount.values()
    34
    35    return keys, techs
    36JavaScript: 3
    37C#: 9
    38Visual studio: 2
    39Docker: 4       
    40Azure: 4        
    41AngularJs: 2
    42Java: 3
    43Visual Studio: 5
    44SQL: 4
    45Javascript: 5
    46Typescript: 3
    47AngularJS: 3
    48WordPress: 2
    49Zoho: 3
    50Drupal: 2
    51CSS: 9
    52.NET: 3
    53Python: 6
    54ReactJS: 3
    55HTML: 8
    56ASP.NET: 2
    57PHP: 2
    58Jira: 2
    59Other: 43
    60JavaScript: 3
    61C#: 9
    62Visual studio: 2
    63Docker: 4       
    64Azure: 4        
    65AngularJs: 2
    66Java: 3
    67Visual Studio: 5
    68tech_count = {'JavaScript': 3, 'Visual studio': 2, 'Visual Studio': 5, 'Javascript': 5}
    69
    70consolidated = dict()
    71
    72for item in tech_count.items():
    73    norm_key = item[0].lower()
    74    if norm_key not in consolidated:
    75        consolidated[norm_key] = item[1]
    76    else:
    77        consolidated[norm_key] += item[1]
    78
    79print(consolidated)
    80tech_count = {'JavaScript': 3, 'Visual studio': 2, 'Visual Studio': 5, 'Javascript': 5}
    81
    82consolidated = dict()
    83
    84for item in tech_count.items():
    85    norm_key = item[0].lower()
    86    consolidated[norm_key] = consolidated.get(norm_key, 0) + item[1]
    87
    88print(consolidated)
    89

    A more specialized data structure for this sort of thing is the collections.Counter which ships with python. One benefit to the counter is that querying for keys you have not yet seen will return 0 values which can make for fewer edge case considerations.

    With counter one way would look like this:

    1def getVal(keys, data):
    2    techCount = dict()
    3    other = 0
    4    remList = []
    5
    6    # Initialize Dictionary with Keys
    7    for item in keys:
    8        techCount[item] = 0
    9
    10    # Load Values into Dictionary
    11    for item in data:
    12        techCount[item] += 1
    13
    14    # Creates the 'Other' field
    15    for key, val in techCount.items():
    16        if val <= 1:
    17            other += 1
    18            remList.append(key)
    19
    20    techCount['Other'] = other
    21
    22    # Remove Redundant Keys
    23    for item in remList:
    24        techCount.pop(item)
    25
    26    
    27    # Sort the Dictionary
    28    techCount = {key: val for key, val in sorted(
    29        techCount.items(), key=lambda ele: ele[1])}
    30
    31    # Break up the Data
    32    keys = techCount.keys()
    33    techs = techCount.values()
    34
    35    return keys, techs
    36JavaScript: 3
    37C#: 9
    38Visual studio: 2
    39Docker: 4       
    40Azure: 4        
    41AngularJs: 2
    42Java: 3
    43Visual Studio: 5
    44SQL: 4
    45Javascript: 5
    46Typescript: 3
    47AngularJS: 3
    48WordPress: 2
    49Zoho: 3
    50Drupal: 2
    51CSS: 9
    52.NET: 3
    53Python: 6
    54ReactJS: 3
    55HTML: 8
    56ASP.NET: 2
    57PHP: 2
    58Jira: 2
    59Other: 43
    60JavaScript: 3
    61C#: 9
    62Visual studio: 2
    63Docker: 4       
    64Azure: 4        
    65AngularJs: 2
    66Java: 3
    67Visual Studio: 5
    68tech_count = {'JavaScript': 3, 'Visual studio': 2, 'Visual Studio': 5, 'Javascript': 5}
    69
    70consolidated = dict()
    71
    72for item in tech_count.items():
    73    norm_key = item[0].lower()
    74    if norm_key not in consolidated:
    75        consolidated[norm_key] = item[1]
    76    else:
    77        consolidated[norm_key] += item[1]
    78
    79print(consolidated)
    80tech_count = {'JavaScript': 3, 'Visual studio': 2, 'Visual Studio': 5, 'Javascript': 5}
    81
    82consolidated = dict()
    83
    84for item in tech_count.items():
    85    norm_key = item[0].lower()
    86    consolidated[norm_key] = consolidated.get(norm_key, 0) + item[1]
    87
    88print(consolidated)
    89from collections import Counter
    90tech_count = {'JavaScript': 3, 'Visual studio': 2, 'Visual Studio': 5, 'Javascript': 5}
    91
    92consolidated = Counter()
    93
    94for item in tech_count.items():
    95    norm_key = item[0].lower()
    96    consolidated[norm_key] += item[1]
    97
    98print(consolidated)
    99consolidated['assembly'] # returns 0 
    100

    Now consolidated will have the sum of the counts from the colliding key-value pairs in the original dictionary. If there are more similar transformations on the keys you could write a separate function that takes a string as input and replace the item[0].lower() keys.

    Source https://stackoverflow.com/questions/71271645

    QUESTION

    React TS variable is undefined

    Asked 2022-Feb-25 at 17:49

    New to ReactTS here. Can somebody explain to me why the variable content is undefined and how to set it so I can pass its value to <App />?

    It is showing undefined in both the index.tsx file and the subsequent App.tsx file.

    index.tsx

    1import 'react-app-polyfill/ie11';
    2import 'react-app-polyfill/stable';
    3import React from 'react';
    4import ReactDOM from 'react-dom';
    5import App from './App';
    6
    7// Declare type for drupalSettings.
    8declare global {
    9    interface Window {
    10        drupalSettings: {
    11            mydashboard: Settings;
    12        };
    13    }
    14}
    15
    16// Declare types for the React component.
    17interface Elements {
    18    content: string[];
    19}
    20
    21interface Settings {
    22    [index: string]: Elements;
    23}
    24
    25// Get Drupal settings.
    26console.log('window.drupalSettings', window.drupalSettings.mydashboard) &lt;!--- shows correct value ---&gt;
    27
    28const drupalAndReactApp: Settings = window.drupalSettings.mydashboard || '';
    29console.log('drupalAndReactApp', drupalAndReactApp, drupalAndReactApp['test']);&lt;!--- shows correct value ---&gt;
    30
    31
    32const { content } = drupalAndReactApp['test'];
    33console.log('content', content) &lt;!--- shows undefined ---&gt;
    34
    35
    36ReactDOM.render(&lt;App content={content} /&gt;, document.getElementById('my-app-target'));
    37

    index.tsx

    1import 'react-app-polyfill/ie11';
    2import 'react-app-polyfill/stable';
    3import React from 'react';
    4import ReactDOM from 'react-dom';
    5import App from './App';
    6
    7// Declare type for drupalSettings.
    8declare global {
    9    interface Window {
    10        drupalSettings: {
    11            mydashboard: Settings;
    12        };
    13    }
    14}
    15
    16// Declare types for the React component.
    17interface Elements {
    18    content: string[];
    19}
    20
    21interface Settings {
    22    [index: string]: Elements;
    23}
    24
    25// Get Drupal settings.
    26console.log('window.drupalSettings', window.drupalSettings.mydashboard) &lt;!--- shows correct value ---&gt;
    27
    28const drupalAndReactApp: Settings = window.drupalSettings.mydashboard || '';
    29console.log('drupalAndReactApp', drupalAndReactApp, drupalAndReactApp['test']);&lt;!--- shows correct value ---&gt;
    30
    31
    32const { content } = drupalAndReactApp['test'];
    33console.log('content', content) &lt;!--- shows undefined ---&gt;
    34
    35
    36ReactDOM.render(&lt;App content={content} /&gt;, document.getElementById('my-app-target'));
    37    let accessToken = &quot;&quot;;
    38    let embedUrl = &quot;&quot;;
    39    let reportContainer: HTMLElement;
    40    let reportRef: React.Ref&lt;HTMLDivElement&gt;;
    41    let loading: JSX.Element;
    42
    43    // eslint-disable-next-line @typescript-eslint/no-empty-interface
    44    interface AppProps { content: string[] };
    45    interface AppState { accessToken: string; embedUrl: string; error: string[]};
    46
    47    class App extends React.Component&lt;AppProps, AppState&gt; {
    48    
    49        constructor(props: AppProps) {
    50            super(props);
    51            const { content } = props;
    52            this.state = { accessToken: &quot;&quot;, embedUrl: &quot;&quot;, error: [] };
    53
    54            reportRef = React.createRef();
    55            console.log('props', props, content)  &lt;!--- shows undefined ---&gt;
    56            // Report container
    57            loading = (&lt;&gt;
    58                &lt;div id=&quot;welcome&quot;&gt;
    59                    Welcome
    60                &lt;/div&gt;
    61                &lt;div
    62                   id=&quot;reportContainer&quot;
    63                    ref={reportRef} &gt;
    64                    Loading the report...
    65                &lt;/div&gt;
    66            &lt;/&gt;
    67        );
    68    }
    69    ...
    70

    Edit

    Output of the console logs...

    window.drupalSettings Object { test: "[\"authenticated\",\"administrator\"]" }

    drupalAndReactApp Object { test: "[\"authenticated\",\"administrator\"]" } ["authenticated","administrator"]

    content undefined

    props Object { content: undefined } undefined

    Edit 2

    window.drupalSettings Object { content: "[\"authenticated\",\"administrator\"]" }

    drupalAndReactApp Object { content: "[\"authenticated\",\"administrator\"]" } ["authenticated","administrator"]

    content undefined

    props Object { content: undefined } undefined

    ANSWER

    Answered 2022-Feb-25 at 17:49

    Based on your data, your TypeScript definitions should look like this:

    1import 'react-app-polyfill/ie11';
    2import 'react-app-polyfill/stable';
    3import React from 'react';
    4import ReactDOM from 'react-dom';
    5import App from './App';
    6
    7// Declare type for drupalSettings.
    8declare global {
    9    interface Window {
    10        drupalSettings: {
    11            mydashboard: Settings;
    12        };
    13    }
    14}
    15
    16// Declare types for the React component.
    17interface Elements {
    18    content: string[];
    19}
    20
    21interface Settings {
    22    [index: string]: Elements;
    23}
    24
    25// Get Drupal settings.
    26console.log('window.drupalSettings', window.drupalSettings.mydashboard) &lt;!--- shows correct value ---&gt;
    27
    28const drupalAndReactApp: Settings = window.drupalSettings.mydashboard || '';
    29console.log('drupalAndReactApp', drupalAndReactApp, drupalAndReactApp['test']);&lt;!--- shows correct value ---&gt;
    30
    31
    32const { content } = drupalAndReactApp['test'];
    33console.log('content', content) &lt;!--- shows undefined ---&gt;
    34
    35
    36ReactDOM.render(&lt;App content={content} /&gt;, document.getElementById('my-app-target'));
    37    let accessToken = &quot;&quot;;
    38    let embedUrl = &quot;&quot;;
    39    let reportContainer: HTMLElement;
    40    let reportRef: React.Ref&lt;HTMLDivElement&gt;;
    41    let loading: JSX.Element;
    42
    43    // eslint-disable-next-line @typescript-eslint/no-empty-interface
    44    interface AppProps { content: string[] };
    45    interface AppState { accessToken: string; embedUrl: string; error: string[]};
    46
    47    class App extends React.Component&lt;AppProps, AppState&gt; {
    48    
    49        constructor(props: AppProps) {
    50            super(props);
    51            const { content } = props;
    52            this.state = { accessToken: &quot;&quot;, embedUrl: &quot;&quot;, error: [] };
    53
    54            reportRef = React.createRef();
    55            console.log('props', props, content)  &lt;!--- shows undefined ---&gt;
    56            // Report container
    57            loading = (&lt;&gt;
    58                &lt;div id=&quot;welcome&quot;&gt;
    59                    Welcome
    60                &lt;/div&gt;
    61                &lt;div
    62                   id=&quot;reportContainer&quot;
    63                    ref={reportRef} &gt;
    64                    Loading the report...
    65                &lt;/div&gt;
    66            &lt;/&gt;
    67        );
    68    }
    69    ...
    70interface Settings {
    71    [index: string]: string;
    72}
    73

    And later parse the JSON:

    1import 'react-app-polyfill/ie11';
    2import 'react-app-polyfill/stable';
    3import React from 'react';
    4import ReactDOM from 'react-dom';
    5import App from './App';
    6
    7// Declare type for drupalSettings.
    8declare global {
    9    interface Window {
    10        drupalSettings: {
    11            mydashboard: Settings;
    12        };
    13    }
    14}
    15
    16// Declare types for the React component.
    17interface Elements {
    18    content: string[];
    19}
    20
    21interface Settings {
    22    [index: string]: Elements;
    23}
    24
    25// Get Drupal settings.
    26console.log('window.drupalSettings', window.drupalSettings.mydashboard) &lt;!--- shows correct value ---&gt;
    27
    28const drupalAndReactApp: Settings = window.drupalSettings.mydashboard || '';
    29console.log('drupalAndReactApp', drupalAndReactApp, drupalAndReactApp['test']);&lt;!--- shows correct value ---&gt;
    30
    31
    32const { content } = drupalAndReactApp['test'];
    33console.log('content', content) &lt;!--- shows undefined ---&gt;
    34
    35
    36ReactDOM.render(&lt;App content={content} /&gt;, document.getElementById('my-app-target'));
    37    let accessToken = &quot;&quot;;
    38    let embedUrl = &quot;&quot;;
    39    let reportContainer: HTMLElement;
    40    let reportRef: React.Ref&lt;HTMLDivElement&gt;;
    41    let loading: JSX.Element;
    42
    43    // eslint-disable-next-line @typescript-eslint/no-empty-interface
    44    interface AppProps { content: string[] };
    45    interface AppState { accessToken: string; embedUrl: string; error: string[]};
    46
    47    class App extends React.Component&lt;AppProps, AppState&gt; {
    48    
    49        constructor(props: AppProps) {
    50            super(props);
    51            const { content } = props;
    52            this.state = { accessToken: &quot;&quot;, embedUrl: &quot;&quot;, error: [] };
    53
    54            reportRef = React.createRef();
    55            console.log('props', props, content)  &lt;!--- shows undefined ---&gt;
    56            // Report container
    57            loading = (&lt;&gt;
    58                &lt;div id=&quot;welcome&quot;&gt;
    59                    Welcome
    60                &lt;/div&gt;
    61                &lt;div
    62                   id=&quot;reportContainer&quot;
    63                    ref={reportRef} &gt;
    64                    Loading the report...
    65                &lt;/div&gt;
    66            &lt;/&gt;
    67        );
    68    }
    69    ...
    70interface Settings {
    71    [index: string]: string;
    72}
    73const content: string[] = JSON.parse(drupalAndReactApp.content);
    74

    Source https://stackoverflow.com/questions/71269081

    QUESTION

    ERROR: the &quot;PHPCompatibility&quot; coding standard is not installed

    Asked 2022-Feb-14 at 09:05

    When I execute git commit, I get this error:

    ERROR: the "PHPCompatibility" coding standard is not installed. The installed coding standards are MySource, PEAR, Zend, PSR2, PSR1, Squiz, PSR12, Drupal and DrupalPractice
    Fix the PHPCompatibility error before commit please

    Then I execute:

    1phpcs --config-set installed_paths vendor/phpcompatibility/php-compatibility
    2

    Executed git commit again; a new error appeared again:

    ERROR: the "Drupal" coding standard is not installed. The installed coding standards are MySource, PEAR, Zend, PSR2, PSR1, Squiz and PSR12
    Fix the Drupal Standard error before commit please

    I executed the command again:

    1phpcs --config-set installed_paths vendor/phpcompatibility/php-compatibility
    2phpcs --config-set installed_paths vendor/drupal/coder/coder_sniffer
    3

    As a result, the original error appeared again:

    the "PHPCompatibility" coding standard is not installed

    What's wrong with my configuration?

    enter image description here

    enter image description here

    enter image description here

    ANSWER

    Answered 2022-Jan-11 at 09:43

    I understand your pre-commit hook launches a linter that requires both standards to be installed simultaneously:

    1phpcs --config-set installed_paths vendor/phpcompatibility/php-compatibility
    2phpcs --config-set installed_paths vendor/drupal/coder/coder_sniffer
    3phpcs --config-set installed_paths vendor/phpcompatibility/php-compatibility,vendor/drupal/coder/coder_sniffer
    4

    Source https://stackoverflow.com/questions/70664444

    QUESTION

    .htaccess drupal 7 RedirectMatch or RewriteRule nothing seams to work

    Asked 2022-Feb-12 at 20:05

    I'm having some real issues getting a redirect to work in .htaccess with drupal 7.

    I have links like this:

    1example.com/vid/category/filter?subcat_filter_depth=125
    2

    and I need them to go to: (on same domain)

    1example.com/vid/category/filter?subcat_filter_depth=125
    2example.com/vid/category/filter?type=All&amp;subcat_filter_depth=125
    3

    after = the number may be different like 67 or 32 etc. meaning that can be any number and whatever number is at the end of the original link needs to also be at the end of the new link.

    I think the fact that the link is pretty much the same path just different filter is what is causing the issue as even the Drupal redirect url module will not allow it at an attempt to add them one at a time as they occur.

    here is everything I've tried:

    1example.com/vid/category/filter?subcat_filter_depth=125
    2example.com/vid/category/filter?type=All&amp;subcat_filter_depth=125
    3RedirectMatch 301 ^/vid/category/filter?subcat_filter_depth=(.*) /vid/category/filter?type=All&amp;subcat_filter_depth=$1
    4
    5RewriteRule ^(.*)/vid/category/filter?subcat_filter_depth=(.*) $1/vid/category/filter?type=All&amp;subcat_filter_depth=$2 [R=301]
    6
    7RedirectMatch ^/vid/category/filter?subcat_filter_depth=(.*) ^/vid/category/filter?type=All&amp;subcat_filter_depth=$1
    8
    9RedirectMatch 301 ^(.*)/filter?subcat_filter_depth=(.*) ^$1/filter?type=All&amp;subcat_filter_depth=$2
    10
    11RedirectMatch ^/(.*)/filter?subcat_filter_depth=(.*) ^/$1/filter?type=All&amp;subcat_filter_depth=$2
    12
    13RewriteRule &quot;^/(.*)/filter?subcat_filter_depth=(.*)&quot; &quot;^/$1/filter?type=All&amp;subcat_filter_depth=$2&quot;
    14

    mod_rewrite is on and there is an AllowOverride pathed/to/the/.htaccess file under <Directory> inside <VirtualHost> in the 000-default.conf running on Debian Apache ..pretty much latest versions.

    I know mod_rewrite is working because if I add a bad rule or rewrite with a syntax error I get error 500 response page.

    I've searched and tried just about everything I can think of and nothing seems to work.

    Any help getting this sorted and functioning would be greatly appreciated!

    ANSWER

    Answered 2022-Feb-11 at 23:19

    Both the RedirectMatch (mod_alias) and RewriteRule (mod_rewrite) directives match against the URL-path only, which notably excludes the query string.

    To match against the query string you need to use RewriteRule with an additional condition (RewriteCond directive) that checks against the QUERY_STRING server variable.

    This rule also needs to go near the top of the .htaccess file, before any existing rewrites.

    For example:

    1example.com/vid/category/filter?subcat_filter_depth=125
    2example.com/vid/category/filter?type=All&amp;subcat_filter_depth=125
    3RedirectMatch 301 ^/vid/category/filter?subcat_filter_depth=(.*) /vid/category/filter?type=All&amp;subcat_filter_depth=$1
    4
    5RewriteRule ^(.*)/vid/category/filter?subcat_filter_depth=(.*) $1/vid/category/filter?type=All&amp;subcat_filter_depth=$2 [R=301]
    6
    7RedirectMatch ^/vid/category/filter?subcat_filter_depth=(.*) ^/vid/category/filter?type=All&amp;subcat_filter_depth=$1
    8
    9RedirectMatch 301 ^(.*)/filter?subcat_filter_depth=(.*) ^$1/filter?type=All&amp;subcat_filter_depth=$2
    10
    11RedirectMatch ^/(.*)/filter?subcat_filter_depth=(.*) ^/$1/filter?type=All&amp;subcat_filter_depth=$2
    12
    13RewriteRule &quot;^/(.*)/filter?subcat_filter_depth=(.*)&quot; &quot;^/$1/filter?type=All&amp;subcat_filter_depth=$2&quot;
    14RewriteCond %{QUERY_STRING} ^subcat_filter_depth=\d+$
    15RewriteRule ^vid/category/filter$ /$0?type=All [QSA,R=302,L]
    16

    This redirects example.com/vid/category/filter?subcat_filter_depth=<number> to example.com/vid/category/filter?type=All&subcat_filter_depth=<number>.

    In .htaccess there is no slash prefix on the URL-path matched by the RewriteRule pattern. ie. ^vid/category (not ^/vid/category).

    $0 is a backreference that contains the matched URL-path from the RewriteRule pattern.

    QSA causes the original query string (eg. subcat_filter_depth=125) to be appended to the query string stated in the substitution string, ie. type=All becomes type=All&subcat_filter_depth=125.

    Test with 302 (temporary) redirect to avoid potential caching issues. Only change to a 301 (permanent) redirect - if that is the intention - once you have confirmed it works as intended.

    You will likely need to clear your browser cache before testing.

    Source https://stackoverflow.com/questions/71087103

    QUESTION

    Does Drupal 7.87 support JQuery 3.6.x

    Asked 2022-Jan-25 at 21:38

    I am trying to update jQuery for Drupal 7.87 to version 3.6.x. The jQuery_update module (7.x-3.0-alpha5)installed and the highest JQuery version I can pick from the dropdown list is 3.3.

    Does anyone know if Drupal 7.87 support JQuery 3.6.x? If yes, how can I upgrade it properly?

    Thanks

    ANSWER

    Answered 2022-Jan-25 at 21:38

    The module jquery_update allows to use "recent" versions of jQuery within Drupal but does not provide the latest versions because the changes tend to break Drupal 7 core JS.

    A solution is to "side load" the newer version using the module jQuery Multi :

    jQuery Multi allows you to load an extra version of the jQuery library in parallel to Drupal's version, without conflicting with Drupal's version.

    For instance, if you're loading jQuery-3.6.0, the alias will be jq360, and you can use it in your scripts by wrapping your code as follows :

    1(function($){
    2  // Code here 
    3  // ....
    4})(jq360)
    5

    Source https://stackoverflow.com/questions/70855637

    QUESTION

    How to programmatically query the translated content of a block in drupal9

    Asked 2022-Jan-18 at 04:49

    I created a block, the default language is English and the translation language is Chinese. Now I query the content of this block in my code:

    1$block = \Drupal::entityTypeManager()-&gt;getStorage('block_content')
    2      -&gt;loadByProperties([
    3        'info' =&gt; $info,
    4        'langcode' =&gt; 'zh-hant'
    5      ]);
    6

    But what I got is still in English, what am I doing wrong?

    ANSWER

    Answered 2022-Jan-18 at 04:49

    You have to load the block_content entities without langcode condition, then get the translation in the language you need by getTranslation():

    1$block = \Drupal::entityTypeManager()-&gt;getStorage('block_content')
    2      -&gt;loadByProperties([
    3        'info' =&gt; $info,
    4        'langcode' =&gt; 'zh-hant'
    5      ]);
    6$blocks = \Drupal::entityTypeManager()-&gt;getStorage('block_content')
    7  -&gt;loadByProperties([
    8    'info' =&gt; $info
    9  ]);
    10$translated_blocks = array_map(function ($block) {
    11  return $block-&gt;getTranslation('zh-hant');
    12}, $blocks);
    13// do somthing with $translated_blocks
    14

    Source https://stackoverflow.com/questions/70750095

    Community Discussions contain sources that include Stack Exchange Network

    Tutorials and Learning Resources in Drupal

    Tutorials and Learning Resources are not available at this moment for Drupal

    Share this Page

    share link

    Get latest updates on Drupal