text:
Q: Use wmd function of gensim for sentence clustering I have a list of sentences. I want to cluster my sentences on similarity using the WMD (word mover's distance). I am using a word2vec model from gensim to create embeddings for my words.
The clustering algorithms I know (nltk, sklearn) use number vectors as input so I need to give the sentences as an array (or list) of the embeddings of the words in them. I think I can use the nltk clustering methods with a custom distance function. I want to use the WMD as his custom function. But the WMD function of gensim uses a 2 lists of strings as input.
Is there a prebuild WMD function that uses the embeddings and not the strings as input? Or is there a clustering (kmeans or something else) that can handle lists of strings as input and can have the WMD as custom distance function?
Thanks

A: Clustering algorithms don't take strings (or lists-of-string-tokens) as input. Rather, you'll always have to preprocess your texts into some sort of numerical data, for use by a clustering algorithm.
But as the documentation for scikit-learn's clustering notes:

One important thing to note is that the algorithms implemented in this
module can take different kinds of matrix as input. All the methods
accept standard data matrices of shape [n_samples, n_features]. These
can be obtained from the classes in the sklearn.feature_extraction
module. For AffinityPropagation, SpectralClustering and DBSCAN one can
also input similarity matrices of shape [n_samples, n_samples]. These
can be obtained from the functions in the sklearn.metrics.pairwise
module.

To further clarify what it's saying: if the algorithm is taking input of shape [n_samples, n_features], then it's assuming each of your texts has already been reduced to a fixed-size vector (of n_features size). A calculation like like "Word Mover's Distance" doesn't inherently reduce a single text to a fixed-size vector – as you've noted, WMD only works on pairs of texts. So you'd not be able to directly use WMD to convert single texts, alone, into the n_features-sized vectors that these algorithms. (But also: see the 'final note' at bottom.)
On the other hand, if the algorithm is able to take input of shape [n_samples, n_samples], then it needs all possible pairwise similarities. That, you can pre-calculate using WMD, in a couple of loops over your texts (or using the scikit-learn utility function pairwise_distances()). And note, these scikit-learn algorithms need affinity='precomputed' specified, and expect similarity values, where the more-similar pairs return higher values, rather than distance values, where more-similar pairs return higher values. So you'd need to convert WMD distances to some sort of similarity-scale. (One simple way that may suffice is to negate the distance value.)
For example, if texts includes all your (tokenized) texts, and wv your gensim word-vectors:
import numpy as np

dist_matrix = np.zeros((len(texts), len(texts)))
for i in range(len(texts)):
    for j in range(len(texts)):
        if i == j:
            continue  # self-distance is 0.0
        if i > j:
            dist_matrix[i, j] = dist_matrix[j, i]  # re-use earlier calc
        dist_matrix[i, j] = wv.wmdistance(texts[i], texts[j])
# this negation simply makes largest dists into smallest (most-negative) sims
# you could also consider instead a calc that maps all dists to [-1.0, 1.0]
sim_matrix = -dist_matrix

That sim_matrix should work inside one of the scikit-learn algorithms that accepts the affinity='precomputed' option.
But beware: WMD is quite expensive to calculate (especially on longer texts), so depending on the size of your set of sentences, just precomputing all the pairwise distances may be very time-consuming.
A final note: you could also consider, like with the similarity-matrix, converting your individual texts into fixed-sized vectors using WMD calculations, but by converting each text into the vector of its distances (or similarities) to all other texts.
That is, essentially use the same pairwise-process above - but then pass the resulting matrix into one of the algorithms that take a [n_samples, n_features]-shaped input.
I'm unsure if this will work as well as an algorithm designed for such an input, but as long as you've spent the time calculating all pairwise distances (or similarities), it could be worth a try.


text:
Q: passing a pointer as a local into a function gcc 4.7.2 c89

Hello,
I have the following function:
void module_param_destroy(module_param_t *param)
{
    param = NULL;

    /* Stop the compiler from complaining */
    APR_UNUSED(param);
}

And I am calling it like this:
module_param_destroy(module->call_param);

Would the parameter param be set to NULL. As I am passing in a local copy, I don't think it is doing anything useful here.
Would it be better to do this:
void module_param_destroy(module_t *md)
{
    md->param = NULL;

    /* Stop the compiler from complaining */
    APR_UNUSED(md->param);
}

And calling it like this:
module_param_destroy(md);

The structures have globally allocated memory from malloc.
Many thanks for any suggestions,

A: If param points to memory obtained from malloc, then setting it to NULL is not enough to properly cleanup.
There are two common ways to use module_param_destroy:
void module_param_destroy(module_param_t *param)
{
    free(param);
}

or
void module_param_destroy(module_param_t **param)
{
    free(*param);
    *param = NULL;
}

The main difference is that with the second variant, param gets set to a testable value to indicate it has been cleaned up. With the first variant, you have to remember yourself that the pointer passed to module_param_destroy is unusable after the function has returned.
You call them respectively as
module_param_destroy(module->call_param);

and
module_param_destroy(&module->call_param);

A: Your second module_param_destroy looks good to me, but for completenes, this is working version of your first function:
void module_param_destroy(module_param_t **pparam)
{
    *pparam = NULL;
}

Edit: Yeah, as is explained in the other answer, that does not release any memory, so that is the last pointer to a malloced memory, you have to free it before setting it to NULL...

A: The first version won't change the pointer because you're assigning to a local copy of the pointer, instead, use a pointer to the pointer to assign:
void module_param_destroy(module_param_t **param)
{
    *param = NULL;
}

And call it like this:
module_param_destroy(&module->call_param);

redpajama_set_name: RedPajamaStackExchange


text:
Q: find and delete duplicates in multiple subdirectorys how can I expand on the following batch code so that everything in the Tim folder is checked against all folders in the Tom directory.
Beter said if Tim has a file named Mytext.txt in it how can I check all and not just the top directory fond starting with C:\Tom, it may be that in tom there is a another folder with an other folder in that yet again with Mytext.txt in it.
All the code below currently dose is check the specifide directory only i would also like to check through any subdirectorys?
for /r "C:\Tim" %%f in (*) do if exist "C:\Tom\%%~nxf" del /s /q "C:\Tim\%%~nxf"

A: You nearly got it, you only need a second FOR /R loop, to search in all subdirs of TOM
for /r "c:\tim" %%I in (*) do (
  echo searching for %%~nxI
  for /r "C:\tom" %%O in (%%~nxI) do (
    if exist %%O echo found in %%O
  )
)


text:
Q: ActiveRecord transaction not rolling back on failure I am trying to use an ActiveRecord::Base.transaction to ensure that a Customer, CustomerAccount and StockNotification all get created at once, or none gets created at all if one of them fails
Here is my transaction
stock_notification.rb:
  validates_presence_of :email

  def self.make parameters
    ActiveRecord::Base.transaction do
      shop_id = ProductVariant.find(parameters[:product_variant_id]).shop_id
      parameters[:customer_account_id] = CustomerAccount.find_or_make!(parameters[:email], shop_id).id
      @stock_notification = StockNotification.create(parameters) # reference A
    end
    @stock_notification
  end

You might need this as well
customer_account.rb:
  def self.find_or_make! email, shop_id
    customer = Customer.where(email: email).first_or_create!
    CustomerAccount.where(shop_id: shop_id, customer_id: customer.id).first_or_create!
  end

If I call StockNotification.make with a blank email, the create fails (reference A) and no stock notification is created, but the problem is that a Customer/CustomerAccount is still being created.
So the transaction is not doing it's job at all, or am I missing something?

A: Yep. Transaction will fail if an exception is raised. You should use not create, but create! that will do that in case of failure. See here.


text:
Q: SOQL Type conversion (SalesForce.com) The problem is that I need to compare two fields of different types in a SOQL query.
TextField is a Picklist (so really text) and IntField is a Number(2, 0).  Changing the types of these fields is not possible.
I would like to write SOQL like;
SELECT Id FROM SomeObject__c
WHERE Cast(TextField as Integer) > IntField

Obviously Cast(TextField as Integer) does NOT work.
Any advise on type conversion within SOQL.  The normal APEX functions (e.g. integer.valueof) don't seem to be of any help here.
Thanks

A: SOQL itself does not support casting but you can always lend a helping hand ;)
Create a Numeric formula field in SomeObject__c:
IF(ISNUMBER(TextField__c), VALUE(TextField__c), NULL)

or something similar depending on your definition of cast to int. Now you can use this field in a SOQL query.


text:
Q: Blazor Wasm Microsoft.JSInterop.JSException: Could not find 'blazorCulture.get' I have followed the documentation and implemented the localization for my Blazor Wasm as 100% as in the article. Microsoft suggests to invoke js at the application start as below.
builder.Services.AddLocalization();

var host = builder.Build();

CultureInfo culture;
var js = host.Services.GetRequiredService<IJSRuntime>();
var result = await js.InvokeAsync<string>("blazorCulture.get");

if (result != null)
{
    culture = new CultureInfo(result);
}
else
{
    culture = new CultureInfo("en-US");
    await js.InvokeVoidAsync("blazorCulture.set", "en-US");
}

CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;

await host.RunAsync();

This works fine but sometimes when I open the start page, it returns a Js error telling me that

blazor.webassembly.js:1 Microsoft.JSInterop.JSException: Could not find 'blazorCulture.get' ('getBlazorCulture' was undefined).
blazor.webassembly.js:1 Error: Could not find 'blazorCulture.get' ('blazorCulture.get' was undefined).

When I press contol+f5 to force reload cached data, error goes away. What could cause this problem and how can I fix it?
EDIT:  Below how my Index.html Body looks like, here I suspect that since cultureget.js cultureset.js are the last, other js files loading takes longer than Blazor start although it doesnt happen always. So since blazor already started and last js files are loaded after blazor start, this error occurs. Question is is there way to ensure all js files are loaded before Blazor started? Of course quicker fix could be here to move those js right after blazor.webassembly.js.
<script src="_framework/blazor.webassembly.js"></script>
<script src="_content/Radzen.Blazor/Radzen.Blazor.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- third party -->
<script src="https://unpkg.com/js-logger/src/logger.min.js"></script>

<!-- custom code -->
<script type="module" src="_content/logger.js"></script>
<script type="module" src="_content/eventHandlerUtils.js"></script>
<script src="_content/cultureget.js"></script>
<script src="_content/cultureset.js"></script>


text:
Q: How do I take the log of a whole matrix in stata? In Stata, how do I take the log of all elements in a matrix?  In matlab you just do log(Matrix).  Apparently things aren't so simple in Stata.
Thanks

A: You're right that it appears there's no simple way to do that in Stata's main language. But things are that simple in Mata, Stata's matrix programming language, which was introduced in version 9 of Stata in 2005 and behaves more like Matlab:
. mata
--------------------------------- mata (type end to exit) -----------------------------
: A=(1, 2 \ 3, 4)

: A
       1   2
    +---------+
  1 |  1   2  |
  2 |  3   4  |
    +---------+

: log(A)
                 1             2
    +-----------------------------+
  1 |            0   .6931471806  |
  2 |  1.098612289   1.386294361  |
    +-----------------------------+

A: This is easier than implied with matmap from SSC. Install using ssc inst matmap.
. matmap A A, map(ln(@))

Here @ is substituted by each matrix element installed. In the example A A instructs replacing an existing, while A B would create or replace another matrix.


