text:
Q: regex to convert string 018v-s001v => 18v-s1v but 020v_001 => 20v_001 I'm struggling with a Regex to convert the following strings
018v-s001v => 18v-s1v
018v-s001r => 18v-s1r
018r-s002v => 18r-s2v
020v_001 => 20v_001
020r_002 => 20r_002
0001 => 0001

I could manage to convert the first three cases but I'm struggling with the latter three: How to preserve the zeros after_ and the all zeros in the last case?
My attempt: (0*)([1-9]{0,4}[vr]?)((-s)?+([0]{0,2}))?+([1-9][vr])?
https://regex101.com/r/2go5KO/1

A: For your given examples, you could use
000\d+(*SKIP)(*FAIL)|(?<=\b|[a-z])0+

See a demo on regex101.com.

A: To get the expected result for your example data you might use preg_replace.
You could match one or more times a zero 0+, capture in a group one or more digits and use a character class to match by v or r ([0-9]+[vr])
Regex
0+([0-9]+[vr])
Replace
Captured group 1 $1
Demo Php

A: How about this one:
$result = preg_replace('/(?:(\d{4})|(0)?(\d{2}\w))(?:([-_])(?:(\d{3})|(\w)(0+)(\d+?\w)))?/m',
'$1$3$4$5$6$8', $subject);

This produces all the results you require from your test strings. But it wasn't clear where a zero definitely will appear or only optionally. But I'm sure it can be adapted. Also I noticed the separator was occasionally a hyphen - and occasionally an underscore _ and it wasn't clear if that was just your typing or was significant. In any case I've assumed it could be either somewhat randomly.


text:
Q: Entering text to a  tag with selenium C# I've spent the last hour or so trying to find an element on the screen to add text too. I've managed with the title but can't seem to add the body text.

When I search the element it directs me to the
 tag.

I'm stumped.
driver.FindElement(By.Id("tinymce")).SendKeys("Lorem ipsum dolor sit amet, consectetur adipiscing elit");

A: You can do it by below way. just change the syntax as code is in java
driver.findElement(By.id("tinymce")).findElement(By.tagName("p")).sendKeys("Lorem ipsum dolor sit amet, consectetur adipiscing elit");

Hope it will help you :)

A: Done it. in this case here was my fix. Which pretty much goes with what you guys said with a few tweaks.
        driver.SwitchTo().Frame(driver.FindElement(By.Id("content_ifr")));
        driver.FindElement(By.Id("tinymce")).SendKeys("your data");

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change img position when I change window size I'm trying to create a website in css / html.
I've a pic in my section, and text next to it. I wanted to make my pic above the text when the window size is under 1300 px.
I've tried to play with width/display/flex but it doesn't work. Any ideas?
HTML part:

 Qui suis-je ?

Lorem

             C.V

CSS part:
@media(max-width:1300px){
  .max-width{
    margin-left: 0px;
    max-width: 800px;
  }
  .who .who-content .left img{
    height: 350px;
    width: 350px;
  }
  .who .who-content .column{
    width: 100%;
  }

  .who .who-content .left{
    display: flex;
    justify-content: center;
    margin: 0 auto 60px;
  }
  .who .who-content .right{
    flex:100%;
  }
}

A: Using flex in CSS, you can set the flex-flow to column in your media query so that the text goes below the image as intended. But you want to set the display: flex and flex-flow: column properties on a parent element, such as the section tag I used in the code below:

.who-content {
  display: flex;
}

@media(max-width:1300px) {
  .max-width {
    margin-left: 0px;
    max-width: 800px;
  }
  .who-content {
    flex-flow: column;
  }
  .who .who-content .left img {
    height: 350px;
    width: 350px;
  }
  .who .who-content .column {
    width: 100%;
  }
  .who .who-content .left {
    justify-content: center;
    margin: 0 auto 60px;
  }
  .who .who-content .right {
    flex: 100%;
  }
}

 Qui suis-je ?

Lorem

             C.V

A: try this:
/*here goes the code for when its above 1300px*/

@media screen and (max-width: 1300px) {
    /*here goes the code for when its under 1300 pixels*/
}


text:
Q: excludeCat function reverses order of blog posts I'm using the code below to remove category #5377 from the query on the home page. However, this code is also reversing the order of blog posts for some reason. How can I alter this code to only remove category #5377 and keep the same order of posts?
function excludeCat($query) {
    if ( $query->is_home ) {
        $query->set('cat', '-5377');
    }
    return $query;
}
add_filter('pre_get_posts', 'excludeCat');

Edit 1: Full index.php code:
<?php get_header(); ?>

    <?php if (dt_is_sidebar_active('homepage_ad')) : ?>

                <?php dynamic_sidebar('homepage_ad'); ?>

    <?php endif; ?>

                    <?php get_sidebar(); ?>

            <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

                <div <?php post_class(); ?> id="post-<?php the_ID(); ?>">

                    <?php if ( has_post_thumbnail() ) : ?>

                                <?php the_title(); ?>
                                <?php dt_overlay_icon(); ?>

                        <a href="<?php the_permalink(); ?>"><?php dt_image(300, ''); ?>

                    <?php endif; ?>

                    <?php the_category(', '); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

                        <?php $format = get_post_format(); ?>
                        <?php if ($format == "image" || $format == "gallery" || $format == "video") : ?>
                        <img src="<?php echo get_template_directory_uri(); ?>/images/icon-<?php echo $format; ?>.png" alt="<?php echo $format; ?>" />
                        <?php endif; ?>

                        <?php dt_excerpt(20); ?>

                    <a class="read-more" href="<?php the_permalink(); ?>"><?php _e('Read More', 'engine'); ?>

                        <?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' '.  __('ago', 'engine'); ?>

                        <?php comments_number(__('No Comments', 'engine'), __('1 Comment', 'engine'), __('% Comments', 'engine')); ?>

            <?php endwhile; endif; ?>

            <?php get_template_part('includes/index-loadmore'); ?>

            <?php dt_pagination(); ?>

<?php get_footer(); ?>

Edit 2: Added <?php global $wp_query; var_dump($wp_query->query_vars); ?> just before <?php if (have_posts()) : while (have_posts()) : the_post(); ?> in the code above and got this:
array(61) {
  ["error"]=>
  string(0) ""
  ["m"]=>
  string(0) ""
  ["p"]=>
  int(0)
  ["post_parent"]=>
  string(0) ""
  ["subpost"]=>
  string(0) ""
  ["subpost_id"]=>
  string(0) ""
  ["attachment"]=>
  string(0) ""
  ["attachment_id"]=>
  int(0)
  ["name"]=>
  string(0) ""
  ["static"]=>
  string(0) ""
  ["pagename"]=>
  string(0) ""
  ["page_id"]=>
  int(0)
  ["second"]=>
  string(0) ""
  ["minute"]=>
  string(0) ""
  ["hour"]=>
  string(0) ""
  ["day"]=>
  int(0)
  ["monthnum"]=>
  int(0)
  ["year"]=>
  int(0)
  ["w"]=>
  int(0)
  ["category_name"]=>
  string(0) ""
  ["tag"]=>
  string(0) ""
  ["cat"]=>
  string(0) ""
  ["tag_id"]=>
  string(0) ""
  ["author"]=>
  string(0) ""
  ["author_name"]=>
  string(0) ""
  ["feed"]=>
  string(0) ""
  ["tb"]=>
  string(0) ""
  ["paged"]=>
  int(0)
  ["comments_popup"]=>
  string(0) ""
  ["meta_key"]=>
  string(0) ""
  ["meta_value"]=>
  string(0) ""
  ["preview"]=>
  string(0) ""
  ["s"]=>
  string(0) ""
  ["sentence"]=>
  string(0) ""
  ["fields"]=>
  string(0) ""
  ["menu_order"]=>
  string(0) ""
  ["category__in"]=>
  array(0) {
  }
  ["category__not_in"]=>
  array(0) {
  }
  ["category__and"]=>
  array(0) {
  }
  ["post__in"]=>
  array(0) {
  }
  ["post__not_in"]=>
  array(0) {
  }
  ["tag__in"]=>
  array(0) {
  }
  ["tag__not_in"]=>
  array(0) {
  }
  ["tag__and"]=>
  array(0) {
  }
  ["tag_slug__in"]=>
  array(0) {
  }
  ["tag_slug__and"]=>
  array(0) {
  }
  ["post_parent__in"]=>
  array(0) {
  }
  ["post_parent__not_in"]=>
  array(0) {
  }
  ["author__in"]=>
  array(0) {
  }
  ["author__not_in"]=>
  array(0) {
  }
  ["ignore_sticky_posts"]=>
  bool(false)
  ["suppress_filters"]=>
  bool(false)
  ["cache_results"]=>
  bool(true)
  ["update_post_term_cache"]=>
  bool(true)
  ["update_post_meta_cache"]=>
  bool(true)
  ["post_type"]=>
  string(0) ""
  ["posts_per_page"]=>
  int(6)
  ["nopaging"]=>
  bool(false)
  ["comments_per_page"]=>
  string(2) "50"
  ["no_found_rows"]=>
  bool(false)
  ["order"]=>
  string(4) "DESC"
}

A: function exclude_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
    $query->set( 'cat', '-5377' );
    $query->set( 'orderby', 'date' );
    $query->set( 'order', 'DESC' );
    }
}
add_action( 'pre_get_posts', 'exclude_category' );

Use ASC or DESC for order.
Add code to child themes functions file.
Tested and works.


