text:
Q: List data is disappear I'm not sure its a problem or not, i use scrapy crawl data and save it.
I can save my list data as well. For example movieDate

Here is my way:
def parse(self, response):

# i use yield Request to another function prase_page
i = 1000
        dataLen = len(response.xpath('//div[@class="release_foto"]'))
        photoNodes = response.xpath('//div[@class="release_foto"]')
        for photoNode in photoNodes:
            contentHref = photoNode.xpath('.//a/@href').extract_first()
            yield Request(contentHref, callback=self.parse_page, priority = i, dont_filter=True)
            i -= 1
            photoHref = photoNode.xpath('.//a/img/@src').extract_first()
            moviePhotoArray.append(photoHref)

        detailDict.update({
             'cnName': cnNameArray,
             'enName': enNameArray,
             'movieContent': movieContentArray,
             'versionType': versionTypeArray,
             'movieStyle': movieStyleArray,
             'releasedTime': releasedTimeArray,
             'moviePhoto': moviePhotoArray,
             'movieDate': movieDateArray,
             'movieTime': movieTimeArray,
             'movieStills': movieStillsArray,
             'movieActorCn': movieActorCnArray,
             'imdbScore': imdbArray,
             'rottenScore': rottenArray,
             'videoId': videoIdArray,
             'movieActorPhoto': movieActorPhotoArray})
        print 'Test enNameArray=>'
        print ', '.join(enNameArray)
        print 'Test movieDateArray=>'
        print ', '.join(movieDateArray)

I found that i can't get the movieDateArray value. Its print empty although when i save it to database it has value.
Here is my print movieDateArray is empty:
Test enNameArray=>
Pacific Rim Uprising, Tomb Raider, Ready Player One
Test movieDateArray=>

I find my global list all of under the function is empty:
def parse_page(self, response):

        global movieContentArray, countLen, dataLen
        global movieDateArray, movieTimeArray, movieStillsArray, movieStyleArray, movieActorCnArray, movieActorPhotoArray
        movieContent = response.xpath('//div[@class="gray_infobox_inner"]/span/text()').extract_first()
        movieDate = response.xpath('//*[@class="movie_intro_info_r"]/span/text()')[0].extract()
        movieTime = response.xpath('//*[@class="movie_intro_info_r"]/span/text()')[1].extract()
        movieStills = response.xpath('//ul[@class="trailer_list imglist"]//div[@class="foto"]/img/@src').extract()
        movieStyle = response.xpath('//div[@class="level_name_box"]//div[@class="level_name"]/a/text()').extract()
        movieActorCn = response.xpath('//ul[@class="trailer_list alist starlist"]/li/a//div[@class="fotoinner"]/img/@title').extract()
        movieActorPhoto = response.xpath('//ul[@class="trailer_list alist starlist"]/li/a//div[@class="fotoinner"]/img/@src').extract()
        movieContentArray.append(movieContent)
        movieDateArray.append(movieDate)
        movieTimeArray.append(movieTime)
        movieStillsArray.append(movieStills)
        movieStyleArray.append(movieStyle)
        movieActorCnArray.append(movieActorCn)
        movieActorPhotoArray.append(movieActorPhoto)
        # i can print the value here
        print 'Test=>inside movieDateArray=>',movieDateArray

        countLen += 1
        if countLen == dataLen:
            yield tainan

I have no idea why the list movieDateArray is empty. Because i save the list to database it is not empty, but when i try to print it or for in it is empty.
It is so strange. Some one can tell me what step i miss it.  Thanks in advance.

A: I beleive the issue is that each time you call parse_page you define a new global variable called movieDateArray. Perhaps during the last call this variable is initialized to None and that's why you don't print anything. Try debugging by printing movieDateArray in each loop iteration