text:
Q: ffmpeg output separate channel from an input with multiple channels i run this command to be able to stream a udp live stream to a http live stream that is playable using a mobile application that am building.
its just a stream with audio streams only.
ffmpeg -i udp://@localhost:1111 -map 0:a  http://localhost:8090/feed1.ffm
Input #0, mpegts, from 'udp://@localhost:1111':
  Duration: N/A, start: 54616.264622, bitrate: 768 kb/s
  Program 1
    Metadata:
  service_name    : Service 1
  service_provider: TLK
    Stream #0:0[0x101]: Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 96 kb/s
  Program 2
Metadata:
  service_name    : Service 2
  service_provider: TLK
Stream #0:1[0x111]: Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 96 kb/s
 Program 3
Metadata:
  service_name    : Service 3
  service_provider: TLK
Stream #0:2[0x121]: Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 96 kb/s
 Program 4
Metadata:
  service_name    : Service 4
  service_provider: TLK
Stream #0:3[0x131]: Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 96 kb/s
  Program 5
Metadata:
  service_name    : Service 5
  service_provider: TLK
Stream #0:4[0x141]: Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 96 kb/s
  Program 6
Metadata:
  service_name    : Service 6
  service_provider: TLK
Stream #0:5[0x151]: Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 96 kb/s
  Program 7
Metadata:
  service_name    : Service 7
  service_provider: TLK
Stream #0:6[0x161]: Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 96 kb/s
 Program 8
Metadata:
  service_name    : Service 1
  service_provider: TLK
Stream #0:7[0x171]: Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 96 kb/s

i get this output
Stream mapping:
  Stream #0:0 -> #0:0 (mp2 (native) -> mp2 (native))
  Stream #0:0 -> #0:1 (mp2 (native) -> mp2 (native))
Press [q] to stop, [?] for help
size=     100kB time=00:00:07.19 bitrate= 113.8kbits/s speed=3.01x
video:0kB audio:84kB subtitle:0kB other streams:0kB global headers:0kB  muxing overhead: 18.358242%

i really want a way i can be able to map every input stream to have an output stream that can be accessed separately from the other like maybe if i need the first stream maybe i will just
ffplay http://localhost:8090/feed1.ffm

and if i need the 7th stream i will just
ffplay http://localhost:8090/feed7.ffm

Please can someone help me crack this issue. FFmpeg dont have complex examples for my current situation.
this is my header information
ubuntu@ip-localhost:~$ \
ffmpeg -i udp://@localhost:4000 \
  -map 0:a:0     http://localhost:8090/feed1.ffm
  -map 0:a:1 http://localhost:8090/feed2.ffm
  -map 0:a:2 http://localhost:8090/feed3.ffm
  -map 0:a:3 http://localhost:8090/feed4.ffm
  -map 0:a:4 http://localhost:8090/feed5.ffm
  -map 0:a:5 http://localhost:8090/feed6.ffm
  -map 0:a:6 http://localhost:8090/feed7.ffm
  -map 0:a:7 http://localhost:8090/feed8.ffm

ffmpeg version 3.2.4-1~16.04.york0 Copyright (c) 2000-2017 the FFmpeg    developers built with gcc 5.4.1 (Ubuntu 5.4.1-5ubuntu2~16.04.york1) 20170210
  configuration: --prefix=/usr --extra-version='1~16.04.york0' -- toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --enable-gpl --disable-stripping --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libebur128 --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmp3lame --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libopencv --enable-libx264 --enable-shared
  libavutil      55. 34.101 / 55. 34.101
  libavcodec     57. 64.101 / 57. 64.101
  libavformat    57. 56.101 / 57. 56.101
  libavdevice    57.  1.100 / 57.  1.100
  libavfilter     6. 65.100 /  6. 65.100
  libavresample   3.  1.  0 /  3.  1.  0
  libswscale      4.  2.100 /  4.  2.100
  libswresample   2.  3.100 /  2.  3.100
  libpostproc    54.  1.100 / 54.  1.100
Input #0, mpegts, from 'udp://@localhost:1111':
  Duration: N/A, start: 60047.944622, bitrate: 768 kb/s
  Program 1
    Metadata:
  service_name    : Service 1
  service_provider: TKL
Stream #0:0[0x101]: Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 96 kb/s
 Program 2
Metadata:
  service_name    : Service 2
  service_provider: TKL
Stream #0:1[0x111]: Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 96 kb/s
 Program 3
Metadata:
  service_name    : Service 3
  service_provider: TKL
Stream #0:2[0x121]: Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 96 kb/s
Program 4
Metadata:
  service_name    : Service 4
  service_provider: TKL
Stream #0:3[0x131]: Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 96 kb/s
Program 5
Metadata:
  service_name    : Service 5
  service_provider: TKL
Stream #0:4[0x141]: Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 96 kb/s
Program 6
Metadata:
  service_name    : Service 6
  service_provider: TKL
Stream #0:5[0x151]: Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 96 kb/s
Program 7
Metadata:
  service_name    : Service 7
  service_provider: TKL
Stream #0:6[0x161]: Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 96 kb/s
Program 8
Metadata:
  service_name    : Service 8
  service_provider: TKL
Stream #0:7[0x171]: Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 96 kb/s
Output #0, ffm, to 'http://localhost:8090/feed1.ffm':
Metadata:
creation_time   : now
encoder         : Lavf57.56.101
Stream #0:0: Audio: mp2, 44100 Hz, mono, s16, 32 kb/s
Metadata:
  encoder         : Lavc57.64.101 mp2
Stream #0:1: Audio: mp2, 44100 Hz, stereo, s16, 64 kb/s
Metadata:
  encoder         : Lavc57.64.101 mp2
Output #1, ffm, to 'http://localhost:8090/feed2.ffm':
Metadata:
creation_time   : now
encoder         : Lavf57.56.101
Stream #1:0: Audio: mp2, 44100 Hz, stereo, s16, 64 kb/s
Metadata:
  encoder         : Lavc57.64.101 mp2
Output #2, ffm, to 'http://localhost:8090/feed3.ffm':
Metadata:
creation_time   : now
encoder         : Lavf57.56.101
Stream #2:0: Audio: mp2, 44100 Hz, stereo, s16, 64 kb/s
Metadata:
  encoder         : Lavc57.64.101 mp2
Output #3, ffm, to 'http://localhost:8090/feed4.ffm':
Metadata:
creation_time   : now
encoder         : Lavf57.56.101
Stream #3:0: Audio: mp2, 44100 Hz, stereo, s16, 64 kb/s
Metadata:
  encoder         : Lavc57.64.101 mp2
Output #4, ffm, to 'http://localhost:8090/feed5.ffm':
Metadata:
creation_time   : now
encoder         : Lavf57.56.101
Stream #4:0: Audio: mp2, 44100 Hz, stereo, s16, 64 kb/s
Metadata:
  encoder         : Lavc57.64.101 mp2
Output #5, ffm, to 'http://localhost:8090/feed6.ffm':
Metadata:
creation_time   : now
encoder         : Lavf57.56.101
Stream #5:0: Audio: mp2, 44100 Hz, stereo, s16, 64 kb/s
Metadata:
  encoder         : Lavc57.64.101 mp2
Output #6, ffm, to 'http://localhost:8090/feed7.ffm':
Metadata:
creation_time   : now
encoder         : Lavf57.56.101
Stream #6:0: Audio: mp2, 44100 Hz, stereo, s16, 64 kb/s
Metadata:
  encoder         : Lavc57.64.101 mp2
Output #7, ffm, to 'http://localhost:8090/feed8.ffm':
Metadata:
creation_time   : now
encoder         : Lavf57.56.101
Stream #7:0: Audio: mp2, 44100 Hz, stereo, s16, 64 kb/s
Metadata:
  encoder         : Lavc57.64.101 mp2
Stream mapping:
Stream #0:0 -> #0:0 (mp2 (native) -> mp2 (native))
Stream #0:0 -> #0:1 (mp2 (native) -> mp2 (native))
Stream #0:0 -> #1:0 (mp2 (native) -> mp2 (native))
Stream #0:0 -> #2:0 (mp2 (native) -> mp2 (native))
Stream #0:0 -> #3:0 (mp2 (native) -> mp2 (native))
Stream #0:0 -> #4:0 (mp2 (native) -> mp2 (native))
Stream #0:0 -> #5:0 (mp2 (native) -> mp2 (native))
Stream #0:0 -> #6:0 (mp2 (native) -> mp2 (native))
Stream #0:0 -> #7:0 (mp2 (native) -> mp2 (native))
Press [q] to stop, [?] for help

thats my full console.