text:
Q: Adjusting horizontal spacings around product signs, in math mode This issue may be inexistent to the eyes of most people, but it currently scroches my aesthetical eyes!
I would like to adjust the spacings around the usual product signs (scalar product, vectorial and tensorial products, ...), to get a more balanced output when vectors and tensors have indices or exponents.  Here's a MWE code to show the issue:
\documentclass[11pt,letterpaper,twoside]{book}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[total={6in,10in},left=1.5in,top=0.5in,includehead,includefoot]{geometry}
\usepackage{microtype}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{mathtools}
\usepackage{tensor}
\newcommand*{\bvec}[1]{\mathbf{#1}}
\newcommand*{\ssp}{\mskip1mu} % mu = "math unit". Simple space \, = 3mu.
\newcommand*{\psp}{\mskip2mu} % 2mu ; approx 1.2pt.

\begin{document}

Default spacing around product signs:
    \begin{gather}
        \tensor{\bvec{e}}{_i} \cdot \tensor{\bvec{e}}{_j}
        \ne \tensor{\bvec{e}}{_i} \times \tensor{\bvec{e}}{_j}
        \ne \tensor{\bvec{e}}{_i} \wedge \tensor{\bvec{e}}{_j}
        \ne \tensor{\bvec{e}}{_i} \otimes \tensor{\bvec{e}}{_j}. \\[1ex]
        \bvec{a} \cdot \bvec{b} \ne \bvec{a} \times \bvec{b} \ne \bvec{a} \wedge \bvec{b} \ne \bvec{a} \otimes \bvec{b}.
    \end{gather}
More space on right of the product signs:
    \begin{gather}
        \tensor{\bvec{e}}{_i} \cdot \ssp \tensor{\bvec{e}}{_j}
        \ne \tensor{\bvec{e}}{_i} \times \ssp \tensor{\bvec{e}}{_j}
        \ne \tensor{\bvec{e}}{_i} \wedge \ssp \tensor{\bvec{e}}{_j}
        \ne \tensor{\bvec{e}}{_i} \otimes \ssp \tensor{\bvec{e}}{_j}.
    \end{gather}
    Less space on left of product sides:
    \begin{gather}
        \tensor{\bvec{e}}{_i} \!\psp \cdot \tensor{\bvec{e}}{_j}
        \ne \tensor{\bvec{e}}{_i} \!\psp \times \tensor{\bvec{e}}{_j}
        \ne \tensor{\bvec{e}}{_i} \!\psp \wedge \tensor{\bvec{e}}{_j}
        \ne \tensor{\bvec{e}}{_i} \!\psp \otimes \tensor{\bvec{e}}{_j}.
    \end{gather}

\end{document}

Preview (the spacing issue is subtle, maybe not visible on a first look):

In the default case (first two equation lines), the spacings around the product sign aren't well balanced because of the index (see equation (1)).  There seems to be more space on the left side than on the right side.  The spacing feels perfect when the vectors don't have any index (line (2)).  Currently, I could add a small space by hand on the right, like on line (3).  But the result isn't very appealing.
I could also reduce a bit the space on the left side, like on line (4).  The result is almost right to my eyes.  But I wonder if there's a better way of doing this, maybe without doing it by hand in each case.  I also had to hack the product by eye, using an arbitrary small space (one third of a regular \, space)
So how could we adjust the spacing/kerning around the product signs to get well balanced math expressions in all cases (with and without any lower or upper indices)?
Important:  Take note that I don't want to create new macros to redefine all of the products as two entry functions: I don't want products as "machines with slots".  I may have to redefine the products without adding entries to them, though, but I would prefer the simplest thing possible.

EDIT: Maybe the best way is to redefine the product commands (\times, \cdot, \otimes, \wedge, \odot) to add an optional spacing argument, but I need your suggestions to implement the idea.  So let the new \times command stays the same as the old \times when no argument is added to it, and \times[?] (or \times{?} ??) be the command with a negative space added to the left side.  How to do that in a proper way?
I would like to replace the default \times to something like \!\ssp \times, or maybe \!\psp \times, from a new \times with an optional argument (one third or two third of negative space).


text:
Q: getting a dependency conflict when downloading map-maker for python anaconda I'm trying to download map maker on windows with anaconda but it gives me this error
WARNING: Discarding https://files.pythonhosted.org/packages/29/72/5c1888c4948a0c7b736d10e0f0f69966e7c0874a660222ed0a2c2c6daa9f/pyproj-1.9.5.1.tar.gz#sha256=53fa54c8fa8a1dfcd6af4bf09ce1aae5d4d949da63b90570ac5ec849efaf3ea8 (from https://pypi.org/simple/pyproj/). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
Collecting map-maker
  Using cached map_maker-1.4.2-py3-none-any.whl (19 kB)
  Using cached map_maker-1.4.1-py3-none-any.whl (19 kB)
  Using cached map_maker-1.4.0-py3-none-any.whl (19 kB)
ERROR: Cannot install map-maker==1.4.0, map-maker==1.4.1, map-maker==1.4.2 and map-maker==1.4.3 because these package versions have conflicting dependencies.

The conflict is caused by:
    map-maker 1.4.3 depends on pyproj<2 and >=1.9.5.1
    map-maker 1.4.2 depends on pyproj<2 and >=1.9.5.1
    map-maker 1.4.1 depends on pyproj<2 and >=1.9.5.1
    map-maker 1.4.0 depends on pyproj<2 and >=1.9.5.1

To fix this you could try to:
1. loosen the range of package versions you've specified
2. remove package versions to allow pip attempt to solve the dependency conflict

ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/user_guide/#fixing-conflicting-dependencies


text:
Q: Highcharts Error 13 on Ajax Result and Dynamic Div I've tried to find a solution to why my code does not work with Highcharts. The following code results in a Error # 13, element not found.
I'm creating the element

 on the return of data from the Ajax result and append it to a td.
I know this has an easy answer, but I've been searching for an answer and nothing has come up.
request.done(function(data) {
            ajaxData = data;
            $(function() {
                $('tr#_CPID_' + cpid + ' td').html(''+
'
'+
'
'+
'
'+
'

Cross Project ID:
'+ ajaxData['details']['cpid'] + '
'+
'

Also Known As:
' + ajaxData['details']['name'] + '
'+
'
'+
'
'+
'

'+
'
'+
'               ');
                Highcharts.stockChart('#_CPID_Chart_' + cpid, {
                    rangeSelector: { selected: 1 },
                    title: { text: 'CPID Chart for ' + cpid },
                    series: [{ name: cpid, data: ajaxData['magnitude'], tooltip: { valueDecimals: 8 } }]
                });
            });
        });

I have also tested that the div is actually there and working with the following code $('#_CPID_Chart_' + cpid).html('Test'); instead of the Highcharts.stockChart code, and it works without any issue.
I assume I've missed something about how Highcharts renders its data.

A: You are receiving error #13 (https://www.highcharts.com/errors/13) because instead of using Highcharts.stockChart('_CPID_Chart_' + cpid, {...}); you are using Highcharts.stockChart('#_CPID_Chart_' + cpid, {...});. Check the corrected demo below.
Example:
http://jsfiddle.net/ueaguauh/


text:
Q: ValueError at / Missing staticfiles manifest entry for '' I'm trying to migrate from Django 1.9.7 to Django 1.11.5. I have three different django apps, and they are pretty much the same regarding packages and settings. I have deployed all three of them to a web server and two apps are working without any problems, but third one gives me headache - i get this error all the time:
ValueError at / Missing staticfiles manifest entry for ''

Here are the most relevant settings from settings.py:
# -*- coding: utf-8 -*-
from settings import *

SECRET_KEY = '***'

SITE_ID = 3

ALLOWED_HOSTS = [
    'localhost',
    '127.0.0.1',
    '.example.com',
    '.example.com.',

    ]

INSTALLED_APPS += (
    'storages',
    'example',
    'example2',
    'el_pagination',
    'debug_toolbar',
)

ROOT_URLCONF = 'example.urls'

WSGI_APPLICATION = 'example.wsgi.application'

DEFAULT_FROM_EMAIL = 'web@example.com'

MANAGERS = ADMINS

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
        'DEFAULT_MIDDLEWARE_ALIAS': 'default',
        'DEFAULT_MIDDLEWARE_SECONDS': '300',
        'DEFAULT_MIDDLEWARE_KEY_PREFIX': '',
    }
}

PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.SHA1PasswordHasher',
)

#AWS_HEADERS = {  # see http://developer.yahoo.com/performance/rules.html#expires
#       'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT',
#        'Cache-Control': 'max-age=94608000',
#S    }

# AMAZON S3 & CLOUDFRONT SERVING MEDIA FILES
AWS_S3_HOST = 's3.eu-central-1.amazonaws.com'
AWS_STORAGE_BUCKET_NAME = '***'
AWS_CLOUDFRONT_DOMAIN = '***.cloudfront.net'
AWS_ACCESS_KEY_ID = "***"
AWS_SECRET_ACCESS_KEY = "***"
MEDIAFILES_LOCATION = 'example/media'
MEDIA_ROOT = '/%s/' % MEDIAFILES_LOCATION
MEDIA_URL = '//%s/%s/' % (AWS_CLOUDFRONT_DOMAIN, MEDIAFILES_LOCATION)
DEFAULT_FILE_STORAGE = 'example.custom_storages.MediaStorage'

# WHITENOISE SERVING STATIC FILES
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, '***/static/example')
STATIC_URL = '/static/'

I don't know why i'm getting this error because i did nothing different (while deploying) comparing to the other two apps which are working regularly. Settings are almost the same! I've also tried to empty .css files so i could throw away possibility that css files are somewhere pointing to files that doesn't exist, but it didn't help. I've updated all of the packages that my websites are using.
This app is working normally under Django 1.9.7, but i can't make it to work under 1.11.5.
EDIT - HOW DID I FIX THIS?
Thanks to @evansd's answer i've managed to find the problem! In one of my templates i've had this code which messed the whole thing up:
{% for num in numbers  %}

{% endfor %}

and i've changed it to:
{% for num in numbers  %}

{% endfor %}

After this fix everything works well! For custom addstr template tag look this answer.

A: The problem is that somewhere in your templates you're referencing a static file that doesn't exist. Specifically, your passing an empty string to static. Perhaps you have a line like {% static some_variable %} where some_variable is undefined?
In Django 1.11 the behaviour changed so that errors are thrown on missing files. See:
https://docs.djangoproject.com/en/1.11/ref/contrib/staticfiles/#django.contrib.staticfiles.storage.ManifestStaticFilesStorage.manifest_strict
If you fix this reference then everything should work.

A: Not running following ( python manage.py collectstatic ) may be your issue.
Solution:
You can circumvent this issue and improve the code by moving the static() call out of the model field and changing the default value to the string "pledges/images/no-profile-photo.png". It should look like this:
avatar_url = models.URLField(default='pledges/images/no-profile-photo.png')
When you access avatar_url, use either

*

*(frontend / Django Templates option) {% static profile_instance.avatar_url %}, where profile_instance is a context variable referring to a Profile object.

*(backend / Python option) use static(profile_instance.avatar_url).
Explanation:
By using the result of static() for a default value, the app is putting a URL in the database that includes the STATIC_URL prefix -- which is like hard-coding it because data won't change when settings.py does. More generally, you shouldn't store the results of static() in the database at all.
If you ensure that you're using the {% static %} tag or static() function each time you're accessing avatar_url for display on the frontend, STATIC_URL will still be added based on your environment config at runtime.
This SO thread has a lot of good content on staticfiles
Why the error is happening:
It looks like you have a circular dependency:

*

*collectstatic needs to run in order to create manifest.json

*your application needs to load in order to run manage.py commands, which calls static()

*static() relies on an entry in manifest.json to resolve.
Source answer here.
Django Model: ValueError: Missing staticfiles manifest entry for "file_name.ext"


text:
Q: X11. How to know the full size of a window (with the size of its decorations) I would like to retrieve the complete size of any windows in X11 in order to automatically resize it.
So far I have used wmctrl but the size seems to be incomplete.
for instance
>$ wmctrl -lG
0x00e0000f -1 0    0    1920 1200 tclogin1 KDE Desktop
0x010000ee -1 0    1160 1920 40   tclogin1 kicker
0x01200008  0 4    28   1920 1127 tclogin1 ...p7zip_9.13/bin - Shell No. 8 - Konsole