text:
Q: How to migrate containerized app to Visual Studio? Is there a way to run and debug a solution with custom pre-existing docker-compose and DOCKERFILEs when migrating to Visual Studio?
I'll try to elaborate as requested:
I'm working on a .Net Core project with multiple services (web APIs), each one with a respective DOCKERFILE. The containers and their dependencies are built and run via a compose file which is used for CD purposes and is optimized for our needs, but I can't use it together with VS2019 because the IDE doesn't recognize these files, and forces the creation of a new docker-compose (in the solutions' root folder) and DOCKERFILE when I attempt to add orchestrator support to any of the projects. These behavior results in the error message "the file ./docker-compose.yml already exists" and the creation of the docker-compose project fails (I'm following the instructions from here: https://learn.microsoft.com/en-us/visualstudio/containers/tutorial-multicontainer?view=vs-2019)
I don't want pollute my repository with the files generated by Visual Studio, but the naming convention used by the IDE makes ignoring them not as simple as it should (IMHO).
So, my question is, is it possible to use a custom docker-compose and DOCKERFILEs when adding container orchestrator support to my projects in Visual Studio?

redpajama_set_name: RedPajamaStackExchange


text:
Q: ArgumentError: Missing required arguments: aws_access_key_id, aws_secret_access_key When deploying to Heroku Despite following this post, and finding similar answers here, and here, I still am getting

ArgumentError: Missing required arguments: aws_access_key_id, aws_secret_access_key`

when I try deploying to Heroku using Carrierwave and Fog gems to upload images to Amazon S3.
/config/initializers/carrierwave.rb:
if Rails.env.production?
  CarrierWave.configure do |config|
    config.fog_credentials = {

      :provider              => 'AWS',
      :aws_access_key_id     => ENV['S3_ACCESS_KEY'],
      :aws_secret_access_key => ENV['S3_SECRET_KEY'],
      :region                => ENV['S3_REGION']
    }
    config.fog_directory     =  ENV['S3_BUCKET']
  end
end

And I set the Heroku config like this:
S3_ACCESS_KEY: ABCDEFGHIJKPMNOPQRS
S3_BUCKET:     mybucket12345
S3_REGION:     us-west-2
S3_SECRET_KEY: 1234567890ABCDEFGHIJKLMNOPQRSTUVWZYZ1234

Logs:
Running: rake assets:precompile
remote:        rake aborted!
remote:        ArgumentError: Missing required arguments: aws_access_key_id, aws_secret_access_key
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/fog-core-1.43.0/lib/fog/core/service.rb:244:in `validate_options'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/fog-core-1.43.0/lib/fog/core/service.rb:268:in `handle_settings'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/fog-core-1.43.0/lib/fog/core/service.rb:98:in `new'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/fog-core-1.43.0/lib/fog/core/services_mixin.rb:16:in `new'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/fog-core-1.43.0/lib/fog/storage.rb:27:in `new'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/carrierwave-0.11.2/lib/carrierwave/uploader/configuration.rb:83:in `eager_load_fog'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/carrierwave-0.11.2/lib/carrierwave/uploader/configuration.rb:96:in `fog_credentials='
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/config/initializers/carrierwave.rb:2:in `block in <top (required)>'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/carrierwave-0.11.2/lib/carrierwave/uploader/configuration.rb:118:in `configure'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/carrierwave-0.11.2/lib/carrierwave.rb:14:in `configure'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/config/initializers/carrierwave.rb:1:in `<top (required)>'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:287:in `load'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:287:in `block in load'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:259:in `load_dependency'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:287:in `load'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:648:in `block in load_config_initializer'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/notifications.rb:166:in `instrument'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:647:in `load_config_initializer'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:612:in `block (2 levels) in <class:Engine>'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:611:in `each'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:611:in `block in <class:Engine>'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:30:in `instance_exec'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:30:in `run'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:55:in `block in run_initializers'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:44:in `each'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:44:in `tsort_each_child'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:54:in `run_initializers'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/application.rb:352:in `initialize!'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/config/environment.rb:5:in `<top (required)>'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:293:in `require'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:293:in `block in require'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:259:in `load_dependency'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:293:in `require'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/application.rb:328:in `require_environment!'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/application.rb:448:in `block in run_tasks_blocks'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/sprockets-rails-3.2.0/lib/sprockets/rails/task.rb:62:in `block (2 levels) in define'
remote:        /tmp/build_d869b0ccafedcf0c55d666f657f499ac/vendor/bundle/ruby/2.2.0/gems/rake-11.3.0/exe/rake:27:in `<top (required)>'
remote:        Tasks: TOP => environment
remote:        (See full trace by running task with --trace)
remote:  !
remote:  !     Precompiling assets failed.
remote:  !
remote:  !     Push rejected, failed to compile Ruby app.
remote:
remote:  !     Push failed

A: Try:

*

*Add to your gemfile: gem "figaro"

*figaro heroku:set -e production

*rake figaro:heroku

*Push again to heroku


text:
Q: Using Fourier transform on a finite interval to prove a formula In the book Controllability of Partial Differential Equations by Enrique Zuazua page 110 I have found a problem  to prove the last equality in the last line formula $$\sum\limits_{n,m} {{a_n}{{\bar a}_m}K({\mu _n} - {\mu _m})}. $$
I tried to use the Fourier transform of $e^{ixt}$ in $S'(R)$ to prove it but I found $$\sum\limits_{n,m} {{a_n}{a_m}K({\mu _n} + {\mu _m})}. $$
(With plus sign).
Any Ideas? Thank you.

Define the function
  $$
         h
  \colon \mathbb{R} \to \mathbb{R},
  \quad  h(t)
  =      \begin{cases}
           \cos(t/2) & \text{if $|t| \leq \pi$}, \\
           0         & \text{if $|t| > \pi$}.
         \end{cases}
$$
  and let us compute its Fourier transform $K(\varphi)$,
  $$
    K(\varphi)
  = \int_{-\pi}^{\pi} h(t) e^{i t \varphi} \,\mathrm{d}t
  = \int_{-\infty}^\infty h(t) e^{i t \varphi} \,\mathrm{d}t
  = \frac{4 \cos \pi \varphi}{1 - 4 \varphi^2}.
$$
  On the other hand, since $0 \leq h(t) \leq 1$ for any $t \in [-\pi, \pi]$, we have that
  $$
  \int_{-\pi}^\pi \left| \sum_n a_n e^{i \mu_n t} \right|^2
  \,\mathrm{d}t
  \geq
  \int_{-\pi}^\pi h(t) \left| \sum_n a_n e^{i \mu_n t} \right|^2
  \,\mathrm{d}t
  =
  \sum_{n,m} a_n \overline{a}_m K(\mu_n - \mu_m)
  =
$$
(Original picture of the problem here.)

A: We have :
$$\int_{-\pi}^\pi h(t) \left\vert \sum_n a_n e^{i\phi_nt} \right\vert^2 dt=\int_{-\pi}^\pi h(t)  \sum_n a_n e^{i\phi_nt}  \overline{\sum_m a_m e^{i\phi_mt}}dt.$$
Since :
$$\sum_n a_n e^{i\phi_nt}  \overline{\sum_m a_m e^{i\phi_mt}}=\sum_{n,m} a_n \overline{a_m} e^{i(\phi_n-\phi_m)t}.$$
Then :
$$\int_{-\pi}^\pi h(t) \left\vert \sum_n a_n e^{i\phi_nt} \right\vert^2 dt=\sum_{n,m} a_n \overline{a_m}\int_{-\pi}^\pi h(t) e^{i(\phi_n-\phi_m)t}dt=\sum_{n,m} a_n \overline{a_m}K(\phi_n-\phi_m).$$


text:
Q: Electromagnetic energy density in a nonlinear medium The energy density associated with the electric field in a linear medium of permitivity  $ \epsilon $ is given as
$$
U = \frac{1}{2}\epsilon\left | E \right |^{2}
$$
As Robert Boyd mentions in the first chapter of Nonlinear Optics, the electric field energy density for a nonlinear medium takes a different form from this equation. It has the usual linear term as above,also terms for each of the harmonic frequency.
The equation is lengthy, but assuming a third order non-linearity, it's proportional to
$$
\vec{E}^*\cdot\vec P,
$$
where $\vec{E}$ and $\vec P$ are the electric field and polarization vectors at third harmonic frequency respectively. If $\vec{E}$ and $\vec P$ were directly proportional to each other with a real number then this term would be real which is required for a quantity like energy density.
However, for situations like meta-materials, we know that this is not the case. In such situations, how do we go about using this equation to get the real energy density?


text:
Q: SQL find records based on two columns Given a users table with primary key of id, I have a foreign table called friends which only has two fields (userid1, userid2). This allows us to create any kind of relationship between different users (one to many, one to one, etc). A user can appear in either column and both columns are equal. IOW, a single entry per relationship.
How can I pull all of the friends that a given user id has. Say Jonny, has 3 friends and his user id is 16... should my sql query look like this?
SELECT *
FROM   db.users
       JOIN db.friends
         ON db.users.id = db.friends.userid1
            AND db.users.id = 16

Hopefully, this is clear. Also, if possible, can I exclude Jonny from the result set?
This query, as listed gies me the following:
id      name    uuid                       birthday        userid1  userid2
16  jonny   ABCDEFGHIJKLMNOP    1967-04-27 01:00:00     1         2
16  jonny   ABCDEFGHIJKLMNOP    1967-04-27 01:00:00     1         3

This is pretty close, except I want his friends, not jonny

Thanks guys, so I got it to work thanks to you. Here is the final working query.
SELECT *
FROM db.users
WHERE db.users.id IN
(
  SELECT db.friends.userid2 as id FROM db.friends WHERE db.friends.userid1 = 16
    union
  SELECT db.friends.userid1 as id FROM db.friends WHERE db.friends.userid2 = 16
)

which gives me:
id      name    uuid                       birthday
2   robin   ABCDEFGHIJKLMNOP    1967-04-27 01:00:00
3   gary    ABCDEFGHIJKLMNOP    1967-04-27 01:00:00

A: You could do a sub query like:
SELECT *
FROM users
WHERE id IN
(
  SELECT userid2 as id FROM db.friends WHERE userid1 = 16
)

A: Add the condition for the user.id to your where clause at the end:
Select * From users
INNER JOIN friends on
users.id = friends.userid1
Where users.id = 16

Also, I would use an Inner Join which will return all records from users only where there is a match in friends

A: You should filter on the friends table, not the users table.
SELECT friends.*
FROM friends
INNER JOIN users
  ON friends.userid2 = users.id
WHERE friends.userid1 = 16

If you just need the friend ID's then there is not reason to join at all
SELECT userid2
FROM friends
WHERE userid1 = 16

A: You need a list of friends ids:
SELECT U
    FROM DB.USERS U
    WHERE U.ID IN ( SELECT F.USERID2 FROM DB.FRIENDS F WHERE F.USERID1 = 16)


text:
Q: Laravel problems with MCrypt I'm trying to install all the package's of a Laravel project on a Virtual Machine. I've installed everything but during the composer install action show me the error MCrypt PHP Exstension Required.
But.. Mcrypt is installed! I've also do this actions:
locate mcrypt.ini
locate mcrypt.so

and writed in mcrypt.ini the mcrypt.so php5 path.
so what contain now the mcrypt.ini file? just this text:
exstension=/usr/lib/20131226/mcrypt.so
also used: php5enmod mcrypt and service apache2 restart without any results..

A: Do you have enabled your mcrypt extension?
Try with this command, it will tell you all the php extensions you have installed and wich one of them is active and wich one is not
dpkg --get-selections | grep php
If mcrypt is not enabled then try again to enable it with
sudo php5enmod mcrypt


text:
Q: Pentaho Kettle Mapping with parameterized Table Input I am passing a value to the sub transformation, sub transformation takes the value fine as i have used java-script step to Alert it.
But i have a table input step in the sub transformation step, where i need to used the parent transformation value as a parameter to the TABLE INPUT step to run a query against it, but its not working, as the table input step does not understand the field, how can i achieve this behavior?
I am stuck at this point and can't go further.
The only option that is left is to use the Pentaho JOBS, but is it possible using Mapping inside a transformation?
I tried to setVariable function from the javascript in the sub transformation but nothing works.

A: I expect that your sub transformation is similar to the one in the figure below. Are you sure you are passing the parameters correctly? The important is to:

*

*have same number of parameters in Mapping input specification as parameters used in Table input step

*Replace variables in script checked

*Insert data from step filled

*parameter ? used in SQL query

If you need to pass more parameters to the table input, the number of parameters in previous step (Mapping input specification in case of my example) needs to respect the number of parameters you use in table input. Then you use ? more times in your query. E.g. for 3 params you could have:
WHERE name = ? AND surname = ? AND age = ?

Also you need to respect the order of parameters which come from previous step:


text:
Q: Sum all integers > 9 individually in R. E.g. 10 = 1+0, 11 = 1+1 Im trying to write a function based on the Luhn algorithm (mod 10 algorithm), and I need a function that sums all integers > 9 in my number vector individually. E.g. 10 should sum to 1+0=1, and 19 should sum to 1+9=10. Example code:
nmr <- ("1_9_8_2_0_5_0_1_3_3_4_8")
nmr <- strsplit(nmr, "_")
nmr <- as.numeric(as.character(unlist(nmr[[1]])))
luhn_alg <- c(0,0,2,1,2,1,2,1,2,1,2,0)
x <- nmr*luhn_alg
x
[1]  0  0 16  2  0  5  0  1  6  3  8  0

sum(x)

[1] 41

I dont want the sum of x to equal 41. Instead I want the sum to equal: 0+0+1+6+2+0+5+0+1+6+3+8+0=32. I tried with a for loop but doesn't seem to get it right. Any help is much appreciated.

A: You may need to split the data again after multiplying it with luhn_alg.
Luhn_sum <- function(x, y) {
  nmr <- as.numeric(unlist(strsplit(x, "_")))
  x1 <- nmr*y
  x1 <- as.numeric(unlist(strsplit(as.character(x1), '')))
  sum(x1)
}

nmr <- ("1_9_8_2_0_5_0_1_3_3_4_8")
luhn_alg <- c(0,0,2,1,2,1,2,1,2,1,2,0)
Luhn_sum(nmr, luhn_alg)
#[1] 32

A: You can use substring and seq to create a vector of single digit numbers, then you only need to do a sum over them:
sum(
  as.numeric(
    substring(
      paste(x, collapse = ""),
      seq(1, sum(nchar(x)), 1),
      seq(1, sum(nchar(x)), 1)
    )
  )
)


text:
Q: Mail from Linux server goes to spam I've made .sh file which send me the mail if disk usage is above a certain level. The script is working fine but the mail goes to spam instead of inbox! What should I do? Do I need to configure anything on the server? I'm new to Linux server.
Here is the script:
#!/bin/sh

current_usage=$( df -h | grep '/var' | awk '{percent+=$4;} END{print percent}' | column -t )
max_usage=50

if [ $current_usage -ge $max_usage ]; then
    mailbody="Max usage exceeded. Your disk usage is at ${current_usage}."
    echo "Sending mail..."

echo ${mailbody} | mail -s "Disk alert!" "mymail@gmail.com"

elif [ ${current_usage%?} -lt ${max_usage%?} ]; then
    echo "No problems. Disk usage at ${current_usage}." > /dev/null
fi

Mail looks like:

A: The From: sender is not set correctly.  If you send an e-mail that is not supposed to look like Spam, set the sender to something like root@yourdomain.com (try mail -r root@mydomain.com):
echo ${mailbody} | mail -s "Disk alert!" -r root@mydomain.com mymail@gmail.com

The sender domain (FQDN, "fully qualified domain name") is determined by the mail backend software by entries in /etc/hosts and/or /etc/hostname and can also be set in its configuration file(s). Since these are not set correctly we force mail to override it here. A better solution would therefore be to configure sendmail or whatever is used here. (Check dmesg output or /var/log/messages or /var/log/maillog (dependent on system here) for error messages by the mailer not finding its FQDN).
If you wish to go further please read up on DKIM (e-mail signing) and SPF (sender protection framework).  Adhering to one or both of these two can help, even if it is no guarantee for success.
The latter (SPF) is easier: Make an entry in your DNS entries (for the server/sender domain in question) that looks like this:
yourdomain.com   TXT   "v=spf1 ip4:1.2.3.4 +a +mx ~all"

where you need to replace 1.2.3.4 with your IP address.  It basically says that mail from whatever@yourdomain.com can only come from the IP address listed here. This also gives credibility to mail coming from this IP address claiming to be from yourdomain.com.

A: It's normal. Because localhost.localdomain is non-existent domain(doesn't have any DNS records in the internet), gmail can't resolve it. You can fix it by clicking "Not spam", or if you configure your mail server with public IP and DNS records.


text:
Q: Load Google Maps without markers I have two radio button. When the first is checked, i display a google map with some markers in it . I would like that when i check the second radion button, it display that same map, but without the markers. Could you help please?

<input type="radio" name="reception" id="rad" value="livraison"> Livraison

<input type="radio" name="reception" value="point"> Point de récuperation

A: Look at which radio button is selected before adding the markers:
var selected = document.querySelector('input[name = "reception"]:checked').value;

if(selected === "livraison") {
    for (var i = 0; i < lieux.length; i++) {
        var marker= new google.maps.Marker({
            position:lieux[i].coordonnees,
            nom:lieux[i].nom,
            map:map
        });

    }
}


text:
Q: How to clean a CGContextRef prior to drawing? I have a CGContextRef with things drawn inside, and I want to clear it out so that it is empty (all transparent). How to do it?

A: CGContextClearRect should do the job.


text:
Q: Why use different type of Assert methods? I'm a bit new to unit testing and I find myself always using the language-equivalent version of AssertTrue, instead of learning the many different type of other Assert statements that are available.
If they all boil down to a true or false, am I missing anything really important if I do AssertTrue(a == b) instead of AssertEquals(a,b)  Or does it just help provide a more clear debug message if the test fails?

A:
does it just help provide a more clear debug message if the test fails

Yes, but that's quite an important feature. I prefer seeing Expected 'foo' to be 'bar' than Expected false to be true.
It also makes the code more readable, and simpler to write in many cases. I don't know the details of phpunit, but it's clearer to me to see something like
assertThat(someCollection).containsExactly("a", "b", "c")

than to see 3 assertions testing that element 0 is "a", element 1 is "b" and element 2 is "c".


text:
Q: save columns of matrix in vector variables in Matlab In Matlab (R2021b) I am using some given function, which reads time-dependent values of several variables and returns them in a combined matrix together with a time vector. In the data matrix each column represents one vector of time-dependent values for one variable.
[data,time] = function_reading_data_of_several_values('filename');

For readability of the following code where the variables are further processed, I would like to store these columns in separate vector variables. I am doing it like that:
MomentX = data(1,:);
MomentY = data(2,:);
MomentZ = data(3,:);
ForceX  = data(4,:);
ForceY  = data(5,:);
ForceZ  = data(6,:);

That is working. But is there some simpler (or shorter) way of assigning the column of the matrix to individual vectors? I am asking because in real program I have more than the 6 columns as in the example. Code is getting quite long. I was thinking of something similar to the line below, but that does not work:
[MomentX,MomentY,MomentZ,ForceX,ForceY,ForceZ] = data; %does not work

Do you have any idea? Thanks for help!
Update:

Thanks to the hint here in the group to use tables, a solution could be like this:
...
[data,time] = function_reading_data_of_several_values('filename');
% data in matrix. Each column representing a stime dependent variable

varNames = {'MomentX', 'MomentX',...}; % Names of columns
T=array2table(data','VariableNames',varNames); % Transform to Table
Stress = T.MomentX/W + T.ForceY/A   %accesing table columns
...

This seems to work fine and readable to me.

A: Solution 1: In industrial solutions like dSpace, it is very common to do it in struct arrays:
mydata.X(1).time = [0.01 0.02 0.03 0.04];
mydata.Y(1).name = 'MomentX';
mydata.Y(1).data = [1 2 3 4];
mydata.Y(2).name = 'MomentY';
mydata.Y(2).data = [2 3 4 5];

Solution 2: It is also very common to create tables
See: https://de.mathworks.com/help/matlab/ref/table.html

A: As already commented, it is probably better to use a table instead of separate variables may not be a good idea. But if you want to, it can be done this way:
A = magic(6): % example 6-column matrix
A_cell = num2cell(A, 1); % separate columns in cells
[MomentX, MomentY, MomentZ, ForceX, ForceY, ForceZ] = A_cell{:};

This is almost the same as your

[MomentX,MomentY,MomentZ,ForceX,ForceY,ForceZ] = data; %does not work

except that the right-hand side needs to be a comma-separated list, which in this case is obtained from a cell array.


text:
Q: How can I add an object to another object in Javascript? I have two javascript variables.  One contains a content object and the other an array of content objects.
If the contents object already has contents then I can do a push and add to it. I have this working okay in the first part of my if statement.
However if the contents object is null then the push does not work.  How can I make it so that I can add just one content to the null contents object. In other words how can I create a contents object and assign self.content to it in the same time.  I have tried here but it is not working:
            if (self.contents) {
                self.contents.push(self.content);
            } else {
                self.contents = [self.content]
            }

A: if (self.contents) {
    self.contents.push(self.content);
} else {
    self.contents = [self.content];
}


text:
Q: Add attribute using Codedom in C# I want to add following line of code while creating page using Codedom in c#.
[Range(typeof(decimal), "-922337203685477.5808", "922337203685477.5807", ErrorMessage = "")]
public string d3 { get; set; }

But not able so please let me know how can I achived it or provide any sample that explain the same.

A: The code below will create the property definition you provided.
One thing to note is that automatic properties (get; set;) are syntactic sugar provided by the C# compiler and cannot be generated by CodeDOM. To create a property you will need to provide the backing field in the traditional way.
The key to answering your question is the CodeAttributeDeclaration class.
const string fieldName = "_d3";

// Create the backing field for the property.
var field = new CodeMemberField(typeof(string), fieldName);

// Create the property.
var prop = new CodeMemberProperty();
prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; // Public, non-virtual.
prop.Name = "d3";
prop.Type = new CodeTypeReference(typeof(string));
prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(fieldName)));
prop.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(fieldName), new CodeVariableReferenceExpression("value")));

// Create the attribute declaration for the property.
var attr = new CodeAttributeDeclaration(new CodeTypeReference(typeof(System.ComponentModel.DataAnnotations.RangeAttribute)));
attr.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(typeof(decimal))));
attr.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("-922337203685477.5808")));
attr.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("922337203685477.5807")));
attr.Arguments.Add(new CodeAttributeArgument("ErrorMessage", new CodePrimitiveExpression("")));
prop.CustomAttributes.Add(attr);

// Create a class to contain the property.
var testClass = new CodeTypeDeclaration("TestClass");
testClass.Members.Add(field);   // Add the backing field.
testClass.Members.Add(prop);    // Add the property.

Executing this code will result in your property being generated in the code variable (wrapped in a test class).
string code;
using (var provider = CodeDomProvider.CreateProvider("CSharp"))
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
{
    provider.GenerateCodeFromType(testClass, writer, new CodeGeneratorOptions() { BracingStyle = "C" });
    writer.Flush();
    stream.Position = 0;
    code = reader.ReadToEnd();
}

Contents of the code variable:
public class TestClass
{

    private string _d3;

    [System.ComponentModel.DataAnnotations.RangeAttribute(typeof(decimal), "-922337203685477.5808", "922337203685477.5807", ErrorMessage="")]
    public string d3
    {
        get
        {
            return _d3;
        }
        set
        {
            _d3 = value;
        }
    }
}


text:
Q: Geometric progression question a GP with positive common ratio is such that the sum of first 2 terms is 17.5 and third term is $4\frac{2}{3}$ compute first term and the common difference
$17.5 = \frac{a(1-r^n)}{1-r} $
$ ar^2 = 4\frac{2}{3} $
how do I solve these 2 to get a and r ?

A: assume that the terms are $a, ar, ar^2$
the sum of the first two terms is $a+ar=17.5$
the third term is $ar^2=14/3$
thus you can write $a$ as  $\frac{14}{3r^2}$ and put in the first equation
$$ \frac{14}{3r^2}+\frac{14}{3r}=17.5$$
$$ 14+14r=17.5*3r^2$$
now can you solve it


text:
Q: How to improve readability of multi_index_container for programmers not used to it? I created a multi-index container with 3 non-unique, non-ordered keys looking like following:
namespace bmi = boost::multi_index;
class SurveyRepository {
// some other code
    using SurveyCodeContainer = boost::multi_index_container<
        SurveyCode,
        bmi::indexed_by<
            bmi::hashed_non_unique<bmi::tag<Survey>, bmi::member<SurveyCode, unsigned, &SurveyCode::survey_id>>,
            bmi::hashed_non_unique<bmi::tag<Table>, bmi::member<SurveyCode, unsigned, &SurveyCode::table_id>>,
            bmi::hashed_non_unique<bmi::tag<Check>, bmi::member<SurveyCode, unsigned, &SurveyCode::check_id>>
        >
    >;

    SurveyCodeContainer m_SurveyCodeContainer;
};

The point was to be able to search the SurveyCode objects using any of those keys and I thought it's totally readable and quite a neat solution.
But there was a code review and although the multi_index_container has been already used in our code base in the past, some people have been confused with comments like:

Isnt there a less ugly container?

So is there a way how to make it less ugly/more readable? We are using Visual Studio 2019 and I would prefer some solution from stl instead of boost, but I guess there isn't any, right?

A: If you're using C++17, there's a slightly more convenient syntax available:
namespace bmi = boost::multi_index;
class SurveyRepository {
// some other code
   using SurveyCodeContainer = boost::multi_index_container<
        SurveyCode,
        bmi::indexed_by<
            bmi::hashed_non_unique<bmi::tag<Survey>, bmi::key<&SurveyCode::survey_id>>,
            bmi::hashed_non_unique<bmi::tag<Table>, bmi::key<&SurveyCode::table_id>>,
            bmi::hashed_non_unique<bmi::tag<Check>, bmi::key<&SurveyCode::check_id>>
        >
    >;

    SurveyCodeContainer m_SurveyCodeContainer;
};


text:
Q: Hadoop: Initialize mapper tasks with delay is there any way to set up a delay between the initialization of the mapper tasks?
For example: I have set mapreduce.job.running.map.limit to 450. Now I don't want Hadoop to create these 450 Processes at once. Instead there should be perhaps half a second between the start of every process.
Is there any chance to do this?

A: You can achieve your purpose by thinking exactly the other way round, i.e. If it's possible to run a MapReduce Job which requires the whole resources of your cluster (so it will block other Jobs until it's finished), and if you can control the execution time of its mapper tasks, then the tasks of your next job will start one by one each time a mapper task from the previous job is finished.
In other words, you start a job that you know how long its tasks will take, and then start your actual job.
This is easier because the first job can simply do a loop or sleep according to a parameter saved in the input files.

A: From possible list of all configurable parameters of MapReduce, it seems that your requirement of introducing delay between map tasks is not possible.
The other work around to solve your problem : Reducing number of map tasks.
mapreduce.job.running.map.limit is a directive to limit Map tasks but Hadoop framework may ignore this property.
I hope that you are aware of relation between InputSplit size & number of mappers. Number of mappers are decided based on InputSplits and not on DFS Blocks.
I have some crude ideas to reduce number of Mapper tasks to solve your problem. You have to play with some parameters.
mapreduce.input.fileinputformat.split.minsize
mapreduce.input.fileinputformat.split.minsize.per.node
mapreduce.input.fileinputformat.split.maxsize

Change this value to multiple of DFS block size. If you have 450 process and want to have <= 50 Mapper tasks,  change the split min size to 10 times of DFS Block size.
If your block size is  128 MB, change the split.min.size to 1280 MB.
Let me know if this approach solves your problem.

A: I believe it's not possible using Apache Hadoop currently.
You could limit number of initializations at the same time manually using Apache Curator's
org.apache.curator.framework.recipes.locks.InterProcessSemaphoreV2
mechanism for example
See for example how Cloudera uses this in batch-load jobs to load data to Solr  -
https://github.com/cloudera/search/blob/cdh6.2.0/search-crunch/src/main/java/org/apache/solr/crunch/MorphlineInitRateLimiter.java#L115
in that particular example they use it to limit number of ZooKeeper initializations
that can be at the same time, to avoid bloating ZooKeeper with a storm of requests from hundreds of mappers.
In one job I use 400 mappers, but only limit number of initializations to to 30 at the same time (once the initializations are doen, mappers run fully independent).
In your example you want to limit number of requests to Oracle backend from mappers, in this example they want to limit number of requests to ZK. So it's the same problem.
Ideally it would be great if Hadoop had a way to put a random delay for mappers ramp-up for exact same reason. Filed enhancement request :
https://issues.apache.org/jira/browse/MAPREDUCE-7219


text: Q: How to implement mobile version of SPA at ReactJS I need to implement a mobile version of my App on ReactJS. I want to make a variable that will take the width of the screen and then depends on this variable render Mobile Components or Desktop Components. Is it OK or are there other solutions?


text:
Q: UIScrollView 1D Bouncing but 2D Scrolling The project I'm currently working requires that a UIScrollView to scroll vertically and horizontally, however, it must only bounce vertically.  Is this possible? I noticed that there is a verticalBouncing and horizontalBouncing property in the declaration, could that be the answer?

A: You cannot access @package ivars directly. However, you can register yourself as delegate of UIScrollView and implemenet this code
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    float maxX = scrollView.contentSize.width - scrollView.frame.size.width;

    CGPoint offset = scrollView.contentOffset;
    offset.x = MAX(MIN(maxX, offset.x), 0);
    scrollView.contentOffset = offset;
}


text:
Q: google Oauth2.0 authenticate - not continue to redirect_uri I'm trying to implement login with google to my web site.
The users can visit my site in 3 domains
1)  regular link (HTTP and WWW...)
2)  http://example.com - no www
3)  apps.facebook.com/example - facebook app
We want to allow the user connect google in those three options.
We're using gapi (google javascript library) in order to authenticate the user.
My code looks like:
   var config = {
        'client_id': 'my_client_id',
        'scope': 'my_scopes',
        **'redirect_uri' : "https://www.example.com/oauth/",**
        'immediate': immediate
    };
    **gapi.auth.authorize(config, function(){});**

As you can see I'm setting my redirect uri as part of the config of gapi.
We've created some popup in order to give the same uri for the three domains.
My problem is that in case I'm login to my site from the domain without the WWW, the authorize isn't working and the user isn't redirect to the redirect_uri link - which means, we don't have his token.
In case I'm removing the WWW in the redirect_uri (so it will looks like https://example.com/oauth/)
the facebook domain isn't working...
It's so frustrated..
Is anyone familiar with this kind of problem?
Any idea?
We've spent on it too many hours....
Thanks
Z

A: You can register multiple redirect URIs for a single client in the Google API Console so you would register one for each domain and pass the one for the currently accessed domain in the redirect_uri parameter of the authorization request. You don't need to use the same redirect URI across your domains so that should solve your state/token restoration problems.


text:
Q: MySql get first occurence of each id in derived table (geo) I'm currently working with geo point with MySql 5.7.
My currently request is :
SELECT pA.id as pa, pB.id as pb, ST_Distance(pA.geo, pB.geo) as distance
FROM point_A pA
JOIN point_B pB
ORDER BY pa, distance

Sample output :
+-------+-------+---------------------+
| pa    | pb    | distance            |
+-------+-------+---------------------+
|     1 |  5535 | 0.23752813469351355 |
|     1 |  5536 |  0.8110224552241297 |
|     1 |  5533 |  0.8359718468573036 |
|     2 |  5536 |  0.8763100264270072 |
|     2 |  5536 |  0.0665454376162462 |
|     2 |  5533 |  1.0669544991122402 |
|     3 |  5533 |  0.2469039758259646 |
|     3 |  5536 |   0.329452951307464 |
|     3 |  5533 |  1.3593527448933072 |

I want only first occurence of each pa. I can't find a way to do this without using subrequest and a second time ST_Distance ( which has a cost in performance )
expected result :
+-------+-------+---------------------+
| pa    | pb    | distance            |
+-------+-------+---------------------+
|     1 |  5535 | 0.23752813469351355 |
|     2 |  5536 |  0.8763100264270072 |
|     3 |  5533 |  0.2469039758259646 |

I already tried with group by and distinct but all my distance value are unique with couple pa, pb.


text:
Q: Kernel of multiplication in noncommutative 2-torus What is $\Omega^1 (A_{\theta})$, that is, what is the kernel of the multiplication map $m:A_{\theta} \otimes A_{\theta} \to A_{\theta}$ where $A_{\theta}$ is the noncommutative 2-torus with parameter $\theta$. Is this known to be isomorphic to anything else more well known?
Does the answer to the question above carry over to the following pre-$C^*$-algebra formulation of $A_{\theta}$? Consider $\mathit{l}^1(\mathbb{Z}^2,c)$ with twisted convolution and $c$ a continuous cocycle. What is the kernel of the multiplication map $m: \mathit{l}^1(\mathbb{Z}^2,c) \otimes \mathit{l}^1(\mathbb{Z}^2,c) \to \mathit{l}^1(\mathbb{Z}^2,c)$?


text:
Q: Why was the existential quantifier symbol ∃ based off of an inverted "E"? Peano introduced a number of logical symbols still used today:

*

*∨ (from Latin vel)

*∧ (inverted ∨)

*∃

This inversion of Latin letters as symbols (and inversion of symbols to signify their 'opposite' operation) was followed by later logicians:

*

*∀ (Gentzen, 1935: inverted A from "All-Zeichen", by analogy to ∃)

*⊥ (inverted ⊤)

I had always assumed that ∃ stood for "E" in "Existential" / "there Exists", but Peano wrote and introduced this symbol in French, not using any words beginning 'E':

Mais nous préférons l'indiquer par la nouvelle notation
Ǝa
qu'on peut lire « il y a des a ».

*

*Formulaire de mathématiques, Peano (1897)

So why did he choose an inverted "E"?

Earliest Uses of Symbols of Set Theory and Logic
What came first, the $\forall$ or the $\exists$?


text:
Q: Create a custom exponential function I want to create a custom inverse exponential pdf with domain [0.00002, 0.0001] and range [0,1], where
x = 0.00002, y = 0 and
x = 0.0001, y = 1
The pdf should have the shape like that for a function like 1 - exp(-x).
How do I form this function?

A: Adding to @MichaelChernick's comment, if y reaches 0 for a function like $y = c(1-e^{-tx})$ , $t$ must be 0 which reduces the function to $c$.
The mapping you have desired for the above function is not correct logically unless you want y to be a constant function.
EDIT
If I understood you well...the family of curves that have shape like $log(1+x)$ and $(1-exp(-x))$ are just $a+b*log(1+c*x)$ and $a*(1-exp(-b*x))$ receptively.


text:
Q: O(n) time O(1) space substring search with bracket patterns For fixed-substring search, there are exactly two known algorithms with O(n) runtime and O(1) working space: SMOA and Two-Way (see http://www-igm.univ-mlv.fr/~lecroq/string/). Both of them depend on having or imposing an ordering on the alphabet.
Suppose instead of searching for fixed substrings, I want to be able to search for any one of a set of substrings expressed with bracket expressions, e.g.
 [abc]d

would match "ad", "bd", or "cd". Assuming the alphabet is finite, the length of any bracket is bounded and thus any term of the form "length of a bracket" in the time or space requirement is O(1).
Is there a way to perform the search in O(n) time (where n is the length of the string to be searched, i.e. the "haystack") and O(1) working space?
Unless the solution involves somehow ordering bracket sets with the alphabet ordering, any solution to this problem would provide a new solution to the fixed-substring search problem in O(n)/O(1) without the ordering requirement, and thus seems very unlikely to exist.

A: I must be missing something.  From your linked page, the brute force method is O(n).  It would appear that you could write what you are looking for every easily:
1.  Pattern is P with index p indicating which element of the pattern we are on.
2.  String is S with index s indicating which element of the string we are on.
3.  if S[s] matches P[p], increment both indicies and repeat until you complete the Pattern.
4.  If S[s] doesn't match P[p], set p=0 and increment p.

That would be O(n) and meet your requirements.


text:
Q: Error parsing yaml file: mapping values are not allowed here I want to upload an app to Google App Engine:
I get this
Error parsing yaml file:
mapping values are not allowed here
  in "/home/antonio/Desktop/ATI/climate-change/app.yaml", line 2, column 8

When running
./appcfg.py update /home/antonio/Desktop/ATI/climate-change

with this app.yaml file:
application:climate-change
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /.*
  script: helloworld.app

line 2, column 8 corresponds to the version line. What is wrong here? Btw, I'm using Ubuntu 12.04 here.

A: Another cause is wrong indentation which means trying to create the wrong objects. I've just fixed one in a Kubernetes Ingress definition:
Wrong
- path: /
    backend:
      serviceName: <service_name>
      servicePort: <port>

Correct
- path: /
  backend:
    serviceName: <service_name>
    servicePort: <port>

A: Or, if spacing is not the problem, it might want the parent directory name rather than the file name.
Not $ dev_appserver helloapp.pyBut $ dev_appserver hello/
For example:
Johns-Mac:hello john$ dev_appserver.py helloworld.py
Traceback (most recent call last):
  File "/usr/local/bin/dev_appserver.py", line 82, in <module>
    _run_file(__file__, globals())
...
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/yaml_listener.py", line 212, in _GenerateEventParameters
    raise yaml_errors.EventListenerYAMLError(e)
google.appengine.api.yaml_errors.EventListenerYAMLError: mapping values are not allowed here
  in "helloworld.py", line 3, column 39

Versus
Johns-Mac:hello john$ cd ..
Johns-Mac:fbm john$ dev_appserver.py hello/
INFO     2014-09-15 11:44:27,828 api_server.py:171] Starting API server at: http://localhost:61049
INFO     2014-09-15 11:44:27,831 dispatcher.py:183] Starting module "default" running at: http://localhost:8080

A: Incorrect:
people:
  empId: 123
  empName: John
    empDept: IT

Correct:
people:
  emp:
    id: 123
    name: John
    dept: IT

A: Maybe this will help someone else, but I've seen this error when the RHS of the mapping contains a colon without enclosing quotes, such as:
someKey:
    another key: Change to make today: work out more
should be
someKey:
    another key: "Change to make today: work out more"

A: I've seen this error in a similar situation to mentioned in Joe's answer:
description: Too high 5xx responses rate: {{ .Value }} > 0.05

We have a colon in description value. So, the problem is in missing quotes around description value. It can be resolved by adding quotes:
description: 'Too high 5xx responses rate: {{ .Value }} > 0.05'

A: There are couple of issues in the yaml file as mentioned by most, with yaml files normally it gets messy to identify the issue,
fortunately it can be identified easily with tools like yaml lint and you may not require help from the community.
Install it
npm install -g yaml-lint

Here is how you can validate
E:\githubRepos\prometheus-sql-exporter-usage>yamllint docker-compose.yaml
√ YAML Lint successful.

A: Change
application:climate-change

to
application: climate-change

The space after the colon is mandatory in yaml if you want a key-value pair. (See http://www.yaml.org/spec/1.2/spec.html#id2759963)

A: My issue was a missing set of quotes;
Foo: bar 'baz'

should be
Foo: "bar 'baz'"

A: In our case, we had weird dash (–) instead of normal one (-) due to copy and paste.


text:
Q: Setting calendar and adding 1 day I have a string (e.g. Oct 15 Wednesday), then I have to get the next day of this day. I have a method that I use to do this, but after the present month, it throws wrong date. Here's the method:
public String getNextDay(String lastDate) {
    String[] wholedate = lastDate.split("\\s+");
    String datemon = wholedate[0];
    String date = wholedate[1];
    String dateday = wholedate[2];

    Calendar cal = Calendar.getInstance();
    cal.setFirstDayOfWeek(Calendar.SUNDAY);
    SimpleDateFormat df = new SimpleDateFormat("MMM dd cccc");

    int dayNo=0;
    if (dateday.equalsIgnoreCase("Sunday")) {
        dayNo = Calendar.SUNDAY;
    } else if (dateday.equalsIgnoreCase("Monday")) {
        dayNo = Calendar.MONDAY;
    } else if (dateday.equalsIgnoreCase("Tuesday")) {
        dayNo = Calendar.TUESDAY;
    } else if (dateday.equalsIgnoreCase("Wednesday")) {
        dayNo = Calendar.WEDNESDAY;
    } else if (dateday.equalsIgnoreCase("Thursday")) {
        dayNo = Calendar.THURSDAY;
    } else if (dateday.equalsIgnoreCase("Friday")) {
        dayNo = Calendar.FRIDAY;
    } else if (dateday.equalsIgnoreCase("Saturday")) {
        dayNo = Calendar.SATURDAY;
    }

    int monNo = 0;
    if (datemon.equalsIgnoreCase("Jan")) {
        monNo = Calendar.JANUARY;
    } else if (datemon.equalsIgnoreCase("Feb")) {
        monNo = Calendar.FEBRUARY;
    } else if (datemon.equalsIgnoreCase("Mar")) {
        monNo = Calendar.MARCH;
    } else if (datemon.equalsIgnoreCase("Apr")) {
        monNo = Calendar.APRIL;
    } else if (datemon.equalsIgnoreCase("May")) {
        monNo = Calendar.MAY;
    } else if (datemon.equalsIgnoreCase("Jun")) {
        monNo = Calendar.JUNE;
    } else if (datemon.equalsIgnoreCase("Jul")) {
        monNo = Calendar.JULY;
    } else if (datemon.equalsIgnoreCase("Aug")) {
        monNo = Calendar.AUGUST;
    } else if (datemon.equalsIgnoreCase("Sep")) {
        monNo = Calendar.SEPTEMBER;
    } else if (datemon.equalsIgnoreCase("Oct")) {
        monNo = Calendar.OCTOBER;
    } else if (datemon.equalsIgnoreCase("Nov")) {
        monNo = Calendar.NOVEMBER;
    } else if (datemon.equalsIgnoreCase("Dec")) {
        monNo =Calendar.DECEMBER;
    }

    cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(date));
    cal.set(Calendar.MONTH, monNo);
    cal.set(Calendar.DAY_OF_WEEK, dayNo);

    cal.add(Calendar.DATE, 1);
    String fd = df.format(cal.getTime());

    return fd;
}

Maybe I set the date wrong or maybe I need to set more for the date, or maybe there is a better way to do this. Thank you so much.

A: If I were you , I would do like this
Calendar c = Calendar.getInstance();

c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

SimpleDateFormat df = new SimpleDateFormat("EEEE dd-MMM-yyyy", Locale.ENGLISH);

c.add(Calendar.DATE, 1);

String nextDate = df.format(c.getTime());

A: My simple solution is to call Calendar.getTimeInMillis() to get the UTC time stamp, add 24x60x60x1000 milliseconds to it, and then put it into another Calendar.
No other extra step needed for this approach. It should be error-free, though the efficiency could be a little bit poor. However, I take simplicity as the first priority.

A: I finally know how to do this, to not set day of week. For some reason, it messes the date up. So now, i just set the day_of_month and month, and i works fine. thank you guys.


text:
Q: Underground animal farm isn't working I and some friends, we have a Minecraft SMP Server. We use the latest recommended Version of the Bukkit Server.
We dug a 40x40, 3 tiles high cave and placed grass at the bottom. Than we dug water canals and made a lava trap. The problem is that no mobs spawn there. Above the cave there is sand, but I think that doesn't really matter. The fact is that in other places on our server, mobs spawn. Does anyone know why they don't spawn in the cave?

A: Ok,
Yesterday I found a great soultion for my problem: The Mobiile Plugin for Bukkit.
It has many options to set your own spawn rules, so that animals can also spawn in the animal farm.
Also it's great for creating a mob filled survival map on the server, just set all mobs to AGGRESIVE and set their spawn rate to 10 percent. =D
I just posted that, because eventually someone could need this informations too.
Leo

A: Actually, the problem is that the cave has a "ceiling".

[Animals] will always spawn on the highest available block in a column i.e. the one that can see the sky.
– Animal Spawning at Minecraft Wiki


text:
Q: What are the advantages of using AWS Elastic Transcoder (for WAV to AAC) vs Lambda and ffmpeg? I did a price comparison between using Elastic Transcoder vs Lambda for WAV-to-AAC conversion. I have to say, AWS ET is significantly pricier than Lambda.
A 9-minute audio file transcoded using ET: $0.04
The same file transcoded on a 1536MB Lambda instance (33sec runtime, excluding free tier): $0.0000002 for the request, and $0.000825165 for the execution time.
Granted, the Lambda transcoding took 33 seconds, and the same job on ET took probably around a third of that. But the cost of ET just doesn't make sense to me. Am I missing something else here? I should add that these transcodings are user-invoked by an upload (similar to how SoundCloud takes uploaded audio and transcodes to MP3), I'm not sending batch jobs. So maybe ET isn't the right application for my use case.


text:
Q: Using a Content Provider to get Calendar instances I am trying to implement the a calendar instance query https://developer.android.com/guide/topics/providers/calendar-provider#query-instances but when I run the code my cursor returns null. I've removed the selection args so that it should return all instances within the query range but still no luck. I've even set the range to look back 2 years (of which there are plenty events in the calendar) yet it still returns null. Does anyone have the same problem when executing the below code?
package com.strath.keepfitct.utils;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CalendarContract;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

public class CalendarManager
{
    private static final int PERMISSION_REQUEST_CODE = 1;
    private static final String DEBUG_TAG = "CalendarManager";

    private static final String[] INSTANCE_PROJECTION = new String[]
            {
            CalendarContract.Instances.EVENT_ID,      // 0
            CalendarContract.Instances.BEGIN,         // 1
            CalendarContract.Instances.TITLE,          // 2
            CalendarContract.Instances.END,         // 3
    };

    private static final int PROJECTION_ID_INDEX = 0;
    private static final int PROJECTION_BEGIN_INDEX = 1;
    private static final int PROJECTION_TITLE_INDEX = 2;
    private static final int PROJECTION_END_INDEX = 3;

    public static void getEvents(Context context)
    {
        Cursor cursor = null;
        ContentResolver contentResolver = context.getContentResolver();

        long startTime = LocalDateTime.now().minusMonths(24).toEpochSecond(OffsetDateTime.now().getOffset());
        long endTime = LocalDateTime.now().plusHours(24).toEpochSecond(OffsetDateTime.now().getOffset());

        Uri.Builder builder = CalendarContract.Instances.CONTENT_URI.buildUpon();
        ContentUris.appendId(builder, startTime);
        ContentUris.appendId(builder, endTime);

//        String selection = CalendarContract.Instances.EVENT_ID + " = ?";
//        String[] selectionArgs = new String[] {"207"};

        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CALENDAR)
                != PackageManager.PERMISSION_GRANTED)
        {
            Log.d("permission", "permission denied to READ_CALENDAR - requesting it");

            ActivityCompat.requestPermissions((Activity) context, new String[] {Manifest.permission.READ_CALENDAR}, PERMISSION_REQUEST_CODE);
        }
        else
        {
            Log.d("Content URI", builder.build().toString());
            cursor =  contentResolver.query(builder.build(),
                    INSTANCE_PROJECTION,
                    null,
                    null,
                    null);

            while (cursor.moveToNext())
            {
                String title = null;
                long eventID = 0;
                long beginVal = 0;

                // Get the field values
                eventID = cursor.getLong(PROJECTION_ID_INDEX);
                beginVal = cursor.getLong(PROJECTION_BEGIN_INDEX);
                title = cursor.getString(PROJECTION_TITLE_INDEX);

                // Do something with the values.
                Log.i(DEBUG_TAG, "Event:  " + title);
                LocalDateTime date = LocalDateTime.ofInstant(Instant.ofEpochSecond(beginVal), TimeZone.getDefault().toZoneId());
                Log.i(DEBUG_TAG, "Date: " + date.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
            }
        }
    }
}

A: My issue was that after converting the LocalDateTime parameters to a long epoch second, I wasn't converting them to miliseconds as is expected! A quick multiply by 1000 fixed the issue.
long startTime = LocalDateTime.now().minusMonths(24).toEpochSecond(OffsetDateTime.now().getOffset()) * 1000;


text:
Q: Do newer browser versions have a way of determining if changes have been made to a .js file? I've been reading about problems people are having with browsers caching an old version of a javascript file and not downloading the new one when changes have been made. However every time I make a change to a js file, close the browser and open it up (or even refresh the page) the changes are reflected.  I've tried this in IE9, FF13, Chrome18 and Safari 5.
Do newer browser versions have a way of determining if changes have been made to a .js file and then replacing the old with the new in the cache?

A: This has nothing to do with the browser or browser version.  This has to do with caching directives.
If your server is outputting headers, allowing the client to cache the resource, then it will be cached.  If your server outputs headers directing the client to not cache, then it will (usually) not be cached.
See also:  http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
Browsers detect if they need to load a new version if the server specifies Must-Revalidate.
https://stackoverflow.com/a/8729854/362536


text:
Q: Sort divs using data attributes and JS I asked an almost identical question about 5 months ago and got a great answer that seemed to work at the time. Since then I have taken a break and have not looked at so much as a line of code. Now that I have some free time, I am realizing I am quite rusty with Javascript.
Link to previous question: https://stackoverflow.com/questions/38470543/sort-divs-using-data-attributes-and-javascript
This is my current JSFiddle. jsfiddle.net/wtckhkdq/3/
As you can see I have 4 divs with a variety of data attributes including price, date of listing, and alphabetical rank. I am trying to get the script working so that when each button is pressed, it sorts the divs according to the referenced function. My JSFiddle will not run properly and after looking it over multiple times I can't seem to find what's wrong. Thanks in advance and happy new years to all!

A: *

*You need to include the jquery library to use it.

*In jsfiddle, due to the way they wrote there final output builder, there is a problem with js-scoping, so the functions you created weren't visible by the html block. You can fix this specifically by changing the function sortDateNewOld (){ to sortDateNewOld = function(){ inside jsfiddle.

Here is a fix (and everything work)

var divList = $(".listing");

function sortDateNewOld() {
  divList.sort(function(a, b){ return $(b).data("date")-$(a).data("date")});
  $("#list").html(divList);
}

function sortDateOldNew(){
  divList.sort(function(a, b){ return $(a).data("date")-$(b).data("date")});
  $("#list").html(divList);}

function sortPriceHighLow(){
  divList.sort(function(a, b){ return $(b).data("price")-$(a).data("price")});
  $("#list").html(divList);}

function sortPriceLowHigh(){
  divList.sort(function(a, b){ return $(a).data("price")-$(b).data("price")});
  $("#list").html(divList);}

function sortAlphAZ(){
  divList.sort(function(a, b){ return $(a).data("alph")-$(b).data("alph")});
  $("#list").html(divList);}

function sortAlphZA(){
  divList.sort(function(a, b){ return $(b).data("alph")-$(a).data("alph")});
  $("#list").html(divList);}
.button {
  font-size: 15px; width: 120px; height: 30px; background-color: white; display: inline-block; cursor: pointer;}

.listing {
  width: 342px; height: 282px; border-radius: 7px; background-color: #f1f1f1; margin: auto; margin-top: 80px; position: relative; box-shadow: 0px 15px 20px rgba(0, 0, 0, 0.15);}

.listinginfo {
  width: 342px; height: 64px; border-bottom-right-radius: 7px; border-bottom-left-radius: 7px; background-color: white; position: absolute; bottom: 0; left: 0; box-shadow: 0px -4px 10px rgba(0, 0, 0, 0.05); font-size: 10px;}

    <button class="button" onclick="sortDateNewOld()">Date New-Old</button>
    <button class="button" onclick="sortDateOldNew()">Date Old-New</button>
    <button class="button" onclick="sortAlphAZ()">Name A-Z</button>
    <button class="button" onclick="sortAlphZA()">Name Z-A</button>
    <button class="button" onclick="sortPriceHighLow()">Price High-Low</button>
    <button class="button" onclick="sortPriceLowHigh()">Price Low-High</button>

            AAA

            Price: $99

            Date: December 1, 2017

            AAB

            Price: $199

            Date: December 2, 2017

            AAC

            Price: $299

            Date: December 3, 2017

            AAD

            Price: $399

            Date: December 4, 2017


text:
Q: Clustering of binary/nominal variables in one sample Assume that a medical school classifies its active, full-time students according to their free time activities. By distributing simple questionnaires individuals have to answer whether or not they're keen on a particular habit (Yes/No) and the following comprises only a small piece of the final results;

I've been searching (rather unsuccessfully) for a way to group positive responses that appear to have a statistically significant correlation eg. students who attend business workshops are also likely to be interested in programming too. That might extend to three or four variables depending on the factors provided by the method. Factor analysis rings some bells, but the data are purely nominal and there's no outcome in the form of a scale or ordinal variable. Any ideas ?
So far I've produced the following resourceful conclusions in SPSS;

*

*Frequency tables. Gives a general idea about the distribution.

*Correlation matrix. Special attention is given to positive values that fall below the 0.05 (*) and 0.001 (**) levels of significance respectively.

*Ordinal Regression. Provides a probability table, indicating the chances of two positive responses in two different variables to be found the same.

A: You could try latent class analysis (LCA), though I'm not sure if SPSS can do it.
LCA assumes that there are underlying (latent) classes, and all individuals belong to one of them. In short, using LCA you can identify clusters of students, grouped by free time activities. For example, you might find that there is one group that is mainly interested in business and programming, another group that is mainly interested in programming and painting, a third group that is interested in movies, and all groups are interested in traveling.
LCA is useful if you believe there are certain latent groups and you want to measure how prevalent they are, or if you simply want to characterize the groups. It is also useful as a data reduction tool. E.g. you might want to predict academic performance based on group affinity rather than on the free time activity variables themselves, because otherwise you might need to include interaction terms and you would need to estimate lots of parameters.

A: Do not use clustering.
You are looking for association rules instead. Give Apriori a try, it is designed exactly for the task of finding rules of the kind $$A, B, C \rightarrow D$$


text:
Q: I don't understand stable algorithm definition
In computer science, a stable sorting algorithm preserves the order of records with equal keys.

I just don't understand why certain sorting algorithm are stable and others none. A basic sorting algorithm orders items of an array of int. If I create a class or a struct and I use the same algorithm considering swapping of the whole object, and choosing to order it by key, o by age ecc, then every algorithm can preserve the order of records!
I think I missed something about the definition.
Thanks a lot.

A: Say you have an array like the following:
a = [5, 4, 2a, 2b, 1]

Where the a and b are simply there to denote that the first 2 (2a) comes before the second 2 (2b). In a stable sorting algorithm, the result will be:
a_stable = [1, 2a, 2b, 4, 5]

That is, the relative order of the elements hasn't changed - 2a came before 2b in the original array, and it remains that way in the sorted array.
With a non-stable algorithm, the result could be:
a_nonstable = [1, 2b, 2a, 4, 5]

This is still correctly sorted, it's just that the positions relative to where they were in the original, unsorted array have now changed.


text:
Q: Show more than 1 panel for Coda Slider 2.0 Is there a way to show more than 1 panel at a time with the coda slider?  I want to keep its original scrolling logic the same. The only difference, to show more than one panel at a time.  Such as 2 or 3 or 4 panels in view.
How would we go about doing that?
Thanks

A: Here is a sample that heads in the direction of a working example of what you'd like. I'll explain why it seems to be more trouble than it's worth (Assuming you want flexible content in both panels) and tell you how I did it.
Here is the jsFiddle.
So, the initial issue is that the current slide is taken into account for height. Well, what if the next slide contains more content and requires a higher slider height? I suppose you'd need to compare the height of both for each height calculation. That's not so difficult, but it may lead you to more trouble if you had to fight with Niall's code.
The second issue is that you have to set a static width for two elements, which is normal in most cases for this slider, but potentially a drag depending on what your content is.
Anyhow:
.coda-slider-wrapper.arrows .coda-slider, .coda-slider-wrapper.arrows .coda-slider .panel { width: 230px }
.coda-slider { float: left; overflow: hidden; position: relative; width: 460px !important }

You should be able to locate these selectors using find in your editor. The !important is a drag, but required if you don't want to rework much code. Basically, you want to set .coda-slider .panel to the width you want each panel, then double the width of .coda-slider.
Let me know if I've missed anything here or failed to explain something properly. I'd be happy to go over this more! I've worked with this slider a lot due to inheriting a project at work that made extremely heavy use of it. I've since moved on to something custom.


text: Q: Remotely change view types in recyclerView firebase realtime database I have created three view types in my project along with one MAIN recyclerView which will hold all the other views. IMAGE VIEW, GRID VIEW & HORIZONTAL RECYCLER VIEW. I want to call this three views multiple times from firebase realtime database.


text:
Q: Fragment loading animation don't start until startactivity intent completed in Android There are two activities which are main and reding. When I click the open book in main activity, a loading fragment should be appear on screen until reading activity loaded completely.
In activity main, activity reading open click event:
@Override
public void onClick(View v) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction()
        // fragment fade in enough
        .setCustomAnimations(R.anim.fade_in, 0, 0, 0)
        // main_root in activity main.
        .add(R.id.main_root, new BookLoadingFragment(), "BookLoaderFragment")
        .addToBackStack("BookLoaderFragmentStackTag")
        .commit();
    fragmentManager.executePendingTransactions();

    Intent intent = new Intent(context, ReadBookActivity.class);
    context.startActivity(intent);
}

So by the above code, loading fragment don't appear until reading activity opened completely (It appear without setCustomAnimations()). I've tried creating new thread or async task for fragment but there was an error creating fragmet not allowed outside of ui thread. Also I've to create fragment in main activity because reading activity has many other fragments attached it with onActivityCreated().

A: public final class BookLoadingFragment extends Fragment {

   ...

   public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
      super.onViewCreated(view, savedInstanceState);

      Intent intent = new Intent(this.getContext(), ReadBookActivity.class);
      startActivity(intent);
   }
}

Start ReadBookActivity after BookLoadingFragment was created

A: Your BookLoadingFragment freezing because main ui thread is no longer at its activity, you cannot work on it anymore. You should add loading fragment in what activity you load and show loading fragment until loaded second activity with AsyncTask.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_read_book);

    AddLoadingFragment();
    new AsyncLoading().execute();
}

class AsyncLoading extends AsyncTask<String,Integer,String> {

    public AsyncAppOpen() {
        super();
    }
    @Override
    protected String doInBackground(String... strings) {
        // Preapare background process only! Get data from Database or build Rcyvlerview adapter.
        return null;
    }
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        // doInBackground finished and it's time to preapare ui thread process. Build RecyclerView or some ui tools.
    }
}


text:
Q: file_put_contents(C:\xampp\htdocs\project\test\portal\storage\framework/cache/...): Failed to open stream: Permission denied
file_put_contents(C:\xampp\htdocs\project\test\portal\storage\framework/cache/85/5f/855f92484c8c414d36c1b25cb24876e30229cbbf):
Failed to open stream: Permission denied at
C:\xampp\htdocs\project\test\portal\vendor\laravel\framework\src\Illuminate\Filesystem\Filesystem.php:187

I am getting this error multiple times even though tried
php artisan view:cache
php artisan config:cache

changed in the cache.php
deleted bootstrap cache file
I am stuck &I don't know what to do, Can any one help me?

A: The problem could be because the following directories are missing:

*

*storage/framework/cache

*storage/framework/views
Creating these and setting appropriate permissions should resolve the issue.


text:
Q: iOS 15 beta 4: AttributedString with Markdown not rendering in Text in SwiftUI? I assumed this was a iOS 15 beta 1 or 2 bug, but as of beta 4 I'm still seeing this behavior, so perhaps I'm doing something wrong:
Text is supposed to render AttributedStrings with Markdown. It appears to render correctly when a direct String literal is passed into the Text, but not when the AttributedString is a variable. Am I doing something super dumb?
struct ContentView: View {
    var text = AttributedString("**Hello**, `world`! Visit our [website](https://www.capitalone.com).")

    var body: some View {
        VStack {
            Text("**Hello**, `world`! Visit our [website](https://www.capitalone.com).")
                .padding()

            Text(text)
                .padding()
        }
    }
}

A: If you pass Markdown directly into a Text.init(), SwiftUI will auto-convert it into an AttributedString.
However, to go from a Markdown string to an AttributedString, you need to use an explicit AttributedString(markdown:options:baseURL:) initialiser. For example:
var text = try! AttributedString(markdown: "**Hello**, `world`! Visit our [website](https://www.capitalone.com).")

Note that this initialiser throws if the conversion can't be made correctly. I've used try! here because your example Markdown will definitely convert, but depending on the source of the Markdown text you may want to handle a thrown error a little more intelligently.


text:
Q: How to set position of RecyclerView's item in Listview's item I have a Listview which has many items and each item has two textview and recyclerview.In recyclerview i have a list of images which is scrolled horizontally but the problem is,when i get json of recyclerview then all item are showing in any item of listview.Suppose i have 4 items in recyclerview of 4 items of listview.Each item of listview has 1 image in recyclerview but its showing all in every item of list.
I want this type of items in listview.
     No:1                  Date:
     img1

     No:2                  Date:
     img2

     No:3                  Date:
     img3

     No:4                  Date:
     img4

I got this listview which i don't want.
     No:1                  Date:
     img1,img2,img3,img4

     No:2                  Date:
     img1,img2,img3,img4

     No:3                  Date:
     img1,img2,img3,img4

     No:4                  Date:
     img1,img2,img3,img4

This is my Listview Adapter
public class POAdapter extends ArrayAdapter {

private Context mContext;

private RecyclerView.Adapter adapter;
private List list = new ArrayList();
PO details;
public POAdapter(@NonNull Context context, int resource) {
    super(context, resource);
    mContext=context;

}

public void add(PO object) {
    super.add(object);
    list.add(object);
}

@Override
public int getCount() {
    return list.size();
}

@Nullable
@Override
public Object getItem(int position) {
    return list.get(position);
}

@Override
public boolean isEnabled(int position) {
    details=(PO)this.getItem(position);
    if(details.getHideStatus()==1){
        return false;
    }
    return true;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View row;
    row = convertView;
    details= (PO) this.getItem(position);
    final DetailHolder detailHolder;
    if(row == null){
        LayoutInflater layoutInflater= (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row=layoutInflater.inflate(R.layout.polist_data_activity,parent,false);
        detailHolder = new DetailHolder();
        detailHolder.poNoTv = (TextView) row.findViewById(R.id.po_no_tv);
        detailHolder.deliveryDtTv = (TextView) row.findViewById(R.id.Delivery_date_tv);
        detailHolder.metersCompletedTv = (TextView) row.findViewById(R.id.total_meters_tv);
        detailHolder.recyclerView=(RecyclerView)row.findViewById(R.id.image_list);
        detailHolder.commentsTv = (TextView) row.findViewById(R.id.comment_tv);
        //detailHolder.totalMeters_tv= (TextView) row.findViewById(R.id.meter_completed_tv);
        row.setTag(detailHolder);
    }else{
         detailHolder = (DetailHolder)row.getTag();
    }

    LinearLayoutManager layoutManager
            = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
    detailHolder.recyclerView.setLayoutManager(layoutManager);
    System.out.println("DESIGNLIST" +((POListActivity)mContext).getDesignList());
    adapter= new ImageAdapter(((POListActivity)mContext).getDesignList(),getContext());
    detailHolder.recyclerView.setAdapter(adapter);

    //detailHolder.lstImages.setLayoutManager(layoutManager);
    detailHolder.poNoTv.setText(details.getPoNo());
    detailHolder.deliveryDtTv.setText(details.getDeliveryDt());
    DecimalFormat formatter = new DecimalFormat("#,###,###");
    try {
        //compMeters = (formatter.format(details.getMetersCompleted()));
    }catch (NumberFormatException e){}

    try {
       // totalMeters = (formatter.format(details.getTotalMeters()));
    }catch (NumberFormatException e){}
   // detailHolder.metersCompletedTv.setText(compMeters+" / "+totalMeters+" Meters");
 //   detailHolder.totalMeters_tv.setText(totalMeters);

    //row.setBackgroundColor(position % 2 == 0 ? ContextCompat.getColor(this.getContext(), R.color.fst_color) : ContextCompat.getColor(this.getContext(), R.color.scnd_color));

    return row;

}

static class DetailHolder {
    TextView poNoTv, deliveryDtTv, metersCompletedTv, commentsTv;
    RecyclerView recyclerView;
}
}

This is adapter of recyclerview
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder>{

private List<Design> horizontalDesignList;
Context context;

public ImageAdapter(List<Design> DesignList, Context context) {
    this.horizontalDesignList= DesignList;
    this.context = context;
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public int getItemViewType(int position) {
    return position;
}

@NonNull
@Override
public ImageAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View designsView = LayoutInflater.from(parent.getContext()).inflate(R.layout.po_image_data, parent, false);
    ViewHolder designsHolder = new ViewHolder(designsView);
    return designsHolder;
}

@Override
public void onBindViewHolder(@NonNull ImageAdapter.ViewHolder holder, int position) {
  //  holder.imageView.setImageResource(horizontalDesignList.get(position).getImgName());
    Picasso.with(context).load(horizontalDesignList.get(position).getBasePath()+horizontalDesignList.get(position).getImgName())
            .into(holder.imageView);
    int workStatus=horizontalDesignList.get(position).getWorkStatus();
    holder.imageView.setBorderWidth(4);
    if(workStatus==1){
        holder.imageView.setBorderColor(Color.GREEN);
    }else if(workStatus == 2){
        holder.imageView.setBorderColor(Color.YELLOW);
    }else if(workStatus==3){
        holder.imageView.setBorderColor(Color.RED);
    }else {
      //  Toast.makeText(context, "No Work Status", Toast.LENGTH_SHORT).show();
    }
    final Design current = (Design) horizontalDesignList.get(position);
    holder.imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, PODesignDetailsActivity.class);
            intent.putExtra("poDesignId",current.getPoDesignId());
            context.startActivity(intent);
        }
    });
    holder.textDesign.setText(horizontalDesignList.get(position).getDesignColor());
}

@Override
public int getItemCount() {
    return horizontalDesignList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{

    public CircleImageView imageView;
    public TextView textDesign;

    public ViewHolder(View v){

        super(v);

        imageView = (CircleImageView) v.findViewById(R.id.img);
        textDesign= (TextView)v.findViewById(R.id.design_color_tv);
    }
}

}

Please explain me,help me and guide me.

A: Use the example below to achieve what you want:
1) Demo2.class:---------------
public class Demo2 extends AppCompatActivity {

private ListView lv;
private Adapter adapter;
private List<String> items;
private List<List<String>> items_inside;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.demo2);

    items = new ArrayList<>(); // one dimensional array

    // Example: index 0 --> A1
    //          index 1 --> A2
    //          ...

    items_inside = new ArrayList<>(); // 2 dimensional array

    // Example: index 0 --> {A1B1 , A1B2 , ...}
    //          index 1 --> {A2B1 , A2B2 , ...}
    //          ...

    // populate items and items_inside
    for(int i = 0 ; i< 4 ; i++){
        List<String> tmp = new ArrayList<>();
        items.add( i , "A" + (i+1));
        for(int j = 0 ; j < 4 ; j++){
            tmp.add(j , "A" + (i+1) + "B" + (j+1));
        }
        items_inside.add(i , tmp);
    }

    lv = (ListView) findViewById(R.id.lv);
    adapter = new Adapter(getApplicationContext() , items , items_inside);
    lv.setAdapter(adapter);

}
}

2) Adapter.class:---------
public class Adapter extends BaseAdapter {

private Context context;
private LayoutInflater layoutInflater;
private List<String> items;
private List<List<String>> items_inside;

public Adapter(Context context , List<String> items  , List<List<String>> items_inside) {

    this.context = context;

    layoutInflater = LayoutInflater.from(context);

    this.items = items;

    this.items_inside = items_inside;

}

public int getCount() {
    return items.size();
}

public Object getItem(int position) {
    return items.get(position);
}

public long getItemId(int position) {
    return position;
}

public View getView(final int position, View convertView, ViewGroup parent) {

    View view = convertView;
    final TextView tv_list_item;
    final ListView lv_inner;

    if (convertView == null) {
        if (layoutInflater != null) {
            view = layoutInflater.inflate(R.layout.list_item, null);
        }
    }

    tv_list_item = (TextView) view.findViewById(R.id.tv_list_item);
    tv_list_item.setText(items.get(position));

    lv_inner = (ListView) view.findViewById(R.id.lv_inner);
    lv_inner.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView absListView, int i) {

        }

        @Override
        public void onScroll(AbsListView absListView, int i, int i1, int i2) {
            lv_inner.getParent().requestDisallowInterceptTouchEvent(true);
        }
    });
    InnerAdapter innerAdapter = new InnerAdapter(context , items_inside.get(position));
    lv_inner.setAdapter(innerAdapter);

    return view;
}
}

3) InnerAdapter.class:------
public class InnerAdapter extends BaseAdapter {

private Context context;
private LayoutInflater layoutInflater;
private List<String> items_inside;

public InnerAdapter(Context context, List<String> items_inside) {

    this.context = context;

    layoutInflater = LayoutInflater.from(context);

    this.items_inside = items_inside;

}

public int getCount() {
    return items_inside.size();
}

public Object getItem(int position) {
    return items_inside.get(position);
}

public long getItemId(int position) {
    return position;
}

public View getView(final int position, View convertView, ViewGroup parent) {

    View view = convertView;
    final TextView tv_inner;

    if (convertView == null) {
        if (layoutInflater != null) {
            view = layoutInflater.inflate(R.layout.list_items_inner, null);
        }
    }

    tv_inner = (TextView) view.findViewById(R.id.tv_inner);
    tv_inner.setText(items_inside.get(position));

    return view;
}
}

4) demo2.xml:--------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="100"
android:orientation="vertical">

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/lv"
    android:layout_marginStart="10dp"
    android:layout_marginEnd="10dp"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp">
</ListView>

</LinearLayout>

5) list_items.xml:-------------
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:layout_height="75dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:id="@+id/ll"
    android:weightSum="100"
    android:orientation="horizontal">

<TextView
    android:id="@+id/tv_list_item"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="50"
    android:layout_marginStart="10dp"
    android:gravity="start"
    android:text="A" />

    <TextView
        android:id="@+id/tv_date"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginEnd="4dp"
        android:gravity="center"
        android:layout_weight="50"
        android:text="Date:" />

</LinearLayout>

<ListView
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_below="@id/ll"
    android:id="@+id/lv_inner">
</ListView>

</RelativeLayout>

6) list_items_inner.xml:--------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_marginEnd="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginStart="10dp"
android:layout_height="match_parent">

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="AB"
    android:gravity="start"
    android:id="@+id/tv_inner"/>

</android.support.constraint.ConstraintLayout>

7) Output:---------


text:
Q: SharedPreferences Validation I'm a bit new to android dev. I have a preference screen on my app with a bunch of EditTextPreference and checkbox pref. I'm interested in doing validation on the input to the edittextpreference. It seems there is no way to do this using android, so I have developed a class that extends the edittextpreference.
For example, I have a text preference that only has a valid range of 0 to 1. The text preference will take in any numbers, but I need to validate this before setting.
I'm overriding the setText method, and trying to do validation there before actually setting the value. SetText only passes in the text string, how do I know what I am trying to validate? How can I get that information? In other words, I'd like to reuse my class to validate all of my text preferences, and I'd like something in the preference itself to tell me what type it is, or what it's range is.

A:              Preference pref = findPreference("OutputFolder");

             pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

             @Override
             public boolean onPreferenceChange(Preference preference,
                     Object newValue) {

                              // Do the validation here

                 }
                 return true;
             }

           });