A: You could do that by running 7 different instances of ffmpeg at the same time as parallel processes; if you're open to that.
Let each instance of ffmpeg demultiplex a single audio stream and output to the respective port.
Would go somewhat like this:
(ffmpeg -i udp://@localhost:1111 -map 0:a:0 http://localhost:8090/feed1.ffm )
 & (ffmpeg -i udp://@localhost:1111 -map 0:a:1 http://localhost:8090/feed2.ffm )
 & (ffmpeg -i udp://@localhost:1111 -map 0:a:2 http://localhost:8090/feed3.ffm )
 & and so on.
Wouldn't recommend it though, will eat up your CPU's capacity.

A: Basic syntax is ffmpeg -i input1 -i input2 {switches} output1 {switches} output2..., so
ffmpeg -i udp://@localhost:1111 -map 0:a:0 http://localhost:8090/feed1.ffm
                                -map 0:a:1 http://localhost:8090/feed2.ffm
                                -map 0:a:2 http://localhost:8090/feed3.ffm
                                ...


text:
Q: Saving node.js postgres query result inside a variable I am trying to save some user_ids from my database in an array so that I can check against that array in a route. The callback function logs the correct data but the value of the const stays undefined. Does anybody have any ideas on how to solve this problem?
I am using the node-postgres library to connect to the database.
This is my code:
database query function:
const getAll = (callback) => {
  const query = `SELECT user_id FROM users`;

  pool
    .query(query)
    .then(data => {
      callback(null,data.rows)
    })
    .catch(e => console.error(e.stack))
}

const with callback function:
const users = db.getAll(function(err,data) {
  if (err) {
    console.log(err);
  } else {
    const ids = data.map(x => x.user_id)
    console.log(ids);  // logs an array of ids
    return ids
  }
})

console.log(users) // returns undefined

Any help is very much appreciated.

A: What's happening in your console log is executing before your callback has completed. To get this to work as you expect you want to refactor to use async/await or promises.


text:
Q: Finding the point of intersection of $y=x^4$ and $x=y^2$. I need to find the point where $y=x^4$ and $x=y^2$ intersect. Since $x=y^2$ is not in $y$, I  need to square root both sides and get $\sqrt{x}$. Where I then set both of them equal to each other. $x^4=\sqrt{x}$.  I then  move $\sqrt{x}$
to the other side and get $x^4-\sqrt{x}=0$, but this is where I'm stuck. What I did is correct, right? and how would I find the point of intersection. I know one of them is $0$ since that is the origin of both functions.

A: Observe that the equations imply that $y=(y^2)^4=y^8$ or equivalently $y(y^7-1)=0$ so that $y=0$ or $y=1$. You can substitute to find $x$.

A: In addition to other answers, you may find complex answers:
$$y=x^2$$
Substitute $x=y^4$ in.
$$y=(y^4)^2=y^8$$
$$y^8-y=0$$
$$y(y^7-1)=0$$
We have two solutions here:
$$y=0$$
Or
$$y^7-1=0$$
$$y^7=1$$
For complex solutions:
$$y=e^{\frac{2n}7\pi i},n=0,1,2,3,4,5,6$$
Plugging this back into the first equation, we have:
$$x=0,y=0$$
$$x=e^{\frac{n}7\pi i},y=e^{\frac{2n}7\pi i},n=0,1,2,3,4,5,6$$

A: If you know that $x=y^2$ then just substitute x in the other equation. You get $y=y^8$:the solutions are $y=0$ and $y=1$. If $y=0$ you get $x=0$, if $y=1$ you get $x^2=1$ then $x=1$ or $x=-1$. The solutions are then the $(x,y)$ couples $(0,0),(1,1),(-1,1)$.

A: From where you left off:
$x^4-\sqrt x=0$
Now factor out a $\sqrt x$
$\sqrt x (x^{\frac 72}-1)=0$
Now you can set
$\sqrt x = 0 \implies x =0$
$x^{\frac 72}-1=0 \implies x=1$
Now that you have your $x$ coordinates, you can plus them in in either equation and find the $y$ coordinates.


text:
Q: How to create a dynamically bound panorama page with wide items using Caliburn Micro? Inspired by some great apps out there, I want to have a PanoramaItem in my Panorama, that is wider than the standard width of the PanoramaItem.
See the item with tiles in LinkedIn's app:

Normally this is achieved in xaml by adding a PanoramaItem with a predefined width:
<controls:PanoramaItem Width="555">

But, I would like to avoid hardcoding my UIs this way, as the application is Caliburn-Micro based, and the Panorama control is data-bound using handy Caliburn conventions. The view model behind it is a Conductor, and pages are injected into it. The Panorama control is bound to the Items property of the view model.
My problem is that if one of the items, or screens, is wider than the standard width of the panorama item, it gets clipped.
I tried solving it by specifying ItemTemplate:
<controls:Panorama.ItemTemplate>
    <DataTemplate>
        <ContentControl cal:View.Model="{Binding}"/>
    </DataTemplate>
</controls:Panorama.ItemTemplate>

but that did not change a thing.
How would one solve this problem?

A: Well, the question is that apparently you can not. I tried overriding OnViewAttached, finding the parent of my dynamically bound control (ContentControl), but I was not able to retrieve its parent ( the PanoramaItem I wanted to make wider).
So after much trial end error I settled on the following solution:
I define my panorama items explicitly in XAML:
<controls:PanoramaItem Header="item1">
    <ContentControl x:Name="Control1"/>
</controls:PanoramaItem>
<controls:PanoramaItem Header="Wide Item" Width="700" Orientation="Horizontal">
    <ContentControl x:Name="WideControl"/>
</controls:PanoramaItem>

They are also injected into the ViewModel and added to the collection of Items, inherited from Caliburn's Cunductor.
Then, I need to make sure that the ViewModel knows about the currently selected item, so the associated view can be activated by CaliburnMicro:
<controls:Panorama  Name="MainPanorama"
    cal:Message.Attach="[Event SelectionChanged] =
    [Action  MainPanorama_OnSelectionChanged($eventArgs)]"
    SelectedIndex="{Binding ActivePage, Mode=TwoWay}">

I also make sure that the ViewModel receives the SelectionChanged event, so it knows when to activate the currently visible item.
And finally the trick that makes it all work in ViewModel:
public void MainPanorama_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ActivateItem(Items[ActivePage]);
}


text:
Q: Decode LDAP-CRL and get FQDN I have a certificate with the following CRL:
URL=ldap:///CN=GOLF Root-CA,CN=VSCERT02,CN=CDP,CN=Public Key Services,CN=Services,CN=Configuration,DC=toplevel-domain,DC=de?certificateRevocationList?base?objectClass=cRLDistributionPoint (ldap:///CN=GOLF%20Root-CA,CN=VSCERT02,CN=CDP,CN=Public%20Key%20Services,CN=Services,CN=Configuration,DC=toplevel-domain,DC=de?certificateRevocationList?base?objectClass=cRLDistributionPoint

Because after migrating from VPN to a ZTNA network solution, we have problems with that CRL. Unfortunately I cant find out the FQDN that is on a DNS/network level asked to access it.
How do I get the FQDN from that CRL?
Best regards
Linus

A: This LDAP URL looks like it was generated by MS AD Certificate Services, pointing to a CRL that's stored in an Active Directory LDAP object.
It's deliberately missing the LDAP server FQDN, as Active Directory does not usually have a fixed FQDN for services (i.e. there's no "ldap.example.com" unless an admin manually creates one), instead AD clients are supposed to make DNS SRV queries to discover all available domain controllers (Windows does this automatically).
To find all DCs in a domain, make an SRV query for the _ldap._tcp subdomain:
host -t SRV _ldap._tcp.toplevel-domain.de

nslookup -q=SRV _ldap._tcp.toplevel-domain.de


text:
Q: validation error in jsf I have a probleme in SelectOneMenu in my accueil.jsf page
xhtml page:
<h:outputText value="Code type opération : " />
<h:selectOneMenu id="op" value="#{mainController.operation}">
    <f:selectItem itemLabel="Choisir Code Opération "
        itemValue="#{null}" noSelectionOption="true" />
    <f:selectItems value="#{mainController.listeTypeOperations}" />
    <f:converter converterId="TypopConverter" />
</h:selectOneMenu>

Converter class:
public class TypOpConverter implements Converter {
    @Override
    public Object getAsObject(FacesContext facesContext,
                              UIComponent component,
                              String value) {
        ClassPathXmlApplicationContext context =
            new ClassPathXmlApplicationContext("spring-web.xml");
        BanqueService banqueService =
            (BanqueService)context.getBean("banqueService");
        TypeOperation typop;
        if (value == null) {
            typop = null;
        } else {
            Long id = new Long(value);

            typop = banqueService.getTypeOperationParId(id);
            if (typop == null) {
                return null;
            }
        }
        return typop;
    }

    @Override
    public String getAsString(FacesContext facesContext,
                              UIComponent component,
                              Object value) {
        if (value == null) {
            return "";
        }
        if (value instanceof String) {
            return (String) value;
        }
        return String.valueOf(((TypeOperation) value).getId());
    }
}

My managed Bean and Controller
@ManagedBean(name="mainController")
@ViewScoped
public class MainController implements Serializable{

private TypeOperation operation;
// get and set

public List<TypeOperation>  getListeTypeOperations(){.....}

The converter run and i did some print to show the string and object but the selected value can't be stored into #{mainController.operation} i think
the error:
j_idt7:op: Validation Error: Value is not valid


text:
Q: ComboBox item not taking up horizontal space - WPF <DataGridTemplateColumn Header="Bl" MinWidth="80" x:Name="BlAssigned">
   <DataGridTemplateColumn.CellTemplate>
      <DataTemplate>
         <ComboBox DisplayMemberPath="SName"
                   SelectedItem="{Binding BModel, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                   SelectedIndex="0"
                   SelectedValuePath="GId"
                   SelectedValue="{Binding B.GId, Mode=TwoWay}"
                   HorizontalContentAlignment="Stretch"
                   MinWidth="{Binding ElementName=BlAssigned, Path=MinWidth}"
                   Style="{StaticResource SPanelComboBox}">
            <ComboBox.ItemsSource>
               <CompositeCollection>
                  <emodels:SModel SName="None" GId="-1"/>
                  <CollectionContainer Collection="{Binding DataContext.BListModels,
                                       Source={x:Reference SDataGrid}}"/>
               </CompositeCollection>
            </ComboBox.ItemsSource>
         </ComboBox>
      </DataTemplate>
   </DataGridTemplateColumn.CellTemplate>
   <DataGridTemplateColumn.CellEditingTemplate>
      <DataTemplate>
         <ComboBox SelectedItem="{Binding BModel, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                   HorizontalContentAlignment="Stretch"
                   Style="{StaticResource SPanelComboBox}">
            <ComboBox.ItemsSource>
               <CompositeCollection>
                  <emodels:SModel SName="None" GId="-1"/>
                  <CollectionContainer Collection="{Binding DataContext.BListModels,
                                       Source={x:Reference SDataGrid}}"/>
               </CompositeCollection>
            </ComboBox.ItemsSource>
         </ComboBox>
      </DataTemplate>
   </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

SPanelComboBox XAML is as follows:
<Style x:Key="SPanelComboBox" TargetType="{x:Type ComboBox}">
    <Setter Property="ItemContainerStyle">
        <Setter.Value>
            <Style TargetType="ComboBoxItem">
                <Setter Property="HorizontalAlignment" Value="Center"/>
                <Setter Property="VerticalAlignment" Value="Center"/>
                <Setter Property="HorizontalContentAlignment" Value="Center"/>
                <Setter Property="VerticalContentAlignment" Value="Center"/>
            </Style>
        </Setter.Value>
    </Setter>
</Style>

And what I'm seeing is as follows:

I have tried to fiddle with it and get it to work but no cigar.... I simply want it so that the combobox items take up all the horizontal space they can. I don't know if it's because it's a data template and it's using a composite collection or what...

A: You have set your items to be centered horizontally always. By changing it to stretch it will have the behavior you seek.
Your ItemContainerStyle needs to look as follows:
<Style x:Key="SPanelComboBox" TargetType="{x:Type ComboBox}">
    <Setter Property="ItemContainerStyle">
        <Setter.Value>
            <Style TargetType="ComboBoxItem">
                <Setter Property="HorizontalAlignment" Value="Stretch"/> <!-- This part is changed -->
                <Setter Property="VerticalAlignment" Value="Center"/>
                <Setter Property="HorizontalContentAlignment" Value="Center"/>
                <Setter Property="VerticalContentAlignment" Value="Center"/>
            </Style>
        </Setter.Value>
    </Setter>
</Style>


text:
Q: Trino count query for array I have a JSON value for a column which is array of objects.  Here, my requirement is to find the count of objects matching the filter
Row 1: Coumn 1
{
  "createdBy": 2,
   "teams": [
    {
     "companyId" : 1,
     "teamId": 1
     },
     {
     "companyId" : 1,
     "teamId": 2
     }
    ]
}

Row 2: Coumn 1
{
  "createdBy": 2,
   "teams": [
    {
     "companyId" : 1,
     "teamId": 3
     },
     {
     "companyId" : 1,
     "teamId": 4
     }
    ]
}

Here, companyId 1 presents in 4 places and i need the query to get the count.
Query tried,
select count(1) from a where any_match(
      split(
        trim(
          '[]'
          FROM
            json_query(
              a.teams,
              'lax $.companyId' WITH ARRAY WRAPPER
            )
        ),
        ',"'
      ),
      x -> trim(
        '"'
        FROM
          x
      ) = 2
    )

Here it returns 1 because of any_match. Not sure how to get the size.


text:
Q: Mocha Typescript test doesn't print Console.log I have setup my test using mocha, chai, typescript, in Node:
import chai = require('chai');
import chaiAsPromised = require('chai-as-promised');
import ReadLine = require('readline');
import FS = require('fs');

before((done) => {
    chai.should();
    chai.use(chaiAsPromised);
    done();
});

describe("Test", function() {
    this.timeout(20000);
    let testFile: string [] = [];

    before((done) => {
        let lineReader = ReadLine.createInterface({
            input: FS.createReadStream("MyFile.txt")
        });

        lineReader.on('line', function (line) {
            testFile.push(line);
        });
        done();
    });
    it("test", () => {
        for(let i=0;i<testFile.length;i++){
            let curLine = testFile[i];
            console.log(curLine);
        }
    }).timeout(30000);
});

Then I run my test like this:
C:\Repository\Folder>npm test