The Kicker height is 40 and the screen resolution is 1920x1200 so If I wanted to resize my Konsole to take all the screen but the kicker its size should be 1920x1160 (1200-40).
But when I do that, the Konsole overlaps the kicker size.
So I assume that its means that the windows decorations might not be taken into account here.
How can I know the size of the decorations that I would have to add to the windows size given by wmctrl ?
Thanks

A: $ cat allborders.sh
# assumptions:
#   windows ids are at least 5 digits long
#   we dont need to bother with windows that have no name
#   "first argument" from the pipe is east (could be west)
#

WINDOW_IDS=`xwininfo -int -root -tree   |\
    grep '[0-9]*\ (has no name)' -v     |\
    grep -Eo '[0-9]{5,}'`

for win in $WINDOW_IDS;
do
    xprop -id $win |\
        grep -Ee '^(_NET_FRAME_EXTENTS|WM_CLASS)' |\
        sed 's/.*=\ //' |\
        sed -e :a -e '/$/N;s/\n/ /;ta' |\
        grep  ^[0-9]    |\
    while read line;
    do
        set -- $line
        E=`echo $1|sed 's/,$//'`
        W=`echo $2|sed 's/,$//'`
        N=`echo $3|sed 's/,$//'`
        S=`echo $4|sed 's/,$//'`
        NAME=`echo $5|sed 's/,$//'`
        CLASS=`echo $6|sed 's/,$//'`
        echo -e "$CLASS $NAME $N $E $S $W"
    done
done
$ ./allborders.sh
"URxvt" "urxvt" 1 1 1 1
"XTerm" "aterm" 0 0 0 0
"XTerm" "aterm" 0 0 0 0
"Firefox" "Navigator" 18 1 3 1
"Gmpc" "gmpc" 18 1 3 1
"XTerm" "aterm" 0 0 0 0
"XTerm" "one" 0 0 0 0
"XTerm" "aterm" 0 0 0 0
"XTerm" "one" 0 0 0 0
"XTerm" "aterm" 0 0 0 0
"XTerm" "aterm" 0 0 0 0
"XTerm" "aterm" 0 0 0 0
"XTerm" "aterm" 0 0 0 0
"XTerm" "aterm" 0 0 0 0
"FbPager" "fbpager" 0 0 0 0


text:
Q: Ubuntu 21.10 with Samba AD unable to create domain trust account I am trying to add domain trust account for additional kerberos5 (MIT) domain
in Samba AD DC with command:
net rpc trustdom add <domain_name>
-UAdministrator%<administrator_password>
What happens is that the account is created into Samba ldap database and I can
see it in Windows 11 machine.
the command gives an error message:
Could not set trust account password: NT_STATUS_ACCESS_DENIED
with command pdbedit -Lw <account_name>$ i see:
<account_name>$:3000052:NO
PASSWORDXXXXXXXXXXXXXXXXXXXXX:2D2C9A3DC21D9CAFD008D1232D77B9D0:[NDU
]:LCT-6207FF7A:
the [NDU    ] should be [I ] according to Samba Wiki documentation.
My version of samba is: Version 4.13.17-Ubuntu
There is nothing on logs I could see of related to this incident. How
should I debug this?
--
Sami Hulkko

A: In recent samba versions the possibility to add Kerberos5 to kerberos5 trust one-way or two-way has not been implemented yet. There is only possibility to add Samba to Samba trust type.
net rpc trustdom add command only supports Domain trust type while Realm trust only has possibility to add it tools like FreeIpa.
Documentation of this trust feature is somewhat stub:
https://wiki.samba.org/index.php/Active_Directory_Trusts states only Domain to Domain trusts are the only trust types that are possible at this moment. Adding an kerberos5-Kerberos5 key based trust is not implemented though in both MIT5 and Heimdal kerberos5 systems adding trust key is a trivial task.


text:
Q: Our IP was listed by Spamhaus - how can we prevent this from happening again? I'm the technical assistant at a small-town public library where we run our own e-mail. If it matters, it's Postfix on an Ubuntu 18.04 box. Gateway / firewall is a 16.04 box with port forwarding set up through a script that runs at boot, issuing a long sequence of iptables commands.
Today our IP address got onto two Spamhaus block lists, first the SBL and then also the XBL. Last week, after we had an outgoing message bounce, I saw we were on the SBL list. I went through the process to remove it and it was removed. But the problem came roaring back this afternoon, and the web server at Spamhaus pretended to accept my requests to remove the IP, but it stayed on the list and after a few runs it also turned up on the XBL.
I called our internet provider and their network engineer went through the removal steps and actually got it removed. (Or perhaps my first request took that long to process.)
Where should I go from here? I am only a novice systems administrator and what I don't know could fill a... library. To prevent this from happening again, I need to find out what, if anything, is sending spam. I've tried tcpdump on the external NIC for the gateway watching port 25 but I didn't see anything suspicious (to me) during the time I looked (after the fact, and it wasn't long before I moved on to something else, I admit). But I don't even know what's going in and what's going out, and I'm in way over my head. I installed Wireshark on the gateway but soon removed it because it seemed to require a graphical desktop to use. I looked at /var/log/mail.log but I don't see anything that looks like bulk mail going out (but what would that look like?).
Am running sudo tcpdump -i enp3s0 port 25 | tee feb26-27-overnight.log overnight (on the gateway, monitoring the external-facing NIC) in hopes of finding something to glom onto. But it would be nice if there were a straightforward way to find out what's going on without requiring a cyberforensic investigation just to be able to send e-mail to people.
Sequel! How do I ensure that only my e-mail server is sending e-mail through my network?

A: Where should I go from here?

I'm not trying to be glib or dismissive, but you ought to move your email to a professionally hosted service. Office 365. GSuite. Whatever. There's no good reason your organization should be hosting your email in house in 2020. You can't provide the level of availability, scalability, and reliability that these services can... not too mention your current email reputation problem, which you won't have with these services.
The only valid reasons I can think of for your continuing to do this yourself are either budgetary issues or legal issues which would prevent you from moving your email "out of house".

A: What I've done so far is get everything set up for SPF, DKIM, and finally DMARC. Implementation details are going to vary by network and by platform, so I won't give a blow-by-blow of absolutely everything I did. But having done it all seems to have greatly improved the acceptance of my mail.
SPF: Pretty low-hanging fruit. All you have to do is set up a DNS record saying who's allowed to send mail for you, and there are lots of resources to help you compose it, e.g. SPF Wizard.
DKIM: Relatively complex. You have to deal with keys and a bunch of other server-side stuff, then set up a corresponding DNS record. I followed these instructions for Ubuntu (using Postfix and Dovecot) on LinuxBabe. This allows e-mails to be checked for authenticity, that the sender wasn't just spoofing the origin to pretend to be from you.
DMARC: Simple, but you need to have at least one of SPF and DKIM set up first. Similar to SPF, you're just making a DNS record that tells third parties what to do with your mail if it doesn't pass SPF and/or DKIM. General wisdom is to start with "p:none" and read reports for a while until you're satisfied that all your outgoing mail (which might be from more than one source - e.g., we also use Sendgrid), is passing. (You can get daily digests from Gmail, for example.) Then you can ratchet your recommendation up to "p:quarantine" or "p:reject". Some basic info here.
Oh, and a quick do-not-do: Don't use virtual domain aliases or whatever they're called for forwarding purposes. They're not only awkward to use (I had to to spell them out for every single alias a user might have, although there might be another way), but also I think they forward messages before they go through any of your own spam-filtering rules. We got blocked by Outlook almost immediately after forwarding one of our staff's email to their Hotmail account. Instead, since in our setup server users = mail users, we can just set up a .forward file in the user's home directory, with contents like so: externalaccount@externalsite.com, \localusername. This is far more elegant and kicks in only after a message actually reaches a mailbox.


text:
Q: Sorting MM-YYYY string using custom comparer How to perform sorting on the list of mm-yyyy strings along with mixed words using custom comparer with memory-optimized way.
List<string> result = new List<string>();
result.Add("04-2020");
result.Add("03-2021");
result.Add("Nan");

