text:
Q: Why does PyAudio only play half my audio? I am trying to use PyAudio (installed via "sudo apt-get install python-pyaudio") to play a recorded sample multiple times.
I've tried:
num_repeats = 6
out.write(numpy.hstack(numpy.tile(d, num_repeats)))

but this plays the audio sample only 3 times.  As far as I can hear, it always plays exactly half the data I give it. (e.g if I simply use out.write(d) I only hear half the recorded sample)
There is an obvious work around (num_repeats *= 2) but I would like to understand why this is necessary!
Full code to reproduce problem
import pyaudio
import numpy

p = pyaudio.PyAudio()
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 80000
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)
frame = stream.read(CHUNK)
stream.stop_stream()
stream.close()
d = numpy.fromstring(frame, 'int16')

out = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, output=True)
num_repeats = 6
out.write(numpy.hstack(numpy.tile(d, num_repeats)))
out.close()

p.terminate()

It behaves the same (i.e. only 3 repeats) whether I use 2 channels or 1.

A: Convert the numpy array to a binary before handing it over. You can use .tobinary() or .tostring()
In case you have matched the datatype this should work.

A: In my case I solved the same issue adding pause before closing the stream. Not sure if it is expected behaviour, but audio on my embedded device was played in async way after writing to the stream. So I had to wait before closing the stream. The setup I finished with was like this:
import time
...

#calculate clip duration in seconds
duration = float(clip_data_length) / rate / bytes_per_sample / channels

startTime = time.time()
stream.write(wav_data)
endTime = time.time()

if ((endTime - startTime) < duration):
    time.sleep(duration - (endTime - startTime))

time.sleep(0.1)
stream.close()


text:
Q: $M\to S^{-1}M$ is an isomorphism iff for all $W$ with $S^{-1}W=0$ all maps $W\to M$ are zero Let $R$ be a commutative ring, let $S\subset R$ be multiplicative and let $M$ be an $R$-module. Is the following true?

The localization map $M\to S^{-1}M$ is an isomorphism if and only if for all $R$-modules $W$ such that $S^{-1}W=0$, all maps $W\to M$ are zero.

The direction $\Rightarrow$ is easy: it follows from functoriality of localization. But I can't prove or disprove $\Leftarrow$. Note that the condition $S^{-1}W=0$ implies that all elements of $W$ are annihilated by some element of $S$.

A: I think $\mathbb{Z} \rightarrow \mathbb{Q}$ (so $R = M = \mathbb{Z}$ and $S = \mathbb{Z} \setminus \{0\}$) provides a counterexample.  Given an abelian group $W$, then $S^{-1} W = 0$ iff $W$ is torsion, i.e., every element has finite order.  Since $0$ is only element of $\mathbb{Z}$ of finite order, given a homomorphism $W \to \mathbb{Z}$, then every element must map to $0$.  Thus the hypothesis on the righthand side is satisfied, but the localization map $\mathbb{Z} \to \mathbb{Q}$ is not an isomorphism.
However, one can show the localization map is injective given the hypothesis on the righthand side.  Letting $\varphi: M \to S^{-1} M$ be the localization map, take $W = \ker(\varphi)$.  Given $m \in \ker(\varphi)$, then $\frac{ms}{s} = \frac{0}{s}$, so there exists $t \in S$ such that
$$
0 = t(ms^2 - 0\cdot s) = s^2 t m \, .
$$
Thus $S^{-1}W = 0$.  By the hypothesis, then the inclusion map $\ker(\varphi) \hookrightarrow M$ must be the zero map, so $\ker(\varphi) = 0$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show that the vector space $F((-\infty, 0)\cup (0, \infty))$ can be written as a direct sum in two different ways. Prove that the vector space $F((-\infty, 0)\cup (0, \infty))$ can be written as a direct sum in two different ways using these pairs of subspaces:
(a) even functions and odd functions
(b) functions $f :(-\infty, 0)\cup (0, \infty)$ such that $f(x) = 0$ for all $x < 0$ and
functions g : $g :(-\infty, 0)\cup (0, \infty)$ such that $g(x) = 0$ for all $x > 0$.
For this question, why the direct sum of even and odd functions does not include 0 in vector? And why $f(x) = 0$, $g(x) = 0$ is nessessary in (b)?
The question can be understood in graph, but can someone give me hints about how to write a formal proof? Thx.

A: For (a):
Observe that any function $h \in F(\Bbb{R} \setminus\{0\})=V$ can be written as
$$h(x)=\underbrace{\frac{h(x)+h(-x)}{2}}_{\in E}+\underbrace{\frac{h(x)-h(-x)}{2}}_{\in D},$$
where $E$ is the subspace of even functions and $D$ is the subspace of odd functions. Observe that for a direct sum we want two things: $V=E+D$ and $E \cap D=\{\mathbf{0}\}$ (only the zero function should be in both). By above we have demonstrated the first condition. The second condition is easy to verify as only the zero function is both even and odd.
For (b).
For any function $h \in F(\Bbb{R} \setminus\{0\})=V$, let us define
$$f(x)=\begin{cases}h(x), & \text{ if } x >0\\ 0, & \text{ if } x < 0\end{cases} \qquad
g(x)=\begin{cases}0, & \text{ if } x >0\\ h(x), & \text{ if } x < 0\end{cases}.$$
Now $h$ can be written as
$$h(x)=\underbrace{f(x)}_{\in R}+\underbrace{g(x)}_{\in L},$$
where $R$ is the subspace of all functions which are zero for $x<0$ and $L$ is the subspace of all the functions which are $0$ for $x>0$.
The reason we want to have $L$ and $R$ to have functions which disappear on a certain interval is to make sure when functions are added then they won't interfere with each other (once again this is to ensure that both the properties $V=R+L$ and $R \cap L=\{\mathbf{0}\}$ associated with the direct sum can be achieved).


text:
Q: SSL certs with AWS SSM Parameter Store I am trying to pass in SSL certificate to AWS SSM parameter store
the SSL certificate is password protected as well
my question is how do i retrieve this as a certificate file inside the containers in ECS? I do know how to use SSM parameter store to store secret environment variables BUT how do i use it to create a secret file to a location on containers? We have a string and a file here, how does SSM manage files?
Thanks

A: I'm not aware of a way to create a file from SSM, but I expect your ENTRYPOINT in the Docker container could handle this logic
Task Definition Snippet
{
  "containerDefinitions": [{
    "secrets": [{
      "name": "MY_SSM_CERT_FILE",
      "valueFrom": "arn:aws:secretsmanager:region:aws_account_id:secret:MY_SSM_CERT_FILE"
    },
    {
      "name": "MY_SSM_CERT_FILE_LOCATION",
      "valueFrom": "arn:aws:secretsmanager:region:aws_account_id:secret:MY_SSM_CERT_FILE_LOCATION"
    }]
  }]
}

entrypoint.sh
echo "$MY_SSM_CERT_FILE" >> $MY_SSM_CERT_FILE_LOCATION
// Run rest of the logic for application

Dockerfile
FROM ubuntu:16.04

COPY ./entrypoint.sh .entrypoint.sh

ENTRYPOINT ["./entrypoint.sh"]

A: Why don't you use AWS Secret Manager which can complement AWS SSM? I think secrets manager supports secrets file:
$ aws secretsmanager create-secret --name TestSecret --secret-string file://secret.txt       # The Secrets Manager command takes the --secret-string parameter from the contents of the file

see this link for further information:
https://docs.aws.amazon.com/secretsmanager/latest/userguide/best-practices.html
The link below shows how you can integrate Secrets manager with SSM
https://docs.aws.amazon.com/systems-manager/latest/userguide/integration-ps-secretsmanager.html
Hope this helps


text:
Q: Is it okay to add comments to old posts on Stack Overflow? I am daily visitor of Stack Overflow and I wonder if it is okay if I add comments on old posts. Say approximately 1 year old post?. I am not sure about it.

A: What are you concerned about? What sort of comments do you have in mind?
The question's asker will get notified of the new comment, but they may no longer be active on the site and might not actually see your comment or respond to it. But even then, there's nothing really wrong with posting a comment in the first place.


text:
Q: PHP Adodb many sleeping connections Currently struggeling with a strange problem:
while using adodb as connection layer for php, it leaves many sleeping and unneeded connections behind. wait_timeout is set to 20 but there are still plenty (~100) of sleeping connections due to high load on the system. MySQL Version: 5.5.24-0ubuntu0.12.04.1
Is there a known bug regarding adodb5 and sleeping connections? I'm not using persistent connections! Connection establishment:
$conn = &ADONewConnection($DBTYPE);
$conn->Connect($DBHOST, $DBUSER, $DBPASSWORD, $DBNAME)

Would really appreciate any hints/suggestions how to reduce sleeping connection count.

A: Okay finally found the problem:
vhost document root was on an nfs mount (remote). this mount had some IO issues which provoked apache to "idle" connections until the nfs mount is ready again.

A: If the snippet is the only thing you do for connecting/disconnecting. Then you most likely just have to close down the connection when you no longer need it.
At most of my php-files I have that use connections this way I have something like following code on the end of the file which opens the connection.
<?php
$conn->Close();
?>