> Test@0.0.1 test C:\Repository\Folder
> mocha -r ts-node/register -R spec test/**/*.ts

  Test
    √ test

  1 passing (16ms)

So it does seem to pass, but it's not printing out to console, what am I doing wrong?

A: The problem lies in this piece of code:
lineReader.on('line', function (line) {
    testFile.push(line);
});
done();

Your ReadLine reader works asynchronously. You attach a listener, and before any line is read, done() is already called as it's the next entry in the Event Loop.
To fix it, wait for the reader to close:
import chai = require('chai');
import chaiAsPromised = require('chai-as-promised');
import ReadLine = require('readline');
import FS = require('fs');

before((done) => {
    chai.should();
    chai.use(chaiAsPromised);
    done();
});

describe("Test", function() {
    this.timeout(20000);
    let testFile: string [] = [];

    before((done) => {
        let lineReader = ReadLine.createInterface({
            input: FS.createReadStream("MyFile.txt")
        });

        lineReader.on('line', function (line) {
            testFile.push(line);
        });
        linereader.on('close', () => done()); // <=====
    });
    it("test", () => {
        for(let i=0;i<testFile.length;i++){
            let curLine = testFile[i];
            console.log(curLine);
        }
    }).timeout(30000);
});

A: You need to use done() after for loop:
it("test", (done) => {
    for(let i=0;i<testFile.length;i++){
        let curLine = testFile[i];
        console.log(curLine);
    }

  done();
}).timeout(30000);


text:
Q: Mapbox 3d model not rendered at globe view I'm following the Mapbox tutorial of adding a 3d model as follows:
https://docs.mapbox.com/mapbox-gl-js/example/add-3d-model/ with my own map style: mapbox://styles/zx238/cl9h8ijd200g014pa6y43ijsx
However I found that when the scene is zoomed out too far (that the map is going to Globe projection), the model cannot be rendered anymore. It isn't influenced by the maxzoom property of addlayer.
Any thoughts on how to solve it?


text:
Q: Cual es la mejor forma de iniciar un proyecto en python cuando estas aprendiendo Hola Comunidad de Stack Overflow, especialmente la comunidad Python.
Como dice mi pregunta, soy principiante en Python, aunque ya llevo un conocimiento basico del mismo, pero me gustaria seguir aprendiendo y estoy abierta a sugerencias, consejos. Tengo planes de hacer proyectos poniendo en practica lo aprendido.
Muchas gracias de antemano.


text:
Q: Qt Copy and Paste within QTableView not working I am designing a user interface with several functions. On the .ui I have a QTableView. After right click on the table view I open a dialog with the same QTableView so in this way is easier to visualize data.
After Trying to copy and paste some of the values say, from a cell to another or from a column to another column I have a weird behavior that I don't know how to solve. Below I try to copy ctrl+C the selected cell:

And paste it ctrl+V I obtain a weird behavior:

For some reasons I am copiyng the header "longitude" on the second row instead of the number 24. Additionally the number 200 is pushed below.
This code also allows to copy and paste from the QTableView to an Excel file, this functions works well but I decided to include it in the explanation so you know how I handle all the loops.
editdialog.h
private:
    Ui::editLeftTableDialog *ui;
    QSqlTableModel *mModel;
    QAction *mActionAppendRow;
    QAction *mActionDeleteRow;

protected:
    void keyPressEvent(QKeyEvent *event);

editdialog.cpp
void editLeftTableDialog::keyPressEvent(QKeyEvent *event)
{
    {
        QAbstractItemModel * modelRemoveAdd = ui->tableViewLeft->model();
        QItemSelectionModel *selectionModel = ui->tableViewLeft->selectionModel();
        QModelIndexList selectedRows = selectionModel->selectedRows();

        QAbstractItemModel * modelNew = ui->tableViewLeft->model();
        QItemSelectionModel *selectedIndexes = ui->tableViewLeft->selectionModel();
        QModelIndexList selectedInd = selectedIndexes->selectedIndexes();

        // Make sure one row is selected
        if(!selectedRows.isEmpty())
        {
            if(event->key() == Qt::Key_Insert)
                mModel->insertRows(selectedRows.at(0).row(),
                                   selectedRows.size());
            else if(event->key() == Qt::Key_Delete)
                mModel->removeRows(selectedRows.at(0).row(),
                                   selectedRows.size());
        }
        // Make sure one cell selected
        if(!selectedInd.isEmpty())
        {
            if(event->key() == Qt::Key_Delete)
                foreach(QModelIndex index, selectedInd)
                    mModel->setData(index, QString());
            else if(event->matches(QKeySequence::Copy))
            {
                QString text;
                QItemSelectionRange range = ui->tableViewLeft->selectionModel()->selection().first();
                for(auto i = range.top(); i <= range.bottom(); ++i)
                {
                    QStringList rowContents;
                    for(auto j = range.left(); j <= range.right(); ++j)
                        rowContents << mModel->index(i,j).data().toString();
                        text += rowContents.join("\t");
                        text += "\n";
                }
                QApplication::clipboard()->setText(text);
            }
            else if(event->matches(QKeySequence::Paste))
            {
                QString text = QApplication::clipboard()->text();
                QStringList rowContents = text.split("\n", QString::SkipEmptyParts);
                QModelIndex initIndex = ui->tableViewLeft->selectionModel()->selectedIndexes().at(0);
                auto initRow = initIndex.row();
                auto initCol = initIndex.column();
                for(auto i = 0; i < rowContents.size(); i++)
                {
                    QStringList columnContents = rowContents.at(i).split("\t");
                    for(auto j = 0; j < columnContents.size(); j++)
                    {
                        mModel->setData(mModel->index(initRow + i, initCol + j), columnContents.at(j));
                    }
                }
            }
        }
    }
    // Copy from QTableView to an Excel or CSV file happens here and works well
    QAbstractItemModel * model = ui->tableViewLeft->model();
    QItemSelectionModel *selection = ui->tableViewLeft->selectionModel();
    QModelIndexList indices = selection->selectedIndexes();
    if(indices.isEmpty())
        return;
    QMap<int, bool> selectedColumnsMap;
    Q_FOREACH (QModelIndex current, indices)
    {
        selectedColumnsMap[current.column()] = true;
    }
    QList<int> selectedColumns = selectedColumnsMap.uniqueKeys();
    int minCol = selectedColumns.first();
    // prepend headers for selected columns
    QString selectedText;
    Q_FOREACH (int column, selectedColumns)
    {
        selectedText += ui->tableViewLeft->model()->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
        if(column != selectedColumns.last())
            selectedText += QLatin1Char('\t');
    }
    selectedText += QLatin1Char('\n');
    qSort(indices);
    int lastRow = indices.first().row();
    int lastColumn = minCol;
    Q_FOREACH(QModelIndex current, indices)
    {
        if(current.row() != lastRow)
        {
            selectedText += QLatin1Char('\n');
            lastColumn = minCol;
            lastRow = current.row();
        }
        if(current.column() != lastColumn)
        {
            for(int i = 0; i < current.column() - lastColumn; ++i)
                selectedText += QLatin1Char('\t');
            lastColumn = current.column();
        }
        selectedText += ui->tableViewLeft->model()->data(current).toString();
    }
    selectedText += QLatin1Char('\n');
    QApplication::clipboard()->setText(selectedText);
}

A: A messy code always brings problems, so I'm not going to analyze it but I'm going to propose an appropriate method where we create a function for each task, and instead of using keyPressEvent you can use a QShorcut:
editlefttabledialog.h
#ifndef EDITLEFTTABLEDIALOG_H
#define EDITLEFTTABLEDIALOG_H

#include <QDialog>
class QSqlTableModel;

namespace Ui {
class EditLeftTableDialog;
}

class EditLeftTableDialog : public QDialog
{
    Q_OBJECT
public:
    explicit EditLeftTableDialog(QWidget *parent = nullptr);
    ~EditLeftTableDialog();
private slots:
    void copy();
    void paste();
private:
    Ui::EditLeftTableDialog *ui;
    QSqlTableModel *mModel;
};

#endif // EDITLEFTTABLEDIALOG_H

editlefttabledialog.cpp
#include "editlefttabledialog.h"
#include "ui_editlefttabledialog.h"

#include <QShortcut>
#include <QSqlTableModel>
#include <QClipboard>

EditLeftTableDialog::EditLeftTableDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::EditLeftTableDialog)
{
    ui->setupUi(this);
    mModel = new QSqlTableModel(this);
    mModel->setTable("test_table");
    mModel->select();
    ui->tableViewLeft->setModel(mModel);

    QShortcut *shortcut_copy = new QShortcut(QKeySequence::Copy, ui->tableViewLeft);
    connect(shortcut_copy, &QShortcut::activated, this, &EditLeftTableDialog::copy);

    QShortcut *shortcut_paste = new QShortcut(QKeySequence::Paste, ui->tableViewLeft);
    connect(shortcut_paste, &QShortcut::activated, this, &EditLeftTableDialog::paste);
}

EditLeftTableDialog::~EditLeftTableDialog()
{
    delete ui;
}

void EditLeftTableDialog::copy()
{
    QString text;
    QItemSelectionRange selection_range =  ui->tableViewLeft->selectionModel()->selection().first();
    for(int i=selection_range.top(); i <= selection_range.bottom(); i++){
        QStringList row_content;
        for(int j= selection_range.left(); j <= selection_range.right(); j++){
            row_content << mModel->index(i,j).data().toString();
        }
        text += row_content.join(QChar('\t')) + QChar('\n');
    }
    QApplication::clipboard()->setText(text);
}

void EditLeftTableDialog::paste()
{
    QModelIndex start = ui->tableViewLeft->selectionModel()->selectedIndexes().first();
    QString text = QApplication::clipboard()->text();
    int i=0, j=0;
    for(const QString & row_string:  text.split("\n", QString::SkipEmptyParts)){
        j=0;
        for(const QString & col:  row_string.split("\t", QString::SkipEmptyParts)){
            QModelIndex ix = mModel->index(start.row() + i , start.column()+ j);
            if(ix.isValid()){
                ui->tableViewLeft->model()->setData(ix, col);
                mModel->submit();
            }
            j++;
        }
        i++;
    }
}


text:
Q: HTML sup tag with absolute position renders incorrectly I'd like to place line numbers periodically to the left of a block of indented text. My idea was to have a  per line with padding to the left (see "poetry" class), then absolutely position a  element for the line number. However, I'm experiencing a strange rendering bug in Firefox. It seems as if the absolutely positioned  is placed at an incorrect height, but if I go into the developer panel and change something, the  suddenly gets placed correctly.
This is represented in the gif below. The first line, marked with 1 shows a block of regular, non-indented text for reference. The second line starts with a 2 that is initially incorrectly positioned. The second 2 that is not absolutely positioned is there for reference to show what I would expect the y offset to be. Going into the developer panel and changing the left attribute suddenly updates the absolutely positioned 2.
However, even the updated position still doesn't look quite right; it looks like it gets placed a little higher than the second 2.

Here is my example HTML file:

<!DOCTYPE html>

    <meta charset="utf-8">

        1 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

        2 2Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Any thoughts to why this is happening and how I can fix it?

A: Don't nest the sup in the poetry span.

        body {
            max-width: 900px;
            /* margin: 0 auto !important; */
            /* float: none !important; */
            line-height: 1.5em;
        }

        .poetry {
            position: relative;
            padding-left: 2em;
        }

        1 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

    2

        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

A: You could use the margin-right property for the sup:

<!DOCTYPE html>

    <meta charset="utf-8">

        1 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

        2Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

A: Why don't you use ordered lists and modify it according to your own preference?

    <!DOCTYPE html>

        <meta charset="utf-8" />

              Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
              eiusmod tempor incididunt ut labore et dolore magna aliqua.

              Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
              nisi ut aliquip ex ea commodo consequat.


text:
Q: Кастомизация плагина Wordpress Есть вот такой замечательный участок кода, который идет в плагине, как расширение для Visual Composer
add_shortcode( 'digital_portfolio_query', 'digital_portfolio_query_shortcode' );

if ( ! function_exists('digital_portfolio_query_shortcode') ) {

function digital_portfolio_query_shortcode($atts, $content = null) {
  extract( shortcode_atts( array(
    'uid'              => '',
    'posts_per_page'   => '',
    'extra_class'      => null,
    'enable_nav'       => 'false',
    'autoplay'         => 'false',
    'speed'            => '1000',
  'category'         => ''
  ), $atts ) );

  global $secretlab;

    $slick_params = array( 'class'      => $extra_class ? $extra_class : 'digital_portfolios_box',
           'enable_nav' => $enable_nav,
           'autoplay'   => $autoplay,
           'speed'      => $speed ? $speed : 5000,
           'dots'       => 'false',
           'arrows'     => 'true',
           'prevArrow'  => '
prev
',
           'nextArrow'  => '
next
',
           'sp_row'     => 1,
           'sp_show'    => 1,
           'sp_scroll'  => 1);
    $secretlab['slick'][] = $slick_params;

  $result = new WP_query('post_type=portfolio&category_name='.$category.'&posts_per_page='.$posts_per_page);

  $output = '';

  //Output posts

  if ( $result->posts ) :

    add_action('wp_footer', 'theseo_add_slick_carousel');

    // Main wrapper div

  $output .= '

';

  // Loop through posts
  foreach ( $result->posts as $post ) :

    // Post VARS
    $post_id          = $post->ID;

      $short_post = types_render_field("short-description", array("post_id" => $post_id, "output"=>"normal"));
      $photo = get_the_post_thumbnail( $post_id, 'large' );
      $link = get_permalink($post_id);
      // Portfolio post article start

      // Open details div
      $output .= '

            '.$photo.'

'.$post->post_title.'

'.$short_post.'

';

    // End foreach loop
    endforeach;

    $output .= '

';

  endif; // End has posts check

  // Set things back to normal
  $result = null;
  wp_reset_postdata();

  // Return output
  return $output;

}

}

Он позволяет настроить выборку постов из Post Type - Portfolio
Вся проблема в том, что когда он делает эту выборку, то не видит постов, потому что в параметрах указано category_name, а не taxonomy_name
$result = new WP_query('post_type=portfolio&category_name='.$category.'&posts_per_page='.$posts_per_page);
Как через functions.php решить эту проблему?

A: Перекройте шорткод в плагине своим. Поскольку файлы темы загружаются после плагинов, можно просто переопределить шорткод своей функцией.
Вставьте в function.php
add_shortcode( 'digital_portfolio_query', 'my_digital_portfolio_query_shortcode' );

function my_digital_portfolio_query_shortcode($atts, $content = null) {
  // здесь модифицированный код digital_portfolio_query_shortcode
}


text:
Q: Improving performance by avoiding python for cycle when using counts of numpy unique I have two numpy arrays, A with shape (N,3) and B with shape (N,) and I generate from the vector A the vector with unique entries, e.g.:
A = np.array([[1.,2.,3.],
              [4.,5.,6.],
              [1.,2.,3.],
              [7.,8.,9.]])

B = np.array([10.,33.,15.,17.])

AUnique, directInd, inverseInd, counts = np.unique(A,
                                             return_index = True,
                                             return_inverse = True,
                                             return_counts = True,
                                             axis = 0)

So that AUnique will be
array([[1., 2., 3.],
       [4., 5., 6.],
       [7., 8., 9.]])
Then I obtain the simil-vector B associated to AUnique, and for each non-unique row in A I sum the associated values of B in this vector, that is:
BNew = B[directInd]

# here BNew is [10., 33.,17]

for Id in np.asarray(counts>1).nonzero()[0]:
  BNew[Id] = np.sum(B[inverseInd == Id])

# here BNew is [25., 33.,17]

The problem is that the for cycle gets extremely slow for large N vectors (millions or tens of millions rows), and I was wondering if there is a way to avoid cycling and/or to make the code much faster.
Thanks in advance!

A: I think you can do what you want with np.bincount
BNew = np.bincount(inverseInd, weights = B)
BNew

Out[]: array([25., 33., 17.])


text:
Q: Apache POI: Word get picture dimensions I am trying to determine the actual size of embedded images in MS Word documents using
        HWPFDocument docB = new HWPFDocument(fileInputStream);
        PicturesTable picB = docB.getPicturesTable();
        List picturesB = picB.getAllPictures();
        for (Object o : picturesB) {
            Picture pic = (Picture) o;
            int height = pic.getHeight();
            int width = pic.getWidht();
        }

This works fine for some images but for others getHeight() and getWidth() will only return -1 as stated in the documentation.
So is there any other way to get the actual size of these pictures in the document?

A: Instead of getHeight() and getWidth() you may resort to getDxaGoal(), resp. getDyaGoal(). These represent the original size of the image prior to scaling / cropping in twips.
You can then multiply this with getVerticalScalingFactor() / 1000.0 resp. getHorizontalScalingFactor() / 1000.0 to get the final (rendered) size. Division by 1000.0 is necessary because those scaling factors are given per mille.


text:
Q: Maven seems to be pulling in jars that have test scope I have a war module that is being built and is including a few shrinkwrap jars that it's not supposed to. Namely:
WEB-INF/lib/shrinkwrap-api-1.0.0.jar
WEB-INF/lib/shrinkwrap-descriptors-api-base-2.0.0-alpha-2.jar
WEB-INF/lib/shrinkwrap-descriptors-spi-2.0.0-alpha-2.jar
WEB-INF/lib/shrinkwrap-resolver-api-1.0.0-beta-6.jar
WEB-INF/lib/shrinkwrap-spi-1.0.0.jar

These dependencies are all listed in our poms as test-scoped so they shouldn't be in our packaged war. More info below but my question is: why are these here. There's obviously something I'm missing - what is it/where can I look to find it?
When I show my effective pom, I see the following dependencies (omitting a bunch of stuff here):
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
...
  <dependencyManagement>
    <dependencies>
    ...
      <dependency>
        <groupId>org.jboss.shrinkwrap</groupId>
        <artifactId>shrinkwrap-extension-descriptors</artifactId>
        <version>1.0.0-beta-6</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>org.jboss.shrinkwrap</groupId>
        <artifactId>shrinkwrap-api</artifactId>
        <version>1.0.0</version>
      </dependency>
      <dependency>
        <groupId>org.jboss.shrinkwrap</groupId>
        <artifactId>shrinkwrap-spi</artifactId>
        <version>1.0.0</version>
        <scope>runtime</scope>
      </dependency>
      <dependency>
        <groupId>org.jboss.shrinkwrap</groupId>
        <artifactId>shrinkwrap-impl-base</artifactId>
        <version>1.0.0</version>
        <scope>runtime</scope>
      </dependency>
      <dependency>
        <groupId>org.jboss.shrinkwrap.resolver</groupId>
        <artifactId>shrinkwrap-resolver-api</artifactId>
        <version>1.0.0-beta-6</version>
      </dependency>
      <dependency>
        <groupId>org.jboss.shrinkwrap.resolver</groupId>
        <artifactId>shrinkwrap-resolver-api-maven</artifactId>
        <version>1.0.0-beta-6</version>
      </dependency>
      <dependency>
        <groupId>org.jboss.shrinkwrap.resolver</groupId>
        <artifactId>shrinkwrap-resolver-impl-maven</artifactId>
        <version>1.0.0-beta-6</version>
        <scope>runtime</scope>
      </dependency>
      <dependency>
        <groupId>org.jboss.shrinkwrap.descriptors</groupId>
        <artifactId>shrinkwrap-descriptors-api-base</artifactId>
        <version>2.0.0-alpha-2</version>
      </dependency>
      <dependency>
        <groupId>org.jboss.shrinkwrap.descriptors</groupId>
        <artifactId>shrinkwrap-descriptors-api-javaee</artifactId>
        <version>2.0.0-alpha-2</version>
      </dependency>
      <dependency>
        <groupId>org.jboss.shrinkwrap.descriptors</groupId>
        <artifactId>shrinkwrap-descriptors-api-jboss</artifactId>
        <version>2.0.0-alpha-2</version>
      </dependency>
      <dependency>
        <groupId>org.jboss.shrinkwrap.descriptors</groupId>
        <artifactId>shrinkwrap-descriptors-gen</artifactId>
        <version>2.0.0-alpha-2</version>
        <scope>provided</scope>
      </dependency>
      <dependency>
        <groupId>org.jboss.shrinkwrap.descriptors</groupId>
        <artifactId>shrinkwrap-descriptors-impl-base</artifactId>
        <version>2.0.0-alpha-2</version>
        <scope>runtime</scope>
      </dependency>
      <dependency>
        <groupId>org.jboss.shrinkwrap.descriptors</groupId>
        <artifactId>shrinkwrap-descriptors-impl-javaee</artifactId>
        <version>2.0.0-alpha-2</version>
        <scope>runtime</scope>
      </dependency>
      <dependency>
        <groupId>org.jboss.shrinkwrap.descriptors</groupId>
        <artifactId>shrinkwrap-descriptors-impl-jboss</artifactId>
        <version>2.0.0-alpha-2</version>
        <scope>runtime</scope>
      </dependency>
      <dependency>
        <groupId>org.jboss.shrinkwrap.descriptors</groupId>
        <artifactId>shrinkwrap-descriptors-spi</artifactId>
        <version>2.0.0-alpha-2</version>
        <scope>runtime</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
  <dependencies>
    ...
    <dependency>
      <groupId>org.jboss.shrinkwrap.resolver</groupId>
      <artifactId>shrinkwrap-resolver-api-maven</artifactId>
      <version>1.0.0-beta-6</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.jboss.shrinkwrap.resolver</groupId>
      <artifactId>shrinkwrap-resolver-impl-maven</artifactId>
      <version>1.0.0-beta-6</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.jboss.shrinkwrap</groupId>
      <artifactId>shrinkwrap-impl-base</artifactId>
      <version>1.0.0</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  ...
</project>