A: You could use Linq as Ran suggested in his answer, and it will work nicely.
However there is another alternative that will probably be more memory-optimized (though admittedly I didn't check):
The List<T> type has a built in Sort method that have several overloads, one of them takes in a Comparison<T> delegate.
Using it will probably be better memory-optimized than using Linq, because you wouldn't need to allocate a new List<T>.
Here's one way you can use it (of course, you can use a named method instead of a lambda expression):
        result.Sort((a, b) => {
            var dateA = DateTime.TryParseExact(a, "MM-yyyy", CultureInfo.InvariantCulture,DateTimeStyles.None, out var dtA) ? dtA : DateTime.MinValue; // change to MaxValue if needed
            var dateB = DateTime.TryParseExact(b, "MM-yyyy", CultureInfo.InvariantCulture,DateTimeStyles.None, out var dtB) ? dtB : DateTime.MinValue; // change to MaxValue if needed
            return dateB.CompareTo(dateA); // Assending order
            return dateA.CompareTo(dateB); // Descending order
        });

A: You can achieve this using Linq and the use of DateTime.TryParseExact
var orderedList = result.OrderByDescending(x =>
      DateTime.TryParseExact(x, "MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var dt)
      ? dt
      : default
    ).ToList();

A: If you also want to sort the "non-dates", then you cannot ignore those (building on previous answers):
List<string> result = new List<string>();
result.Add("04-2020");
result.Add("03-2021");
result.Add("04-2021");
result.Add("2-2021");
result.Add("Nan");
result.Add("Aan");
result.Add("Xan");

var sorted = result.OrderBy(s =>
{
    DateTime dt;
    if (DateTime.TryParseExact(s, "M-yyyy",
            System.Globalization.CultureInfo.InvariantCulture,
            System.Globalization.DateTimeStyles.None, out dt))
        return (dt, "");
    return (DateTime.MaxValue, s);
}).ToList();

This builds a tuple of (DateTime, string), with the date filled in when it did parse, otherwise only the string is filled (with the original string value).
Result:

04-2020
2-2021
03-2021
04-2021
Aan
Nan
Xan


text:
Q: how to increase navigation pane size in preference window in eclipse I want to increase the size of the left navigation pane in the preferences window(the white background one) so that it shows my tool's preferences completely.
As of now a part of it is hidden(full name is mytoolpreference but only mytool is visible whereas preference word is hidden), and I have to increase the navigation pane size manually which I don't want,so please let me know how to increase the navigation pane size.

A: If we are talking about Eclipse itself: That's not possible, as the dialog is not part of the extension point (for good reasons).
If that's for your own RCP application: Feel free to sub class and override the preference dialog. However, this is not recommended, as shared Eclipse UI should seldomly be modified (so users of one Eclipse RCP application still feel like home when using another RCP application).
General advice: Avoid enforcement of UI sizes, whenever you can. The operating system and its windowing system will often "override" your planned sizes anyway. So the result of opening that preference dialog may vary wildly under Windows and Ubuntu, for example. Instead try to shorten your label, that solution will then work under all circumstances.


text:
Q: Algorithm of checking if the number is prime Hello everyone!
I came to this algorithm on how to check if number is prime and probably it's fine for me but I want to find out if it can be improved
bool isPrime(int num)
{
    bool isPrime = 1;
    if (num <= 0)
    {
        return 0;
    }
    if (num == 1)
    {
        return 0;
    }
    for (int i = 2; i <= sqrt(num); ++i)
    {
        if (num % i == 0)
        {
            isPrime = 0;
        }
    }

    return isPrime;
}

Thanks in advance

A: The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = -1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1
Implementation of the above:
#include <iostream>

bool isPrime(int n) {
    // Corner cases
    if(n <= 1) return false;
    if(n <= 3) return true;

    // This is checked so that we can skip
    // middle five numbers in below loop
    if(n % 2 == 0 || n % 3 == 0) return false;

    for(int i = 5; i * i <= n; i = i + 6)
        if(n % i == 0 || n % (i + 2) == 0) return false;

    return true;
}

// Driver Program to test above function
int main() {
    std::cout << std::boolalpha
        << isPrime(11) << '\n'
        << isPrime(15) << '\n';
}

A: A number that is not prime will be divisible by at least one prime number. Hence a way to speed up the algorithm (at the cost of memory) would be to store a list of the prime numbers you have already encountered, and only check whether any of these divide the number you are currently checking in each iteration.

A: To make this more efficient, don't calculate the sqrt of the number
You don't need to check the even numbers if they are divisors.
Also, it's handy to have an early exit in case the number is negative.
Here is my code in C:
#define  boolean  int
#define   TRUE     1
#define   FALSE    0

boolean
isPrime(int number)
{
    if(number == 2)
        return TRUE;

    if(number < 2 || number % 2 == 0)
        return FALSE;

    /*
     * we only need to check until the sqrt
     * and we can omit the even numbers as well
     */
    for(int i = 3; i*i <= number; i += 2)
        if(number % i == 0)
            return FALSE;

    return TRUE;
}

A: *

*2 is the only even prime. So if you start you loop form 3 and increase i by 2, then you can cut off the loop by half.

*And you can break as soon as you find the first divisor.

*Assign the sqrt(num) into a variable so that it does not calculated on every iteration.
    if (num == 2)
    {
        return 1;
    }
    if (num % 2 == 0)
    {
        return 0;
    }
    int square_root = sqrt(num);
    for (int i = 3; i <= square_root; i += 2)
    {
        if (num % i == 0)
        {
            isPrime = 0;
            break;
        }
    }


text:
Q: oracle query - something similar to pivot, but I have a table like this:
ID_ORIG    ID_DEST       DISTANCE
-------    -------      --------
1          101          10
1          102          15
1          103          20
2          101          25
2          102          30
2          103          35
3          101          40
3          102          45
3          103          50

And I want the following result:
ID_ORIG     101         102         103
-------     ---         ---         ---
1           10          15          20
2           25          30          35
3           40          45          50

I tried to use 'pivot', but obiously didn't achive this result. Database is Oracle 11g.
Any help would be appreciated.

A: Please try:
select * From(
    select * from YourTable
  ) PIVOT (sum(DISTANCE) for (ID_DEST) IN (101, 102, 103));

SQL Fiddle Demo


text:
Q: Adding content to Page settings rather than Block settings I have a Gutenberg editor. Some content of the page is global, and not relevant to an individual block. I'd like to add content to the page settings:

I can see how you can add a plugin that creates a secondary sidebar using registerPlugin, however is there a way to hook into and add settings to the Page settings sidebar?

A: Ahh — I found it. It is called the PluginDocumentSettingPanel and can be imported from @wordpress/edit-post.
import { registerPlugin } from '@wordpress/plugins';
import { PluginDocumentSettingPanel } from '@wordpress/edit-post';

const PluginDocumentSettingPanelDemo = () => (
    <PluginDocumentSettingPanel
        name="custom-panel"
        title="Custom Panel"
        className="custom-panel"
    >
        Custom Panel Contents
    </PluginDocumentSettingPanel>
);

registerPlugin( 'plugin-document-setting-panel-demo', {
    render: PluginDocumentSettingPanelDemo,
    icon: 'palmtree',
} );


text:
Q: XML with empty prefix transformation with XSLT I'm willing to use XSLT to transform XML files to other XML files by removing (TextLine) elements. However, the elements are not removed as I expect in the output XML files. I imagine that I'll have to modify the XSLT file, but I don't know how. Let me know what should be done.
I suspect that the root cause of the issue is that elements in the XML files have an empty prefix namespace.
The details are the following ones.
An XML test-01.xml file that contains empty prefix namespace elements:
<?xml version="1.0" encoding="UTF-8"?>
<alto xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns="http://www.loc.gov/standards/alto/ns-v4#"
      xsi:schemaLocation="http://www.loc.gov/standards/alto/ns-v4# http://www.loc.gov/standards/alto/v4/alto-4-2.xsd">
    <TextLine TAGREFS="LT9"/>
    <TextLine TAGREFS="LT10"/>
    <TextLine TAGREFS="LT9"/>
    <TextLine TAGREFS="LT8"/>
</alto>

And I'm using the following date.xslt file:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="TextLine"/>

</xsl:stylesheet>

Note: I'm using python lxml to perform the transformation. However, this shouldn't have any influence on the process as I could use any other XML transformer as xsltproc.

A: Yes. Your assumption that that the default namespace was the cause of your XSLT not functioning as desired was correct. Try this XSLT-1.0 instead:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:loc="http://www.loc.gov/standards/alto/ns-v4#">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="loc:TextLine"/>

</xsl:stylesheet>


text:
Q: Update a record in L2S and L2E I was told in L2S, the code for update and insert are the same,
db.InsertOnSubmit(row);
db.SubmitChanges();

and L2S will check to see if it is a insert or update and act approprately in the background.
Is that true?
How about L2E? I tested, looks like in L2E it is not like that. Maybe I did something wrong.

A: In LINQ to SQL
InsertOnSubmit()

'Adds an entity in a pending insert state to this Table.'
Whereas
SubmitChanges()

'Computes the set of modified objects to be inserted, updated, or deleted, and executes the appropriate commands to implement the changes to the database.'
So Linq to SQL tracks your changes and then uses SubmitChanges to create the neccessary transactions which will commit the changes to your database.
LINQ to Entites uses
SaveChanges()

as the objects in Linq to Entites are not using a lock against the record in the database and so need to be saved rather than the changes submitted.
There's a comprehensive list of differences between L2S and L2E in this stackoverflow question.


text:
Q: Access Atlassian Jira REST API to run super simple report on a filter All I want is basically to login, display info from a simple filter like all open bugs in a milestone. Once I get that far ill be able to work off the documentation
I'm hoping to use simple PHP, that's because I'm new to PHP so the more complicated the coding is the harder it will be for me to figure it out.
This script is the closest I've come to being successful:
    <?php

define('JIRA_URL', 'https://mysite.atlassian.net');
define('USERNAME', 'me@gmail.com');
define('PASSWORD', '11111');

function post_to($resource, $data) {
        $jdata = json_encode($data);
        $ch = curl_init();
        curl_setopt_array($ch, array(
                CURLOPT_POST => 1,
                CURLOPT_URL => JIRA_URL . '/rest/api/2/' . $resource,
                CURLOPT_USERPWD => USERNAME . ':' . PASSWORD,
                CURLOPT_POSTFIELDS => $jdata,
                CURLOPT_HTTPHEADER => array('Content-type: application/json'),
                CURLOPT_RETURNTRANSFER => true
        ));
        $result = curl_exec($ch);
        curl_close($ch);
        return json_decode($result);
}

function create_issue($issue) {
        return post_to('issue', $issue);
}

$new_issue = array(
        'fields' => array(
                'project' => array('key' => 'FOO'),
                'summary' => 'Test via REST',
                'description' => 'Description of issue goes here.',
                'issuetype' => array('name' => 'Story')
        )
);

$result = create_issue($new_issue);
if (property_exists($result, 'errors')) {
        echo "Error(s) creating issue:\n";
        var_dump($result);
} else {
        echo "New issue created at " . JIRA_URL ."/browse/{$result->key}\n";
        var_dump($result);
}
?>

It returns New issue created at http://mysite.atlassian.net/browse/
But when I put the var_dump ($result) in there that just returns null so I have no idea if the jira URL is wrong or my password or if its outdated code for the new rest API.
If I could just make 1 simple query to the API and see anything returned on my PHP page I would be a happy camper. The example above creates a new issue, that's just the example I was using but I'm fine with just returning any sort of data so my main issue is getting a valid connection and returning some info so I know its working and can't start trying some different things then.
I have admin access but I wasn't clear if I needed to enable something on the admin side.

A: Following to this page...
https://developer.atlassian.com/jiradev/api-reference/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-basic-authentication
We need to use header authentication these days which looks - modifying the example in this tread - like:
$username = 'user';
$password = 'pass';

$url = 'https://www.jiradomain.com/rest/api/2/issue/PROJECT-321/worklog';

$curl = curl_init();

curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . base64_encode("$username:$password")) );**
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_VERBOSE, true);

$verbose = fopen('php://temp', 'rw+');
curl_setopt($curl, CURLOPT_STDERR, $verbose);

$issue_list = (curl_exec($curl));
echo $issue_list;

$result = curl_exec($curl);
if ($result === FALSE) {
    printf("cUrl error (#%d): %s
\n", curl_errno($curlHandle),
           htmlspecialchars(curl_error($curlHandle)));
}

rewind($verbose);
$verboseLog = stream_get_contents($verbose);

echo "Verbose information:\n
", htmlspecialchars($verboseLog), "
\n";

A: I figured out what i needed to do, there are lots of examples on the net but i couldnt find one simple like this so hopefully it helps someone else
$username = 'xxx';
$password = 'xxx';

$url = 'https://xxx.atlassian.net/rest/api/2/Issue/Bug-5555';

$curl = curl_init();
curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);

$issue_list = (curl_exec($curl));
echo $issue_list;


text:
Q: basic information about holder in android I'm searching for some information about "holder" in android...because I've seen some code that used it in using checkbox in gridview...but I couldn't find basic information about it. I'll be happy if anyone can help me.
here is a part of a code that used holder :
public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(
                        R.layout.galleryitem, null);
                holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
                holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);

                convertView.setTag(holder);
            }
            else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.checkbox.setId(position);
            holder.imageview.setId(position);

A: ViewHolder is used to improve the performance of list scroll here.
Here's a piece of information that might interest you extracted from Android Developer Website.

A: Using ViewHolder allow you to avoid of calling findViewById() in every getView() method

A: In android, listview use convert view to get better performance, it will reuse the list item view with avoiding create view every time, and the view holder is used to keep subview reference in the convert view. You can dig into the listview source code for details, Thanks

