text:
Q: How do I display mysql data in row span using PHP? I have data from MySQL showing all organisations a customer got, with all details of employess in each organisation. I want to list each organisation name only once i.e. in a single cell ( row span) and all employees in that organisation against this name like:
Org1     Emp1 Name, Emp1 Phone, Emp1 Address
         Emp2 Name, Emp2 Phone, Emp2 Address

Org2     Emp1 Name, Emp1 Phone, Emp1 Address
         Emp2 Name, Emp2 Phone, Emp2 Address

How do I display this data because the number of employess for each organisation is not known in advanced, so I do'nt about setting value of rowspan. Similarly how do I start a row for other organisation? Do I have to write two queries?
Many Thanks.

A: Classic.
Workaround: only display the name if different than the previous one. You can even not bother about the rowspan (you keep an empty cell).
$currentOrg = '';
while ($row = mysql_fetch_object($query)) {
   if ($row->org != $currentOrg) {
      echo "$row->org".
   }
   $currentorg = $row->org;
}

Not the most beautiful but so simple.

A: // Get the data
$data = mysql_query('SELECT org, emp_name, emp_phone, emp_address FROM x');

// Store it all in a 2D array, keyed by org
$rows = array();
while ($row = mysql_fetch_assoc($data))
{
    // Initialise each org to an empty array (not really needed in PHP but I prefer it)
    if (empty($rows[$row['org']]))
        $rows[$row['org']] = array();

    $rows[$row['org']][] = $row;
}

// Print it out
foreach ($rows as $org => $employees)
{
    print('
' . htmlentities($org) . '	');

    foreach ($employees as $i => $employee)
    {
        // If $i == 0, we've already printed the
 before the loop
        if ($i)
            print('
');

        print('......
');
    }
}

A: To make a correct rowspan, you need to know the number in advance.
That leaves you with:

*

*iterating the query result twice, counting the values until they change

*asking the DB server for the count

Personally, I would go with method number two. DB servers are quite efficient with counting rows, this will probably be a lot faster when there are many rows to display.

A: It could be easier (but less efficient) to make a query for each organisation (plus one query to find how many organisations there are presumably).
A better way to do it would be to loop through the array beforehand. For example:
$sql = $mysqli->query('SELECT * FROM `organisation_members` ORDER BY `organisation` DESC');

if (!$sql || $sql->num_rows) {
    // No data
} else {
    $data = array();
    while ($row = $sql->fetch_assoc()) {}
        if (!array_key_exists($row['organisation'], $data)) {
            $data[$row['organisation']] = array();
        }
        $data[$row['organisation']][]['name'] = $row['name'];
        // ...
    }
    $sql->close();
    echo '
';
    foreach ($data as $org => $people) {
        $people_in_org = count($data[$org]) - 1;
        $counter = 0;

        echo '
';
        echo '' . $org . '	';

        while ($counter < $people_in_org) {
            if (counter > 0) {
                echo '
';
            }
            echo '' . $people[$counter]['name'] . '	';
            // etc
            echo '
';
        }
    }
    echo '
';
}

A: To conserve memory you could iterate over the resultset while org is the same buffering the rows, when org changes, print the current batch and start buffering the next batch.

A: It won't help you with the rowspan, but look into the WITH ROLLUP modifier. It returns the data in a format similiar to what you want.

A: What about using pear's HTML_Table package like in the following example, through i also like Jrgns's ROLLUP version
    <?php

    require_once "HTML/Table.php";

    $table = new HTML_Table(array('border'=>'1'));
    $bo=array(
        array('6','a2','a3','a4'),
        array('1','b2','b3','b4'),
        array('1','c2','c3','c4') ,
        array('2','c2','c3','c4') ,
        array('2','c2','c3','c4') ,
        array('4','c2','c3','c4') );

    foreach ($bo as $r => $borow)
        $table->addRow($borow);

    $rsFirst=0;
    $rsLen=0;
    foreach ($bo as $r => $borow) {
        if ($r!=0 and $borow[0]!=$prevrow[0] ) {
            //jump in values
            $table->setCellAttributes ( $rsFirst,0, array('rowspan'=>$rsLen));
            $rsFirst=$r;
            $rsLen=0;
        }
        $prevrow=$borow;
        $rsLen++;
        if ($r==sizeof($bo) - 1) {
            $table->setCellAttributes ( $rsFirst,0, array('rowspan'=>$rsLen));
        }
    }

    echo $table->toHTML();

    ?>

servas, boerl


text:
Q: Hold UIPickerViewDelegate method from being triggered for couple of seconds I have to append name of a city at the end of base API before calling it. I choose UIPickerView to select desired city but when scrolling rows for required city, the scroll pause (as you expect when scrolling through a long list) triggers the following UIPickerViewDelegate method:
- (void)pickerView:(UIPickerView *)pickerView
      didSelectRow:(NSInteger)row
       inComponent:(NSInteger)component

To the point, it makes api call for wrong city. Is there any other way / method to get scroll selection?

A: There is no other method that the UIPickerViewDelegate calls that would provide you with the the selected row. However, there are alternative ways of achieving the effect you are looking for.
Perhaps the simplest thing you could do is add a UIToolbar, place it directly above your UIPicker and add a button that displays "Select" (or whatever word you feel is appropriate). When the user is done with their scrolling and actually on the desired city they can press the button. At that point you can access which index the UIPicker is on with:
- (NSInteger)selectedRowInComponent:(NSInteger)component

Then you can perform your API request and it will be with the correct city!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there an edit distance metric which doesn't rely on order at all? For example, let's say I have these two lists:
var a = [1,2,3];
var b = [3,2,1];

The Levenshtein distance between them would be 2. I'm looking for a metric where the distance would be 0, i.e. lists with the same elements are regarded as the same list, regardless of order. I've searched online, but I'm not really sure what terminology is used for this sort of thing.

A: Sounds like you want a set distance like the Jaccard distance.

A: Why not just sort the arrays and run regular edit distance?


text:
Q: How Jackson taking module beans automatically? I am having below class
@SpringBootApplication
public class TestApplication {

    public static void main(final String[] args) {

        SpringApplication.run(TestApplication.class, args);
    }

    @Bean
    public Module jdk8Module() {
        return new Jdk8Module();
    }

    @Bean
    public Module guavaModule() {
        return new GuavaModule();
    }
}

Here these two beans automatically registered in jackson ObjectMapper. How it's registered this modules automatically?

A: Any beans of type com.fasterxml.jackson.databind.Module are automatically registered with the auto-configured Jackson2ObjectMapperBuilder and are applied to any ObjectMapper instances that it creates. This provides a global mechanism for contributing custom modules when you add new features to your application. so it should be enough to define a bean and it will be automatically registered in jackson ObjectMapper.

A: This is done by the Spring Boot JacksonAutoConfiguration class.
As the javadoc says:

Auto configuration for Jackson. The following auto-configuration will get applied:

*

*an ObjectMapper in case none is already configured.

*a Jackson2ObjectMapperBuilder in case none is already configured.

*auto-registration for all Module beans with all ObjectMapper beans (including the defaulted ones).


text:
Q: test records for rails development database Seems like one of the strengths of the test database is that it can quickly reload fixtures before each test. Is there something similar for the development database in rails? Seems like it could make it easier to be able to load test fixtures into it to have some data to review? I'm sure this question has been asked before but I wasn't able to find an answer to it. I also know that ultimately I should be doing most of the interface testing thru the tests but as a newbie that is sometimes a challenge by itself.
Any tips or solutions that people might offer would be greatly appreciated!
Mark

A: rake db:fixtures:load

will load fixtures in to the database for the current Rails environment


text:
Q: count based on column and add as new column in numpy It should be straight forward but I cannot find the right command.
I want to add a new column (Col3) to my Numpy which counts the occurrence of a value of a column (Col2) for each row. take this example:
before:

Col1
Col2

1
4

2
4

3
1500

4
60

5
60

6
60

after:

Col1
Col2
Col3

1
4
2

2
4
2

3
1500
1

4
60
3

5
60
3

6
60
3

any idea?

A: Using numpy:
Create a frequency dictionary based on the values on Col2
from collections import Counter
freq = Counter(arr[:,1])

generate the values of the Col3 iterating the elements of Col2
new_col =  np.array([freq[val] if val in freq else 0 for val in arr[:,1] ]).reshape(-1,1)
concatenate the new column to the existing array
new_arr = np.concatenate([arr, new_col],axis=1)


text:
Q: NestJS global auth global guard clashing with RabbitMQ subscriber I'm using @golevelup/nestjs-rabbitmq to handle RabbitMQ messages from a queue, the global guard is intercepting the requests from the queue. Is there any way to prevent the global guard to get these requests?
Auth guard
@Injectable()
export default class GqlAuthGuard extends AuthGuard(AuthStrategy.Jwt) {
  constructor(private reflector: Reflector) {
    super();
  }

  getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);

    return ctx.getContext();
  }

  canActivate(context: ExecutionContext) {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (isPublic) {
      return true;
    }

    return super.canActivate(context);
  }
}

RabbitMQ Subscriber
@SubscribeToEvent({
    queue: Topic.SendSurvey,
  })
  async handler({ surveyId, schedulingEventId }: HandlerParams) {
    this.logger.info('Handling message', surveyId, schedulingEventId);

    this.surveysService.dispatch(surveyId, schedulingEventId);
  }

The error I'm getting
[22-03-24 02:52:31] [error] [app] TypeError: Cannot read properties of undefined (reading 'req') {"0":"MotivatoExceptionsHandler"}
[22-03-24 02:52:31] [error] [app] TypeError: Cannot read properties of undefined (reading 'req') {"0":"MotivatoExceptionsHandler"}
[22-03-24 02:52:31] [error] [app] TypeError: Cannot read properties of undefined (reading 'req') {"0":"MotivatoExceptionsHandler"}
[22-03-24 02:52:31] [error] [app] TypeError: Cannot read properties of undefined (reading 'req') {"0":"MotivatoExceptionsHandler"}