When I print the dependency tree, I get the output below (only showing nodes that have the jars in question in them. I do see that some of these jars are listed as "runtime" and "runtime (scope managed from test)" but I'm not sure if that is related or how they got switched/included as runtime since in most of the cases, the dependency those belong to are test-scope:
[INFO] --- maven-dependency-plugin:2.1:tree (default-cli) @ name_removed ---
...
[INFO] +- org.jboss.arquillian.extension:arquillian-seam2:jar:1.0.0.Alpha2:test
[INFO] |  \- org.jboss.shrinkwrap:shrinkwrap-extension-descriptors:jar:1.0.0-beta-6:test (version managed from 1.0.0-beta-5)
[INFO] +- org.jboss.arquillian.protocol:arquillian-protocol-servlet:jar:1.0.0.Final:test
[INFO] |  +- org.jboss.arquillian.container:arquillian-container-spi:jar:1.0.0.Final:test
[INFO] |  |  +- org.jboss.arquillian.config:arquillian-config-api:jar:1.0.0.Final:test
[INFO] |  |  \- org.jboss.arquillian.config:arquillian-config-impl-base:jar:1.0.0.Final:test
[INFO] |  +- org.jboss.arquillian.container:arquillian-container-test-api:jar:1.0.0.Final:test
[INFO] |  \- org.jboss.shrinkwrap.descriptors:shrinkwrap-descriptors-spi:jar:2.0.0-alpha-2:runtime
[INFO] |     \- org.jboss.shrinkwrap.descriptors:shrinkwrap-descriptors-api-base:jar:2.0.0-alpha-2:runtime (version managed from 1.2.0-alpha-1)

[INFO] +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-api-maven:jar:1.0.0-beta-6:test (scope not updated to runtime)
[INFO] +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-impl-maven:jar:1.0.0-beta-6:test (scope not updated to runtime)
[INFO] |  +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-api:jar:1.0.0-beta-6:test
[INFO] |  +- org.sonatype.aether:aether-api:jar:1.8:test
[INFO] |  +- org.sonatype.aether:aether-util:jar:1.8:test
[INFO] |  +- org.sonatype.aether:aether-connector-wagon:jar:1.8:test
[INFO] |  |  +- org.sonatype.aether:aether-spi:jar:1.8:test
[INFO] |  |  \- org.codehaus.plexus:plexus-container-default:jar:1.5.5:test
[INFO] |  |     +- org.codehaus.plexus:plexus-classworlds:jar:2.2.2:test
[INFO] |  |     +- org.apache.xbean:xbean-reflect:jar:3.4:test
[INFO] |  |     |  \- commons-logging:commons-logging-api:jar:1.1:test
[INFO] |  |     \- com.google.collections:google-collections:jar:1.0:test
[INFO] |  +- org.apache.maven:maven-aether-provider:jar:3.0.1:test
[INFO] |  |  +- org.apache.maven:maven-model:jar:3.0.1:test
[INFO] |  |  +- org.apache.maven:maven-model-builder:jar:3.0.1:test
[INFO] |  |  +- org.apache.maven:maven-repository-metadata:jar:3.0.1:test
[INFO] |  |  +- org.sonatype.aether:aether-impl:jar:1.8:test
[INFO] |  |  +- org.codehaus.plexus:plexus-component-annotations:jar:1.5.5:test
[INFO] |  |  \- org.codehaus.plexus:plexus-utils:jar:2.0.4:test
[INFO] |  +- org.apache.maven:maven-settings-builder:jar:3.0.1:test
[INFO] |  |  +- org.codehaus.plexus:plexus-interpolation:jar:1.14:test
[INFO] |  |  +- org.apache.maven:maven-settings:jar:3.0.1:test
[INFO] |  |  \- org.sonatype.plexus:plexus-sec-dispatcher:jar:1.3:test
[INFO] |  |     \- org.sonatype.plexus:plexus-cipher:jar:1.4:test
[INFO] |  +- org.apache.maven.wagon:wagon-provider-api:jar:1.0-beta-7:test
[INFO] |  +- org.apache.maven.wagon:wagon-file:jar:1.0-beta-7:test
[INFO] |  \- org.apache.maven.wagon:wagon-http-lightweight:jar:1.0-beta-7:test
[INFO] |     \- org.apache.maven.wagon:wagon-http-shared:jar:1.0-beta-7:test
[INFO] \- org.jboss.shrinkwrap:shrinkwrap-impl-base:jar:1.0.0:test (scope not updated to runtime)
[INFO]    \- org.jboss.shrinkwrap:shrinkwrap-spi:jar:1.0.0:runtime (scope managed from test)
[INFO]       \- org.jboss.shrinkwrap:shrinkwrap-api:jar:1.0.0:runtime

A: It looks like this was a problem with a BOM used by Arquillian:
https://issues.jboss.org/browse/ARQ-889
We've updated to the fix version and all is well.

A: The 5 shrinkwrap jars you don't want are all dependencies of your test-scoped dependencies. But in the dependencyManagement section, shrinkwrap-spi, shrinkwrap-descriptors-spi, and shrinkwrap-resolver-impl-maven are listed as runtime scope.  My guess is that these runtime declarations override the test scope on the transitive dependencies.  And the runtime scope is inherited by dependencies of these dependencies.
So shrinkwrap-spi and shrinkwrap-descriptors-spi are included because their runtime declarations in dependencyManagement overrides the test-scope transitively inherited from your explicit test-scope dependencies.  Because these two dependencies are now runtime-scoped, they cause shrinkwrap-api and shrinkwrap-descriptors-api-base to become runtime as well.  I think shrinkwrap-resolver-api also gets runtime-scope transitively from shrinkwrap-resolver-impl-maven (it's runtime in dependencyManagement), which itself not included because of the explicit test-scope.
However, this is all mostly a guess, backed up by testing different scopes with some shrinkwrap dependencies in an empty project and seeing what got resolved.
If there isn't a reason you need shrinkwrap-spi, shrinkwrap-descriptors-spi, and shrinkwrap-resolver-impl-maven to be runtime-scoped in dependencyManagement, I'd remove the scope bits and try packaging again.  If you do need those to be runtime-scoped for some reason, you might have to set your five jars to explicit test scope in your dependencies block.

Edit:
Here's a simple project to demonstrate:
pom.xml
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>my.group</groupId>
    <artifactId>my-artifact</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.0.6.RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>3.0.6.RELEASE</version>
                <scope>runtime</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

(The spring-beans artifact depends on spring-core.)
Then I run mvn clean package and get the following output:
[INFO] Building war: /home/matts/test/target/my-artifact-0.0.1-SNAPSHOT.war
[DEBUG] adding directory META-INF/
[DEBUG] adding entry META-INF/MANIFEST.MF
[DEBUG] adding directory WEB-INF/
[DEBUG] adding directory WEB-INF/classes/
[DEBUG] adding directory WEB-INF/lib/
[DEBUG] adding entry WEB-INF/classes/Test.class
[DEBUG] adding entry WEB-INF/lib/spring-core-3.0.6.RELEASE.jar
[DEBUG] adding entry WEB-INF/lib/spring-asm-3.0.6.RELEASE.jar
[DEBUG] adding entry WEB-INF/lib/commons-logging-1.1.1.jar
[DEBUG] adding entry WEB-INF/web.xml

But if I remove the dependencyManagement section from the POM, and create the war again, I get the following output:
[INFO] Building war: /home/matts/test/target/my-artifact-0.0.1-SNAPSHOT.war
[DEBUG] adding directory META-INF/
[DEBUG] adding entry META-INF/MANIFEST.MF
[DEBUG] adding directory WEB-INF/
[DEBUG] adding directory WEB-INF/classes/
[DEBUG] adding entry WEB-INF/classes/Test.class
[DEBUG] adding entry WEB-INF/web.xml

Even though spring-beans was test scope, because I set spring-core to runtime scope in the dependencyManagement section, it was still included in the war.

A: Your dependency tree report shows runtime scope for some of those jars, so they are included into the war accordingly, i.e. to be available at runtime. Effective pom also shows default scope for some jars, hence the inclusion. All in all, you have to trace down the origin of your dependencies. Check dependencies and dependency management section in your poms, as well as all parent poms.
To make it easier to investigate, I'd create a test war project with some of those dependencies declared, so you can incrementally add and remove pieces of pom and see how does it affect the end result.


text:
Q: Unwanted Blank screen showing on app start up android jetpack compose - android studio chipmunk.-How to remove it? I just created an empty project and run it on device. On the app start up it shows a default blank screen on start up(app launch) before the first activity. I went through many answers and didn't find an exact answer or the root cause from where it is showing up. Many answers told to add
<item name="android:windowDisablePreview">true</item>

in themes.xml. Even after adding I still see the blank screen appearing.
Also in some other answer they told about new splash screen api, but I didn't feel it much customizable for doing server calls and other operations in splash screens. Also its available in below 12 versions.
What is right solution to handle this unwanted glitches during app startup?
Your help is highly appreciated.
<resources>

    <style name="Theme.Owl" parent="@style/Theme.Material.DayNight.NoActionBar">
        <item name="android:colorPrimary">#ff00ff</item>
        <item name="android:colorAccent">#ff00ff</item>
        <item name="android:statusBarColor">@color/immersive_sys_ui</item>
        <item name="android:navigationBarColor">@color/nav_bar</item>
        <item name="android:windowDisablePreview">true</item>
    </style>

    <style name="Theme.Material.DayNight.NoActionBar" parent="@android:style/Theme.Material.Light.NoActionBar" />

</resources>


text:
Q: Unknown wrong behavior in PHP IF statement I'm writing a code to upload a file in PHP. But there is an unknown and strange problem in it's IF statement. It does operations in both true and false condition! Look at the code below please:
if (is_uploaded_file($_FILES['catalogue']['tmp_name']))
{
    $ext = find_extension('catalogue');
    $ext_array = array('pdf');

    if (!in_array($ext,$ext_array))
    {
        // echo something for error message.
    }
    else
    {
        echo ' Step1 ';
        @unlink ('../../catalogues/'.$id.'.pdf');
        if(@move_uploaded_file($_FILES['catalogue']['tmp_name'],"../../catalogues/".$id.'.pdf'))
        {
            @chmod ("../../catalogues/".$id.".pdf",'644');
            $sql = "UPDATE tbl_products SET catalogue = ? WHERE id = ?";
            $q = $db->prepare($sql);
            $query = $q->execute(array($id.'.pdf',$id));
        }
    }
}
else
{
    echo ' Step2 ';
    @unlink ('../../catalogues/'.$id.'.pdf');
    $sql = "UPDATE tbl_products SET catalogue = ? WHERE id = ?";
    $q = $db->prepare($sql);
    $query = $q->execute(array('',$id));
}

And the result is Step1 Step2 !
So when the file is uploaded successfully, new file will be uploaded and set to database, and then it will removed in step2 and its field in database will be empty. :(
This is very strange for me. Please help me.
Note: find_extension() function and $id are defined before these lines of code.

A: Try this:
if (is_uploaded_file($_FILES['catalogue']['tmp_name']))
{
    $ext = find_extension('catalogue');
    $ext_array = array('pdf');

    if (!in_array($ext,$ext_array))
    {
        // echo something for error message.
    }
    else
    {
        echo ' Step1 ';
        @unlink ('../../catalogues/'.$id.'.pdf');
        if(@move_uploaded_file($_FILES['catalogue']['tmp_name'],"../../catalogues/".$id.'.pdf'))
        {
            @chmod ("../../catalogues/".$id.".pdf",'644');
            $sql = "UPDATE tbl_products SET catalogue = ? WHERE id = ?";
            $q = $db->prepare($sql);
            $query = $q->execute(array($id.'.pdf',$id));
     }
}
else
{
    echo ' Step2 ';
    @unlink ('../../catalogues/'.$id.'.pdf');
    $sql = "UPDATE tbl_products SET catalogue = ? WHERE id = ?";
    $q = $db->prepare($sql);
    $query = $q->execute(array('',$id));
}

    }


text:
Q: Wordpress stripping HTML code from some captions in jQuery Lightbox The issue is occurring on this site: http://jessicasilvermangallery.com/exhibitions/dashiell-manley/
I am including captions with  and  tags for all the images.
When they are clicked the open in a light box and some honor the HTML and other strip the HTML.
It is very strange and i cannot figure out why it occurs to some images an not others.
It seems it may have to do with portrait vs. landscape orientation.
Can anyone offer any insight as to why this is happening and how I could fix it?


text:
Q: Single NPN Emitter-Follower in amplifier's input stage I am currently examining the "El Cheapo" amplifier and despite its apparent obviousness I'm still not sure about NPN/PNP interchangeability.
Is there any particular reason why there is PNP in the emitter follower and not NPN? I mean, can I just recalculate biasing and use NPN if I find it more suitable without any drawbacks?
Also, there are examples of single transistor input stage in some books, e.g. Douglas Self's that use PNP and I feel a bit unsecure because of it :P
I realise that AB amp requires NPN/PNP combination but other than that, I find NPN simplier to use, perhaps more intuitive - hence my doubts.

A: If the output from Q1 is biased close to ground then a PNP will drive effectively close to ground better than an NPN would.  As drawn, the PNP has an effective impedance of 150k(R2) divided by the Hfe of Q1 which is likely to be 100 or so.  If we turn the input circuit upside down and use R3 as a pull-down then the output impedance is 33k.  Keeping the output of Q1 biased to a low voltage improves supply rejection and minimises the voltage on C2, which could reduce cost and possibly microphonic effects.  So a PNP is preferable but an NPN could be used.


text:
Q: select/poll really busted with C#? I've read lots of articles, blogs, which said that under C#, you shouldn't consider the select/poll because it is just not "the best way to do things" (too "Unix way")
Yes the select/pool behavior is pretty strange... But finally, why should I bother with callbacks and other delegates over a "simple" while()

A: Simple does not mean optimal, performance optimization and clean code is opposite things.
If you want to write high performance server, with effective CPU utilization and memory consumption, you must bother about this.


text:
Q: session not created: This version of ChromeDriver only supports Chrome version 76 receiving the following error session not created: This version of ChromeDriver only supports Chrome version 76
Using latest webdrivermanager version 3.6.2
Seems like it is not finding the latest version of chrome on my machine Version 75.0.3770.142 (Official Build) (64-bit).
code is below, failure is occuring on return statement
WebDriver getDriver() {
        WebDriverManager.chromedriver().setup();

        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("disable-infobars");

        return new ChromeDriver(chromeOptions);
    }

org.openqa.selenium.SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 76
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'QJ07301311', ip: '10.58.72.245', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_25'
Driver info: driver.version: Driver
remote stacktrace: Backtrace:
    Ordinal0 [0x00FF7C93+1473683]
    Ordinal0 [0x00F7ADB1+961969]
    Ordinal0 [0x00F042E3+475875]
    Ordinal0 [0x00E9F365+62309]
    Ordinal0 [0x00E9BC77+48247]
    Ordinal0 [0x00EB9149+168265]
    Ordinal0 [0x00EB8D1D+167197]
    Ordinal0 [0x00EB742B+160811]
    Ordinal0 [0x00EA0AE6+68326]
    Ordinal0 [0x00EA1BF0+72688]
    Ordinal0 [0x00EA1B89+72585]
    Ordinal0 [0x00F94B77+1067895]
    GetHandleVerifier [0x01096875+506677]
    GetHandleVerifier [0x01096610+506064]
    GetHandleVerifier [0x0109D1B8+533624]
    GetHandleVerifier [0x0109704A+508682]
    Ordinal0 [0x00F8C266+1032806]
    Ordinal0 [0x00F8C0DF+1032415]
    Ordinal0 [0x00F96A8B+1075851]
    Ordinal0 [0x00F96BF3+1076211]
    Ordinal0 [0x00F95BA5+1072037]
    BaseThreadInitThunk [0x757F343D+18]
    RtlInitializeExceptionChain [0x77DA9802+99]
    RtlInitializeExceptionChain [0x77DA97D5+54]


text:
Q: Recyclerview - CardView with Headers for cards and different cards I have a CardView in my app and I don't to know how I can add TextView and headers for some cards like on the picture. I marked it with the arrows. Also I want to know how I can add different cards in a RecyclerView and not just the same cards.

Thanks for your answers and sorry for my bad english :)


text:
Q: Integrating salesforce org with php Site -> As I am new to salesforce and currently i did the integration of salesforce org with php site using Enterprise WSDL and what are records are inserted in php site will come in salesforce and what are records are inserted in salesforce will get in php site.
-> And in client php site there are several user among them i mention above about one user.
-> But now client requirements is that if other user create their profile in php site and his having salesforce org then by entering their api, username, password and token in php site should get automatically integrate with their salesforce org and it behaves the same like i mention above scenario.
Is it possible? if its possible then can you plz share it any example how to do this?Any Steps
Any help will be grateful
Thanks for you any feedback....


text:
Q: Linux - Feed a command input with a file and delete the file while the command is running Could some one tell me a single line command to feed my cmd input from a file and delete the same file while the command is still running?
EDIT: By single line command I meant, performing this entire action in one command. This behavior has got to do with executing processes and commands simultaneously. Hence I would want to see what happens when the command line input is fed with a file and in the same command using the concept of simultaneous process execution (Read foreground and background) delete the file while the cmd input is still reading it
I tried
$ cat dummy_file.txt | rm -i
rm: missing operand
Try rm --help for more information

Obviously the cmd I tried is wrong. Maybe I need to run one of the command as background jobs but I'm not sure

A: Not sure what you're actually trying to achieve; but your example command can be "fixed" in a way by using xargs:
echo "dummy_file.txt" > dummy_file.txt
cat dummy_file.txt | xargs rm -i

Btw. if you're worried about deleting a file while it is being used: while a file is in use (ie. kept open) by a process, its contents will not be deleted from disk. Even if you delete the file with rm, only the file name in the directory structure is removed; the disk space for the actual contents is only freed when the file is no longer kept open by any process.


text:
Q: Oracle Sequence mismatch I have five different schemas that use the same sequence in the code from the Main Schema.
The code is schema by schema and never overlaps.
By the end of all the schema programs, the sequence should never overlap as it runs individually.
But it is getting duplicate for one schema:
select min(FUTURE_RETAIL_ID), max(FUTURE_RETAIL_ID) From dmfuser_ame.MIG_RPM_FUTURE_RETAIL;
282 950 868
288 967 925

select min(FUTURE_RETAIL_ID), max(FUTURE_RETAIL_ID) From dmfuser_bts.MIG_RPM_FUTURE_RETAIL;
288 967 926
289 773 677

This duplicated:
select min(FUTURE_RETAIL_ID), max(FUTURE_RETAIL_ID) From dmfuser_mot.MIG_RPM_FUTURE_RETAIL;
**289 773 678
311 239 253**

select min(FUTURE_RETAIL_ID), max(FUTURE_RETAIL_ID) From dmfuser_riv.MIG_RPM_FUTURE_RETAIL;
289 773 678
290 761 583

select min(FUTURE_RETAIL_ID), max(FUTURE_RETAIL_ID) From dmfuser_wes.MIG_RPM_FUTURE_RETAIL;
290 761 584
290 826 644

What could be the possible error with this?
Edit:
Here is how the table is populated for each schema: Insert via a PLSQL code
 select /*+ PARALLEL(il,8) */
        rpm_future_retail_seq.NEXTVAL       future_retail_id,
        im.item,
        im.dept,
        im.class,
        im.subclass,
        rzl.loc_type                        zone_node_type,
        rzl.location,
        TRUNC(im.create_datetime)           action_date,
        il.selling_unit_retail              selling_retail,
        loc.currency_code                   selling_retail_currency,
        il.selling_uom,
        il.multi_units,
        il.multi_unit_retail,
        loc.currency_code                   multi_unit_retail_currency,
        il.multi_selling_uom,
        il.selling_unit_retail              clear_retail,
        loc.currency_code                   clear_retail_currency,
        il.selling_uom                      clear_uom,
        il.selling_unit_retail              simple_promo_retail,
        loc.currency_code                   simple_promo_retail_currency,
        il.selling_uom                      simple_promo_uom,
        0                                   on_simple_promo_ind,
        0                                   on_complex_promo_ind,
        0                                   lock_version,
        im.item_parent,
        im.diff_1                           diff_id,
        rzl.zone_id,
        'IL'                                max_hier_level,
        'IL'                                cur_hier_level
   from mig_item_master im,
        (select wh as location,
                currency_code,
                0 as type
           from mig_wh) loc,
        mig_item_loc il,
        rpm_zone_location rzl --required to use RMS migrated table as its the only one with the WH
  where il.item      = im.item
    and il.loc       = loc.location
    and rzl.location = loc.location
    and item_level   = tran_level
    and rzl.loc_type = 2
    and sellable_ind = 'Y'
    and il.loc_type  = 'W'
    and not exists (select 1
                      from mig_rpm_future_retail rfr
                     where rfr.item     = il.item
                       and rfr.location = il.loc);


text:
Q: Rails 3 mail not working, however devise mail does works I have a rails 3.2.3 application that works fine and delivers devise's created mail messages as, registration confirmation and password forget mail messages to set a new password.
However I have a different places that I want to deliver mail notifications.
This is my Notifiermodel.
# encoding: utf-8
class Notifier < ActionMailer::Base
  default from: "no-reply@domain.com"
  default to: "admin@domain.com"

  def new_post_submitted(post)
    @post = post
    mail(subject: "Anúncio enviado: #{@post.title}")
  end

  def new_message(message)
    @message = message
    mail(subject: "Mensagem de contato: #{@message.subject}")
  end

end

and the controller calls:
def create
  @message = Message.new(params[:message])

  if @message.valid?
    Notifier.new_message(@message).deliver
    redirect_to(root_path, :notice => "Obrigado. Sua Mensagem enviada com sucesso")
  else
    flash.now.alert = "Por favor preencha todos os campos."
    render :new
  end
end

The log output says it was delivered:
Started POST "/contato" for 187.57.102.168 at 2012-08-31 11:28:51 +0900
Processing by ContactController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"TVdmDYCA4x3JVi+9pMcpY7OSU/P1lE9enLiFJlK9W1M=", "message"=>{"name"=>"kleber", "email"=>"test@gmail.com", "subject"=>"teste", "body"=>"hello there"}, "commit"=>"Enviar"}
  Rendered notifier/new_message.html.erb (0.1ms)

Sent mail to admin@domain.com (152ms)
Redirected to http://www.domain.com/
Completed 302 Found in 158ms (ActiveRecord: 0.0ms)

And the following configuration on my config/production.rbfile.
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
  :address => "localhost",
  :port => 25,
  :domain => "domain.com",
  :authentication => :login,
  :user_name  => "admin@domain.com",
  :password  => "mypassword",
  :enable_starttls_auto => false
}