A: Your code might call findViewById() frequently during the scrolling of ListView, which can slow down performance. Even when the Adapter returns an inflated view for recycling, you still need to look up the elements and update them. A way around repeated use of findViewById() is to use the "view holder" design pattern.
A ViewHolder object stores each of the component views inside the tag field of the Layout, so you can immediately access them without the need to look them up repeatedly.
For more info refer here

A: ViewHolder is used to avoid an expensive call that is running on all calls. I refer to obtaining a reference to each of the objects to be modified by the method findViewById(). Search for a particular control ID of the object tree within a layout can also be a costly depending on the complexity of the layout itself.
With ViewHolder pattern we can save the reference to the controls so we don´t have to search them again.The only ViewHolder class will contain a reference to each of the controls that we have to handle our layout, in your case:
static class ViewHolder {
    ImageView imageview;
    Checkbox checkbox;
}

We will save the holder with the references in the tag property, presented in every control in Android, with setTag(), and we can obtain it with getTag().

A: These links may help you.
http://xjaphx.wordpress.com/2011/06/16/viewholder-pattern-caching-view-efficiently/
http://vsvydenko.blogspot.in/2011/06/android-use-viewholder.html
Your code might call findViewById() frequently during the scrolling of ListView, which can slow down performance. Even when the Adapter returns an inflated view for recycling, you still need to look up the elements and update them. A way around repeated use of findViewById() is to use the "view holder" design pattern.
A ViewHolder object stores each of the component views inside the tag field of the Layout, so you can immediately access them without the need to look them up repeatedly


text:
Q: EF usage from thread spawned from Role.OnStart() I'm using EF code-first to manage my DB connection, with an explicit connection string declared in web.config. I would like to schedule some DB cleaning process (like deleting test transactions every day), so I'm spawning a thread from Role.OnStart() with proper concurrency management among the instances.
But I'm getting DB database exceptions, like the DB not matching my model, whereas I'm sure it does (the same code used from "inside" the app works well). So my guess is that web.config is not used from the thread, so EF probably uses the default connection string.
What would be the best way to use my connection string from there ?
Thanks

A: The OnStart method doesn't run in the same process as your web application meaning it doesn't make use of the web.config. I suggest you store the connection string in the service configuration and read it from here when initializing your context.
An other advantage is that you change the setting without re-deploying the application.


text:
Q: GWT tries to load a deleted module I am using Eclispe with Google plugin for AppEngine and GWT. Recently I created a test GWT module, but eventually it has been deleted from the project and I can not find any sign of it in the project now.
However, whenever I run the web app locally, I get in console the following message:
Loading modules
   com.piq.exemity.Test
      [ERROR] Unable to find 'com/XXXXXX/Test.gwt.xml' on your classpath; could be a typo, or maybe you forgot to include a classpath entry for source?

Has anyone got any idea where it can be hiding?

A: It could be there in two places -

*

*When you invoke GWTC (via the compile option in Eclipse), the module name com.xxx.Test is passed to the compiler. This causes GWT to look for com/xxx/Test.gwt.xml file

*You could have a module that inherits the module "com.xxx.Test". Check your gwt.xml file if this is the case
I think (1) is more likely the culprit.

A: Open Run Configurations... from the Run pulldown menu and go to tab Arguments. In the Program arguments box delete the path to your deleted module.


text:
Q: Closed form for $\sum_{k=0}^{n} k \sum_{j=0}^k {n \choose j}$ Closed form for $$S=\sum_{k=0}^{n} k \sum_{j=0}^k {n \choose j}$$
becomes interesting because we do not know the $j$-sum but on the other hand we can simply expand $S$ as
$$S=\sum_{k=0}^n f_k {n \choose k},$$
where $f_k$ is like frequency of $k$-th binomial coefficient. The question is what could be the closed form for $S$ with proof?

A: You have :
$$S = \sum_{k=0}^n k \sum_{j=0}^k {n \choose j} = \sum_{j=0}^n \sum_{k=j}^n k {n \choose j} = \sum_{j=0}^n  {n \choose j}\sum_{k=j}^n k  = \sum_{j=0}^n  {n \choose j} \left[ \frac{n(n+1)}{2}  - \frac{(j-1)j}{2}\right]$$ $$=\frac{n(n+1)}{2} 2^n - \frac{1}{2}\sum_{j=0}^n j(j-1)  {n \choose j}  = n(n+1) 2^{n-1} - n(n-1)2^{n-3}$$ $$=2^{n-3} \left( -n(n-1) + 4n(n+1)\right) = 2^{n-3} \left( 3n^2 + 5n\right)$$