I tried changing the getRequest but it didn't work

A: async canActivate(context: ExecutionContext): Promise<boolean> {
  const type = context.getType<'rmq'>()
  if (type === 'rmq') {
    return true
  }
  ...
}

It works when adding in this way


text:
Q: Extracting Tweets for a week using Tweepy I want to store tweets in CSV, I used tweepy and I managed to store it in CVS but it only extracts data for one day. I want to extract and store data for a week without needing to extract it every day.
This is what I have done:
def tweets_to_data_frame(public_tweets):
    df = pd.DataFrame(data=[tweet.text for tweet in public_tweets], columns=['Tweets'])
    df['len'] = np.array([len(tweet.text) for tweet in public_tweets])
    df['date'] = np.array([tweet.created_at for tweet in public_tweets])
    df['retweets'] = np.array([tweet.retweet_count for tweet in public_tweets])
    df['lang'] = np.array([tweet.lang for tweet in public_tweets])
    return df

public_tweet= api.search('donald trump')
df = tweets_to_data_frame(public_tweet)
df.to_csv('donaldtrump.csv')
df.head(15)
    Tweets  len date    retweets    lang
0   RT @mehdirhasan: Stephen Miller's Jewish uncle...   140 2019-04-09 11:08:23 67  en
1   RT @errollouis: "If the House ever gets his re...   140 2019-04-09 11:08:23 7927    en
2   RT @BillKristol: "This is what Kirstjen Nielse...   140 2019-04-09 11:08:22 73  en
3   RT @Newsweek: Trump claimed he wouldn't have t...   140 2019-04-09 11:08:21 7   en
4   RT @mehdirhasan: Stephen Miller's Jewish uncle...   140 2019-04-09 11:08:20 67  en
5   The real reason Donald Trump just fired the he...   112 2019-04-09 11:08:19 0   en
6   RT @BillKristol: "This is what Kirstjen Nielse...   140 2019-04-09 11:08:19 73  en
7   RT @BobbyEberle13: Ilhan Omar is now praying f...   140 2019-04-09 11:08:18 457 en
8   The guy met the queen last time out and lots o...   140 2019-04-09 11:08:17 0   en
9   RT @PalmerReport: Donald Trump's deconstructio...   135 2019-04-09 11:08:17 107 en
10  RT @ByronYork: Donald Trump has been paying ta...   139 2019-04-09 11:08:16 1232    en
11  RT @mehdirhasan: Stephen Miller's Jewish uncle...   140 2019-04-09 11:08:16 67  en
12  RT @SayWhenLA:  YUGE !!\n\nPresident Donald J...  140 2019-04-09 11:08:15 1316    en
13  "As long as you're going to be thinking anyway...   100 2019-04-09 11:08:15 0   en
14  RT @TheLastRefuge2: Diana West Discusses The R...   140 2019-04-09 11:08:15 113 en

What I want is the data for one week,
my idea is:
def tweets_to_data_frame1(public_tweets):
    for tweets in tweepy.Cursor(api.search,q = (public_tweets),count=100,
                           since = "2019-04-04",
                           until = "2019-04-07").items():
        df = pd.DataFrame(data=[tweets.text for tweet in tweets], columns=['Tweets'])
        df['len'] = np.array([len(tweets.text) for tweet in tweets])
        df['date'] = np.array([tweets.created_at for tweet in tweets])
        df['retweets'] = np.array([tweets.retweet_count for tweet in tweets])
        df['lang'] = np.array([tweets.lang for tweet in tweets])

        return df

df1 = tweets_to_data_frame1('donald trump')

error:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-96745c16c99c> in <module>
----> 1 df1 = tweets_to_data_frame1('donald trump')

<ipython-input-23-e5866a4adb3f> in tweets_to_data_frame1(public_tweets)
      3                            since = "2019-04-04",
      4                            until = "2019-04-07").items():
----> 5         df = pd.DataFrame(data=[tweets.text for tweet in tweets], columns=['Tweets'])
      6
      7         #df['id'] = np.array([tweet.id for tweet in tweets])

TypeError: 'Status' object is not iterable

expected results:
Tweets  len date    retweets    lang
0   RT @mehdirhasan: Stephen Miller's Jewish uncle...   140 2019-04-09 11:08:23 67  en
1   RT @errollouis: "If the House ever gets his re...   140 2019-04-09 11:08:23 7927    en
2   RT @BillKristol: "This is what Kirstjen Nielse...   140 2019-04-09 11:08:22 73  en
3   RT @Newsweek: Trump claimed he wouldn't have t...   140 2019-04-09 11:08:21 7   en
4   RT @mehdirhasan: Stephen Miller's Jewish uncle...   140 2019-04-09 11:08:20 67  en
5   The real reason Donald Trump just fired the he...   112 2019-04-09 11:08:19 0   en
6   RT @BillKristol: "This is what Kirstjen Nielse...   140 2019-04-09 11:08:19 73  en
7   RT @BobbyEberle13: Ilhan Omar is now praying f...   140 2019-04-09 11:08:18 457 en
8   The guy met the queen last time out and lots o...   140 2019-04-09 11:08:17 0   en
9   RT @PalmerReport: Donald Trump's deconstructio...   135 2019-04-09 11:08:17 107 en
10  RT @ByronYork: Donald Trump has been paying ta...   139 2019-04-09 11:08:16 1232    en
11  RT @mehdirhasan: Stephen Miller's Jewish uncle...   140 2019-04-09 11:08:16 67  en
12  RT @SayWhenLA:  YUGE !!\n\nPresident Donald J...  140 2019-04-09 11:08:15 1316    en
13  "As long as you're going to be thinking anyway...   100 2019-04-09 11:08:15 0   en
14  RT @TheLastRefuge2: Diana West Discusses The R...   140 2019-04-09 11:08:15 113 en

but for one week

A: So I guess the issue is here:
for tweets in tweepy.Cursor(api.search,q = (public_tweets),count=100,since = "2019-04-04",until = "2019-04-07").items():

tweepy.Cursor(...).items() is a list. So each value of tweets variable is a single tweet. And then you're trying to using list comprehension, so you are trying to iterate over that single tweet. That is exactly what error message told you.
What you could do instead would be something like:
tweets = tweepy.Cursor(...).items()
df = pd.DataFrame(data=[tweet.text for tweet in tweets], columns=['Tweets'])

BTW also I would rename public_tweets argument of def tweets_to_data_frame1(public_tweets):
public_tweets argument in this case is just a search query string so the name is misleading


text:
Q: 7z program prompts and asks for the password if I didn't provide one. How to let it just errors out and exit in this case? I'm using the 7z.exe program to extract some .rar files. If the file is a password protected file, and if I didn't provide the password, the 7z program prompts and asks for the password. It looks like this:

7-Zip 18.06 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2018-12-30

Scanning the drive for archives:
1 file, 10199038 bytes (9960 KiB)

Extracting archive: c:\temp\test\a.rar

Enter password (will not be echoed):

Is it possible to modify this behavior so that when I didn't provide a password, it just errors out and exit? Thanks.
Btw, I'm on Windows 10.


text:
Q: Aguardar finalização da thread antes de encerrar o programa Tenho um loop while que finaliza somente quando aperto a tecla q, então o programa é encerrado. Dentro desse loop, em determinado momento ou condição, inicio uma thread que demora mais ou menos uns 10 segundos para executar.
Meu problema é, se saio do loop apertando q com uma thread em execução, esta é cancelada.
Eu gostaria que o loop/script aguardasse a execução da thread, para depois finalizar o programa. É possível isso?
Obrigado.

A: Além do modo mencionado pelo Felipe Avelar usando o método Thread.is_alive(), há também o método Thread.join(). Ambos podem ser utilizados em conjunto.
Quando Thread.join() é chamado, diz a thread principal para esperar que uma determinada thread termine, antes que a thread principal prossiga e execute a próxima instrução. Segue um exemplo:
import time, threading

def fun():
    for i in range(5):
        time.sleep(1)
        print(i)

def main():
    thread = threading.Thread(target=fun)
    thread.start()
    thread.join()
    # A thread foi finalizada, fazer algo a partir daqui
    print("Thread finalizada")

main()

DEMO


text:
Q: What is the difference between FUTEX_WAIT and FUTEX_WAIT_PRIVATE? I have been tracing a process with strace and have seen entries such as:
futex(0x7ffff79b3e00, FUTEX_WAKE_PRIVATE, 1) = 1
futex(0x7ffff79b3e00, FUTEX_WAIT_PRIVATE, 2, NULL) = 0

However, when I looked at the man page for futex, I have only seen entries such as FUTEX_WAIT and FUTEX_WAKE.  So my question is what does _PRIVATE that is appended to the end of these names in my strace output mean?  For instance is there any difference between something like FUTEX_WAKE that is documented in the futex man page and FUTEX_WAKE_PRIVATE that I see in the strace output or can I assume that they are the same when I am trying to understand what is happening with the program I am debugging.

A: This is an optimization done by linux/glibc to make futexes faster when they're not shared between processes. Glibc will use the _PRIVATE versions of each of the futex calls unless the PTHREAD_PROCESS_SHARED attribute is set on your mutex
It's explained in more detail here: http://lwn.net/Articles/229668/
For the purposes of your debugging, you can just ignore the _PRIVATE suffixes


text:
Q: How to get HDMI audio on RX 480? My RX 480 is not working well with Ubuntu 16.04.2. I finished the installation yesterday and since then I do not have audio over HDMI. I've tried several options among them I upgraded Mesa, tried the AMD GPU Pro. Nothing is solving my problem. The other issue that I have is when I use the AMD GPU Pro the monitor linked over HDMI will just turn black only the monitor using the DP port is working. I am wondering if this is an issue related to Ubuntu if so what is the best distro for the RX480?