Any clue on what is happening here?

A: Here are the settings that work in my production.rb file.
ActionMailer::Base.smtp_settings = {
   :address => 'mail.domain.com',
   :port => 587,
   :domain => 'domain.com',
   :authentication => :login,
   :user_name => 'postmaster@domain.com',
   :password => 'password'
  }

Not sure you have to specify delivery_method?
ActionMailer::Base.delivery_method = :smtp

I don't have that in my config and everything works properly.
In the rails API http://api.rubyonrails.org/ ActionMailer section there is an option to set a delivery error.
raise_delivery_errors - Whether or not errors should be raised if the email fails to be delivered.

You could try that to further troubleshoot the problem.

A: First, make sure you haven't turned off deliveries somewhere else in the environment file:
# the default is true anyway, so if you don't see it anywhere in
# the file, you should be okay
config.action_mailer.perform_deliveries = true

I would next try changing the delivery method to either :sendmail or :file. If you have sendmail installed and configured on your system (at least a development system), then you should receive the e-mails you send. I was surprised at one point to discover that sendmail worked out of the box on OS X. I'm not sure if you'd find the same on CentOS.
If you don't have sendmail or don't want to configure it, use the :file delivery method to dump the e-mails to a file on the filesystem.
At this point, if the e-mails don't deliver via sendmail or file, you know there's a problem further up the stack. If they do deliver, then the problem is your SMTP configuration. Try using a known working SMTP server (such as your Gmail account). If that works, then you know it's a problem with the SMTP server running on localhost and not with ActionMailer.