text:
Q: Twitter OAuth Authorization Issue with .NET (C#) I have been pulling my hair to figure our what goes wrong here and apparently I haven't been able to. I try to create a basic structure to work with Twitter API over OAuth in .NET (C#) but something is wrong and I cannot see what that is.
For example, when I send a request in order to obtain a request token, I get back 401 Unauthorized response back with a message as follows:

Failed to validate oauth signature and token

The signature base that I use to create the signature is as follows (I replaced my actual Consumer Key with a dummy value):

POST&http%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%3A%2F%2Flocalhost%3A44444%2Faccount%2Fauth%26oauth_consumer_key%3XXXXXXXXXXXXXXXXXXXXXXXXXXX%26oauth_nonce%3DNjM0NzkyMzk0OTk2ODEyNTAz%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1343631900%26oauth_version%3D1.0

The signing key only consists of my Consumer Key Secret and an ampersand given the fact that I don't have a token secret available yet (again, I replaced my actual Consumer Key with a dummy value):

signingKey: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&

At the end, I end up with the following Authorization header (again, dummy Consumer Key):

OAuth oauth_callback="http%3A%2F%2Flocalhost%3A44444%2Faccount%2Fauth",oauth_consumer_key="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",oauth_nonce="NjM0NzkyMzk0OTk2ODEyNTAz",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1343631900",oauth_version="1.0",oauth_signature="ttLvZ2Xzq4CHt%2BNM4pW7X4h1wRA%3D"

The code I use for this is as follows (it is a little bit long but I'd rather paste it here instead of giving a gist URL or something):
public class OAuthMessageHandler : DelegatingHandler {

    private const string OAuthConsumerKey = "oauth_consumer_key";
    private const string OAuthNonce = "oauth_nonce";
    private const string OAuthSignature = "oauth_signature";
    private const string OAuthSignatureMethod = "oauth_signature_method";
    private const string OAuthTimestamp = "oauth_timestamp";
    private const string OAuthToken = "oauth_token";
    private const string OAuthVersion = "oauth_version";
    private const string OAuthCallback = "oauth_callback";

    private const string HMACSHA1SignatureType = "HMAC-SHA1";

    private readonly OAuthState _oAuthState;

    public OAuthMessageHandler(OAuthCredential oAuthCredential, OAuthSignatureEntity signatureEntity,
        IEnumerable<KeyValuePair<string, string>> parameters, HttpMessageHandler innerHandler) : base(innerHandler) {

        _oAuthState = new OAuthState() {
            Credential = oAuthCredential,
            SignatureEntity = signatureEntity,
            Parameters = parameters,
            Nonce = GenerateNonce(),
            SignatureMethod = GetOAuthSignatureMethod(),
            Timestamp = GetTimestamp(),
            Version = GetVersion()
        };
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {

        //add the auth header
        request.Headers.Authorization = new AuthenticationHeaderValue(
            "OAuth", GenerateAuthHeader(_oAuthState, request)
        );

        return base.SendAsync(request, cancellationToken);
    }

    private string GetTimestamp() {

        TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        return Convert.ToInt64(timeSpan.TotalSeconds).ToString();
    }

    private string GetVersion() {

        return "1.0";
    }

    private string GetOAuthSignatureMethod() {

        return HMACSHA1SignatureType;
    }

    private string GenerateNonce() {

        return Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
    }

    private string GenerateSignature(OAuthState oAuthState, HttpRequestMessage request) {

        //https://dev.twitter.com/docs/auth/creating-signature
        //http://garyshortblog.wordpress.com/2011/02/11/a-twitter-oauth-example-in-c/

        SortedDictionary<string, string> signatureCollection = new SortedDictionary<string, string>();

        //Required for all requests
        signatureCollection.Add(OAuthConsumerKey, oAuthState.Credential.ConsumerKey);
        signatureCollection.Add(OAuthNonce, oAuthState.Nonce);
        signatureCollection.Add(OAuthVersion, oAuthState.Version);
        signatureCollection.Add(OAuthTimestamp, oAuthState.Timestamp);
        signatureCollection.Add(OAuthSignatureMethod, oAuthState.SignatureMethod);

        //Parameters
        if (oAuthState.Parameters != null) {
            oAuthState.Parameters.ForEach(x => signatureCollection.Add(x.Key, x.Value));
        }

        //Optionals
        if (!string.IsNullOrEmpty(oAuthState.Credential.Token))
            signatureCollection.Add(OAuthToken, oAuthState.Credential.Token);

        if (!string.IsNullOrEmpty(oAuthState.Credential.CallbackUrl))
            signatureCollection.Add(OAuthCallback, oAuthState.Credential.CallbackUrl);

        //Build the signature
        StringBuilder strBuilder = new StringBuilder();
        strBuilder.AppendFormat("{0}&", request.Method.Method.ToUpper());
        strBuilder.AppendFormat("{0}&", Uri.EscapeDataString(request.RequestUri.ToString()));
        signatureCollection.ForEach(x =>
            strBuilder.Append(
                Uri.EscapeDataString(string.Format("{0}={1}&", x.Key, x.Value))
            )
        );

        //Remove the trailing ambersand char from the signatureBase.
        //Remember, it's been urlEncoded so you have to remove the
        //last 3 chars - %26
        string baseSignatureString = strBuilder.ToString();
        baseSignatureString = baseSignatureString.Substring(0, baseSignatureString.Length - 3);

        //Build the signing key
        string signingKey = string.Format(
            "{0}&{1}", Uri.EscapeDataString(oAuthState.SignatureEntity.ConsumerSecret),
            string.IsNullOrEmpty(oAuthState.SignatureEntity.OAuthTokenSecret) ? "" : Uri.EscapeDataString(oAuthState.SignatureEntity.OAuthTokenSecret)
        );

        //Sign the request
        using (HMACSHA1 hashAlgorithm = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey))) {

            return Convert.ToBase64String(
                hashAlgorithm.ComputeHash(
                    new ASCIIEncoding().GetBytes(baseSignatureString)
                )
            );
        }
    }

    private string GenerateAuthHeader(OAuthState oAuthState, HttpRequestMessage request) {

        SortedDictionary<string, string> sortedDictionary = new SortedDictionary<string, string>();
        sortedDictionary.Add(OAuthNonce, Uri.EscapeDataString(oAuthState.Nonce));
        sortedDictionary.Add(OAuthSignatureMethod, Uri.EscapeDataString(oAuthState.SignatureMethod));
        sortedDictionary.Add(OAuthTimestamp, Uri.EscapeDataString(oAuthState.Timestamp));
        sortedDictionary.Add(OAuthConsumerKey, Uri.EscapeDataString(oAuthState.Credential.ConsumerKey));
        sortedDictionary.Add(OAuthVersion, Uri.EscapeDataString(oAuthState.Version));

        if (!string.IsNullOrEmpty(_oAuthState.Credential.Token))
            sortedDictionary.Add(OAuthToken, Uri.EscapeDataString(oAuthState.Credential.Token));

        if (!string.IsNullOrEmpty(_oAuthState.Credential.CallbackUrl))
            sortedDictionary.Add(OAuthCallback, Uri.EscapeDataString(oAuthState.Credential.CallbackUrl));

        StringBuilder strBuilder = new StringBuilder();
        var valueFormat = "{0}=\"{1}\",";

        sortedDictionary.ForEach(x => {
            strBuilder.AppendFormat(valueFormat, x.Key, x.Value);
        });

        //oAuth parameters has to be sorted before sending, but signature has to be at the end of the authorization request
        //http://stackoverflow.com/questions/5591240/acquire-twitter-request-token-failed
        strBuilder.AppendFormat(valueFormat, OAuthSignature, Uri.EscapeDataString(GenerateSignature(oAuthState, request)));

        return strBuilder.ToString().TrimEnd(',');
    }

    private class OAuthState {

        public OAuthCredential Credential { get; set; }
        public OAuthSignatureEntity SignatureEntity { get; set; }
        public IEnumerable<KeyValuePair<string, string>> Parameters { get; set; }
        public string Nonce { get; set; }
        public string Timestamp { get; set; }
        public string Version { get; set; }
        public string SignatureMethod { get; set; }
    }
}

There is a mix of new .NET HttpClient here but the Authorization header generation code is clear to understand.
So, what would be my problem here and what am I missing?
Edit:
I gave it a try for different endpoint (such as /1/account/update_profile.json), and it works when I send a request whose body doesn't require encoding. E.g: location=Marmaris works but location=Marmaris, Turkey doesn't work even if I encode it using Uri.EscapeDataString.
Edit:
I gave it a try with Twitter OAuth tool to see if there is any particular difference between my signature base and twitter's and I can see that twitter's encoding is different than mine. For example, Twitter produces location%3DMarmaris%252C%2520Turkey value for location=Marmaris, Turkey but what I produce is location%3DMarmaris%2C%20Turkey.

A: It seems that all the problem was related to encoding issue and for now, it seems that I solved the problem out. Here is a few information about the issue:
When we are creating the signature base, the parameter values needs to be encoded twice. For example, I have a collection as below:
var collection = new List<KeyValuePair<string, string>>();
collection.Add(new KeyValuePair<string, string>("location", Uri.EscapeDataString(locationVal)));
collection.Add(new KeyValuePair<string, string>("url", Uri.EscapeDataString(profileUrl)));

When I pass this to GenerateSignature method, that method encodes these one more time and this results percentage signs to be encoded as %25 and this made it work. One of my problems was solved but I still couldn't issue a request token request successfully at that time.
Then, I looked at the "request_token" request and saw the below line of code:
OAuthCredential creds = new OAuthCredential(_consumerKey) {
    CallbackUrl = "http://localhost:44444/account/auth"
};

I was sending the CallbackUrl as it is in order for it to be encoded but as twitter needs to encode things twice for the signature base, I thought that might be the problem. Then, I replaced this code with the following one:
OAuthCredential creds = new OAuthCredential(_consumerKey) {
    CallbackUrl = Uri.EscapeDataString("http://localhost:44444/account/auth")
};

One more change I made was inside the GenerateAuthHeader method since I don't need to encode CallbackUrl twice.
//don't encode it here again.
//we already did that and auth header doesn't require it to be encoded twice
if (!string.IsNullOrEmpty(_oAuthState.Credential.CallbackUrl))
    sortedDictionary.Add(OAuthCallback, oAuthState.Credential.CallbackUrl);

And I made it run w/o any problems.

A: Tugberk here is another OAuth lib, no magic here.
http://oauth.googlecode.com/svn/code/csharp/OAuthBase.cs


text:
Q: Mathematica interoperability with Max/MSP A little foreword: I'm an absolute beginner of Mathematica (but I'm a programmer in other languages/software).
Now the question: I have a Mathematica Notebook written by a friend of mine which takes two input (an integer and an array of integers) and returns 2 strings (I don't think the details are relevant to my question) and he asked me to convert it in a Max/MSP plugin.
Before to port the Notebook in C (Max/MSP plugins are written in this language) I did some research about interoperability between Mathematica and other software, I found some reference for Java here: How to integrate Mathematica with other software but for Max/MSP but for C I didn't find anything.
Somebody has some good tip on this? Thank you in advance.


text:
Q: Check if a connection is TLSv1 vs SSLv3 (SSL_CIPHER_description/SSL_CIPHER_get_name) I have a server application that uses OpenSSL.  I'm trying to understand what type of SSL connections are hitting my system (i.e. SSLv2, SSLv3, TLSv1, TLSv1.1, TLSv1.2).  In particular, I'm working towards disabling SSLv3 (re: POODLE).  Before I can do that, I want to see who/what is connecting on SSLv3
I'm currently using the SSL_CIPHER_description and SSL_CIPHER_get_name functions, which provide really good information on the ciphers negotiated for each connection
I'm having some challenges trying to differentiate SSLv3 vs TLSv1 connections.  Per
https://www.openssl.org/docs/ssl/SSL_CIPHER_get_name.html:
"The TLSv1.0 ciphers are flagged with SSLv3. No new ciphers were added by TLSv1.1."

I've confirmed that TLSv1 connections get noted as SSLv3
Ex: SSL_CIPHER_description returns the following on a connection that is definitely TLSv1.0:
AES256-SHA              SSLv3 Kx=RSA      Au=RSA  Enc=AES(256)  Mac=SHA1
Does anyone have any ideas on how to detect if a connection is SSLv3 versus TLSv1 in OpenSSL?

A: See the API SSL_get_cipher_version() and friends.
Additionally, SSLv3/TLS packets all start with a header which you can easily inspect as well:
Byte 0  : Record Type
Byte 1  : Version Major
Byte 2  : Version Minor
Byte 3-4: Length of payload minus header (16k max)

Version Major breaks down like this:
Major == 2: SSLv2 (The rest differs from SSLv3+ headers)
Major == 3: SSLv3, TLSv1.0, TLSv1.1, or TLSv1.2

Version Minor:
Minor == 0: SSLv3
Minor == 1: TLSv1.0
Minor == 2: TLSv1.1
Minor == 3: TLSv1.2

Do note though that until the handshake/negotiation is complete, the versions used can change. If you wait until Application Data, it should be accurate. Example Application Data of a TLSv1.2 record:
0x17 0x03 0x03 ...

Sniff the Data!
Yet another approach if this is simply for research is to sniff the data with Wireshark or similar.

A: You can use the method SSL_get_version(SSL *ssl) after the connection is successfully negotiated.


text:
Q: Custom domain name to serve Python packages from Google Artifact Registry? We're serving Python packages through Google's Artifact Registry. Actually the URL is the "default" one, so:
https://[REGION].pkg.dev/[PROJECT_ID]/.....

But what if we wanted to use a custom domain name? For example, we'd like to serve packages from a custom domain link like:
https://[MY-CUSTOM-DOMAIN]/...

Is there an official way to do that? What are my options?

A: We got an "official" answer from a Google Cloud Community Team member, please see this link.
It pretty answer my question.

There is no official support for custom domains in AR but you can run a reverse proxy on Cloud Run (which supports Custom domains). This article might help - Hack your own custom domains for Container Registry


text:
Q: Laravel 4 public files not updating on edit I am using Laravel together with a Vagrant setup, on my developer box.
I have run into an odd problem though. When I edit a css or js files, in my Laravel public folder, the changes does not apply.
If I SSH to the Vagrant box, and edit the file, I can see my changes are there in the file, but its like Laravel caches the old ones, and do not update to the new file.
If I then write the file again, that I just opened for edit, in my SSH terminal, the file will update on reload.
How come that when I edit it through my editor, and save it, Laravel do not seem to recognize the change, until it is opened and saved again through SSH?

A: I have seen this kind of behaviour when the clocks on your PC and the server are out of sync. So the PC might be setting the timestamp into the past, therefore the cache won't update the changes.
(Not sure if you're saying you are using a cache in Laravel or not, if not then this probably won't be the cause).

A: In case anyone else has this issue when using Nginx and Vagrant, I found this article (http://jeremyfelt.com/code/2013/01/08/clear-nginx-cache-in-vagrant/) that worked for me. To summarize (in case the URL above goes dead) update your nginx.conf file so the 'sendfile' setting is set to off.


text:
Q: classes are not listing in Class view(Architecture Explorer) in VS2010 I want to generate UML Class diagram from my existing solution. As per the link
    https://msdn.microsoft.com/en-us/library/ff657806.aspx, I have to drag and drop the classes from class view. But if I opened class view in Architecture explorer, the classes are missing.
1 MFC project and 5 Win32 projects present in my solution.
Am I missing anything, while opening the class view?
EDIT: The link says for C# classes. Doesn't this work for C++ code? (My projects are in C++)


text:
Q: Swipeable Tabs With Active Tab How're you doing guys.
Please I need your help on this matter.
I've found this code on codepen : https://codepen.io/grahn195/pen/oNZvwRL and it works very perfectly on codepen.io
I wanted to create three swipeable tabs, and I've succeeded to create them perfectly. But what I want is to make the middle tab to be active instead of the first tab.

<!DOCTYPE html>

  <meta charset="UTF-8">

  <title>CodePen - Swipeable Tabs</title>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.1.2/css/swiper.min.css'>

Tab 1x

Tab 2x

Tab 3x

A: Refer to https://swiperjs.com/swiper-api#param-initialSlide
initialSlide
Index number of initial slide.
Add the parameter
initialSlide: 1,


text:
Q: Selenium Webdriver javascript - pop up is getting open 4 times on every dropdown click I am new to selenium. The scenario is that pop up is getting open when I click on popupid, there are 4 dropdowns in the pop up where i need to select the values from each dropdown but while selecting values from each dropdown new pop up window opens which overrides the existing one. Due to which also facing issue in selecting the correct values.
Selenium code:
WebDriverWait waitFortab = new WebDriverWait(driver, 15);
waitFortab.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".node.settings.asettings.bookmgmt.undefined.ready")));
WebElement el5 = driver.findElement(By.cssSelector(".bookrouting")); // opens the page
js.executeScript("arguments[0].click();", el5);
WebElement el6 = driver.findElement(By.cssSelector(".ruleEnControls .fr.bookroute.addcategory")); // opens up popup
el6.click();
WebDriverWait waitForcategory = new WebDriverWait(driver, 15);
waitForcategory.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".popup.wrapper.bookroute_save.dffPopup")));
WebElement el8 = driver.findElement(By.cssSelector(".tag.dropdown.product_brm .downArrow.closed"));
js.executeScript("arguments[0].click();", el8);
WebElement el9 = driver.findElement(By.xpath("//*[text()='Vanilla (V)']")); // selects value from first pop up
js.executeScript("arguments[0].click();", el9);