text:
Q: When is go reflect CanInterface false? As per this playground example (https://play.golang.org/p/Jr64yE4zSpQ), and the implementation of CanInterface in reflect/value.go, it looks like CanInterface is false only for private fields?
What are other scenarios when CanInterface is false?
Playground example:
num := 6
meta := reflect.ValueOf(num)
fmt.Println("canInterface:", meta.CanInterface() == true)

meta = reflect.ValueOf(&num)
fmt.Println("canInterface:", meta.CanInterface() == true)

foo := Foo{}
meta = reflect.ValueOf(&foo)
fmt.Println("canInterface:", meta.CanInterface() == true)
meta = meta.Elem()
fmt.Println("canInterface:", meta.CanInterface() == true)
publicField := meta.FieldByName("Number")
privateField := meta.FieldByName("privateNumber")
fmt.Println(
    "canInterface:",
    publicField.CanInterface() == true,
    // Woah, as per the implementation (reflect/value.go)
    // this is the only time it can be false
    privateField.CanInterface() != true)

var fooPtr *Foo
var ptr anInterface = fooPtr
meta = reflect.ValueOf(ptr)
fmt.Println("canInterface:", meta.CanInterface() == true)

meta = reflect.ValueOf(&foo)
meta = meta.Elem() // ptr to actual value
publicField = meta.FieldByName("Number")
ptrToField := publicField.Addr()
fmt.Println("canInterface:", ptrToField.CanInterface() == true)

reflect/value.go
func (v Value) CanInterface() bool {
if v.flag == 0 {
    panic(&ValueError{"reflect.Value.CanInterface", Invalid})
}
// I think "flagRO" means read-only?
return v.flag&flagRO == 0
}

A: If you dive into the source code for CanInterface, you can see this line:
return v.flag&flagRO == 0

And a bit below it, this block of code from the function valueInterface:
if safe && v.flag&flagRO != 0 {
    // Do not allow access to unexported values via Interface,
    // because they might be pointers that should not be
    // writable or methods or function that should not be callable.
    panic("reflect.Value.Interface: cannot return value obtained from unexported field or method")
}

Since v.flag&flagRO != 0 is equivalent to !CanInterface, we can conclude from the comment below it that CanInterface is false when the reflect.Value is an unexported struct field or method.


text:
Q: Android app appears multiple times in the 'Recent Apps' list A number of users of my app have reported that on the Nexus One, running Froyo 2.2, the app appears multiple times in the 'Recent Apps' list that is displayed when you long press the home button.
Personally, I have not been able to replicate the issue. Have tried killing the app with a task killer then restarting it to see if that would cause the app to appear more than once on the list. Also tried spawning multiple thread from within an activity in the app, but still no go. I have also tested on Droid phones running 2.2 as well as on the 2.2 emulator but to no avail. It is curious that only Nexus One Froyo users experience the issue.
The app has one main launcher activity, about 30 different activities and is divided into 4 main tasks to help manage the activity stack. The app also has an IntentService for running network operations in the background.
Is there any know scenario that could cause an app to appear multiple times in the 'Recent Apps' list? Is the 'Recent Apps' list populated based on the app package name e.g. com.mycompany.myappname or based on the tasks defined in the application manifest file?

A: As Reuben said this behaviour is caused by starting an Activity via an Intent with FLAG_ACTIVITY_NEW_TASK flag enabled


text:
Q: how to fix openssl SSL_connect SSL_ERROR_SYSCALL errror in git clone enterprise repository when behind a proxy? I have an Ubuntu 18.04 VM in VMWare. This VM connects to internet behind a proxy. When I'm trying to git clone a repository from my enterprise github account, it gives the following error:
OenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to {my github enterprise url}
I get the same error when trying to curl the same git url.
I have tried configuring the git proxy by:
git config --global http.proxy http://myproxy:port
git config --global https.proxy http://myproxy:port
The connection to proxy is successful but there is an error in connection to https://{github enterprise repository}
I expect the "git clone" command to ask my credentials for the repository but it gives the openssl error.


text:
Q: Rename caption of figures and tables I am new to Latex. I want to rename the figures and the table as "Exhibit" instead of the standard "Figures" and "Tables". This is my code:
\documentclass{article}
\usepackage[left=2.54cm, right=2.54cm,top=2.54cm,bottom=2.54cm]{geometry}
\usepackage{graphicx}
\usepackage[affil-it]{authblk}
\usepackage[greek,english]{babel}
\usepackage{natbib}
\usepackage{float}
\usepackage[resetlabels]{multibib}
\usepackage{amsmath}
\usepackage{placeins}
\usepackage{xcolor}
\usepackage{color}
\usepackage{colortbl}
\usepackage{multirow}
\usepackage{tabularx}
\usepackage{amsfonts}
\usepackage{longtable}
\usepackage{subfig}
\usepackage{soul}
\usepackage{amssymb}
\usepackage{longtable}
\usepackage{setspace}
\graphicspath{{Figures/}}

\title{}
\sethlcolor{yellow}

\makeatletter
\def\SOUL@hlpreamble{%
    \setul{}{3.5ex}% increased by 1ex
    \let\SOUL@stcolor\SOUL@hlcolor
    \dimen@\SOUL@ulthickness
    \dimen@i=-.75ex % increased by -0.25ex
    \advance\dimen@i-.5\dimen@
    \edef\SOUL@uldepth{\the\dimen@i}%
    \let\SOUL@ulcolor\SOUL@stcolor
    \SOUL@ulpreamble
}
\makeatother
\usepackage{etoolbox}

\usepackage[colorlinks]{hyperref}

\makeatletter
\newcommand{\sectionbiblio}{%
    \patchcmd{\std@thebibliography}{\chapter*}{\section*}{}{}
}

% define \c
%citetpos just like \citet
\DeclareRobustCommand\citetpos
{\begingroup
    \let\NAT@nmfmt\NAT@posfmt% ...except with a different name format
    \NAT@swafalse\let\NAT@ctype\z@\NAT@partrue
    \@ifstar{\NAT@fulltrue\NAT@citetp}{\NAT@fullfalse\NAT@citetp}}

\makeatother

\makeatletter
% make numeric styles use name format
\patchcmd{\NAT@test}{\else \NAT@nm}{\else \NAT@nmfmt{\NAT@nm}}{}{}

\let\NAT@orig@nmfmt\NAT@nmfmt
\def\NAT@posfmt#1{\NAT@orig@nmfmt{#1's}}

\makeatother
\newcommand{\Y}[1]{{\color{green}#1}}
\newcommand{\N}[1]{{\color{red}#1}}
\renewcommand{\baselinestretch}{1.9}

\usepackage[labelsep=endash]{caption}

\newcommand{\highlight}[1]{{\ttfamily\hyphenchar\font=45\relax\hl{#1}}}
\renewcommand{\figurename}{Exhibit}
\renewcommand{\tablename}{Exhibit}
\begin{document}
    \begin{figure}
        \centering
        \rule{1cm}{1cm}
        \caption{This is a figure}
    \end{figure}
\end{document}

Can anyone point me to what is clushing with the  \renewcommand{\figurename}{Exhibit} \renewcommand{\tablename}{Exhibit} ?


text:
Q: How can I dynamically resize a select2 input to be the same width as the selected option? I'm building a 'natural language' search form using a series of inline select inputs, using jQuery Select2 for styling. The widths of the Select2 inputs appear to be set to the width of the selected option on initialisation, which is great. I just can't work out how to get the width to update when the selected option is changed. Any ideas?
Many thanks!

A: You can use window resize function.
Example:
// Fix select2 width
$(window).on('resize', function() {
    $('.form-group').each(function() {
        var formGroup = $(this),
            formgroupWidth = formGroup.outerWidth();

        formGroup.find('.select2-container').css('width', formgroupWidth);

    });
});

A: Try to add this to yor CSS file:
.select2-container {
    width: 100% !important;
}

It solved my resize problems with select2
(Edited: I do not use placeholders)

A: I know this is an old post However, I had an issue when I used NMC's code.
As I can't comment on his answer, after using his code I had some annoying scrollbars appearing after using the select2 dropdowns, to fix this I used width auto instead.
.select2-container {
    width: auto !important;
}

A: Just had to do something like this for a site
$(e).on("select2:closing", function(e) {
    if (e.hasOwnProperty('params') &&
        e.params.hasOwnProperty('args') &&
        e.params.args.hasOwnProperty('originalEvent') &&
        e.params.args.originalEvent.hasOwnProperty('target')) {
            var newWidth = $(e.params.args.originalEvent.target).width();
            var id = $(e.params.args.originalEvent.target).attr('id');
            var container = $("span[aria-labelledby=\""+id.split("-result")[0]+"-container"+"\"]");
            $(container).parents('span.select2').width(newWidth + 21);
    }
});

This is probably not fool-proof and is tied to the current API. But it gets the width of the element in the dropdown before the dropdown closes and then applies that to the container.
One thing of note, you may need to float the dropdown items to get their real size.
.select2-results__option {
    float: left;
    clear: both;
}

A: $('.select2-search__field').attr('style','width:auto');

$('.select2-search__field[placeholder=""]').attr('style','width:10px');

A: For dynamically resize a select2 you can use width: 'style' option as below:
$('#field_'+field.name).select2({
    placeholder: "select a option...",
    maximumSelectionLength: 1000 ,
    allowClear: true,
    ...
    width: 'style',
    data: data
});

And next you have to use style="width:100%;" as attribute for your select tag.
<select class="input-element-item fontsize13" id="select2" style="width:100%;" >
    <option></option>
</select>

A: For other than problems of responsive width, read the documentation of Select2. Everything is explained.
https://select2.org/appearance#container-width
<select class="js-example-responsive" style="width: 50%"></select>

$(".js-example-responsive").select2({
   width: 'resolve' // need to override the changed default
});


text:
Q: Ruby metaprogramming: define_method block not maintaining scope I'm working on dynamically patching a bunch of classes and methods(most of the time these methods are not simple "puts" like a lot of examples I've been able to find on the internet)
Say for instance I have the following code:
foo.rb
module Base
  class Foo
    def info
      puts 'Foo#info called'
    end
  end
 end

& I also have the following class:
test.rb
module Base
  class Test
    def print
      puts "Test#print called"
      Foo.new.info
    end
  end
end

Then in main.rb I have the following where I want to add a method that uses a class within the same module(Foo in this case)
require_relative './foo'
require_relative './test'

new_method_content = "puts 'hi'
                      Foo.new.info"

Base::Test.instance_eval do
  def asdf
    puts "Test#asdf called"
    Foo.new.info
   end
end

Which, when executed will net the following:
Uncaught exception: uninitialized constant Foo

Which sort of makes sense to me because the main.rb file doesn't know that I want Base::Foo, however, I need a way to maintain lookup scope because Base::Test should be able to find the class Foo that I want.
Base::Test.instance_eval do
  def asdf
    puts "Test#asdf called"
    Foo.new.info
   end
end

I've done a fair bit of googling and SO'ing but haven't found anything about how to maintain constant lookup scope while class_eval/instance_eval/module_eval/define_method(I've tried a lot of Ruby's dark magic methods all of which have ended in varying degrees of failure lol)
https://cirw.in/blog/constant-lookup

Confusingly however, if you pass a String to these methods, then the String is evaluated with Module.nesting containing just the class itself (for class_eval) or just the singleton class of the object (for instance_eval).

& also this:
https://bugs.ruby-lang.org/issues/6838

Evaluates the string or block in the context of mod, except that when
  a block is given, constant/class variable lookup is not affected.

So my question is:
How can I redefine a method BUT maintain constant/class scope?
I've been trying a bunch of other things(in the context of main.rb):
Base::Test.class_eval('def asdf; puts "Test#asdf called"; Foo.new.info; end')
Base::Test.new.asdf
=>
Test#asdf called
Uncaught exception: uninitialized constant Base::Test::Foo
Did you mean?  Base::Foo

(which is a diff problem in that it's trying to look it up from the evaluated module nesting? I'm not sure why it doesn't try all module paths available from Base::Test though, I would think it would try Base::Test::Foo which doesn't exist, so then it would go up the module tree looking for the class(Base::Foo) which would exist)

A: When you reference the class Base::Test like this, ruby does not take the Base:: as the module context to look up constants. That is the normal behaviour and would also not work, if you would define the moethod directly.
But you could do it in this way:
module Base
  Test.instance_eval do
    def asdf
      puts "Test#asdf called"
      Foo.new.info
    end
  end
end


text:
Q: Since updating to Xcode 13 I get a codsign error After updating to Xcode 13.x on Monterey, I've started getting numerous Code sign error(s): Command usr/bin/codesign failed with a nonzero exit code when building my project.
Cleaning Build Folder and deleting derived data are NOT working as a fix. Any suggestions?

A: I found a solution to delete the Apple Worldwide Certificate in my Keychain Access. It seems to recreate when building and fixes the codesign error. Sometimes there are 2 certificates and I just delete the older one:

A: For me, xcode13.4 / monterey osx, iOS 15.0 device. I recently upgraded to monterey and for some reason was the certificate not trusted in the keychain. I had to manually trust the keychain and then it worked. See this also. https://support.apple.com/guide/keychain-access/change-the-trust-settings-of-a-certificate-kyca11871/mac


text:
Q: Why did Gauss think the reciprocity law so important in number theory? Gauss's Disquitiones Arithmeticae centers around the quadratic reciprocity law.
It seems that he developed the genus theory of integral binary quadratic forms to find a natural proof of the quadratic reciprocity law.
He later wrote 5 papers on number theory.
All of them are about the quadratic and biquadratic reciprocity laws.
Why did Gauss think the reciprocity law so important in number theory?

A: It's the first non-trivial result in elementary number theory, and to find out whether a second-degree equation has a solution modulo some number, basically comes down to knowing quadratic reciprocity. The Disquisitiones starts with the basic definition of congruences, then solutions of first-degree congruence equations, and then second-degree, where one naturally bumps up against this problem.
Here is from the book itself:

Since almost everything that can be said about quadratic residues
  depends on this theorem, the term fundamental theorem which we will
  use from now on should be acceptable.

Later on he speaks of how Euler and Legendre came close to finding a proof, but despite their best efforts, could not. Clearly it was also a matter of pride for him.
Given how much of modern number theory revolves around generalizations of quadratic reciprocity, such as Artin reciprocity and the reciprocity conjecture of Langlands, it's easy to consider Gauss's intuition as justified.


text:
Q: Count occurrences of array elements with JavaScript I have this JavaScript array with length 129.
var fullnames = [Karri, Ismo, Grigori, Ahmed, Roope, Arto .....]

I would like to find how many times those names appeared in an array and store that information in an array like this:
var counter = [2, 5, 7, ..]

where Karri occured in fullnames array 2 times, Ismo occured 5 times etc. Any ideas about how to do it?

A: This is the best - and simple - way I can think of:

var fullnames = ["Karri", "Ismo", "Grigori", "Ahmed", "Roope", "Ahmed", "Karri", "Arto", "Ahmed"];
var counts = {};

for (var i = 0; i < fullnames.length; i++)
{
    if (!counts.hasOwnProperty(fullnames[i]))
    {
        counts[fullnames[i]] = 1;
    }
    else
    {
        counts[fullnames[i]]++;
    }
}

console.log(counts);

Original Fiddle.
Using an array to store the counts doesn't makes much sense, so I used an object instead.

A: I am assuming that fullnames is array of strings. If so, you can do it like so:
var occurences = { };
for (var i = 0; i < fullnames.length; i++) {
    if (typeof occurences[fullnames[i]] == "undefined") {
        occurences[fullnames[i]] = 1;
    } else {
        occurences[fullnames[i]]++;
    }
}

console.log(occurences); // Prints out something like: {"Karri": 2, "Ismo": 5, ...}

A: var fullnames = ['Karri', 'Ismo', 'Grigori', 'Karri', 'Ismo', 'Grigori', 'Grigori', 'Karri', 'Ismo', 'Grigori', 'Grigori'];
var counts = [];
fullnames.forEach(function(_item) {
    if(typeof counts[_item] === 'undefined') counts[_item] = 1;
    else counts[_item]++;
});
var result = [];
for(i in counts) result.push(counts[i]);
console.log(result);

// outputs [3, 3, 5]


text:
Q: Вывести строку с противоположным регистром Допустим, у меня есть строка:
stroka = input()

Вводные данные:
QWERTYUIOPASdfghjklzxcvbnm

Как сделать так, чтобы на выходе все буквы поменяли свой регистр (маленькие буквы стали большими, большие — маленькими)?
qwertyuiopasDFGHJKLZXCVBNM

A: Используйте метод swapcase:
s = 'QWERTYUIOPASdfghjklzxcvbnm'
print(s.swapcase())

Результат:

qwertyuiopasDFGHJKLZXCVBNM


text:
Q: Kivy Matplotlib cannot be founded I'm using kivy and matplotlib for visualization of data, these are the libraries:
`from kivy.uix.button import Button
from kivy.uix.spinner import Spinner

import pandas as pd
import matplotlib.pyplot as plt
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg as FCK`

`def view_stats(self):
    plt.cla()
    self.ids.analysis_res.clear_widgets()
    target_product = self.ids.target_product.text
    target = target_product[:target_product.find(' | ')]
    name = target_product[target_product.find(' | '):]

    df = pd.read_csv('products_purchase.csv')
    purchases = []
    dates = []
    count = 0
    for x in range(len(df)):
        if str(df.Product_Code[x]) == target:
            purchases.append(df.Purchased[x])
            dates.append(count)
            count += 1
    plt.bar(dates, purchases, color='teal', label=name)
    plt.ylabel('Total Purchases')
    plt.xlabel('day')

    self.ids.analysis_res.add_widget(FCK(plt.gcf()))`

When I run my code, it goes fine except for this function. I's not working because of the last import.
I have already downloaded kivy, kivy-garden and matplotlib as well. However, when I import:
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
I cannot run my program. Because of this only line

`

`from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg as FCK
   File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
   File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
   File "<frozen importlib._bootstrap>", line 672, in _load_unlocked
   File "<frozen importlib._bootstrap>", line 640, in _load_backward_compatible
 KeyError: 'kivy.garden.matplotlib'
`

Is there any suggestions? any other package that might be easier to use?


text:
Q: Unity not liking void using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {

// Use this for initialization
void Start () {
    //Declare intager Hunger
    int Hunger;
        Hunger = 100;
    GUI.Box(new Rect(10,10,100,90), "Stats");

    GUI.Label (Rect (10,40,100,20), GUI.tooltip,GUIContent("Hunger", Hunger));
}
}

// Update is called once per frame
void Update () {
    //Every ten seconds Hunger goes down by one.
    Hunger = Hunger - 1;
    yield WaitForSeconds = 10;
}
};

};

This is my code for the UI in my upcoming game Rust and Wood. It is perfect but Unity yells at the void in void Update (). Please help.

A: You can not use yield in a Update() method because it is executed every frame.
Only the Start() method can be declared as coroutine by replacing void with IEnumerator.
try this.
public class HungerClass : MonoBehaviour {

    int Hunger = 100;

    IEnumerator Start ()
    {
        while (true)
        {
            //Every ten seconds Hunger goes down by one.
            Hunger = Hunger - 1;
            yield return  new WaitForSeconds(10);
        }
    }

    void OnGUI()
    {
        GUI.Label(new Rect (10,40,100,20), "Hunger = " + Hunger);
    }
}

A: The problem is not in the void declaration.
You have an extra } on Start method and also at the end of the file };
Also int Hunger; should be outside Start method.
Edit:
I notice that you are trying to use Coroutines wrong. Replace void with IEnumerator and use properly WaitForSeconds coroutine. Also as @JeanLuc said Update method cannot be used as a coroutine. Only Start method. So you need to change that too.
So it should be:
using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {

    int Hunger;

    void Start () {
        Hunger = 100;
        GUI.Box(new Rect(10,10,100,90), "Stats");

        GUI.Label (Rect (10,40,100,20), GUI.tooltip,GUIContent("Hunger", Hunger));

        StartCoroutine(TickHunger());
    }

    IEnumerator TickHunger () {
        while(Hunger > 0)
        {
           //Every ten seconds Hunger goes down by one.
           Hunger = Hunger - 1;
           yield return new WaitForSeconds(10);
        }
    }

};


text:
Q: C++/Qt Object to Vector & Back to Object Simply, I am unable to call non-inherited methods from an object in a Vector.
I'm using Qt Creator 2.7.0 which to my knowledge doesn't use the full C++11 yet (?) - I'm unsure if this is what is causing the following problem (although I'm very sure it's me not the IDE/Compiler):
I have 3 classes which inherit from the base class and have an additional primitive/getter/setter each.
Simply, my classes look like:
class A
{
  public:
    virtual std::string getName() = 0 ;
    virtual void setName(std::string) = 0 ;
    virtual int getNumber() ;
    virtual void setNumber(int) ;
  protected:
    std::string name ;
    int number ;
}

class B : public A
{
  public:
    std::string getName() ;
    void setName(std::string) ;
    int getNumber() ;
    void setNumber(int) ;

    std::string getEmail() ;
    void setEmail(std::string) ;
  protected:
    std::string email ;
}

In my main I have a Vector of pointers, i.e.:
std::vector<A*> contacts ;

//Add Pointers to Vector
A *a ;
B *b ;
contacts.push_back(a) ;
contacts.push_back(b) ;

I then Check Object Class Type, to ensure it's of class type B.
if (dynamic_cast<B*>(contacts.at(1)) != NULL) //nullptr not working in Qt yet
{

I can access the getters & setters of Class A, but not B:
std::string name = contacts.at(1)->getName() ; //Works

std::string email = contacts.at(1)->getEmail() ; //Compiler Error: 'class A' has
                                                 //no member named 'getEmail'

}

The Error ('class A' has no member named 'getEmail') is happening at compile time and not at run-time.
I can't see it being Object Slicing as this should all be polymorphic, should I be using some type of C++ Casting?
Any help or kick in the right direction would be appreciated, thanks.

A: You need to use a dynamic_cast to get a pointer to the derived type. You are not actually doing that, you are calling a B method on an A*:
contacts.at(1)->getEmail() ; // look, no dynamic_cast

You would need to do the equivalent of this:
B* b = dynamic_cast<B*>(contacts.at(1));
std::string email = b ? b->getEmail() : "N/A";

A: contacts pertains to A which is base class.! You've to perform the operation on derived one.!
Instead of
        contacts.at(1)->getName
use         vector<B*> b->getName.
Hope this clears :)

A: Your contacts vector contains A*. C++ verifies types at compilation so there is no problem when executing the code. Since contacts is of A* type, only methods of class A can be called.
In your case, you want to cll a B method on an objct that might be a B, or not! C++ is sure it is an A, but it might be a C  (if class C  inherits from A).
Whay you want to do is to get the instance of the B object in the vector and cast it into a B so you can call the method: B* b = dynamic_cast<B*>(contacts.at(1)); noyw use the b to do whatever you want.


text:
Q: Excel VBA - How to Save Named Charts, Tables, Ranges to HTML I'm struggling with this.
Here is my code, taken directly from MS Excel Documentation, but I keep getting a runtime 1004 error: Application-defined or object-defined error. https://learn.microsoft.com/en-us/office/vba/api/excel.publishobjects.add
Sub publishsimple()
Dim ws As Worksheet
Dim sheetcount As Long
sheetcount = Application.Sheets.Count
    With ActiveWorkbook.PublishObjects.Add(SourceType:=xlSourceChart, _
                    filename:="C:\Users\gblack\Downloads\testing.htm", _
                    Sheet:="Income, Worth, Age - Charts", Source:="Housing Stock", _
                    HtmlType:=xlHtmlChart, DivID:="", Title:="")
                        .Publish (True)
                        .AutoRepublish = False
    End With
End Sub

It will work with ranges, but doesn't seem to work with my charts. I'd rather not brute force exporting the ranges. There must be an elegant solution to saving my charts as HTML...
I'm open to using Python as well...


text:
Q: How can I use variable defined in build.gradle in strings.xml? I have a variable in build.gradle (Module: app) which counts the build number (number of compilations to be precise:
String content = ""

def buildCountFile = new File("c:\\projects\\aviacheck\\spec\\aviacheck-build-counter.txt")

if (buildCountFile.exists()) {
    content = buildCountFile.getText('UTF-8')
}
int count = 0;
if (content.isNumber()) {
    count = content.toInteger() + 1;
}
buildCountFile.write(count.toString())
// build counter ends

buildTypes {
    debug{
        resValue "string", "bNr", count.toString()
    }
    release {
        resValue "string", "bNr", count.toString()
    }
}

which is stored in "bNr".
Of course I can use it in code by getResoures(), but I would like to concatenate it in strings.xml with one more string without writing code.
So, defining version compilation like that:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE resources [
    <!ENTITY appVer "1.2">
    ]>

<resources>
//    ........
    <string name="ver">"&appVer; Build: &bNr;</string>
//    ........
</resources>

Unfortunately,  &bNr remains unresolved.
Any ideas on what the problem could be?

A:
I would like to concatenate it in strings.xml with one more string without writing code

That is not supported, sorry.

unfortunately &bNr keeps unresolved.

There is no HTML entity by that name.


text:
Q: Loading a nib file within a nib file I've setup a nib file to include some basic UIView elements within a larger UIView element. Two elements are subclasses of the UIImageView class (meters to display data to the user). Anyway, in my mind I'd like to have these meters be their own nib file as they have a number of visual elements and for sanity sake it would be nice to place the meter individually in its own nib file. I would also like to have one controller for the meter and the other basic elements in the parent nib file. I've set the child meter nib objects in the parent nib to my custom class (say UIMeter). I'm having trouble loading the child nib into the parent nib, when I override the UIMeter initWithCoder method it creates an infinite loop as i'm trying to use loadnibnamed to reach into the child nib file for loading. I've also tried loading the nib from the parent controller but it loads both the child nib and the nib from the loadnibnamed. This will probably make more sense with code and images:
UIMeter code, not really certain that I even need this as it causes an infinite loop but I'm hoping that the view can be smart enough to load itself in some way though in reading the docs it seems more appropriate to do this in the controller for the view.
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if(self)
{
    self = [[[NSBundle mainBundle] loadNibNamed:@"PowerMeterView" owner:self options:nil] firstObject];
}
return self;

}
In the parent controller I'm dialing up the view like so:
-(void)loadView
{
if(![self isViewLoaded])
{
    GameMenuView *menuView = [GameMenuView new];
    menuView.userEnergy = [[[NSBundle mainBundle] loadNibNamed:@"PowerMeterView" owner:self options:nil] firstObject];
    menuView.userReactor = [[[NSBundle mainBundle] loadNibNamed:@"PowerMeterView" owner:self options:nil] firstObject];
    _gameMenuView = menuView;
//--This places the child nib from the file on the view but it is not replacing the UIMeter in the parent nib
    [menuView.userEnergy setFrame:CGRectMake(0, 0, 20, 20)];
    [menuView addSubview:menuView.userEnergy];
    [self setView:menuView];
}

}

A: to break out of the loop, you can check if the elements you are trying to initialize with the loop are not already loaded
for example if you have a view called "label"
then your initWithCoder would look like this
-(id) initWithCoder:(NSCoder *)aDecoder{
     self = [super initWithCoder:aDecoder];
       if (self){
            if(!self.label){
               load the nib

            }
      return self;

}


text:
Q: AutoMapper: Migrar de la versión 4.1.1 a la 5.2.0 Estoy usando la versión 4.1.1 de AutoMapper en este servicio y me gustaría actualizar a la versión 5.2.0 de AutoMapper. ¿Alguien me puede ayudar?
public class ViewModelMapperService
{
private ConfigurationStore _configuration;
private MappingEngine _engine;

public ViewModelMapperService()
{
    this._configuration = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers);
    this._engine = new MappingEngine(_configuration);
}

public void Map<TSource, TTarget>(TSource source, TTarget target)
{
    this.CreateMap<TSource, TTarget>();
    this._engine.Map(source, target);
}

public TTarget Map<TSource, TTarget>(TSource source)
{
    this.CreateMap<TSource, TTarget>();
    return this._engine.Map<TSource, TTarget>(source);
}

public void MapToModel<TSource, TTarget>(TSource source, TTarget target) where TTarget : IBaseObject
{
    this.CreateVmToModelMap<TSource, TTarget>();
    this._engine.Map(source, target);
}

public void MapToViewModel<TSource, TTarget>(TSource source, TTarget target) where TTarget : IViewModel
{
    this.CreateModelToVmMap<TSource, TTarget>();
    this._engine.Map(source, target);
}

private void CreateMap<TSource, TTarget>()
{
    this._configuration.CreateMap<TSource, TTarget>();
}

private void CreateModelToVmMap<TSource, TTarget>() where TTarget : IViewModel
{
    this._configuration.CreateMap<TSource, TTarget>().ForMember(t => t.IsDirty, opt => opt.Ignore());
}

private void CreateVmToModelMap<TSource, TTarget>() where TTarget : IBaseObject
{
    this._configuration.CreateMap<TSource, TTarget>().ForMember(t => t.IsDirty, opt => opt.Ignore());
}
}


text:
Q: cppcheck stops analysis of whole file when array of struct is declared I am running static code analysis using cppcheck.
I have a cpp source file which as bugs like "null pointer dereferenced" etc.
There is a piece of code in file. A structure is declared inside a class
class Example{
    public:
        typedef struct {
            int num;
        }MyStruct;
};

When array of structure is declared
Example::MyStruct st_arr[5];

Cppcheck stops the analysis as soon as it reaches this code and doesn't go further and report other bugs in file.
But if I simply declare a struct variable
Example::MyStruct st;

It goes fine.
So, the cppcheck stops the analysis when array of struct (declared in a class) is created.
Is this a issue with cppcheck?

A: Most static analysis tools can be configured to not report errors from library headers. You probably have to configure cppcheck to recognize the headers, e.g. by defining paths which are treated as library files. They also usually parse special comments in the source code which can be used to suppress errors in regions of code, e.g. suppress errors before the include and then re-enable afterwards. How this works is described in the documentation of the tools.
These tools also have the ability to define suppressions to discard errors, e.g. false positives. This can also be used to suppress errors from third-party code.
The cppcheck manual chapters "Chapter 8. Suppressions" and "Chapter 9. Library configuration" should explain how to do this. If you have specific problems with the configuration you can post more detailed questions.

A: I am a Cppcheck developer.
I see such weird behaviour also. It is not by intention. I will investigate.
Best regards,
Daniel Marjamäki


text: Q: Random looking Gray Codes or Hamiltonian Cycles on Hypercubes Cyclic Gray codes come in many flavors and correspond 1-1 to Hamiltonian cycles on hypercubes. I would like to find a type that looks like a random walk on the hypercube. In a sense this is an oxymoron, since a real random walk will almost certainly not produce a Hamiltonian cycle. However, it might be possible to produce Gray codes where such that most segments up to some length look sufficiently random. Clearly the self avoiding property of a Hamiltonian path quickly becomes strong evidence of non randomness, but my critrea are not very strong I just need something where the structure is not completely obvious.


text:
Q: How to find the cheapest combinations from a number of products I am given with a certain table
Stores
[A][B][C]

Products
[P1][P2][P3][P4]

And their prices are listed as below
[  ][A][B][C]
[P1][6][4][2]
[P2][3][5][7]
[P3][1][9][9]
[P4][8][4][9]

Assume the user want to buy all of the things in 2 stores as cheap as possible, is there only efficient algorithm for that?
Is this the Travelling Purchaser Problem?

A: Assuming that:

user want to buy all of the things in 2 stores

Algorithm sketch:
Use a two dimensional lookup tables with stores as columns and rows.
[x][A]  [B]  [C]
[A][inf][]   []
[B][]   [inf][]
[C][]   []   [inf]

The diagonal is initialized to infinity as you need to select two different stores.
Now fill the upper right triangle or the lower left triangle of the lookup table.
e.g. in position [A],[B] you have selected store A and store B. Therefore it is only possible to buy the products from these two stores, which means you can do a greedy approach (take the cheaper one). Finally store the sum of the prices in the lookup table.
The entry with the lowest value is the solution to your problem.
Furthermore you need to check the case that one store has every product cheaper than the other, so in this sketch all products would be bought in one store.
The complexity of the algorithm should be O(n²m) where n is the number of stores and m is the number of products.

A: I have feeling that it is possible to use exclusion only. At each steap, you remove one most ineficient store. This makes solution in polynomail at worst O(N³) time complexity.

A: You can add three more columns.
One for min(A,B)
One for min(A,C)
One for min(B,C)
Calculate the sum for these new three columns. If the lowest sum is column min(A,C), then go to stores A and C.
This algorithm would be very efficient in terms of complexity.


text:
Q: Clip Text with Moving background I have found a great method to move a background continuously horizontally.  The effect I am after is to create the illusion of flame, so the background needs to move vertically.  Is there a way to do this?  I am using Elementor as the builder.
The css code I have is as follows
.mask_text .elementor-widget-container {
    background-clip: text;
    -webkit-background-clip: text;
    -moz-background-clip: text;
    -o-background-clip: text;
    animation: maskText 50s linear infinite;
    -webkit-animation: maskText 50s linear infinite;
}

.mask_text .elementor-widget-container h2{
    color:transparent !important;
}

@keyframes maskText{
  from{ background-position: 0px center}
  to{ background-position: 2000px center}

}

@-webkit-keyframes maskText{
  from{ background-position: 0px center}
  to{ background-position: 2000px center}
}

A: To move vertically all you need to change is to add a second value to background-position:
background-position: <horizontal> <vertical>

h1 {
        margin: 0;
        font-size: 100px;
        color: transparent;
        background: rgb(203,8,202);
        background: linear-gradient(175deg, rgba(203,8,202,1) 0%, rgba(131,46,189,1) 35%, rgba(255,252,0,1) 100%);
        background-clip: text;
        -webkit-background-clip: text;
        animation: maskText 50s linear infinite;
      }

      @keyframes maskText{
        from{ background-position: center 2000px}
        to{ background-position: center 0}
      }

My Text


text:
Q: HasManyThrough with one-to-many relationship I am working on small scale CMS for a project with tables like so:
- pages
    - id
    …
- translations
    - page_id
    …
- menus
    - id
    …
- menu_page
    - menu_id
    - page_id
    …

In the Menu model I have this relationship:
function pages(){
    return $this->hasMany('Page');
}

Is it possible to create a relation directly between Menu and Translations that translates to something like this SQL query:
select translations.*
from translations
inner join menu_page on menu_page.page_id = translations.page_id
where menu_page.menu_id = ?;

Thanks!

A: You can't do it with builtin methods, hasManyThrough won't work with many-to-many relation menus-pages.
However you can try a workaround like this:
public function getTranslationsAttribute()
{
    if ( ! array_key_exists('translations', $this->relations)) $this->loadTranslations();

    return $this->getRelation('translations');
}

protected function loadTranslations()
{
    $translations = Translation::join('menu_page', 'translations.page_id', '=', 'menu_page.page_id')
        ->where('menu_page.menu_id', $this->getKey())
        ->distinct()
        ->get(['translations.*','menu_id']);

    $hasMany = new Illuminate\Database\Eloquent\Relations\HasMany(Translation::query(), $this, 'menu_id', 'id');

    $hasMany->matchMany(array($this), $translations, 'translations');

    return $this;
}

Now you can do this:
$menu = Menu::find($id);
$menu->translations; // Eloquent Collection of Translation models

So basically just like you would use any relation. The only trouble is that you can't eager load it.


text:
Q: Entity Framework 6 code-first relations with Fluent API I have 3 related tables in an existing database.
Many-to-Many (Many Person Many Group) and a table between - Event, witch ralate these two tables.
public class Person
    {
        public int PersonID { get; set; }
        public string No { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public virtual ICollection<Event> Events { get; set; }
    }
   public class Event
    {
        public int EventID { get; set; }
        public string EventData { get; set; }
        public int PersonID { get; set; }
        public int GroupID { get; set; }
        public virtual Person Person { get; set; }
        public virtual Group Group { get; set; }
   }

   public class Group
    {
        public int GroupID { get; set; }
        public string GroupName { get; set; }
        public virtual ICollection<Event> PersonGroup { get; set; }
    }

I ddescribed relations using Fluent API.
First I declared PK's
modelBuilder.Entity<Person>()
.HasKey(k => k.PersonID });

modelBuilder.Entity<Event>()
.HasKey(k => k.EventID);

modelBuilder.Entity<Group>()
.HasKey(k => k.GroupID });

Now foreign keys:
Person has many Events
modelBuilder.Entity<Person>()
.HasKey(k => k.PersonID })
.HasMany(k => k.Events)
.WithRequired()
.HasForeignKey(f => f.PersonID);

In Event class I have Person (and all its parameters)
modelBuilder.Entity<Event>()
.HasRequired(s => s.Person)
.WithMany()
.HasForeignKey(fk => fk.PersonID);

Also I need a Group with all data:
modelBuilder.Entity<Event>()
.HasOptional(s => s.Group)
.WithMany()
.HasForeignKey(fk => fk.GroupID });

At least I need a Person group participating in an Event
modelBuilder.Entity<Group>()
.HasKey(k =>k.GroupID })
.HasMany(k => k.PersonGroup)
.WithOptional()
.HasForeignKey(fk => fk.GroupID);

It seems I have everything I need, but I need one mo collection (Group of persons with their names)
What I get through PersonGroup relation I have all events but also need to get Persons. Could You help?

A: Edit
I just realize it's not a typical many-to-many, since your Event-Group relation is optional. Is this intended?
Maybe your model should be changed to reflect a more natural event structure:
Group-Person: many-to-many
Event-Group: many-to-many
Event-Person: no direct relation, only via groups; alternative many-to-many
The way your model is currently designed, a single event entry can't be related to more than one group and one person and a person can't be part of a group unless they are associated in the context of an event entry.

Basically, the thing you ask for is not directly available, because you decided to explicitely create the many-to-many table with additional properties.
However, in queries you can always write a select to get the persons collection
db.Groups.Select(g => new {Group = g, PeopleInGroup = g.PersonGroup.Select(ev => ev.Person)})

Few side-notes regarding your model:

*

*Consider removing EventID and instead use modelBuilder.Entity<Event>().HasKey(k => new { k.PersonID, k.GroupID }), like a typical many-to-many table would be designed.

*Mention reverse properties in fluent api:

.
modelBuilder.Entity<Person>()
.HasKey(k => k.PersonID })
.HasMany(k => k.Events)
.WithRequired(e => e.Person)
.HasForeignKey(f => f.PersonID);

// redundant with the previous configuration
modelBuilder.Entity<Event>()
.HasRequired(s => s.Person)
.WithMany(p => p.Events)
.HasForeignKey(fk => fk.PersonID);

// same to be done for groups

In order to have a convenient access to the associated people of a group, you could create a not-mapped property getter which wraps the necessary query:
public class Group
{
    public int GroupID { get; set; }
    public string GroupName { get; set; }
    public virtual ICollection<Event> PersonGroup { get; set; }

    [NotMapped]
    public IEnumerable<Person> PersonsInGroupEvents
    {
        return PersonGroup.Select(ev => ev.Person);
    }
}

// or fluent api way of NotMapped:
modelBuilder.Entity<Group>()
    .Ignore(x => x.PersonsInGroupEvents);


text:
Q: SDO Oracle Table not recognized as Geometry in QGIS I can connect to the Oracle Database with QGIS but spatial table/layers are not recognized as such.
I have read the following in the QGIS documentation:

Normally, an Oracle Spatial layer is defined by an entry in the
  USER_SDO_METADATA table.
  Source: QGIS Oracle connection documentation

But I have not found this in the database and I cannot edit it.
The layers were created with ArcMap (so with ArcSDE). I know under ArcMap the spatial layers are recognized.
I found that the following tables has informations about spatial tables:

Is it an option to overwrite USER_SDO_METADATA table ?

A: As commented by @Vince:

To the best of my knowledge, QGIS doesn't read SDE.ST_GEOMETRY, which
  won't have an entry in USER_SDO_GEOM_METADATA. You'd need to change
  your enterprise geodatabase configuration to use SDO_GEOMETRY then
  recreate the table before QGIS can see the table. It would be unwise
  to let QGIS modify rows in a versioned feature class.


text:
Q: React - issue with initialValues ant design when using referenced component Using ant design input and forms, I am having trouble using intialValues when a component is referenced in. In this case, I am trying to pass in CustomInput.js, a ant design Input, into my form as <Component/>. Everything works except the initialValues.
Any ideas what to do to make intialValues work?
https://codesandbox.io/s/initialvalues-forked-keftp?file=/index.js:382-414

A: You have to pass the props from your custom component down to Input, specifically the value prop:
function CustomInput(
  { field, value = "", onChange = (e) => {}, disabled, ...rest },
  ref
) {
  return (
    <Input
      ref={ref}
      value={value}
      onChange={onChange}
      disabled={disabled}
      {...rest}
    />
  );
}

DEMO
Note: I'm unsure as to what your field prop is. Since it's not a supported prop as part of the component's API, I left it out.


text:
Q: Building a 24h visualisation with chartjs I am trying to build a custom chart using chartjs, but I couldn't find the right documentation that explains how dataset works.
I am trying to build a 24 hours timebar that contains different blocks stacked next to each other with different colors for each (ie: bars to represent the activity with start & end date)

with the current options object I couldn't achieve the goal required.

stackblitz

    new Chart(myChartRef, {
      type: 'horizontalBar',
      data: {
        labels: [
          "no-shift",
          "in",
          "work",
          "out",
          "absence",
          "leave"
        ],
        datasets: [
          {
            label: "Attendance",
            data:[
            [new Date("2021-08-11T00:00:00"),new Date("2021-08-11T08:00:00")],
            [new Date("2021-08-11T08:00:00"),new Date("2021-08-11T08:01:00")],
            [new Date("2021-08-11T10:00:00"),new Date("2021-08-11T10:05:00")],
            [new Date("2021-08-11T10:00:00"),new Date("2021-08-11T12:00:00")],
            [new Date("2021-08-11T12:00:00"),new Date("2021-08-11T10:05:00")],
            ],
            backgroundColor: "rgb(220,20,60)"
          },
        ]
      },
      options: {
        //Customize chart options
        scales: {
          xAxes: [
            {
              type: 'time',
              time: {
                format: 'HH:mm',
                unit: 'minute',
                unitStepSize: 1,
                displayFormats: {
                  minute: 'HH:mm',
                  hour: 'HH:mm',
                  min: '00:00',
                  max: '23:59'
                }
              },
              display: true,
              scaleLabel: {
                display: true,
                labelString: 'Time'
              }
            }
          ],
          yAxes: [{
            display: true,
            ticks: {
              min: 0,
              max: 1,
              stepSize: 1
            }
        }]
        }
      }
    });

A: You can use floating bars together with the datalabels plugin and a stacked y axis to achieve what you want:

Chart.register(ChartDataLabels)

var ctx = document.getElementById('chart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Day 1", "Day 2", "Day 3"],
    datasets: [{
        label: 'working',
        data: [
          [new Date('2021-09-18T04:00:00'), new Date('2021-09-18T20:30:00')],
          [new Date('2021-09-18T06:00:00'), new Date('2021-09-18T17:00:00')]
        ],
        backgroundColor: "red",
      },
      {
        label: 'sleep',
        data: [
          [new Date('2021-09-18T00:00:00'), new Date('2021-09-18T04:00:00')],
          [new Date('2021-09-18T00:00:00'), new Date('2021-09-18T06:00:00')],
          [new Date('2021-09-18T00:00:00'), new Date('2021-09-18T06:00:00')]
        ],
        backgroundColor: "blue",
      },
      {
        label: 'sleeping',
        data: [
          [new Date('2021-09-18T20:30:00'), new Date('2021-09-18T23:59:59')],
          [new Date('2021-09-18T17:00:00'), new Date('2021-09-18T23:59:59')],
          [new Date('2021-09-18T17:00:00'), new Date('2021-09-18T23:59:59')]
        ],
        backgroundColor: "orange",
      },
    ]
  },
  options: {
    responsive: false,
    indexAxis: 'y',
    plugins: {
      legend: {
        display: false
      },
      datalabels: {
        color: 'white',
        formatter: (val, ctx) => (ctx.dataset.label)
      }
    },
    scales: {
      y: {
        stacked: true
      },
      x: {
        type: 'time',
        time: {
          // Luxon format string
          tooltipFormat: 'DD'
        },
        min: new Date('2021-09-18T00:00:00'),
        max: new Date('2021-09-18T23:59:59')
      }
    }
  }
});
<div class="chart-view">
  <canvas id="chart" width="600" height="200" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.js"></script>
</div>

A: Thanks @HeadhunterKev for the reply;
based on this issue : chartjs, I couldn't find anything in chartjs that can lead to the desired chart.
If you need to build something like such, react google charts can do the trick documentation.


text:
Q: Relations, Eloquent and Joins Lets say I have 2 Tables:
Pages [id, parent_id, content]
Comments [id, page_id, content]
When I'm viewing a page I want to display all comments for that page PLUS comments for pages that have this page as parent.
class Comment extends Eloquent
{
    protected $table = "comments";

    public function page()
    {
        return $this->belongsTo('Page','page_id','id');
    }
}

class Page extends Eloquent
{
    protected $table = "pages";

    public function comments()
    {
        return $this->has_many('Comment');
    }
}

$comments = new Comment();
$comments= $comments->where('page_id',$id)->with('page')->get();

I need comments for the current page, pages that have the current page as parent and I want all the data from the pages table to come along with the comments so I could print out the page_id/title whatever next to each comment.

A: I haven't tested this, but it theory Laravel should parse nested relations like so:
Page::where('page_id',$id)->with('comments','parent.comments')->get();

That's assuming you have a 'parent' relationship on the Page model.
public function parent()
{
    return $this->hasOne('Page','parent_id');
}


text:
Q: How can you programmatically get the endpoint value of the root domain for an S3 Bucket (static website) that was assigned by AWS via the SDK? For example: example.com.s3-website-us-east-1.amazonaws.com?

How can I get this value programmatically via the SDK?  I can't seem to find it:
link to docs:  http://docs.aws.amazon.com/sdkforruby/api/Aws/S3.html

A: The value doesn't appear to be exposed by the S3 API, itself.
It is, however, easily derived from the bucket location, which is accessible via the S3 REST API, though it isn't obvious from skimming the docs whether this is implemented in the Ruby SDK, either, in spite of its presence in the underlying API. I didn't find it.
But the web site endpoints are always in this form:
${bucket}.s3-website-${region}.amazonaws.com

In us-east-1, as shown in the screen shot, the endpoint for a bucket named example.com fits this pattern, example.com.s3-website-us-east-1.amazonaws.com.
http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region


text:
Q: How do you airdrop ERC20 tokens to certain NFT holders from a smart contract? How do you airdrop ERC20 tokens to certain holders of an NFT all from a smart contract, let's say out of the 10k holders I only want to airdrop to NFT's from 1 to 1k
I can't find answers anywhere

A: You can't find answer anywhere because it's a custom logic. You have to implement this in your contract.
Tips:

*

*Connect you ERC20 and NFT contract to you new contract

*You can get the owner by using ownerOf function from NFT contract.

*Send bulk ERC20 transfer like here


text:
Q: How many unique domains can I added to the Authorized Javascript Origins on Google Cloud Platform OAuth2.0? I have 100+ websites that will be using Sign-in with Google (Google Identity), and I want to know is it possible to add 100+ unique domains on the Authorized Javascript Origins of OAuth2.0?
I have read the rules on the doc - https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow#origin-validation
But nothing mention about it, if you any of you have experienced this?


text:
Q: Client side validation not working using validate() I am doing validation inside validate() method.
public void validate(){
    if(continent.equals("-1")){
        HttpServletRequest request=ServletActionContext.getRequest();
        HttpSession session=request.getSession();
        String s=(String)session.getAttribute("operation");
        if(s.equals("edit"))
                edit();
        else if(s.equals("add"))
                add();
        addFieldError( "Continent", "Continent must be selected");
    }
}

And in jsp(view) added form attribute validate=true
<s:form action="add" name="aaa" cssClass="yy" method="post" validate="true">
        <s:textfield name="Code" label="Code" readonly="false" cssClass="defaultTextBox"/>
        <s:textfield name="Name" label="Name" cssClass="defaultTextBox"/>
        <s:select name="Continent" label="Continent" headerKey="-1" headerValue="Select" list="continentlist" cssClass="defaultTextBox"/>
        <s:textfield name="IndepYear" label="Independance Year" cssClass="defaultTextBox" />
        <s:submit value="Save" cssClass="login login-submit" theme="simple"/>
</s:form>

But only server side validation is working. My question is -->is it not possible to add client side validation using validate() method?

A: In Struts 2, Client Side Validation has different meanings, and totally depends on the type of theme you are using.

*

*With XHTML (default) and CSS XHTML, you can use the

*

*Pure JavaScript Client Side Validation
that is totally client side, Javascript based and doesn't communicate with the server.

*With the AJAX theme instead, you can run the

*

*AJAX Client Side Validation
that will contact the server, running the whole validation Stack, and (to answer your question) running your validate() methods too.

I personally prefer to use the SIMPLE theme, completely handling the HTML, the CSS and the JavaScript on my own.
Since the server-side validation is mandatory, the client-side validation is to be considered just a surplus, positive for making the page more user-friendly, and to reduce the network traffic in high users environment (you block unsuccessfull - but legit - requests before they go through the wire :)
Consider using HTML5 types with fallback on jQuery, especially if you are targeting the mobile.

A: actually you shouldn't mix up server side and client side code.
validate method can be invoked only in server side... So there is no way to use this method on client side.
You need to write your own JS side validation as the same as server side validation.

A: It is possible to perform AJAX validation using your server side code using struts2-jquery plugin , as shown in the Showcase under:

*

*Form Forms with Validation

*Form Forms with Custome Validation
The example that might interest you more is Form Submit without AJAX.


text:
Q: How to initialize value based on ajax response? I need to create a checkbox that will be checked/unchecked depending on the value of a parameter coming from the database.
I'm not able to load that value when I'm rendering the page, so the idea is: render the page, "tell" the checkbox to "ask" the server what is the current value of the parameter and then check/uncheck the checkbox depending on the response. Then, if the user checks/unchecks the checkbox, make a new Ajax request to update the value in the database.
I wrote some code (I'm new in Vuejs, so for sure I'm doing something wrong):
var vm = new Vue({
    el: '#root',
    computed: {
        checked() {
            return this.initialize()
        },
        value() {
            return this.checked
        }
    },
    watch: {
        checked() {
            alert('watcher')
            this.update();
        }
    },
    methods: {
        initialize(){
            // Just pretending an initial value
            var randomBoolean = Math.random() >= 0.5;
            alert('Ajax request here to initialize it as ' + (randomBoolean ? 'checked' : 'unchecked'));
            return randomBoolean;
        },
        update(){
            alert('ajax request here to set it to ' + this.value)
        }
    }
});

You can check and run the code here: https://jsfiddle.net/hyn9Lcv2/
Basically it works to initialize the checkbox, but then it fails to update. If you check the console, there is this error:
[Vue warn]: Computed property "checked" was assigned to but it has no setter.

A: First have you thought of using the created() hook from the vue instance instead of watcher?
It's recommended and will execute the code as soon as the component is created.
From the doc:
    new Vue({
      data: {
        a: 1
      },
      created: function () {
        //Ajax call:
         //onsuccess(response){
           this.a = reponse.data.a
         }
      }
   })

in the created hook you can do your ajax call, (axios is good library for that, worth checking it out: https://github.com/axios/axios ).
Then from your ajax response you can link the desired value to your checkbox by assigning it to a variable in the data object of the instance (in our case 'a')
Then bind it to your checkbox with the v-model like this:
<input
  type="checkbox"
  v-model="a">

I recommend to check the vue doc for more info on biding: https://v2.vuejs.org/v2/guide/forms.html#Checkbox-1
Hope it helps.

A: Just add bind click event

  <input id="check" type="checkbox" name="active" v-model="checked" @click="update">
  Click me

A: You need to fetch the database value when the component is created or mounted.
You then need to bind your checkbox with the initialized data.
Finally you need to watch the data to send an update to the database.
  var vm = new Vue({
  el: '#root',
  data: {
    //Your data
    checked: null
  },
  // Function where you are going to fetch your data
  mounted: function () {
    console.log("Ajax call to initialize");
    this.checked = Math.random() >= 0.5;
  },
  watch: {
    // Watcher to save your data in the database
    checked: function(newValue, oldValue){
        if (oldValue === null) { return; } // to not make an useless update when data has been fetched
        console.log("Ajax call to update value " + newValue);
    }
  }
});

  <input id="check" type="checkbox" name="active" v-model="checked" :disabled="checked === null">
  Click me

To fetch your data you can use for example Axios that works great with Vue.
To know more about life cycle of a component (to know if you should do the fetching at created or mounted) : https://v2.vuejs.org/v2/guide/instance.html


text:
Q: NPM script that runs command for each file in folder on Windows? I currently have this pretty npm script that runs the electron command on each file in a folder:
"test": "electron . --input './test/line.svg' --output './test' --headless && electron . --input './test/script.svg' --output './test' --headless && electron . --input './test/xlink.svg' --output './test' --headless && electron . --input './test/multitransform.svg' --output './test' --headless",

Is it possible to rewrite this script as a loop?
I have found scripts that work on Linux, but haven't found any solution for Windows.

A: One of the options is to use a premade NPM package like this.


text:
Q: UITableViewCell: dequeueReusableCellWithIdentifier: Change button background per cell on a certain action I have table view that rendering cells. I created the cell once and reuse it. In each cell there is a button to do vote action for a place. On the vote action I want to change the background image of the button. When I click on the button in a certain cell the background image changes, but when I scroll down I find another button with the changed background image. I believe that the problem is because I'm using dequeueReusableCellWithIdentifier but I can't find a way to solve this problem.
Here is my code:
// .h file

@interface VotePlaceView : UIView < UITableViewDataSource, UITableViewDelegate>
{
    VotePlaceView *votePlaceCell;

}

and in the implementation file
// .m File
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"votePlaceCell"];

    if (cell)
    {
        votePlaceCell = (VotePlaceView*)[cell viewWithTag:10];
    }

    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"votePlaceCell"];

        //GlobalObjects is a customised thing for me to load the cell in different languages
        votePlaceCell = [[GlobalObjects loadNibNamed:@"votePlaceCell" owner:self options:nil] objectAtIndex:0];

        votePlaceCell.tag = 10;
        [cell addSubview:votePlaceCell];

    }

        .
        . //Fill data in the cell
        .

    //This gives different IDs, no ID like the others (unique ID)
    NSLog(@"ID %d", [[[self.votePlacesResults objectAtIndex:indexPath.row] valueForKey:@"id"] intValue]);

    UIButton* voteButton = (UIButton*)[votePlaceCell viewWithTag:20];

    voteButton.tag = [[[self.votePlacesResults objectAtIndex:indexPath.row] valueForKey:@"id"] intValue];

    return cell;
}

-(IBAction)votePlace:(UIButton *)sender
{
     // I tried two ways to achieve my point with no luck
    //Selected case give the new background image

    //THE FIRST WAY
    sender.selected = YES;

    //OR THE SECOND WAY
    UIButton* newVotePlace;
    newVotePlace = (UIButton*)[[sender superview] viewWithTag:sender.tag];
    newVotePlace.selected = YES;
}

Any idea?
The Solution
@Akhilrajtr's answer solved my problem, after I made some changes to his answer. Here is the solution, in case if anyone faced the same problem.
Instead of using a UIButton, I used UIButton and UIImageView. I put the UIImageView behind the UIButton and I give the UIImageView two images in the default case and in the highlighted case. I cleared the background image of the UIButton and then followed the accepted answer as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

      .
      .

    int placeId = [[[self.votePlacesResults objectAtIndex:indexPath.row] valueForKey:@"id"] intValue];

    UIButton* voteButton = (UIButton*)[votePlaceCell viewWithTag:20];
    if (!voteButton) {
        voteButton = (UIButton*)[votePlaceCell viewWithTag:placeId];
    }
    voteButton.tag = [[[self.votePlacesResults objectAtIndex:indexPath.row] valueForKey:@"id"] intValue];
    if ([selectedIdArray containsObject:[[self.votePlacesResults objectAtIndex:indexPath.row] valueForKey:@"id"]]) {

        UIImageView* voteImage;
        voteImage = (UIImageView*)[votePlaceCell viewWithTag:11];
        voteImage.highlighted = YES;
    } else {
        UIImageView* voteImage;
        voteImage = (UIImageView*)[votePlaceCell viewWithTag:11];
        voteImage.highlighted = NO;
        voteButton.selected = NO;
    }

    return cell;

}

-(IBAction)votePlace:(UIButton *)sender
{

    [selectedIdArray addObject:[NSNumber numberWithInt:sender.tag]];

    UIImageView* voteImage;
    voteImage = (UIImageView*)[[sender superview] viewWithTag:11];
    voteImage.highlighted = YES;
}

A: You need to store an array containing information about the background for each cell, and set the background for each cell in cellForRowAtIndexPath.
As you're using selected on the button, create an NSMutableArray with as many entries as the cells, and instead of setting the button itself to selected, change the bool on the selected index of the array, then you can set selected dependent on the value of the desired index of NSMutableArray in cellForRowAtIndexPath.

A: Try this,
Create a NSMutableArray *selectedIdArray (don't forget to instatiate selectedIdArray in viewDidLoad:) to store selected ID's , and in cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     .
     .
     //Other codes
     .
     .

     NSLog(@"ID %d", [[[self.votePlacesResults objectAtIndex:indexPath.row] valueForKey:@"id"] intValue]);
     int placeId = [[[self.votePlacesResults objectAtIndex:indexPath.row] valueForKey:@"id"] intValue];
     UIButton* voteButton = (UIButton*)[votePlaceCell viewWithTag:20];
     if (!voteButton) {
          voteButton = (UIButton*)[votePlaceCell viewWithTag:placeId];
     }
     voteButton.tag = [[[self.votePlacesResults objectAtIndex:indexPath.row] valueForKey:@"id"] intValue];
     if ([selectedIdArray containsObject:[NSNumber numberWithInt:placeId]) {
          voteButton.selected = YES;
     } else {
          voteButton.selected = NO;
     }
     return cell;
}

and in
-(IBAction)votePlace:(UIButton *)sender
{
     [selectedIdArray addObject:[NSNumber numberWithInt:sender.tag]];
     sender.selected = YES;
}


text:
Q: Weird behavior of flutter and dart commands in PowerShell and CMD I'm relatively new to Flutter but I already have developed and finished some Apps in Flutter.
Recently I noticed a weird behavior of commands with the keywords "dart" or "flutter" in it.
Here is an example:
I was trying to migrate an existing project to the new dart null-safety and typed the command dart migrate into my Visual-Studio-Code Terminal.
I was expecting an output like Migrating C:\.... as a response but instead got these three lines:
The command "git" is either misspelled or could not be found.
Building flutter tool...
Running pub upgrade...

and then the expected output:
Migrating C:\<project path>...

and so on.
So basically the commands work as they would normally do but I get these three lines before the output everytime. And it's not only with this command. Also basic commands like dart help or flutter doctor will get these three lines.
I don't know what I am doing wrong. I uninstalled Flutter and also removed it from the PATH and then reinstalled it freshly but it's still the same. I also searched the web but didn't found anyone who has the same problem.
Any help and explanation would be great. Thank you for your time :)

A: I think I know where the problem is. I ran the commands directly when I opened PowerShell. But the directory was something like C:\Windows\ and then it won't work.
After I did cd C:\Users\User all commands will work as expected.
I was just thinking that it doesn't matter from where I run dartand fluttercommands obviously you have to be in your user directory that they will work properly.


text:
Q: Как заставить IE игнорировать участок кода JS? Есть код:
  const links = document.querySelectorAll('.nav-link');
  const sections = [... document.querySelectorAll('.forJS')];
  const callback = (entries) => {
    links.forEach((link) => link.classList.remove('active'));
    const elem = entries.find((entry) => entry.isIntersecting);
    if (elem) {
      const index = sections.findIndex((section) => section === elem.target);
      links[index].classList.add('active');
    }
  }

  let observer = new IntersectionObserver(callback, {
    rootMargin: '0px',
    threshold: 0.5
  });

  sections.forEach((section) => observer.observe(section));

IE ругается на вторую строчку кода(SCRIPT1002: Синтаксическая ошибка), подcвечиваются квадратные скобки [], затем еще как какую то (если удалить ту на которую он ругался до этого) и т.д. Как можно заставить его игнорировать этот участок кода? Пытался делать так:
const isIE = /*@cc_on!@*/false   || !!document.documentMode;//Определяем IE ли это
if(!isIE){//Если не IE выполняем участок кода

  ...Весь код...

};

Что можно сделать еще?

A: Где-то, когда-то нашел - выручает
    function browserCheck() {
      const ua = navigator.userAgent.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
      let browser = '';
      if (navigator.userAgent.match(/Edge/i) || navigator.userAgent.match(/Trident.*rv[ :]*11\./i)) {
        browser = 'msie';
      } else {
        browser = ua[1].toLowerCase();
      }
      document.body.classList.add(browser);
      return browser;
    }

A: Если вы используете php, можно сделать так. Выносим этот код, на который IE ругается в отдельный файл. Затем следующий скрипт на php, который определяет, является ли текущий браузер IE и затем обычный условный оператор. Если у пользователя не IE загружаем скрипт, иначе нет.
$ie = htmlentities($_SERVER['HTTP_USER_AGENT'], ENT_QUOTES, 'UTF-8');
<?php if (preg_match('~MSIE|Internet Explorer~i', $ie) || (strpos($ie, 'Trident/7.0') == false && strpos($ie, 'rv:11.0') == false)) {
?>
<script src="js/ourScript.js"></script>
<?php };?>

UPD. Можно и без php, но опять таки в отдельный файл наш скрипт и таким образом подключаем:
<!--[if !IE]-->
 <script src="js/ourScript.js"></script>
<!--[endif]-->


text:
Q: Transparent with shading effect in a TextView I have a textView in my layout I want it to show whats behind it but still with a shading effect.
Any ideas?

A: This shadow in textView and also set background Transparent.
<TextView android:layout_width="fill_parent" android:shadowRadius="2"  android:shadowColor="#0000ff"
              android:shadowDx="2"
              android:shadowDy="4" android:id="@+id/EditText01" android:layout_height="wrap_content" />

Thanks.


text:
Q: JSONParsingException - Invalid Token I have a method that when I send a String (which is Standard JSON output) to it it parses it and returns the section I want. It works for the most part but if the String has a low value such as 5.8244367E-4 in it it will fail with the error:

com.codesnippets4all.json.exceptions.JSONParsingException: @Key-Heirarchy::root/resultList/result[5]/  @Key::PercentMisses Invalid VALUE_TOKEN...@Position::282

public String parse(String json, String key) {
    JsonParserFactory factory = JsonParserFactory.getInstance();
    JSONParser parser = factory.newJsonParser();
    Map<?, ?> jsonMap = parser.parseJson(json);
    String parsed = jsonMap.get("result").toString();
    return parsed;
}

Is there any obvious way to get around this or else an alternate approach I can take to get the same result?
Thanks.


text:
Q: How to get Superscript over subscript in XML? I'm coding a program for Android, and I have to display some text with chemistry notation.
Using regular subscripting works when it is defined as a String resource, like this:
<string name="OH">OH-, [mg/l]</string>

This will show up as "OH-, [mg/l]".
However, I need the sign for Carbonate where I've tried this:
<string name="CO23">CO2-3, [mg/l]</string>

Which looks like this: CO2-3
I need the 3 to be under the 2-..


text:
Q: break down pandas dataframe column into multiple columns in a single df I have a dataframe with index, features and time data, but the time data is in one column like this:
id date feature
1  date1 feature1
2  date2 feature2
1  date2 feature3
I want to transform it into this:
id date feature
1  date1 feature1 date2 feature3
2  date2 feature2 NaN    NaN
Already did this by explicitly defining dataframes, queries and joins, but failed to find a dynamic way. What I wrote:
df = pd.read_excel('some path')

import pandas as pd

list1 = []
list2 = []
list3 = []

def placeholder_lists():
    for i in range(7):
        if len(str(i)) == 1:
            if i not in [8,9]:
                i = "0"+str(i+3)
            else:
                i = str(i+3)
        else:
            i = str(i+3)
        list1.append(i)

    for l in range(7):
        if len(str(l)) == 1:
            if l not in [10,9]:
                l = "0"+str(l+2)
            else:
                l = str(l+2)
        else:
            l = str(l+2)
        list2.append(l)

    for g in range(7):
        if len(str(g)) == 1:
            if g not in [9,8]:
                g = "0"+str(g+1)
            else:
                g = str(g+1)
        else:
            g = str(g+1)
        list3.append(g)

placeholder_lists()

for m,n,u in zip(list1,list2, list3):
    df01 = df.query('dw_creation_date == "01-AUG-17" ')
    e = str(u)+"-AUG-17"

    currentdf = df.query('dw_creation_date == "%s"' % e)

    if 1 == "01":
        currentdf = df01
    first = "df"+m
    second = "df"+n
    listie = range(50)
    first = second.join(currentdf.set_index('unique_identifier'), on='unique_identifier', lsuffix = listie[n])

... And the error I get:
first = second.join(currentdf.set_index('unique_identifier'), lsuffix = listie[n])

TypeError: join() takes no keyword arguments
Any ideas?

A: cols = ['id','date','feature']
df = pd.DataFrame({'date': {0: 'date1', 1: 'date2', 2: 'date2'},
                   'id': {0: 1, 1: 2, 2: 1},
                  'feature': {0: 'feature1', 1: 'feature2', 2: 'feature3'}}, columns=cols)

print (df)
   id   date   feature
0   1  date1  feature1
1   2  date2  feature2
2   1  date2  feature3

You can groupby by id and apply new df.
Then reshape by unstack and sort columns by sort_index in second level of Multiindex.
Last flattening Multiindex in columns and reset_index.
df = df.groupby('id')['date','feature'] \
       .apply(lambda x: pd.DataFrame(x.values, columns=['feature','date'])) \
       .unstack() \
       .sort_index(1, level=1)

print (df)
   feature      date feature      date
         0         0       1         1
id
1    date1  feature1   date2  feature3
2    date2  feature2    None      None

df.columns = ['{0[0]}_{0[1]}'.format(x)  for x in df.columns]
df = df.reset_index()
print (df)
   id feature_0    date_0 feature_1    date_1
0   1     date1  feature1     date2  feature3
1   2     date2  feature2      None      None


text:
Q: Cannot read properties of undefined (reading 'Weather') new to node and trying to run the strong soap sample from here ..
https://github.com/loopbackio/strong-soap/blob/master/example/weather.js
    soap.createClient(url, clientOptions, function(err, client) {
  //custom request header
  var customRequestHeader = {timeout: 5000};
  var options = {};
  //navigate to the correct operation in the client using [service][port][operation] since GetCityWeatherByZIP operation is used
  //by more than one port.
  var method = client['Weather']['WeatherSoap']['GetCityWeatherByZIP'];
  //this describes the entire WSDL in a tree form.
  var description = client.describe();
  //inspect GetCityWeatherByZIP operation
  var operation = description.Weather.WeatherSoap.GetCityWeatherByZIP;
  console.log('Invoking operation: ' + operation.name);

getting following error . is it because service is not available or something else?
TypeError: Cannot read properties of undefined (reading 'Weather')
from code line..
var method = client['Weather']['WeatherSoap']['GetCityWeatherByZIP'];


text:
Q: Question about upper bound chromatic number of triangle-free graphs on $n$ vertices I am reading a paper about Ramsey number. There is a statement as following:
It is known that $R(3,t)\le(1+\mathcal{o}(1))\frac{t^2}{\log t}.$ This upper bound easily gives an upper bound of $\chi(G_n^{(3)}),$ $$\max_{G_n^{(3)}}\chi(G_n^{(3)})\le (1+\mathcal{o}(1))2\sqrt{2}\sqrt{\frac{n}{\log n}}$$ where $\chi(G_n^{(3)})$ means a triangle-free graph on $n$ vertices.
The trivial upper bound of $\chi(G_n^{(3)})$ is we find independent number $\alpha(G_n^{(3)})$ (maximum size of independent sets), if we set $n=\frac{t^2}{\log t},$ then the independent number is at least $t$. Then the chromatic number is less than $n-t+1$ meaning that we can color the maximum independent set by 1 color and each remaining vertex by distinct color. But it seems not matched the upper bound given by the author. So I wonder why the upper bound of the chromatic number is true.

A: Let $f(t) = (1+o(1))\frac{t^2}{\log t}$ be our upper bound on $R(3,t)$, and let $g(n)$ be its inverse: $g(f(t))=t$. Some work yields the estimate $g(n) = (1+o(1))\sqrt{\frac12 n \log n}$.
The idea is that if $G$ is triangle-free on $n$ vertices, then it contains an independent set of size $g(n)$, and then once you remove that independent set (by assigning it a color), then you get a graph that's triangle-free on $n - g(n)$ vertices. So we can keep doing that repeatedly.
For a bound that probably won't get the right constant factor in the end, suppose we keep doing this until we are down to fewer than $\frac n2$ vertices. Then at each step, we got to remove at least $g(\frac n2)$ vertices, obtaining fewer than $\frac{n/2}{g(\frac n2)}$ independent sets. This gives us the recursion $$M(n) \le \frac{n/2}{g(\frac n2)} + M(\tfrac{n}{2})$$ where I define $M(n) = \displaystyle{\max_{G_n^{(3)}}\chi(G_n^{(3)})}.$ Note that $\frac{n/2}{g(\frac n2)} = (1+o(1))\sqrt{\frac{n}{\log n}}$. Therefore
$$M(\tfrac{n}{2}) \le (1+o(1)) C\sqrt{\frac{n/2}{\log (n/2)}} \implies M(\tfrac{n}{2}) \le (1 + o(1))\left(\frac{C}{\sqrt 2} + 1\right)\sqrt{\frac{n}{\log n}}$$ and by some mix of induction and asymptotic analysis we can get $C = 2 + \sqrt 2$.
I assume that doing this more carefully (for example, jumping from $n$ to $(1-\epsilon)n$ instead of all the way to $\frac n2$, and then taking $\epsilon \to 0$) improves the constant. Also, there's probably a better way to analyze this recursion, but you see how it gets us bounds on the order of $O(\frac{n}{g(n)})$.


text:
Q: Event handler on Excel.CalculationState starts calculating - Office js Currently the api supports an event handler (onCalculated) that is being fired when the calculation finishes but is there any way to detect when it actually started?
I have a task pane add-in and I would like to block the interaction while there is ongoing calculations but I'm struggling to detect when they started.
.

A: Thanks for your information. The Webadd-in is different from VSTO add-in, web-addin is running in different process, therefore all events that we provided in office.js are after event.
May I know what's your scenario? we would like to learn more information that you want to detect when they started.


text:
Q: How to simplify the IF statement in Python 3 I have the IF statement as follows:
...
if word.endswith('a') or word.endswith('e') or word.endswith('i') or word.endswith('o') or word.endswith('u'):
...

Here I had to use 4 ORs to cover all the circumstances. Is there anyway I can simplify this? I'm using Python 3.4.

A: Use any
>>> word = 'fa'
>>> any(word.endswith(i) for i in ['a', 'e', 'i', 'o', 'u'])
True
>>> word = 'fe'
>>> any(word.endswith(i) for i in ['a', 'e', 'i', 'o', 'u'])
True
>>>

A: Try
if word[-1] in ['a','e','i','o','u']:

where word[-1] is the last letter

A: Simply:
>>> "apple"[-1] in 'aeiou'
True
>>> "boy"[-1] in 'aeiou'
False

A: word.endswith(c) is just the same as word[-1] == c so:
VOWELS = 'aeiou'

if word[-1] in VOWELS:
    print('{} ends with a vowel'.format(word)

will do. There is no need to construct a list, tuple, set, or other data structure: just test membership in a string, in this case VOWELS.


text:
Q: pandas removes rows with nan in df I have a df that contains nan,
A
nan
nan
nan
nan
2017
2018

I tried to remove all the nan rows in df,
df = df.loc[df['A'].notnull()]

but df still contains those nan values for column 'A' after the above code. The dtype of 'A' is object.
I am wondering how to fix it. The thing is I need to define multiple conditions to filter the df, and df['A'].notnull() is one of them. Don't know why it doesn't work.

A: Please provide a reproducible example. As such this works:
import pandas as pd
import numpy as np

df = pd.DataFrame([[np.nan], [np.nan], [2017], [2018]], columns=['A'])
df = df[df['A'].notnull()]

df2 = pd.DataFrame([['nan'], ['nan'], [2017], [2018]], columns=['A'])
df2 = df2.replace('nan', np.nan)
df2 = df2[df2['A'].notnull()]

# output [df or df2]
# A
# 2017.0
# 2018.0


text:
Q: How to remove empty lines in XSLT to CSV output I have XML data which I have transformed using XSLT to output csv formatted text.  My XSLT contains a <xsl:if test> clause to filter the result from the larger dataset of the input XML.  This works but every line that is filtered out of the input is displayed as an empty line in the output.
I have tried <xsl:strip-space elements="*" /> and <xsl:template match="text()" /> but neither remove the empty lines.
A sample of my XML:
<?xml version="1.0" encoding="UTF-8"?>
<session_list xmlns="http://www.networkstreaming.com/namespaces/API" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <session lsid="fef672741e025ffda1acb3041f09252d">
   <session_type>support</session_type>
   <lseq>2899</lseq>
   <start_time timestamp="1290027608">2010-11-17T16:00:08-05:00</start_time>
   <end_time timestamp="1290027616">2010-11-17T16:00:16-05:00</end_time>
   <duration>00:00:08</duration>

   <public_site id="1">Default</public_site>
   <external_key></external_key>
   <session_chat_view_url>https://mysite.com/session_download.ns?lsid=l%3Dfef672741e025ffda1acb3041f09252d%3Bh%3D9bd6081f0b7fee08dcc32a58ef4cb54c7a0e233d%3Bt%3Dsd%3Bm%3Dchat&dl_action=chat&view=1&sessionType=sd</session_chat_view_url>
   <session_chat_download_url>https://mysite.com/session_download.ns?lsid=l%3Dfef672741e025ffda1acb3041f09252d%3Bh%3D9bd6081f0b7fee08dcc32a58ef4cb54c7a0e233d%3Bt%3Dsd%3Bm%3Dchat&dl_action=chat&sessionType=sd</session_chat_download_url>
   <file_transfer_count>0</file_transfer_count>

   <primary_customer gsnumber="3">Smith, John</primary_customer>
   <customer_list>
     <customer gsnumber="3">
     <username>Smith, John</username>
     <public_ip>xxx.xxx.xxx.xxx</public_ip>
     <private_ip>xxx.xxx.xxx.xxx</private_ip>
     <hostname>DESKTOP</hostname>

     <os>Windows 7 Enterprise x64 Edition (Build 7600)</os>
     <primary_cust>1</primary_cust>
      <info>
       <name></name>
       <company></company>
       <company_code></company_code>
       <issue></issue>
       <details></details>
      </info>
     </customer>
   </customer_list>
  ...etc...
 </session>
</session_list>

My XSLT:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:bg="http://www.networkstreaming.com/namespaces/API" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<xsl:output method="text"/>
<xsl:template match="/*">
<xsl:text>Session ID,</xsl:text>
<xsl:text>Start Time,</xsl:text>
<xsl:text>Duration,</xsl:text>
<xsl:text>Public Site,</xsl:text>
<xsl:text>Remedy Ticket Number,</xsl:text>
<xsl:text>Customer's Name,</xsl:text>
<xsl:text>Customer's Operating System,</xsl:text>
<xsl:text>Representative's Name</xsl:text>
<xsl:text>
</xsl:text>
<xsl:apply-templates/>
</xsl:template>

<xsl:template match="bg:session_list">
<xsl:apply-templates select="bg:session"/>
</xsl:template>

<xsl:template match="bg:session">
<xsl:if test="contains(bg:customer_list/bg:customer/bg:os,'Click-To-Chat')">
<xsl:value-of select="bg:lseq"/>,<xsl:text/>
<xsl:value-of select="bg:start_time"/>,<xsl:text/>
<xsl:value-of select="bg:duration"/>,<xsl:text/>
<xsl:value-of select="bg:public_site"/>,<xsl:text/>
<xsl:value-of select="bg:external_key"/>,<xsl:text/>
<xsl:value-of select="bg:primary_customer"/>,<xsl:text/>
<xsl:value-of select="bg:customer_list/bg:customer/bg:os"/>,<xsl:text/>
<xsl:value-of select="bg:primary_rep"/>
</xsl:if>
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>

A sample of the output:
Session ID,Start Time,Duration,Public Site,Remedy Ticket Number,Customer's Name,Customer's Operating System,Representative's Name

6488,2011-03-14T09:17:13-04:00,00:00:06,Default,,User One,Windows® (x86) Click-To-Chat,Rep1
6489,2011-03-14T09:44:50-04:00,00:39:58,Default,,Nate,Windows® (x86) Click-To-Chat,Rep1

6494,2011-03-14T10:25:23-04:00,00:03:29,Default,,User TEST,Windows® (x86) Click-To-Chat,Rep1

6498,2011-03-14T11:01:36-04:00,,Default,,User Two,Windows® (x86) Click-To-Chat,Diane

Each of the lines between the printed lines is data that was filtered out because it didn't pass the <xsl:if test="contains(bg:customer_list/bg:customer/bg:os,'Click-To-Chat')"> but the empty lines are still printed.  This output doesn't look very good when opened in excel.
Does anyone have any ideas how to remove them?
Thanks!

A: Have you tried putting the <xsl:text>
</xsl:text> line inside the xsl:if? This is the bit that puts a newline, so at the moment you are writing one even if you don't write the line.


text:
Q: kaminari undefined method `page' I've been trying to play around with the Kaminari gem for pagination, but am running into problems.
I've got a simple starter project with a simple model:
class Position < ActiveRecord::Base
  validates_presence_of :name
end

I'm running with ruby 1.9.2 and rails 3.0.5 on Ubuntu 10.04. I've installed kaminari (0.10.4).
From what I understand, I should be able to execute Position.order("name").page(1), but when I do so, I get the following:
ruby-1.9.2-p0 > Position.order("name").page(1)
NoMethodError: undefined method `page' for #<ActiveRecord::Relation:0xaacab34>
    from /home/bob/.rvm/gems/ruby-1.9.2-p0@talentskout/gems/activerecord-3.0.5/lib/active_record/relation.rb:371:in `method_missing'
    from (irb):2
    from /home/bob/.rvm/gems/ruby-1.9.2-p0@talentskout/gems/railties-3.0.5/lib/rails/commands/console.rb:44:in `start'
    from /home/bob/.rvm/gems/ruby-1.9.2-p0@talentskout/gems/railties-3.0.5/lib/rails/commands/console.rb:8:in `start'
    from /home/bob/.rvm/gems/ruby-1.9.2-p0@talentskout/gems/railties-3.0.5/lib/rails/commands.rb:23:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

This seems about as simple a scenario as I can get. Any ideas would be greatly appreciated.
Thanks.

A: I figured out my problem, and it have nothing to do with the Kaminari gem per se.
In my Gemfile, I had put the gem 'kaminari' clause under my group :test section by mistake. So it wasn't loading in my development environment. Silly mistake.

A: Rails noob here: had precisely the same issue but for a different reason - I found I had to restart the server after adding the kaminari gem and running bundle install. Just mentioning it in case someone else has the same problem!

A: I'm also a Rails noob and had the same error. I could solve the problem by changing Model.all to Model.order("id").


text:
Q: Replace the special characters with the near matching type-able characters I would like to replace all the special characters such as apostrophe(not single quote), double quote and any other characters(which looks differently on ms word) with single quote, double quote but not limited only these two.
I may replace it by manually using regex or string's replace by finding the unicode value of these characters like re.sub("\u0XXXX", "'", "<apostrophe>")
But I believe there may be a built in function which will replace if there is a exact match and keep as is if it does not have like in PHP iconv("ISO-XXX", "UTF-8//TRANSLIT//IGNORE").
eg: ' to ', ˮ - " any such characters


text:
Q: How can I get request url from retrofit with rx ? - Android MinSdkVersion of my application is 17 and targetSdkVersion is 25 .In this application I am connecting to service with Rx and retrofit, this code don't work on api 17 I can't connect to webService, bellow is my code :
My RetrofitApi.java :
public class RetrofitApi {
    private static PublicApi retrofit = null;

    public static PublicApi getClient(String url) {
        retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build().create(PublicApi.class);
        return retrofit;
    }
}

My PublicApi.java :
public interface PublicApi {

    @GET("/web_service/mobile/rest")
    Observable<LastNews> lastNews(@Query("function") String function);
}

And  :
PublicApi publicApi = RetrofitApi.getClient("https://xxx.xxx.xxx/");
CompositeDisposable mCompositeDisposable = new CompositeDisposable();
mCompositeDisposable.add(publicApi.lastNews("getLastNews")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(this::responseLastNews, this::errorLastNews));
private void responseLastNews(LastNews lastNewses){
}
private void errorLastNews(Throwable error) {
    Log.i("LOG", error.getMessage());
}

When I tested on API 17 get me error and don't connect to server.Told me :
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

A: Your base URL (**https**://xxx.xxx.xxx/) is secured with SSL, you need to implement SSL connection to get it working.
Please refer this link