A: Did you check out the kernel recommended here?
https://www.phoronix.com/scan.php?page=news_item&px=Ubuntu-AMDGPU-DC-Kernel
I had no audio over HDMI on with my RX 480 on ubuntu 16+. After installing the kernel with AMDGPU DC/DAL it all worked perfectly


text:
Q: Что значит это выражение в с#? return
    string.IsNullOrEmpty(wb) ? AddressType.InternalAddress : AddressType.ExternalAddress;

A: return string.IsNullOrEmpty(wb) ?
   AddressType.InternalAddress : AddressType.ExternalAddress;

Если значением переменной wb является пустая строка string.Empty (или просто "") или значение null - будет возвращено значение AddressType.InternalAddress, в противном случае будет возвращено AddressType.ExternalAddress.
Справка MSDN:

*

*Оператор ?: (справочник по C#)

*Метод String.IsNullOrEmpty

*Поле String.Empty

A: Альтернативная форма записи условия if:
if (string.IsNullOrEmpty(wb))
{
    return AddressType.InternalAddress;
}
else
{
    return AddressType.ExternalAddress;
}

A: Если строка wb пустая или не инициализирована - вернуть InternalAddress иначе вернуть ExternalAddress.
MSDN


text:
Q: Facebook redirect buton In this post, Facebook like button that redirects?, I saw a code to redirect after doing a Facebook "like".
I pasted in there, but I can't figure out how to put the link I want to redirect to?

A: If you got everything else running and it is really just the redirect that you can't manage, then replace the 'alert' lines in Ottos example with window.location = "http://www.your-domain.tld/".


text:
Q: Keycloak for backend service We have some APIs that we'd like to allow a specific backend service we'd like Keycloak to work with. We have it working with regular users with the traditional username/password type login. As you can imagine, we don't want to have a password based system, but ideally some sort of long key we can weld into the calling app to start the authentication process. If it helps to know, I'd like this to be a stateless JWT solution (eventually anyway). Yes, I've seen the documentation, but I don't know where this is talked about. Can someone send me a good link.

A: Client Credentials Flow in OAuth 2.0 for backend service.
This is good overview of OAuth Flow
Diagrams And Movies Of All The OAuth 2.0 Flows

How to call Client Credentials  in Keycloak
What is a PAT and how to obtain it
API format
curl -X POST \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -d 'grant_type=client_credentials&client_id=${client_id}&client_secret=${client_secret}' \
    "http://localhost:8080/realms/${realm_name}/protocol/openid-connect/token"

Keycloak: Client Credentials Grant Example
Keycloak Realm VS Keycloak Client


text:
Q: Replace devise_error_messages! with flash messages I generated my devise views using rails g devise:views users
I generated my devise controllers using rails g devise:controllers users
I added my new controllers in routes.rb:
  devise_for :users, controllers: { sessions: "users/sessions",
                                    confirmations: "users/confirmations",
                                    registrations: "users/registrations",
                                    passwords: "users/passwords",
                                    unlocks: "users/unlocks"}

I changed my flash messages to handle Arrays according to this answer: rails - Devise - Handling - devise_error_messages
Like this:
<% flash.each do |key, value| %>
    <% if value.class == Array %>
        <% value.each do |message| %>
            <div class="<%= flash_class(key) %>">
                <%= message %>

        <% end %>
    <% else %>
        <div class="<%= flash_class(key) %>">
            <button type="button" class="close" data-dismiss="alert">×</button>
            <%= value %>

    <% end %>

<% end %>

My new custom registration controller:
class Users::RegistrationsController < Devise::RegistrationsController
# before_filter :configure_sign_up_params, only: [:create]
# before_filter :configure_account_update_params, only: [:update]

  # GET /resource/sign_up
  # def new
  #   super
  # end

  # POST /resource
  # def create
  #   super
  # end

  # GET /resource/edit
  # def edit
  #   super
  # end

  # PUT /resource
  # def update
  #   super
  # end

  # DELETE /resource
  # def destroy
  #   super
  # end

  # GET /resource/cancel
  # Forces the session data which is usually expired after sign
  # in to be expired now. This is useful if the user wants to
  # cancel oauth signing in/up in the middle of the process,
  # removing all OAuth session data.
  # def cancel
  #   super
  # end

  # protected

  # You can put the params you want to permit in the empty array.
  # def configure_sign_up_params
  #   devise_parameter_sanitizer.for(:sign_up) << :attribute
  # end

  # You can put the params you want to permit in the empty array.
  # def configure_account_update_params
  #   devise_parameter_sanitizer.for(:account_update) << :attribute
  # end

  # The path used after sign up.
  # def after_sign_up_path_for(resource)
  #   super(resource)
  # end

  # The path used after sign up for inactive accounts.
  # def after_inactive_sign_up_path_for(resource)
  #   super(resource)
  # end
  flash[:notice] = flash[:notice].to_a.concat resource.errors.full_messages
end

When i add this line:
flash[:notice] = flash[:notice].to_a.concat resource.errors.full_messages

I get this error:

undefined local variable or method `flash' for Users::RegistrationsController:Class

A: I stil don't understand what went wrong with the mentioned solution but found instead a better one I think:
Step 1:
Create a file devise_helper.rb where you override the devise_error_messages! method and copy all errors to a flash notice array
module DeviseHelper
  def devise_error_messages!
    if resource.errors.full_messages.any?
        flash.now[:error] = resource.errors.full_messages
    end
    return ''
  end
end

Step 2:
In application_helper.rb define a new method which configures your html classes for bootstrap:
def flash_class(level)
    case level
        when 'notice' then "alert alert-dismissable alert-info"
        when 'success' then "alert alert-dismissable alert-success"
        when 'error' then "alert alert-dismissable alert-danger"
        when 'alert' then "alert alert-dismissable alert-danger"
    end
end

Step 3:
Configure your flash notice to parse arrays:
<% flash.each do |key, value| %>
    <% if value.class == Array %>
        <div class="<%= flash_class(key) %>">
            <button type="button" class="close" data-dismiss="alert">×</button>
            <% value.each do |message| %>
                <%= message %>

            <% end %>

    <% else %>
        <div class="<%= flash_class(key) %>">
            <button type="button" class="close" data-dismiss="alert">×</button>
            <%= value %>

    <% end %>
<% end %>

Step 4
Make sure you call the NEW devise_error_messages! in your devise registrations view which adds all errors to flash messages which can then be displayed using you flash render layout (in my case _error.html.erb):

Sign up

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>
  <%= render 'layouts/error' %>

    <%= f.label :email %>

    <%= f.email_field :email, autofocus: true %>

    <%= f.label :password %>
    <% if @validatable %>
    (<%= @minimum_password_length %> characters minimum)
    <% end %>

    <%= f.password_field :password, autocomplete: "off" %>

    <%= f.label :password_confirmation %>

    <%= f.password_field :password_confirmation, autocomplete: "off" %>

    <%= f.submit "Sign up" %>

<% end %>

<%= render "users/shared/links" %>

A: A bit more DRY - the view without the application helper flash_card and duplicated html:
add .alert-error in your CSS
<% flash.each do |key, value| %>
    <div class="alert alert-dismissable alert-<% key %>">
        <button type="button" class="close" data-dismiss="alert">×</button>
        <% if value.class == Array %>
            <% value.each do |message| %>
                <%= message %>

            <% end %>
        <% else %>
            <%= value %>
        <% end %>

<% end %>

A: Since I can omit the IF whether it is an array, I like to write like the following.
<% flash.each do |key, value| %>
  <div class="alert alert-dismissable alert-<% key %>">
    <button type="button" class="close" data-dismiss="alert">×</button>
    <% [*value].each do |message| %>
      <%= message %>

    <% end %>

<% end %>


text:
Q: Toggle Boolean on UITableView Selected Row I'm trying to toggle a Boolean value when a table row is selected.  This code was working when my table rows contained NSObjects (in a different class)...I simplified my code so that the rows only contain strings and not objects (cut out the class), but now the boolean won't toggle because my instance variable is a string.  Here's the original working code:
Declared in XYZObject:
@property BOOL checked;

Table view didSelectRowAtIndexPath:
XYZObject *tappedItem = [myArray objectAtIndex:indexPath.row];
tappedItem.checked = !tappedItem.checked;
NSString *addedItem = cell.textLabel.text;
if(!tappedItem.checked) {
    [newArray removeObject:addedItem];
} else {
    [newArray addObject:addedItem];
}

When I change XYZObject to NSString and move the Bool property to the table view, I get the "Property 'checked' not found on object of type 'NSString *'.  Changing NSString to NSObject does the same thing.  If I change NSString to XYZMyTableViewController, it will now compile but then breaks at runtime due to "unrecognized selector sent to instance".
So my question would be, can I toggle the 'checked' Bool value on an array of strings?
UPDATE/SOLUTION
I was able to solve the problem by eliminating the Bool entirely and just using:
if (cell.accessoryType == UITableViewCellAccessoryNone)
{
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    [newArray addObject:addedItem];
}
else {
    cell.accessoryType = UITableViewCellAccessoryNone;
    [newArray removeObject:addedItem];
}

I'm not particularly happy as I had some other methods using 'checked', but I should be able to just rewrite them in the same way.  I'd still like to know why I wasn't able to toggle a bool value on a string that's in my table cell.


text:
Q: Java Null Pointer Exception for JSON Object This is my code and it throws java null pointer exception at a particular JSON Object in my code, named "films". I don't understand why it deems this as "null". Where the error is being given, is where the code should read the contents of the txt file based on the method "readJSONFile". This method adds the elements of the txt file to a list. The new film to be added needs to be added to the JSON object but this does not work as films is apparently "null".
package application;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

import org.json.simple.JSONObject;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;

public class FilmManagement {

    private File selectedImage;

    @FXML
    private Button backBtn, homeBtn, uploadImageBtn, viewFilmsBtn, addFilmBtn;
    @FXML
    private Text newFilmTitle, newFilmDescription, newFilmTime1, newFilmTime2, newFilmTime3, newFilmAge, newFilmRating;
    @FXML
    private Label  newFilmStartDate, newFilmEndDate;
    @FXML
    private TextArea filmDescription;
    @FXML
    private DatePicker filmStartDate, filmEndDate;
    @FXML
    private TextField filmTitle, filmTrailer, filmRating;
    @FXML
    private ComboBox<String> filmTime1, filmTime2, filmTime3, filmAge;
    @FXML
    private ImageView uploadedFilmPoster;

    @FXML
    void initialize() throws IOException{
        ObservableList<String> obsList1 = FXCollections.observableArrayList("13:00", "14:00", "15:00", "16:00", "17:00",
                "18:00", "19:00", "20:00", "21:00", "22:00", "23:00", "00:00", "01:00", "02:00", "03:00");
        ObservableList<String> obsList2 = FXCollections.observableArrayList("U", "PG", "12A", "15", "18", "R");
        filmAge.setItems(obsList2);
        filmAge.setValue("12A");
        newFilmAge.setText("12A");
        filmTime1.setItems(obsList1);
        filmTime2.setItems(obsList1);
        filmTime3.setItems(obsList1);
        filmTime1.setValue("21:00");
        newFilmTime1.setText("21:00");
        filmStartDate.setValue(LocalDate.now());
        LocalDate startDate = filmStartDate.getValue();
        String startDateFormatted = startDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
        newFilmStartDate.setText(startDateFormatted);
    }

    public void goBack(ActionEvent event) throws IOException{
        Main m = new Main();
        m.changeScene("Employee Home.fxml");
    }

    public void goHome(ActionEvent event) throws IOException{
        Main m = new Main();
        m.changeScene("Employee Home.fxml");
    }

    public void goToViewFilms(ActionEvent event) throws IOException{
        Main m = new Main();
        m.changeScene("View Films.fxml");
    }

    //Method that gets called every time the user enters a date, time or age when adding a new movie.
    @FXML
    public void updateDateTimeAge(ActionEvent e) {

        try {
            switch (((Node) e.getSource()).getId()) {
            case "filmStartDate":
                LocalDate startDate = filmStartDate.getValue();
                String startDateFormatted = startDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
                newFilmStartDate.setText(startDateFormatted);
                break;
            case "filmEndDate":
                LocalDate endDate = filmEndDate.getValue();
                String endDateFormatted = endDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
                newFilmEndDate.setText(endDateFormatted);
                break;
            case "filmTime1":
                newFilmTime1.setText(filmTime1.getValue().toString());
                break;
            case "filmTime2":
                newFilmTime2.setText(filmTime2.getValue().toString());
                break;
            case "filmTime3":
                newFilmTime3.setText(filmTime3.getValue().toString());
                break;
            case "filmAge":
                newFilmAge.setText(filmAge.getValue().toString());
                break;
            }
        } catch (NullPointerException ex) {
            ex.getMessage();
        }
    }

    //Method that gets called every time the user types in any TextField when adding a movie
    @FXML
    public void updateFilmText(KeyEvent e) {

        switch (((Node) e.getSource()).getId()) {
        case "filmTitle":
            if (filmTitle.getText().length() > 20) {
                filmTitle.setEditable(false);
            }
            break;
        case "filmDescription":
            if (filmDescription.getText().length() > 220) {
                filmDescription.setEditable(false);
            }
            break;
        case "filmRating":
            //String ratingRegex = "^([1-9]\\d*|0)(\\.\\d)?$";
            //Pattern p = Pattern.compile(ratingRegex)
            if (Float.parseFloat(filmRating.getText()) > 10) {
                filmRating.setEditable(false);
            }
            break;
        }

        if (e.getCode().equals(KeyCode.BACK_SPACE)) {
            filmTitle.setEditable(true);
            filmDescription.setEditable(true);
            filmRating.setEditable(true);
        }

        switch (((Node) e.getSource()).getId()) {
        case "filmTitle":
            newFilmTitle.setText(filmTitle.getText());
            break;
        case "filmDescription":
            newFilmDescription.setText(filmDescription.getText());
            break;
        case "filmRating":
            newFilmRating.setText(filmRating.getText()+"/10");
            break;
        }
    }

    //Method that gets called when the user clicks on the upload image button
    @FXML
    public void uploadImage(ActionEvent event) throws IOException {

        try {
            FileChooser fc = new FileChooser();
            selectedImage = fc.showOpenDialog(null);
            // checking that input file is not null and handling the exception
            if (selectedImage == null)
                return;
            else if (ImageIO.read(selectedImage) == null) {
                Alert alert = new Alert(AlertType.WARNING, "Please upload an image in JPG or PNG format!",
                        ButtonType.OK);
                alert.showAndWait();
                if (alert.getResult() == ButtonType.OK) {
                    return;
                }
            } else {
                Image img = SwingFXUtils.toFXImage(ImageIO.read(selectedImage), null);
                uploadedFilmPoster.setImage(img);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @SuppressWarnings("unchecked")
    @FXML
    public void storeFilmInfo(ActionEvent event) throws ParseException {

        try {
            validateFilmInput();

            // creating JSON objects
            JSONObject films = Main.readJSONFile("films.txt");
            JSONObject filmToAdd = new JSONObject();
            filmToAdd.put("description", filmDescription.getText());
            filmToAdd.put("trailer", filmTrailer.getText());
            filmToAdd.put("startDate", newFilmStartDate.getText());
            filmToAdd.put("endDate", newFilmEndDate.getText());
            filmToAdd.put("time1", newFilmTime1.getText());
            filmToAdd.put("time2", newFilmTime2.getText());
            filmToAdd.put("time3", newFilmTime3.getText());
            filmToAdd.put("age", newFilmAge.getText());
            filmToAdd.put("rating", newFilmRating.getText());
            films.put(filmTitle.getText(), filmToAdd);
            //System.out.println(films.toJSONString());

            // storing film in JSON file - filewriting
            String path = "C:\\Users\\ruben\\OneDrive\\Documents\\Ruben School\\Year 12\\Computer Science\\IA\\films.txt";
            // System.out.println(path);
            PrintWriter writer = new PrintWriter(new File(path));
            writer.print(films.toJSONString());
            writer.close();

            // storing film poster in film images folder
            String folderPath = "C:\\Users\\ruben\\eclipse-workspace\\Clubhouse Cinemas\\src\\Images";
            File uploads = new File(folderPath);
            File file = new File(uploads, filmTitle.getText() + ".png");
            InputStream input = Files.newInputStream(selectedImage.toPath());
            Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
            // confirmation alert to inform the employee of the newly added film
            Alert alert = new Alert(AlertType.INFORMATION, "The film " + filmTitle.getText() + " has been added!",
                    ButtonType.OK);
            alert.showAndWait();

            // reloading film list to include the recently added film, and
            // restoring all fields to empty
            // and closing alert on click
            if (alert.getResult() == ButtonType.OK) {
                Main.resetFilmList();
                Main.readJSONFile("films.txt"); //method in main for file reading - adds items to the list
                filmDescription.setText("");
                filmDescription.setText("");
                filmTitle.setText("");
                filmStartDate.setPromptText("dd/MM/yyyy");
                filmEndDate.setPromptText("dd/MM/yyyy");
                filmTime1.setPromptText("hh:mm");
                filmTime2.setPromptText("hh:mm");
                filmTime3.setPromptText("hh:mm");
                filmAge.setPromptText("");
                filmRating.setText("");
                alert.close();
            }
        } catch (FileNotFoundException e) {
            Alert alert = new Alert(AlertType.WARNING, "File Not Found!", ButtonType.OK);
            alert.showAndWait();
            if (alert.getResult() == ButtonType.OK) {
                alert.close();
            }
        } catch (IOException e) {
            Alert alert = new Alert(AlertType.WARNING, "Error: " + e.getMessage(), ButtonType.OK);
            alert.showAndWait();
            if (alert.getResult() == ButtonType.OK) {
                alert.close();
            }
        } catch (InvalidFilmInputException e) {
            Alert alert = new Alert(AlertType.WARNING, e.getMessage(), ButtonType.OK);
            alert.showAndWait();
            if (alert.getResult() == ButtonType.OK) {
                alert.close();
            }
        }
    }

    @SuppressWarnings("unlikely-arg-type")
    void validateFilmInput() throws InvalidFilmInputException, ParseException {

        try {
            if (filmTitle.getText().equals("") || filmDescription.getText().equals("")
                    || filmTrailer.getText().equals("") || filmStartDate.getValue().equals("dd/MM/yyyy")
                    || filmEndDate.getValue().equals("dd/MM/yyyy") || filmAge.getValue().equals("") || filmRating.getText().equals(""))
                throw new InvalidFilmInputException("Please complete all fields!");
            else if (selectedImage == null)
                throw new InvalidFilmInputException("Please add the film poster!");
            else if (filmStartDate.getValue().compareTo(LocalDate.now()) < 0)
                throw new InvalidFilmInputException("Start date cannot be before today!");
            else if (filmStartDate.getValue().compareTo(filmEndDate.getValue()) == 0)
                throw new InvalidFilmInputException("Screenings cannot start and end on the same day!");
            else if (filmStartDate.getValue().compareTo(filmEndDate.getValue()) > 0)
                throw new InvalidFilmInputException("End date cannot be before start date!");

            // checking that the title of the movie is unique
            for (Film c : Main.getFilmList()) {
                if (c.getTitle().equals(filmTitle.getText()))
                    throw new InvalidFilmInputException(
                            "The title " + filmTitle.getText() + " belongs to another scheduled movie!");
            }

            // looping through the films to find date and time conflicts
            for (Film c : Main.getFilmList()) {

                // converting movie start and end dates to LocalDate for
                // comparison
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
                LocalDate startDateFilms = LocalDate.parse(c.getStartDate(), formatter);
                LocalDate endDateFilms = LocalDate.parse(c.getEndDate(), formatter);

                // if the dates overlap...
                if (!(filmStartDate.getValue().compareTo(endDateFilms) > 0
                        || filmEndDate.getValue().compareTo(startDateFilms) < 0)) {

                    // System.out.println("startDate loop: " + startDateFilms);
                    // System.out.println("endDate loop: " + endDateFilms);

                    // ... and the time(s) overlap as well
                    String[] times = c.getTimes();
                    if (Arrays.asList(times).contains(filmTime1.getValue())
                            || Arrays.asList(times).contains(filmTime2.getValue())
                            || Arrays.asList(times).contains(filmTime3.getValue())) {
                        throw new InvalidFilmInputException("The screening time(s) of your film: " + filmTitle.getText()
                                + " overlap(s) with the film: " + c.getTitle().toString() + "!");
                    }
                }
            }
        } catch (NullPointerException e) {
            throw new InvalidFilmInputException("Please complete all fields!");
        }
    }
}

class InvalidFilmInputException extends Exception {

    private static final long serialVersionUID = 1L;

    InvalidFilmInputException(String s) {
        super(s);
    }
}

Below is the errors it gives me:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1857)
    at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1724)
    at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
    at javafx.graphics/javafx.scene.Scene$KeyHandler.process(Scene.java:4105)
    at javafx.graphics/javafx.scene.Scene.processKeyEvent(Scene.java:2156)
    at javafx.graphics/javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2630)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:218)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:150)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleKeyEvent$1(GlassViewEventHandler.java:250)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:424)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:249)
    at javafx.graphics/com.sun.glass.ui.View.handleKeyEvent(View.java:548)
    at javafx.graphics/com.sun.glass.ui.View.notifyKey(View.java:972)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
    at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: java.lang.reflect.InvocationTargetException
    at jdk.internal.reflect.GeneratedMethodAccessor21.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:77)
    at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:84)
    at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1852)
    ... 28 more
Caused by: java.lang.NumberFormatException: empty String
    at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
    at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
    at java.base/java.lang.Float.parseFloat(Float.java:461)
    at application.FilmManagement.updateFilmText(FilmManagement.java:150)
    ... 38 more
Unexpected token END OF FILE at position 0.
    at org.json.simple.parser.JSONParser.parse(Unknown Source)
    at org.json.simple.parser.JSONParser.parse(Unknown Source)
    at application.Main.readJSONFile(Main.java:83)
    at application.FilmManagement.storeFilmInfo(FilmManagement.java:210)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:77)
    at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:84)
    at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1852)
    at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1724)
    at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
    at javafx.graphics/javafx.scene.Node.fireEvent(Node.java:8792)
    at javafx.controls/javafx.scene.control.Button.fire(Button.java:203)
    at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:208)
    at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
    at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:247)
    at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
    at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3897)
    at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1878)
    at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2623)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:411)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:301)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:450)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:424)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:449)
    at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:557)
    at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:943)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
    at java.base/java.lang.Thread.run(Thread.java:832)
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1857)
    at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1724)
    at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
    at javafx.graphics/javafx.scene.Node.fireEvent(Node.java:8792)
    at javafx.controls/javafx.scene.control.Button.fire(Button.java:203)
    at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:208)
    at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
    at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:247)
    at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
    at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3897)
    at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1878)
    at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2623)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:411)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:301)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:450)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:424)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:449)
    at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:557)
    at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:943)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
    at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:77)
    at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:84)
    at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1852)
    ... 46 more
Caused by: java.lang.NullPointerException: Cannot invoke "org.json.simple.JSONObject.put(Object, Object)" because "films" is null
    at application.FilmManagement.storeFilmInfo(FilmManagement.java:221)
    ... 57 more

A: Your movies are not null, that's not the problem.
This is your error:
Caused by: java.lang.NumberFormatException: empty String.

This is mean that your JSONParser try to parse an empty string to a number. You need to check if all entries have the valid format.


text:
Q: Unable to compress into volumes with 7zip I'm trying to compress some files into a 7Z split archive from the command line. But when I run the following command:
7z.exe a -t7z myarchive.7z *.dat -v250m

I get the message 'Not implemented!'. It seems to work when I switch to -tzip (and .zip) instead of -t7z. Any ideas as to what the problem is? Btw, I'm running v9.20.


text:
Q: Using python, I'm trying to access text from a database, but I'm getting different results when I do just print vs a foreach loop Using python, I'm trying to access text from a database (FileMaker Pro) using a pyodbc connection. When I use a foreach loop, for some reason the text prints. But, when I just straight away print it then I think it prints the location or something. The following code explains it better:
 import pyodbc
 connectString = "DSN=FMODBC32;UID=...;PWD=..."
 connection = pyodbc.connect(connectString)
 cursor = connection.cursor()

 param = cursor.execute("select Parameters from Info")
       ## Parameters = fieldName in the database, Info = tableName in database

 print(param)
       ## This prints: <pyodbc.Cursor object at 0x08930C20>  (Is this the location?)

 for info in param:
     print(info)
       ## This prints the actual text I need, not the location

I want to just do print(param) and not a whole foreach loop to get the text I need. Any advice?

A: print(param)

only prints you the param object.
You should add
cursor = connection.cursor()
cursor.execute("select Parameters from Info")
param = cursor.fetchall()

and print(param) should be ok.


text:
Q: JavaFX ListView using custom component but with multiple columns? I was tinkering with the JFX Library for a project but I'm unable to render my UI the way I planned.
I was able to make a list view using custom components loaded with fxml but it seems like we can't make multiple columns.
What I have with ListView:

What I want :

I also took a look at TableView but the cell factory isn't loading my custom controller.
Is there any way around?

A: Use TilePane. I think this is the most correct answer to your question.


text:
Q: Combine lists in a list I have a list like
$`1`
[1] 1959   13

$`2`
[1] 2280  178   13

$`3`
[1] 2612  178   13

$`4`
[1] 2902  178   13

And the structure is something like:
structure(list(`1` = c(1959, 13), `2` = c(2280, 178, 13), `3` = c(2612,
178, 13), `4` = c(2902, 178, 13)......,.Names = c("1", "2", "3", "4"....)

How can I combine the lists within this list and produce a list like:
$`list`
[1] 1959   13
[2] 2280  178   13
[3] 2612  178   13
[4] 2902  178   13

A: This is the closest I can get to what you're asking for as a matrix:
LIST <- structure(list(`1` = c(1959, 13), `2` = c(2280, 178, 13), `3` = c(2612,
178, 13), `4` = c(2902, 178, 13)))

cbind.fill <-
function(...) {
    nm <- list(...)
    nm<-lapply(nm, as.matrix)
    n <- max(sapply(nm, nrow))
    do.call(cbind, lapply(nm, function(x) rbind(x,
        matrix(, n - nrow(x), ncol(x)))))
}

t(do.call('cbind.fill', LIST))
print(X$list, na.print="", quote=FALSE)

Or using plyr
LIST <- lapply(LIST, function(x) data.frame(t(x)))
library(plyr)
rbind.fill(LIST)

Maybe you just don't want names ?
If so...
names(LIST) <- NULL
LIST

I think I just don't get the output structure you're after.

A: Try the following code. The problem is that I'm not too sure what you want as your output; you're calling it a list but it looks an awful lot like matrix. Assuming that you do want it as a matrix, the following should do the trick:
x <- list()
x$`1` <- c(1959, 13)
x$`2` <- c(2280, 178, 13)
x$`3` <- c(2612, 178, 13)
x$`4` <- c(2902, 178, 13)

# maximum number of elements in any vector
max <- max(sapply(x, function(y) length(y)))

# make all vectors the same length
x <- lapply(x, function (y){length(y) <- max; y})

# combine them in a matrix
result <- do.call(rbind, x)

result:
> result
  [,1] [,2] [,3]
1 1959   13   NA
2 2280  178   13
3 2612  178   13
4 2902  178   13

You can always save this matrix output as an element of a list. I got the idea to make the lengths equal from here.
You won't be able to get rid of the NA if you want your matrix to be numeric (you can always turn it into characters and make the NA be "", but it's probably not a good idea for further work with the matrix).
It may be that I'm confused and that you want a list after all, but as Josh mentioned in his comment, your data is correct to begin with in that case.


text:
Q: use a Bottle server to re-stream a content (e.g. mimic port forwarding) I have a number of raspberry PIs on an internal network streaming successfully an mjpg feed through HTTP.
The PI is controlled by a WEB server that runs on a hub. The hub belongs to the same network of the PIs but can also be reached through the internet.
Now - I want the HUB to relay the stream that it gets from the PI from within its own webserver.
In principle, in pseudocode, I would want something like this running on the HUB:
@app.get('/device/<id>/stream')
def get_device_stream(rPI):

    url = "http://rPI.ip:rPI.port/stream.jpg"
    req = urllib2.Request(url)
    f = urllib2.urlopen(req, timeout=5)
    return f.read()

Obviously, this will not work because a live-feed does not have a Content-Length.
I can get this to work setting up a tcp forwarder but I am looking for a  solution that does not require me to create a port forwarding thread.

A: I found a solution. One needs to receive the stream and break it down into single frames and then send it out again as a video feed. Like so:
def relay_stream():
stream_url = "http://217.7.233.140:80/cgi-bin/faststream.jpg?stream=full&fps=0"

    req = urllib2.Request(stream_url)
    stream = urllib2.urlopen(req, timeout=5)
    bytes = b''
    while True:
        bytes += stream.read(1024)
        a = bytes.find(b'\xff\xd8') #frame starting
        b = bytes.find(b'\xff\xd9') #frame ending
        if a != -1 and b != -1:
            frame = bytes[a:b+2]
            bytes = bytes[b+2:]
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

@app.get('/device/<id>/stream')
@error_decorator
def get_device_stream(id):

    response.set_header('Content-type', 'multipart/x-mixed-replace; boundary=frame')
    return relay_stream()


text:
Q: apache don't rewrite index.php and others I have problems with my rewrite rules, I want that http://example.com/b/abc calls banner.php?b=abc, that works. But when I type http://example.com/index.php?mode=mybanners it will call banner.php?b=index.php?mode=mybanners (or something like this). My .htacces file:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule b/?(.+)$ ./banner.php?b=$1
    RewriteRule i/?(.+)$ ./banner.php?bi=$1
</IfModule>

Some ideas to let /index.php interact normal?

A: Try below rules :
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !^/index.php
    RewriteRule b/?(.+)$ ./banner.php?b=$1
</IfModule>


text:
Q: Cheerio: How to select by data tag Let's say I have an element like this:

Count: 3

How can I select that element by querying for the "counter" data-testid?

A: This is all just css so if you need reference look at the w3c specs:
$('[data-testid="counter"]')


text:
Q: Network connection settings on Android TV emulator I want to turn off network connection on Android TV emulator.
I found: Settings -> Network -> Wifi on/off, but I still have internet for my emulator device. Is there some shortcut (iMac) or easy terminal command that would disable network?
Running ./adb shell am broadcast -a gives me this messageL
android.intent.action.WIFI_OFF
Broadcasting: Intent { act=android.intent.action.WIFI_OFF }
Broadcast completed: result=0

But I still have network connection on my emulator.

A: if it is rooted device then use the below code to disable the  network
try {
Runtime.getRuntime().exec("su -c svc data disable");
} catch (IOException e) {
Log.d("Error", e.getMessage());
}

again want to enable simply change disable to enable
in manifest file
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

OR
WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the below one to check enabled or not
boolean wifiEnabled = wifiManager.isWifiEnabled()

Permissions in Manifest
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>


text:
Q: Previous Values and subtract to Current Value thru DAX Newbie Here, I have a question can you help me on how to minus the previous value to current value.
Here's my sample data

Year
Month
ColumnNames_Arr[1]
Dax_Index
Prev Row
ABS Pearl - PP Variance
Prev Value

2022
January
4
1
1
47,995,316,145.30
41,311,832,137,577.00

2022
January
5
2
1
45,209,572,763.95
41,322,103,602,554.00

2022
January
6
3
2
47,356,507,708.56
41,347,782,264,996.50

2022
January
7
4
3
44,216,874,999.36
41,347,782,268,939.00

2022
January
8
5
4
43,355,752,518.63
41,352,918,001,428.00

2022
January
9
6
5
30,737,632,408.37
41,352,917,997,485.00

2022
January
10
7
6
12,426,555,561.18
41,440,202,704,645.70

2022
January
11
8
7
8,455,805,007.64
13,653,252,477,600.00

2022
January
12
9
8
4,270,561,948.35
13,653,252,477,600.00

2022
January
13
10
9
3,255,537,329.87
6,466,767,735,895.66

2022
January
14
11
10
1,413,187,797.47
4,251,783,486,823.47

2022
January
15
12
11
1,590,936,958.80
792,524,041,378.52

2022
January
20
13
12
1,166,652,069.73
792,622,029,019.64

2022
January
21
14
13
1,074,232,861.42
2,016,297,717,439.00

2022
January
22
15
14
417,314,123.54
2,016,297,717,439.00

2022
January
24
16
15
334,977,061.27
605,143,918,528.92

2022
January
25
17
16
337,486,960.07
258,818,798,710.00

2022
January
26
18
17
312,943,283.87
258,818,798,710.00

2022
January
28
19
18
309,823,301.63
258,818,798,710.00

2022
January
29
20
19
267,521,363.21
258,818,798,710.00

2022
January
34
21
20
265,011,464.41
45,829,617,248.84

2022
January
35
22
21
265,011,464.41
45,829,617,248.84

2022
February
4
1
1
61,329,820,813.11
51,799,995,259,173.30

2022
February
5
2
1
58,239,996,756.14
51,799,995,259,174.00

2022
February
6
3
2
71,458,764,215.45
51,812,661,843,819.00


text:
Q: How to display a small bar even when a value is zero in Google Charts? I have sometimes series where the values are all zero. When I apply a ColumnChart the figure is all empty, not showing that there are actually zero values.
How can I display the bars even when the values are zero?
I tried the following options:
{
     type: options.type,
     cssStyle: options.cssStyle,
     data: {},
     options: {
                chartArea:{width:'80%'},
                pointsVisible: true,
                lineWidth: 4,
                curveType: "none",
                fontName: "Open Sans",
                fontSize: 10,
                colors: options.colors,
                isStacked: "false",
                fill: 10,
                displayExactValues: true,
                vAxis: {viewWindowMode:'explicit', minValue: -1, viewWindow: {min:0}, gridlines: {"color": "#f2f2f2", "count": 2}, baselineColor: "#f2f2f2", textStyle: options.textStyle},
                hAxis: {gridlines: {"color": "#f2f2f2"}, baselineColor: "#f2f2f2", textStyle: options.textStyle},
                legend: {position: 'bottom', alignment: 'center', textStyle: options.textStyle},
}

A: a bar will only be displayed if the value is not equal to zero
however, using object notation, we can provide the value (v:) and the formatted value (f:)
using the following, the bar will display, but when hovered, the tooltip shows a value of zero
{v: 0.1, f: '0'}

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));

  var data = google.visualization.arrayToDataTable([
    ['x', 'y'],
    ['A', {v: 0.1, f: '0'}],
    ['B', 2],
    ['C', 3],
    ['D', 4]
  ]);

  google.visualization.events.addListener(chart, 'ready', function () {
    chart.setSelection([{row: 0, column: 1}]);
  });

  chart.draw(data, {
    tooltip: {
      trigger: 'both'
    }
  });
});

A: In your code, test for zero values and convert that to .1 or whatever is appropriate for your scale.
function vAxisTest (vAxis) {
   let scale = .1; //
   if(vAxis === 0) {
       vAxis = scale;
       return scale;
   }
  else { return vAxis; }
}


text:
Q: Why does a `null` Nullable have a hash code? Bit of a weird question...
But can anyone give me a justification for why this would be expected behaviour?
This just seems totally odd to me....
//Makes perfect sense
object o = null;
o.GetHashCode().Dump();

NullReferenceException: Object reference not set to an instance of an
  object.

//Seems very odd
int? i = null;
i.GetHashCode().Dump();

0

This obviously means:
int? zero = 0;
int? argh = null;

zero.GetHashCode() == argh.GetHashCode(); //true

A: It looks like documented behaviour of Nullable<T>.GetHashCode(), as documentation says:

The hash code of the object returned by the Value property if the
  HasValue property is true, or zero if the HasValue property is false.

A: The point here is that
int? i = null;

does not create a variable i which is null, but (by performing an implicit cast) a Nullable<int> instance which does not have a value.
This means the object/instance is not null (and as Nullable<T> is a struct/value type it actually can't be null) and therefore has to return a hash-code.
This is also documented here:

The hash code of the object returned by the Value property if the HasValue property is true, or zero if the HasValue property is false.

A: int? is actually just shorthand for Nullable<int>, a struct which wraps the int type in order to allow it to be null. Nullable can be used with any value type.
Because Nullable is actually a struct (it can't be null), it has to return something for a hash code, and normally it would return the value's hash code (presumably in order to be as transparent as possible to the value within). When the value is null, it is hard-coded to return 0 by default:
public override int GetHashCode() {
    return hasValue ? value.GetHashCode() : 0;
}

See here.


text:
Q: More efficent way to select number of occurences in a string Hi all i have the following script which is all fine and dandy and does the job, however i don't think it is very nice or efficient. Just wondering if there's a better and more efficient way of doing the same? The job is to calculate the number of occurrences of numbers in a number string and then select the total. So for example with the number '014812000', the expected outcome should be 6 as we have 4 x 0 occurrences and 2 x 1 occurrences. We are only concerned with occurrences over 1. Just to add this is being using in a user defined function.
DECLARE @Number nvarchar(50)
SET @Number = '014812000'

DECLARE @count0 int
DECLARE @count1 int
DECLARE @count2 int
DECLARE @count3 int
DECLARE @count4 int
DECLARE @count5 int
DECLARE @count6 int
DECLARE @count7 int
DECLARE @count8 int
DECLARE @count9 int

DECLARE @countTotal int
SET @countTotal = 0

SET @count0 = LEN(@Number) - LEN(REPLACE(@Number, '0', ''))
SET @count1 = LEN(@Number) - LEN(REPLACE(@Number, '1', ''))
SET @count2 = LEN(@Number) - LEN(REPLACE(@Number, '2', ''))
SET @count3 = LEN(@Number) - LEN(REPLACE(@Number, '3', ''))
SET @count4 = LEN(@Number) - LEN(REPLACE(@Number, '4', ''))
SET @count5 = LEN(@Number) - LEN(REPLACE(@Number, '5', ''))
SET @count6 = LEN(@Number) - LEN(REPLACE(@Number, '6', ''))
SET @count7 = LEN(@Number) - LEN(REPLACE(@Number, '7', ''))
SET @count8 = LEN(@Number) - LEN(REPLACE(@Number, '8', ''))
SET @count9 = LEN(@Number) - LEN(REPLACE(@Number, '9', ''))

IF @count0 > 1
    BEGIN
        SET @countTotal = @countTotal + @count0
    END
IF @count1 > 1
    BEGIN
        SET @countTotal = @countTotal + @count1
    END
IF @count2 > 1
    BEGIN
        SET @countTotal = @countTotal + @count2
    END
IF @count3 > 1
    BEGIN
        SET @countTotal = @countTotal + @count3
    END
IF @count4 > 1
    BEGIN
        SET @countTotal = @countTotal + @count4
    END
IF @count5 > 1
    BEGIN
        SET @countTotal = @countTotal + @count5
    END
IF @count6 > 1
    BEGIN
        SET @countTotal = @countTotal + @count6
    END
IF @count7 > 1
    BEGIN
        SET @countTotal = @countTotal + @count7
    END
IF @count8 > 1
    BEGIN
        SET @countTotal = @countTotal + @count8
    END
IF @count9 > 1
    BEGIN
        SET @countTotal = @countTotal + @count9
    END

SELECT @countTotal

A: You can use a number table to split the number to rows. Here I use master..spt_values.
select sum(C)
from (
       select count(*) as C
       from master..spt_values as N
       where N.type = 'P' and
             N.number between 1 and len(@Number)
       group by substring(@Number, N.Number, 1)
       having count(*) > 1
     ) as T

A: This would be able to handle your problem even if the number wasn't numeric, it can count any occurence of characters where more than 1 identical character exists.
It was made for a table characters.
declare @t table(number nvarchar(max))
insert @t values ('014812000')
insert @t values ('0148120001')
insert @t values ('0148120001aa')

;with a as
(
select number n, 0 i from @t
union all
select replace(n, cast(n as char(1)), ''),
case when replace(n, cast(n as char(1)), '') = stuff(n,1,1,'') then i else
i + cast(len(n) - len(replace(n, cast(n as char(1)), '')) as int)
end
from a
where n <> ''
)
select i from a where n = ''

If you only want for one specific number this is how you could use it:
declare @Number nvarchar(max)
set @Number = '014812000'

;with a as
(
select @number n, 0 i
union all
select replace(n, cast(n as char(1)), ''),
case when replace(n, cast(n as char(1)), '') = stuff(n,1,1,'') then i else
i + cast(len(n) - len(replace(n, cast(n as char(1)), '')) as int)
end
from a
where n <> ''
)
select i from a where n = ''

A: take a look at this. Its using a custom function.
FUNCTION dbo.com_CountString(@Input nVarChar(max), @SearchString nVarChar(1000))
RETURNS INT
BEGIN
DECLARE @Count INT, @Index INT, @InputLength INT, @SearchLength INT
DECLARE @SampleString INT

if @Input is null or @SearchString is null
    return 0

SET @Count = 0
SET @Index = 1
SET @InputLength  = LEN(@Input)
SET @SearchLength = LEN(@SearchString)

if @InputLength = 0 or @SearchLength = 0 or @SearchLength > @InputLength
    return 0

WHILE @Index <= @InputLength - @SearchLength + 1
BEGIN
    IF SUBSTRING(@Input, @Index, @SearchLength) = @SearchString
    BEGIN
        SET @Count = @Count + 1
        SET @Index = @Index + @SearchLength
    END
    ELSE
        SET @Index = @Index + 1
END

RETURN @Count
END


text:
Q: Search in Japan Language in Salesforce using SOQL? I have create a custom lookup in my salesforce one app. when i tried to enter a search term in Japan language it won't get any result and if i type in english it show results.
Any Solution for this?
Thanks

A: There is a field Account name (local) [in case of Account] is associated with SObject which will store information in local language, run SOQL on that field it will give results. Every object has this field available.
Hope this helps


text:
Q: The relation of a set $ A$ and the closure of ${\rm conv} B$ We have $A,\ B,\ C\subset \mathbb{R}^{p}$, nonempty, $C$ is bounded and $A+C \subset B+C$. Prove that $A \subset {\rm cl}({\rm conv}B)$.
For ${\rm cl}({\rm conv}B)$, I started using the definition with sequences of a closed set, but I don't know how to reffer to the information that $C$ is bounded.

A: Here we need the condition where $C$ is bounded : If not, assume
that $C = \mathbb{R}^p$. Hence for any $A,\ B$ we have $A+C\subset
B+C$
Assume that $C$ is bounded and $A+C\subset B+C$ Hence $A+C \subset
X+ C$ where $X ={\rm cl\ conv} \ B$. Assume that $a\in A-X$. Hence
there is a plane $l$ s.t. $l$ is between $a$ and $X$, since $X$ is
convex.
Here we can assume that origin $o$ is in $C$, without generality.
There is $v\in C$ s.t. $v$ is orthogonal to $l$ and $|v|$ is
largest. Hence $a+v \in X+C$, which is a contradiction. Hence
$A\subset X$.


text:
Q: How to convert entire list in a column to string to pass into API? I need to pass a comma seperated string into an api.
currently df looks like this:
id      tags
1       ['dc','independent_press','exclusive_variants','marvel']

The API docs for tags found here say that I need to pass in a string like so:
'comics,marvel,dc,batman'

How can I convert the list in the tags column into a string so the df looks like this:
id      tags
1       'comics,marvel,dc,batman'

I would like to pass this string into the api like so:
for index, row in df.iterrows():
            params = {
                'id': row['id'],
                'tags':row['tag'],
                }
            r = requests.post(url, data=params, headers=headers)
            print(r)

I tried a string replace like so:
df.tags.str.replace('[',"'")

but got result:
0   NaN

edit:
dataframe head in dict:
{'Email': {0: 'test@test.com'},
 'subcategory': {0: 'comics'},
 'category': {0: 'comic'},
 'id': {0: '1'},
 'is_new': {0: 1},
 'tag': {0: 'dc, independent_press, exclusive_varients, marvel'}}

A: It looks like tags is just a list of str, so this should do the trick:
for index, row in df.iterrows():
    params = {
        'id': row['id'],
        'tags': ','.join(row['tags']),
    }
    print(params)

    r = requests.post(url, data=params, headers=headers)
    print(r)


text:
Q: Setting TTL for expire data from collection Is there a correct way to configure data self-deletion by key using the official mongo driver? The only method that I found in the Mongo-driver module is ExpireAfterSeconds, but I'm not sure how to use it correctly.
Here's the repository with what is ready at the moment.

A: You need to create an ttl index on the field which needs to be removed after n seconds.
In the below code snippet, have created an expirationTime field on which ttl can be set. After 60 seconds from the expirationTime set in the record, the record will be removed.
Following is the code to create a TTL index:
var ttl *int32
    *ttl = 60
    keys := bsonx.Doc{{Key: "expirationTime", Value: bsonx.Int32(int32(1))}}
    idx := mongo.IndexModel{Keys: keys, Options: &options.IndexOptions{ExpireAfterSeconds: ttl}}
    _, err := collection.Indexes().CreateOne(context.Background(), idx)
    if err != nil {
        fmt.Println("Error occurred while creating index", err)
    } else {
        fmt.Println("Index creation success")
    }


text:
Q: Regex capture groups confusion I have the following text

Jul 31, 2015 - Departure 2 stops Total travel time:20 h 40 m
  Aug 26, 2015 - Return 1 stop Total travel time:19 h 0 m Chicago
  nonstop

I want to get the digit that precedes text that looks like "stop(s)" and all instances of "nonstop", however I want both to be in the same capture group.
I wrote this regex
(\d)(?:\Wstops?)|(nonstop)
This does what I want but as you see it consists of two capture groups (group #1 for the digits and group #2 for 'nonstop'), can this be done with a single capture group?
My other question, is it possible to directly return 'nonstop' as 0 using regex, instead of processing the text in code later on?
Here is a live demo of my regex: regex101

A: You need to use positive lookahead assertion.
Matcher m = Pattern.compile("\\d(?=\Wstops?)|nonstop").matcher(s);
while(m.find())
{
System.out.println(m.group());
}

*

*\\d(?=\Wstops?) matches all the digits only if it's followed by a non-word character again followed by the string stop or stops

*| OR

*nonstop match the string nonstop


text:
Q: Count rows matching a criteria relative to current row I have a dataframe structured like this (but it actually has ~400k rows):
library(data.table)
df <- fread("    id     start     end
174095 2018-12-19 2018-12-31
227156 2018-12-19 2018-12-31
210610 2018-04-13 2018-09-27
 27677 2018-04-12 2018-04-26
370474 2017-07-13 2017-08-19
303693 2017-02-20 2017-04-09
 74744 2016-10-03 2016-11-05
174095 2018-12-01 2018-12-20
 27677 2018-03-01 2018-05-29
111111 2018-01-01 2018-01-31
111111 2018-11-11 2018-12-31")

(edited, thanks to Uwe)
For each row, I want to count how many rows in the dataframe have the same id as the current row and a start-end period that overlaps the period in the current row. For example, for the first row, the result would be 2, since there is another row with id = 174095 and its end is greater than first row start.
I tried to do it with dplyr's rowwise, like:
df = df %>% rowwise() %>% mutate(count = sum(id == df$id & ((start >= df$start & start <= df$end) | (end >= df$start & end <= df$end))))

But this is extremely slow. I gave it a try and two hours later it was still running.
I also tried to use mapply, but it takes way too much time as well:
df$count = mapply(function(id, start, end) {
return(sum(df$id == id & (between(df$start, start, end) | between(df$end, start, end))) }, id, start, end)

Is there an efficient reasonable way to do this?
Thank you very much

EDIT 2019-03-06
@Uwe 's suggested solution:
df[, overlapping.rows := df[.SD, on = .(id, start <= end, end >= start), .N, by = .EACHI]$N][]

works just fine for the sample data.frame above. But it turns out the sample wasn't illustrative enough, or I didn't really make myself understood maybe :)
I added a third record for id 174095 and modified the other two:
df <- fread("id     start     end
174095 2018-12-19 2018-12-31
            227156 2018-12-19 2018-12-31
            210610 2018-04-13 2018-09-27
            27677 2018-04-12 2018-04-26
            370474 2017-07-13 2017-08-19
            303693 2017-02-20 2017-04-09
            74744 2016-10-03 2016-11-05
            174095 2018-12-01 2018-12-18
            27677 2018-03-01 2018-05-29
            111111 2018-01-01 2018-01-31
            111111 2018-11-11 2018-12-31
            174095 2018-11-30 2018-12-25")

Now, id 174095 has two intervals that do not overlap between them (rows 1 and 2) and another interval that overlaps the other two (row 3):
           id      start        end
1: 174095 2018-12-19 2018-12-31
2: 174095 2018-12-01 2018-12-18
3: 174095 2018-11-30 2018-12-25

So, the result should be:
       id      start        end overlapping.rows
1: 174095 2018-12-19 2018-12-31                2
2: 174095 2018-12-01 2018-12-18                2
3: 174095 2018-11-30 2018-12-25                3

But it actually is:
       id      start        end overlapping.rows
1: 174095 2018-12-19 2018-12-31                3
2: 174095 2018-12-01 2018-12-18                3
3: 174095 2018-11-30 2018-12-25                3

If I'm not mistaken, this is happening because the final join is done by "id" only, so all the rows with the same id have the same result.
My solution consists on performing the final merge also by "start" and "end":
df[tmp, on = .(id, start, end), overlapping.rows := N]

For some reason (I would love to find out...), on the self-join, start dates end up in the "end" column and vice-versa, so I had to add this line right after it:
setnames(tmp, c("id", "end", "start", "N"))

Now, the result is:
            id      start        end overlapping.rows
 1: 174095 2018-12-19 2018-12-31                2
 2: 227156 2018-12-19 2018-12-31                1
 3: 210610 2018-04-13 2018-09-27                1
 4:  27677 2018-04-12 2018-04-26                2
 5: 370474 2017-07-13 2017-08-19                1
 6: 303693 2017-02-20 2017-04-09                1
 7:  74744 2016-10-03 2016-11-05                1
 8: 174095 2018-12-01 2018-12-18                2
 9:  27677 2018-03-01 2018-05-29                2
10: 111111 2018-01-01 2018-01-31                1
11: 111111 2018-11-11 2018-12-31                1
12: 174095 2018-11-30 2018-12-25                3

Which is exactly what I expected!

A: Edit 2019-03-07 to cope with OP's expanded dataset
This can be solved by aggregating in a non-equi self-join
library(data.table)
# coerce character dates to IDate class
cols <- c("start", "end")
setDT(df)[, (cols) := lapply(.SD, as.IDate), .SDcols = cols]
# non-equi self-join and aggregate
tmp <- df[df, on = .(id, start <= end, end >= start), .N, by = .EACHI]
# append counts to original dataset
df[, overlapping.rows := tmp$N]
df

        id      start        end overlapping.rows
 1: 174095 2018-12-19 2018-12-31                2
 2: 227156 2018-12-19 2018-12-31                1
 3: 210610 2018-04-13 2018-09-27                1
 4:  27677 2018-04-12 2018-04-26                2
 5: 370474 2017-07-13 2017-08-19                1
 6: 303693 2017-02-20 2017-04-09                1
 7:  74744 2016-10-03 2016-11-05                1
 8: 174095 2018-12-01 2018-12-18                2
 9:  27677 2018-03-01 2018-05-29                2
10: 111111 2018-01-01 2018-01-31                1
11: 111111 2018-11-11 2018-12-31                1
12: 174095 2018-11-30 2018-12-25                3

Using data.table chaining the code can be written in a more compact but also more convoluted way:
library(data.table)
cols <- c("start", "end")
setDT(df)[, (cols) := lapply(.SD, as.IDate), .SDcols = cols][
  , overlapping.rows := df[df, on = .(id, start <= end, end >= start), .N, by = .EACHI]$N][]

Note that the part to append the results to the original df is based on Frank's comment.

My original attempt to use a second join to append the results to the original df failed in case there are different counts for the same id as pointed out by the OP. This can be fixed by including the row number in the second join:
library(data.table)
# coerce character dates to IDate class
cols <- c("start", "end")
setDT(df)[, (cols) := lapply(.SD, as.IDate), .SDcols = cols]
# append row number
tmp <- df[, rn := .I][
  # non-equi self-join and aggregate
  df, on = .(id, start <= end, end >= start), .(rn = i.rn, .N), by = .EACHI]
# append counts to original dataset by joining on row number
df[tmp, on = "rn", overlapping.rows := N][, rn := NULL]
df

        id      start        end overlapping.rows
 1: 174095 2018-12-19 2018-12-31                2
 2: 227156 2018-12-19 2018-12-31                1
 3: 210610 2018-04-13 2018-09-27                1
 4:  27677 2018-04-12 2018-04-26                2
 5: 370474 2017-07-13 2017-08-19                1
 6: 303693 2017-02-20 2017-04-09                1
 7:  74744 2016-10-03 2016-11-05                1
 8: 174095 2018-12-01 2018-12-18                2
 9:  27677 2018-03-01 2018-05-29                2
10: 111111 2018-01-01 2018-01-31                1
11: 111111 2018-11-11 2018-12-31                1
12: 174095 2018-11-30 2018-12-25                3

Explanation
The join condition in the non-equi join does the trick. Two intervals do not overlap if the first one ends before the second one starts or the first interval starts after the second interval has ended,
e1 < s2 OR e2 < s1
Now, if two intervals do intersect/overlap then the opposite of the above must be true. By negating and applying De Morgan's law we get the conditions
s2 <= e1 AND e2 >= s1
which are used in the non-equi join.
Data
OP's expanded dataset as described in OP's EDIT 2019-03-06:
library(data.table)
df <- fread("id     start     end
174095 2018-12-19 2018-12-31
227156 2018-12-19 2018-12-31
210610 2018-04-13 2018-09-27
27677  2018-04-12 2018-04-26
370474 2017-07-13 2017-08-19
303693 2017-02-20 2017-04-09
74744  2016-10-03 2016-11-05
174095 2018-12-01 2018-12-18
27677  2018-03-01 2018-05-29
111111 2018-01-01 2018-01-31
111111 2018-11-11 2018-12-31
174095 2018-11-30 2018-12-25")

A: I've misunderstood the question initially, and I think @Uwe's approach is the way to go. In my first answer I've used data.table to identify groups (and how many rows in a group) of consequent dates per id, obviously not what you're after.
Here's also a short sqldf snippet to complement @Uwe's approach (though not as adequate, as here the row order is not preserved - this would require some additional tinkering):
library(sqldf)

df <- sqldf('SELECT id, start, end, COUNT(*) as overlappingRows FROM (SELECT df.* FROM df
            LEFT OUTER JOIN df AS df2
            ON df.id = df2.id AND df.start <= df2.end AND df.end >= df2.start) as origdf
            GROUP BY id, start, end')

Output:
       id      start        end overlappingRows
1   27677 2018-03-01 2018-05-29               2
2   27677 2018-04-12 2018-04-26               2
3   74744 2016-10-03 2016-11-05               1
4  111111 2018-01-01 2018-01-31               1
5  111111 2018-11-11 2018-12-31               1
6  174095 2018-12-01 2018-12-20               2
7  174095 2018-12-19 2018-12-31               2
8  210610 2018-04-13 2018-09-27               1
9  227156 2018-12-19 2018-12-31               1
10 303693 2017-02-20 2017-04-09               1
11 370474 2017-07-13 2017-08-19               1


text:
Q: Different activity layouts with shared sublayouts I have two applications which are sharing some code through a library. The layout of the main activities are mostly the same with just minor changes here and there. Specifically I have the following structure
App 1:
<somelayout>
    <somestuff with certain attributes />

    <some_common_sublayout />

    <someotherstuff />
</somelayout>

App 2:
<somelayout>
    <somestuff with other attributes/>

    <some_common_sublayout />

    <someotherstuff />
</somelayout>

How can I avoid duplicating the code in  and be able to just modify one layout file rather than manually changing the code in both layout files?

A: Try this :
Create a layout example abc.xml and create one more layout and just call the xml file
<include
            android:id="@+id/"
            android:layout_width="match_parent"
            layout="@layout/abc.xml" />


text:
Q: Cannot upload app to google play console, App was signed in debug Mode As the question says I am not able to upload an APK generated and signed by Unity. It gives me the error saying that the app is signed I debug mode.
Things I have already tried

*

*check if the APK is actually signed by the upload key

*Check the AndroidManifest of the APK using the aapt tool to check for the debuggable flag set (it wasn't there)

*Use Monodevelop to set the app configuration to release

*Build the app from Android studio

I can also see that my apkj is signed with the same key as my upload certificate on google play console

However none of these things work, Google play console still thinks that the app was signed in debug mode
Any idea how I can fix this ?

A: Do you have the Development Build box checked? Check this link.

I hope this helps you :)


text:
Q: post-up only once after reboot I need to run a script ONCE the first time the system connects to the internet. So I use post-up in my interface to run the script.
However, I only want to run the script once per boot. So if the interface were to be brought down and up again, I don't want my script to run again.
What can I do?

A: In order to make your script only run once per boot you can do one of the following:

*

*assuming you have cron: Create a cron job with time specification @reboot (check man 5 crontab) to run your script.  The script then has to wait for devices or connection and such things itself.

*assuming you run the script in some other way: Your script can create a empty file in a place that will be deleted on reboot. Some temp directory might be suitable.  You have to check that the marker file will only (but always) be deleted on reboot.  You can also create a counter part script that will be executed on shutdown which will delete the file again.  The problem is that the second script might not execute in some error conditions (hard reset).  Your script can then check if the file exists and exit early if it already ran.