text:
Q: Is there someone who is using Google Service Account and Google Play Api? I need to use  Google Play api service. I try to get the authorization token using "Service Account" authentication method but I always get "400 Bad request" as response and the json: "error": "invalid_grant".
Is there someone that is using this authorization method with Google Play Api as scope and C# as programming language?
I searched everywhere for implementing it by existing libraries or by myself following this guide (https://developers.google.com/accounts/docs/OAuth2ServiceAccount#libraries) and other users suggestions but it doesn't work
Here is the code
// HEADER
Dictionary<string, string> JWTHeaderObject = new Dictionary<string, string>();
JWTHeaderObject.Add("alg", "RS256");
JWTHeaderObject.Add("typ", "JWT");
string JWTHeader = JsonConvert.SerializeObject(JWTHeaderObject);

Dictionary<string, object> JWTContentObject = new Dictionary<string, object>();
JWTContentObject.Add("iss", ".....@developer.gserviceaccount.com");
JWTContentObject.Add("scope", "https:\\/\\/www.googleapis.com\\/auth\\/androidpublisher");
JWTContentObject.Add("aud", "https:\\/\\/accounts.google.com\\/o\\/oauth2\\/token");
DateTime now = DateTime.UtcNow;
// set to maximum expiration time: 1h from now
DateTime expireDate = now.Add(new TimeSpan(0, 55, 0));
// to UNIX timestamp
JWTContentObject.Add("exp", (int)Utils.ConverDateTimeToUnixTimestamp(expireDate));
JWTContentObject.Add("iat", (int)Utils.ConverDateTimeToUnixTimestamp(now));
string JWTContent = JsonConvert.SerializeObject(JWTContentObject);

string JWTBase64Header = Utils.Base64Encode(Encoding.UTF8.GetBytes(JWTHeader));
string JWTBase64Content = Utils.Base64Encode(Encoding.UTF8.GetBytes(JWTContent));

// create JWT signature with encoded header and content and the private key obtained from API console
byte[] JWTSignatureInput = Encoding.UTF8.GetBytes(JWTBase64Header + "." + JWTBase64Content);

X509Certificate2 cert = (X509Certificate2)Utils.GetCertificate(StoreName.My, StoreLocation.CurrentUser, "thumbprint");

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;

// without these two lines I get invalid algorithm on SHA256
// (see: http://blogs.msdn.com/b/shawnfa/archive/2008/08/25/using-rsacryptoserviceprovider-for-rsa-sha256-signatures.aspx)
RSACryptoServiceProvider rsaClear = new RSACryptoServiceProvider();
// Export RSA parameters from 'rsa' and import them into 'rsaClear'
rsaClear.ImportParameters(rsa.ExportParameters(true));

string JWTBase64Signature = Utils.Base64Encode(rsaClear.SignData(JWTSignatureInput, CryptoConfig.CreateFromName("SHA256")));

 return JWTBase64Header + "." + JWTBase64Content + "." + JWTBase64Signature;

and the method specified here to encode to base 64: Utils.Base64Encode()
Then I call command below and I get {"error":"invalid_grant"}:
curl -d 'grant_type=assertion&assertion_type=http%3a%2f%2foauth.net%2fgrant_type%2fjwt%2f1.0%2fbearer&assertion=eyJhbGciOiJSUzI1N---.eyJpc3MiOiIxIiwic2---.KJ-DtTtdp5oIKPWVNqN---' https://accounts.google.com/o/oauth2/token

(encoded JWT reduced for brevity)


text:
Q: converting python output in spread sheet format here, i need to get two values from user and save that output in a spread sheet format.
the mcve of my code is :
while True:
    a=input('enter the string')
    print(a)
    b=input('enter the number')
    print(b)

the sample output is:
enter the stringa
a
enter the number2
2
enter the stringb
b
enter the number4
4
enter the string

I need to assign each integer value to the respective string in an spreadsheet

A: Try using openpyxl to save the outputs in excel sheet
from openpyxl import Workbook

book = Workbook()
sheet = book.active
a = input('enter the string')
print(a)
b = input('enter the number')
print(b)
sheet['A1'] = a
sheet['B1'] = b

book.save("test.xlsx")

A: Using xlsxwriter it's pretty simple:
import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()

rowCount = 0
while <some condition>:
    a=input('Enter the string: ')
    print(a)
    b=input('Enter the number: ')
    print(b)

    worksheet.write_row(rowCount, 0, (a,b))
    rowCount += 1

workbook.close()

This will create a workbook with a worksheet, then it will ask the user to enter the string and the associated value. It will then store the values in the workbook, increasing the row at each loop.


text:
Q: How to search in multiple indexes with same field I want to search in two indexes. I need to extract one field's value from the first index and search for it in the second index, and then I need the count. It's hard to write it down, sorry.
Soo.. something like.:
index=firstIndex someUniqueField=something | rex commonField=someregex |

And the other search:
index=secIndex someOtherUniqueField=something2 | commonfield= theRegexedStuff

And I want this to be in one query and get the count of it. Is it even possible?
One thing to add:
The second search will usually have less results, since it is an error case. So actually I want a number as a result, where the first search's unique field is there AND for the common field there is a result in the second search AND in the second search the unique field is there. Ugh, cannot really explain it better.
Thanks in advance.

A: If the first search returns fewer than 10,000 results then you can use a subsearch.  The first search goes into the subsearch because subsearches run first.
index=secIndex someOtherUniqueField=something2
  [ search index=firstIndex someUniqueField=something
  | rex commonField=someregex
  | fields commonField
  | format ]


text:
Q: GtkTreeView select row editing a column I'm working with c, glade and gtk2
One column is editable. Editing one value, scrolling to no visible row and select (clicking) on one of this rows, the cursor go to one third row. The row selected is near edited value on the same row displayed position that clicked.
I think the problem is when GtkTreeView receives focus (end edition) set the display on the first value and after this is selected the row.
Is possible to force the selected/focused row to be displayed on GtkTreeView focus-in signal.

A: Try setting the selection mode to GTK_SELECTION_BROWSE, then one row should always be selected


text: Q: How to make dropdown component behave like select element in HTML I have created a dropdown component with div tags. It works fine except for one scenario. when I use that dropdown inside a popover with scroll then the dropdown visibility is hidden. But when I use select with the same setup, the options are showing up.


text:
Q: Nginx - Execute php files in different docker container I am using an automated docker-image for php-fpm and nginx (https://hub.docker.com/r/tobi312/rpi-php/ and https://hub.docker.com/r/tobi312/rpi-nginx/ ) running on a raspberry pi with with libreelec on top.
The php container successfully starts with port 9000 open by running the following command:
docker run --name php -v /var/www/restTools:/var/www/html -d 3dd6ff8c0d58

After that I started the nginx-container like this:
docker run --name nginx -d -p 8081:80 --link php:9000 -v /var/www/restTools:/var/www/html 0d90cc6eb00f

Both containers are running but the nginx is not executing php files, it's just offering them for download.
After a while I tried to commit the connection details to the php-container trough a default.conf by adding -v /var/www/.config/nginx:/etc/nginx/conf.d:ro to the command.
Excerpt from default.conf:
root /var/www/html;

location / {
    root /var/www/html;
    index index.html index.htm index.php;
}

location ~ \.php$ {
    root /var/www/html;
    fastcgi_pass php:9000;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_index index.php;
    fastcgi_param REMOTE_ADDR $http_x_real_ip;
    fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
    include fastcgi_params;
    if (!-f $document_root$fastcgi_script_name) {
        return 404;
    }
}

What am I missing?

A: You are trying to use the (deprecated!!) "link" option of docker, this is not a problem itself, but you have to respect the syntax
--link <name or id>:alias

so, you have to substitute your
--link php:9000

with the correct
--link php

you do not need an alias because you named the fpm container the same as you referred it in default.conf.
The other important thing is to mount the php files folder in the fpm container but you already did this right.


text:
Q: Restrict that only one element has a specific attribute with DTD This is the xml file that I need to validate with DTD:
<branch state="hessen">
    <city>Marburg</city>
    <headquarter/>
    <staff manager="yes">Egon</staff>
    <staff manager="no">Erna</staff>
    <staff manager="no">Claudia</staff>
</branch>

The problem is that only one manager is allowed per branch. The task is now to restrict that with a DTD file but I dont now how to do that.
This is what I've got so far:
 <!ELEMENT insurance (branch*)>
            <!ELEMENT branch (city,zentrale?,(staff,staff+))>
            <!ATTLIST branch
                    state ID #REQUIRED
            >
            <!ELEMENT city (#PCDATA)>
            <!ELEMENT headquarter EMPTY>
            <!ELEMENT staff (#PCDATA)>
            <!ATTLIST staff
                    manager (yes|no) #REQUIRED
            >

How can I now implement that restriction?

A: You won't be able to enforce that rule with a DTD.
I agree with Michael Kay's suggestion of using XML Schema 1.1.
You can use xs:assert to enforce the rule.
Example...
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
  xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <xs:element name="branch">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="city"/>
        <xs:element ref="headquarter"/>
        <xs:element maxOccurs="unbounded" ref="staff"/>
      </xs:sequence>
      <xs:attribute name="state" use="required" type="xs:NCName"/>
      <xs:assert test="count(staff[@manager='yes']) le 1"/>
    </xs:complexType>
  </xs:element>

  <xs:element name="city" type="xs:NCName"/>

  <xs:element name="headquarter">
    <xs:complexType/>
  </xs:element>

  <xs:element name="staff">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:NCName">
          <xs:attribute name="manager" use="required" type="xs:NCName"/>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

You could also use Schematron or XSLT to do the rule checking.


text:
Q: Interpretation of ordiellipise NMDS I am using metaNMDS to explore a multivariate dataset I am working with. I have constrained the dataset by a factor of interest that has 6 levels. The ordination is being run on a matrix of bray-curtis dissimilarities, is not being autotransformed, has 2 dimensions (or axises), and is set to run for a max of 300 iterations. The ellipses are based on 95% confidence and use the SE.
The NMDS is solved in about 10-15 iterations and has an okay to poor stress value (15-18).  When I plot the data with ordiellipse to visualize which levels might be different I am struck by how little of the data  are actually within the confidence ellipses. Can someone explain this? Is this just an artifact of the ordination is not providing a good fit to the data; not capturing the variation inherent in the dataset in 2-dimensions?
Any thoughts?  My reputation isn't high enough to post a picture of the plot but I can send one out if I get a few bumps.

A: You are plotting a confidence ellipse for the mean (group centroid), which tells you something about the sampling distribution of the mean (centroid) you might see if you repeated your data collection a lot of times. In other words you are looking at the uncertainty in the estimate of the population mean (centroid) given the sample of data you collected.
The other type of confidence ellipse is based on the standard deviation. That is a measure of spread of the data (not the mean) and hence if you switch to that type your confidence ellipses should have less surprising coverage.
Note that this is the same misunderstanding the people have when discussing the standard deviation and the standard error of the mean in descriptive statistics.