WebElement el10 = driver.findElement(By.cssSelector(".tag.dropdown.currency_pair_brm .downArrow.closed"));
js.executeScript("arguments[0].click();", el10);
WebElement el11 = driver.findElement(By.xpath("//*[text()='AUD/CAD']")); // selects value from second pop up
js.executeScript("arguments[0].click();", el11);

WebElement el12 = driver.findElement(By.cssSelector(".tag.dropdown.currency_brm .downArrow.closed"));
js.executeScript("arguments[0].click();", el12);
WebElement el13 = driver.findElement(By.xpath("//*[text()='AUD']"));  // selects value from third pop up
js.executeScript("arguments[0].click();", el13);

HTML Snippet :

<input type="hidden" value="0" class="toggleValue value">

  Select All

<input type="hidden" value="0" class="toggleValue value">

  Vanilla (V)

A: I bet you're running in to some timing issues with the popups being present, but not yet ready on the DOM--so the clicks are happening on the previous elements.
Try something like this:
WebDriverWait wait = new WebDriverWait(driver, 15);
WebElement el8 = driver.findElement(By.cssSelector(".tag.dropdown.product_brm .downArrow.closed"));
wait.until(ExpexctedConditions.elementIsClickable(el8);
js.executeScript("arguments[0].click();", el8);

WebElement el9 = driver.findElement(By.xpath("//*[text()='Vanilla (V)']")); // selects value from first pop up
wait.until(ExpexctedConditions.elementIsClickable(el9);
js.executeScript("arguments[0].click();", el9);

A couple things:

*

*You don't need a new wait for different things. Just reuse existing one.

*Note that the pattern is

*

*Find the element

*Wait for element to be clickable

*Click the element.

*Also, not sure why you're using the JavaScriptExecutor. You could simply do "el9.click();" unless there's something goofy with JavaScript on your pop ups.

HTH


text:
Q: How to build QT 4.8.7 For 32-bit I am using Ubuntu 14.04 (64-bit). I want to build QT 4.8.7 Source code for 32-bit. How to configure the build?

A: Well if all solutions in the comments fail. Do it as me in VirtualBox. Install 32b operating system there and build what you want.


text:
Q: Sort Dictionary of Dictionaries I have a dataset
{6317637: {'name': 'Le Petit Souffle', 'Votes': 314, 'Cuisines': 'French, Japanese, Desserts', 'AverageCostfortwo': 1100, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.8', 'Ratingcolor': 'lightgreen', 'Ratingtext': 'Excellent'}, 6304287: {'name': 'Izakaya Kikufuji', 'Votes': 591, 'Cuisines': 'Japanese', 'AverageCostfortwo': 1200, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.5', 'Ratingcolor': 'lightgreen', 'Ratingtext': 'Excellent'}, 6300002: {'name': 'Heat - Edsa Shangri-La', 'Votes': 270, 'Cuisines': 'Seafood, Asian, Filipino, Indian', 'AverageCostfortwo': 4000, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.4', 'Ratingcolor': 'green', 'Ratingtext': 'Very Good'}, 6318506: {'name': 'Ooma', 'Votes': 365, 'Cuisines': 'Japanese, Sushi', 'AverageCostfortwo': 1500, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'No', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.9', 'Ratingcolor': 'lightgreen', 'Ratingtext': 'Excellent'}, 6314302: {'name': 'Sambo Kojin', 'Votes': 229, 'Cuisines': 'Japanese, Korean', 'AverageCostfortwo': 1500, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.8', 'Ratingcolor': 'lightgreen',
'Ratingtext': 'Excellent'}, 18189371: {'name': 'Din Tai Fung', 'Votes': 336, 'Cuisines': 'Chinese', 'AverageCostfortwo': 1000, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'No', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.4', 'Ratingcolor': 'green', 'Ratingtext': 'Very Good'}, 6300781: {'name': 'Buffet 101', 'Votes': 520, 'Cuisines': 'Asian, European', 'AverageCostfortwo': 2000, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4', 'Ratingcolor': 'green', 'Ratingtext': 'Very Good'}, 6301290: {'name': 'Vikings', 'Votes': 677, 'Cuisines': 'Seafood, Filipino, Asian, European', 'AverageCostfortwo': 2000, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.2', 'Ratingcolor': 'green', 'Ratingtext': 'Very Good'}, 6300010: {'name': 'Spiral - Sofitel Philippine Plaza Manila', 'Votes': 621, 'Cuisines': 'European, Asian, Indian', 'AverageCostfortwo': 6000, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No',
'Aggregaterating': '4.9', 'Ratingcolor': 'lightgreen', 'Ratingtext': 'Excellent'}}

I tried sorting using this code:
sorted(frontend_content,key=lambda x:frontend_content[x]['name']), but I got no change.
How do I sort this based on a particular field say name or votes?

A: You cannot sort a dict in python since it is orderless, you need to convert it to other data types such as list of list or list of tuple first.
x = {6317637: {'name' : .... } }
sorted_x = sorted(x.items(),key = lambda kv : kv[1]['Votes'])

By calling x.items() you are iterating through it as a tuple of (key,value). Therefore, kv[1] would be the value here


text:
Q: How @PreAuthorize checks the roles? I have several REST APIs.
I would like to put Security on top of all of them, in order to allowed the functionalities only for certain roles.
I put the @EnableGlobalMethodSecurity(prePostEnabled = true) in the configuration class.
I have a DB with a table which stores the roles.
@RequestMapping(path = "/error", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public ResponseEntity<ResponseWrapper> getError(...

INSERT INTO table USER_ROLE VALUES ('ADMIN','PASSWORD','ROLE_ADMIN');

How can the method "hasRole" query the table USER_ROLE?
Is there any setting that I must give to Spring in order to communicate with that table?

A: Ensure you add the following to your configuration:
Annotation style:
@EnableGlobalMethodSecurity(prePostEnabled = true)

XML Style:
<global-method-security pre-post-annotations="enabled"/>

It's all in the spring docs.
Using @Pre and @Post annotations requires you to have first set up spring security in your project. User roles are loaded during authentication in the standard implementation.
It doesn't check your table when checking the annotation (by default), it just checks the Principal (User) object in  memory for the list of assigned GrantedAuthority (Roles).
A closer look...
Take a look at the UserDetailsService interface, this returns an instance of UserDetails (the Principal). This is where we fetch your "user" from the database.
The UserDetails interface defines a method called getAuthorities() that returns a Collection<? extends GrantedAuthority>, essentially your Role table. This is where the "Roles" make it into memory, and can be later checked by the @Pre and @Post annotations.
The implementation I've explained above can be found here.


text:
Q: wp_nav_menu() to display current page and its subitems of depth = 1 Here's what I'm trying to do. Let's say I have a menu that looks like this:

Page #1

Sub-Page #1

Sub-Sub-Page #1

Sub-Sub-Page #2

Sub-Page #2

Sub-Page #3

Page #2

Page #3

What I'd like to do is use wp_nav_menu to display only the page the user is currently viewing and its subitems, so for example if someone's on Sub-Page #1 or on one of its subitems (Sub-Sub-Page #1 or #2) the generated menu should look like this:

Sub-Page #1

Sub-Sub-Page #1

Sub-Sub-Page #2

If the user is currently on a Page #1 the generated menu should look like this:

Page #1

Sub-Page #1

Sub-Page #2

Sub-Page #3

Is it possible to achieve something like this via wp_nav_menu or any other way for that matter? Any help would be greatly appreciated.

A: You can achieve something like this via "get_posts". Just pass parameter "post_parent" in query arguments and you will get all child page.
https://codex.wordpress.org/Template_Tags/get_posts

  <?php global $post;
  $args = array( 'posts_per_page' => -1, 'post_parent'=> get_the_ID() );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>

    <a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php endforeach;  ?>

you can get same goal via wp_query.
https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters


text:
Q: Does "I play football at the park near my house every Tuesday evening." sound natural? The answer to this post (Is it idiomatic to say "he wakes up early always" or "he wakes up always early"?) says

It is unusual and odd to use the adverbs "usually" or "always" at the end of the sentence.

I agree with that.
Besides, Cambridge dictionary gives this grammar rule

The adverb usually refers to what typically or normally happens. We use it mostly in mid position, between the subject and the main verb, or after the modal verb or first auxiliary verb, or after be as a main verb:

I guess the rule above is also applicable to other adverbs of frequency.

I play football every Tuesday evening at the park near my house."

I am curious that, does putting the adverbs of frequency at the end of the sentence like the following also natural?

I play football at the park near my house every Tuesday evening.

A: It is perfectly natural to put "every Tuesday night" at the end of your example. Yes, usually adverbs are placed close to the adjective or verb that they are modifying. But "every Tuesday night" is an adverbial phrase rather than a simple adverb and those frequently come after the direct object or before the subject.

Every Tuesday night, we play football

and

We play football every Tuesday night

are both quite natural.


text:
Q: How to get the data sorted based on column values before comma In an unsorted large CSV file, How could i sort the Resource Name column so i can get all the same name results aligned sequentially lined up One after another like grep in my example below.
In the Resource Name column we need select the data before comma , in order to get it required result.
My trial code:
#!/home/uatacto/bin/python
# -*- coding: utf-8 -*-

import pandas as pd

cols = ['Status', 'Resource Name', 'Appliance',  'State',  'Description', 'Corrective Action']
df = pd.read_csv("ResourceAlertsReport.csv", usecols=cols)
#df['Resource Name'] = df['Resource Name'].str.lower()
df = df.apply(lambda x: x.astype(str).str.lower())

print(df)

Resulted DataFrame Structure:
        Status                                      Resource Name                     Appliance   State                                        Description                                  Corrective Action
0     critical                                     enc8005, bay 4                        ov8002  active  there are failed entries in the ilo integrated...  log into the ilo and view the integrated manag...
1     critical                                     enc8013, bay 9                        ov8004  active              the bios/hardware status is critical.  log into the ilo and view the integrated manag...
2     critical                                     enc8013, bay 9                        ov8004  locked  the ilo for the server hardware in bay 9 is re...  check the ilo system information - health summ...
3     critical                                            enc8002                        ov8001  locked  encountered connectivity problems with synergy...  refresh the enclosure, reseat the appliance, r...
4     critical                                    enc3061, bay 12                        ov3004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
5     critical                                            enc8002                        ov8001  locked  encountered connectivity problems with synergy...  refresh the enclosure, reseat the appliance, r...
6     critical                                     enc3070, bay 3                        ov3007  active  service event: the state of the processor in s...  a support ticket has been opened by the hpe su...
7     critical                                     enc2029, bay 3                        ov2002  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
8     critical                                     enc8058, bay 6                        ov8013  active  there are failed entries in the ilo integrated...  log into the ilo and view the integrated manag...
9     critical                                     enc8056, bay 8                        ov8013  active  there are failed entries in the ilo integrated...  log into the ilo and view the integrated manag...
10    critical                                     enc3054, bay 4                        ov3002  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
11    critical                                            enc8002                        ov8001  locked  encountered connectivity problems with synergy...  refresh the enclosure, reseat the appliance, r...
12    critical                                     enc8005, bay 4                        ov8002  locked  the product id and/or serial number of the ser...  if the server is running a workload, schedule ...
13    critical                                     enc1019, bay 1                        ov1001  active  the firmware integrity scan or boot time valid...  if configured for automatic recovery, the repa...
14    critical                                    enc8048, bay 11                        ov8010  active              the bios/hardware status is critical.  log into the ilo and view the integrated manag...
15    critical                                     enc8043, bay 5                        ov8008  active  service event: the physical status of a drive ...  a support ticket has been opened by the hpe su...
16    critical                                     enc8043, bay 5                        ov8008  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
17    critical                                    enc2009, bay 14         ov c7000 enclosures 1  active  there are failed entries in the ilo integrated...  log into the ilo and view the integrated manag...
18    critical                                     enc3054, bay 9                        ov3002  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...

Sorted result with grep:
$ python test_ov.py | grep enc8013
1     critical                                     enc8013, bay 9                        ov8004  active              the bios/hardware status is critical.  log into the ilo and view the integrated manag...
2     critical                                     enc8013, bay 9                        ov8004  locked  the ilo for the server hardware in bay 9 is re...  check the ilo system information - health summ...
324   critical                                     enc8013, bay 3                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
389   critical                                    enc8013, bay 11                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
436   critical                                     enc8013, bay 8                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
491   critical                                     enc8013, bay 7                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
499   critical                                     enc8013, bay 5                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
643   critical                                     enc8013, bay 2                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
716   critical                                     enc8013, bay 1                        ov8004  locked            unable to discover the server hardware.  verify your request. if credentials were speci...
717   critical                                     enc8013, bay 1                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
1197  critical                                     enc8013, bay 3                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
1208  critical                                     enc8013, bay 5                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
1266  critical                                     enc8013, bay 7                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
1329  critical                                     enc8013, bay 2                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
1362  critical                                    enc8013, bay 11                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
1365  critical                                     enc8013, bay 1                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
1502  critical                                     enc8013, bay 8                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
1685  critical                                     enc8013, bay 2                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
1723  critical                                     enc8013, bay 1                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...
1735  critical                                     enc8013, bay 3                        ov8004  active  remote insight/ integrated lights-out self tes...  to decode the error-code look into cpqsm2cntlr...

any help will be much appreciated.

A: FYI, aligning names sequentially is sorting but what you did using grep is filtering/searching. Both are different tasks.
For filtering (like you did with grep):
df = df[df['Resource Name'].str.contains('enc8013')]

Output:
    Status      Resource Name
1   critical    enc8013
2   critical    enc8013, bay 9

For sorting by resource name:
df['resource_name_only'] = df['Resource Name'].str.split(',').str[0]
df = df.sort_values(by=['resource_name_only'])

Output:
    Status      Resource Name       resource_name_only
0   critical    enc8005, bay 4      enc8005
1   critical    enc8013             enc8013
2   critical    enc8013, bay 9      enc8013

A: You should be able to do that with the following.
df["sort_column"] = df['Resource Name'].str.extract(r'(\S+)[,]|(\S+)', flags=0, expand=False).fillna(method='bfill', axis=1).iloc[:, 0]
df.sort_values('sort_column', inplace=True)

A: You can create two columns out of the 'Resource Name' using the extract() method with an regular expression and sort your values afterwards.
from io import StringIO
import pandas as pd

t = """ Status   Resource Name
0     critical   enc8005, bay 4
1     critical   enc8013, bay 9
2     critical   enc8013, bay 9
3     critical   enc8002
"""

df = pd.read_csv(StringIO(t), sep='\s\s+')

ans = df['Resource Name'].str.extract(r'(?P<a>\w+\d+)\,?\s*(?P<b>\w+\s+\d+)?') # this creates two columns 'a' and 'b'
df['a'] = ans['a']
df['b'] = ans['b']
df = df.sort_values(['a', 'b'])
>>> df
     Status   Resource Name        a       b
3  critical  enc8002         enc8002     NaN
0  critical  enc8005, bay 4  enc8005   bay 4
1  critical  enc8013, bay 9  enc8013   bay 9
2  critical  enc8013, bay 9  enc8013   bay 9


text:
Q: How to stop fscanf from copying into array when its at the end of the line? I have a file that has lines like
Bob, 2,3,13,4
Jim 3,4,15,3
...

and I'm trying to copy into my numbers array only the integers in each line, so that i I could do some math with them.
Problem is, I don't know before hand how many numbers there will be after the name of the person, but I know it will be less than 100. However, when I run my code, it copies 2,3,13,4 into my array and then assigns a bunch of random numbers into the other slots of the array. How do I get around this?
I want it to stop copying after it sees a carriage return, and I tried to do that by doing an if statement like if (fgetc=!'\r') but it doesn't work, nor does it work with '\n'. Can someone help me out of this problem?
Here's my code
#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *myFile;
myFile = fopen("bob.txt", "r");

//read file into array
int numberArray[100];
int i;

if (myFile == NULL)
{
printf("Error Reading File\n");
exit (0);
}

int k=0;
while(k==0){
if(fgetc(myFile)==',')
k=1;
} //brings pointer to the first number after the first comma
//still need a way to stop copying into array random numbers after the line is done
//so need it to stop after carriage return, but it doesn't work
//also need to start it again after for the next line

for (i = 0; i <100 ; i++)
{
fscanf(myFile, "%d,", &numberArray[i])
}

for (i = 0; i < 100 ; i++)
{
printf("Number is: %d\n\n", numberArray[i]);
}

fclose(myFile);

return 0;
}

A: fscanf will return the number of items scanned; in your situation, as soon as it returns 0, you know you are done with that line (because it couldn't scan an integer).

A: Wrong tool for the job trying to read text that has a special line format.
Although it is possible to do this with fscanf(), it is far easier to handle bad input with fgets().  Use sscanf() with "%n" (or strtol()) to parse each line.
It appears a comma is optional between elements given OP's 2 examples.
char name[40];
char buf[sizeof name + 100*22 + 2];
// read the entire line
if (fgets(buf, sizeof buf, myFile) == NULL) Handle_EOF();

int n;
char *p = buf;
// Get the name
if (sscanf(p, "%39[A-Za-z] %n", name, &n) != 1) Handle_NoName();
p += n;

// Get the integers
for (i=0; i<100; i++) {
  if (*p == ',') p++;
  if (sscanf(p, "%d %n", &numberArray[i], &n) != 1) break;
  p += n;
}

// Initialize remaining elements
for (; i<100; i++) {
  numberArray[i] = 0;
}

if (*p) Hanlde_ExtraTextAtEndOfLine();

// Use name and numberArray[] with i elements.

A: int numberArray[100];
int i, ch, n;

while(1){
    while((ch=fgetc(myFile))!=EOF && ch != ',')
        ;//skip name and ','
    if(ch == EOF)
        break;
    //check of the end of the line is not necessary if name do not begin with a digit.
    for (i = 0; i < 100 && 1==fscanf(myFile, "%d,", &numberArray[i]); i++)
        ;

    n = i;
    for (i = 0; i < n ; i++){
        printf("Number is: %d\n", numberArray[i]);
    }
}


text:
Q: Is CFBundleIdentifier Localizable? Can we localize CFBundleIdentifier , I am using CFBundleIdentifier as a key to store something in Plist , In case CFBundleIdentifier is localizable I would not be able to access the data stored in Plist, I have looked into apple doc, as per my understanding CFBundleIdentifier is not localizable, Please correct me If I am wrong

A: No, the bundle identifier is not localizable. It's the unique ID of your app. It must remain constant.

A: CFBundleIdentifier uniquely identifies the bundle. Each distinct app
     or bundle on the system must have a unique bundle ID. The system
     uses this string to identify your app in many ways. For example, the
     preferences system uses this string to identify the app for which a
     given preference applies; Launch Services uses the bundle identifier
     to locate an app capable of opening a particular file, using the
     first app it finds with the given identifier; in iOS, the bundle
     identifier is used in validating the app's signature.
The bundle ID string must be a uniform type identifier (UTI) that
     contains only alphanumeric (A-Z,a-z,0-9), hyphen (-), and period (.)
     characters. The string should also be in reverse-DNS format. For
     example, if your company's domain is Ajax.com and you create an app
     named Hello, you could assign the string com.Ajax.Hello as your
     app's bundle identifier.


text:
Q: Wordpress Multisite restict user access I have a Wordpress Network with 3 sites.
I want to know how can I restrict the user access in the subdomains.
Actually, members of the principal site can login on the subdomains.
Do you know if a tiny plugin or a function can restrict users of just one single site ?
I have tried this, but still not work, or I don't know how to use it...
add_action( 'template_redirect', function() {

if ( ! is_user_member_of_blog() )
    die( 'Please ask the network administrator to get access to this blog.' );
});

In wp-admin/network/site-users.php.
Can you help me ?
Thanks guys

A: I hope this plugin is best for you. see
https://wordpress.org/plugins/advanced-access-manager
You can also see the video tutorial for this plugin from this link.
https://www.youtube.com/results?search_query=Advanced+Access+Manager
I hope it will help you.


text:
Q: What is the behavior of procedure declaration without parameter type? While trying some code, I found that if we provide a parameter to a function or procedure without type, it will not give us a compile-time error.
Why is this happening and please give some explanation as I am not able to find such a code anywhere?
procedure declaration:
Procedure TestProc(var objTest);

If we remove the keyword var, then compile time error is presented as Type required.
Can anyone please explain this?

A: Untyped parameters are usually used when the actual type of the parameter is irrelevant. One example would be the standard "FillChar" procedure that fills a variable - ANY variable - with a specified byte value. Instead of needing several (actually an infinite number of) overloaded procedures to be able to fill an arbitrary variable with a value, an untyped parameter is used.
An untyped parameter (like any other parameter) can be "input" (data going INTO the procedure/function) by using the CONST prefix, "output" (data coming OUT of the the procedure/function) using the OUT prefix, or both (data being sent into the procedure, modified, and sent back out) by using the VAR prefix.
As you may notice, the FillChar procedure uses a VAR prefix, although an OUT would be more correct. However, the FillChar procedure was "created" at a time, when OUT prefixes didn't exist in the language (only CONST and VAR existed, and of the two, VAR was the only one that allowed data to be going back out of the procedure, so VAR was used).

A: Like Victoria said it is a untyped parameter
If you would like to create a procedure or a function that can handle different types of parameter, you should use overload. Everytime you call a overloaded function it depends on your Inpout what exclusive function oder procedure would be used.