text:
Q: Heroku h10 issue now rails s wont work Im having extreme difficulty getting my blog app to push to heroku and after searching forums and putting in different solutions it seems my app is pushing to heroku however showing the standard heroku application error
 Shawns-MacBook-Air-2:blog Shawn$ git push heroku master
Counting objects: 9, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (8/8), done.
Writing objects: 100% (9/9), 1.21 KiB | 0 bytes/s, done.
Total 9 (delta 2), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Using set buildpack heroku/ruby
remote: -----> Ruby app detected
remote: -----> Compiling Ruby/Rails
remote: -----> Using Ruby version: ruby-2.2.1
remote: -----> Installing dependencies using bundler 1.9.7
remote:        Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment
remote:        Using i18n 0.7.0
remote:        Using rake 10.4.2
remote:        Using json 1.8.3
remote:        Using minitest 5.8.2
remote:        Using thread_safe 0.3.5
remote:        Using builder 3.2.2
remote:        Using erubis 2.7.0
remote:        Using rack 1.5.5
remote:        Using mime-types 1.25.1
remote:        Using polyglot 0.3.5
remote:        Using arel 5.0.1.20140414130214
remote:        Using bcrypt 3.1.10
remote:        Using coffee-script-source 1.10.0
remote:        Using execjs 2.6.0
remote:        Using thor 0.19.1
remote:        Using orm_adapter 0.5.0
remote:        Using hike 1.2.3
remote:        Using multi_json 1.11.2
remote:        Using pg 0.18.4
remote:        Using bundler 1.9.7
remote:        Using tilt 1.4.1
remote:        Using rails_serve_static_assets 0.0.4
remote:        Using rails_stdout_logging 0.0.4
remote:        Using rdoc 4.2.0
remote:        Using sass 3.2.19
remote:        Using tzinfo 1.2.2
remote:        Using coffee-script 2.4.1
remote:        Using uglifier 2.7.2
remote:        Using treetop 1.4.15
remote:        Using rack-test 0.6.3
remote:        Using warden 1.2.3
remote:        Using sprockets 2.12.4
remote:        Using rails_12factor 0.0.3
remote:        Using activesupport 4.1.5
remote:        Using mail 2.5.4
remote:        Using sdoc 0.4.1
remote:        Using actionview 4.1.5
remote:        Using activemodel 4.1.5
remote:        Using jbuilder 2.3.2
remote:        Using actionpack 4.1.5
remote:        Using activerecord 4.1.5
remote:        Using actionmailer 4.1.5
remote:        Using railties 4.1.5
remote:        Using sprockets-rails 2.3.3
remote:        Using coffee-rails 4.0.1
remote:        Using devise 3.3.0
remote:        Using jquery-rails 3.1.4
remote:        Using rails 4.1.5
remote:        Using sass-rails 4.0.5
remote:        Using turbolinks 2.5.3
remote:        Bundle complete! 13 Gemfile dependencies, 50 gems now installed.
remote:        Gems in the groups development and test were not installed.
remote:        Bundled gems are installed into ./vendor/bundle.
remote:        Bundle completed (0.34s)
remote:        Cleaning up the bundler cache.
remote:        Detected manifest file, assuming assets were compiled locally
remote:
remote:
remote: -----> Discovering process types
remote:        Procfile declares types     -> web
remote:        Default types for buildpack -> console, rake, worker
remote:
remote: -----> Compressing... done, 29.8MB
remote: -----> Launching... done, v10
remote:        https://hidden-island-1801.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/hidden-island-1801.git
   033bb79..ad0279d  master -> master
Shawns-MacBook-Air-2:blog Shawn$ heroku open
Opening hidden-island-1801... done
Shawns-MacBook-Air-2:blog Shawn$ heroku logs
2015-11-17T16:25:44.893903+00:00 heroku[slug-compiler]: Slug compilation finished
2015-11-17T16:25:44.732134+00:00 heroku[api]: Release v8 created by info@listedbyshawn.com
2015-11-17T16:25:44.732098+00:00 heroku[api]: Deploy 12501c4 by info@listedbyshawn.com
2015-11-17T16:25:44.853232+00:00 heroku[web.1]: State changed from crashed to starting
2015-11-17T16:25:46.881436+00:00 heroku[web.1]: Starting process with command `bundle exec rails server thin -p 5516 -e production`
2015-11-17T16:25:50.524318+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:274:in `require': cannot load such file -- thin (LoadError)
2015-11-17T16:25:50.524233+00:00 app[web.1]: Exiting
2015-11-17T16:25:50.524322+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:274:in `block in require'
2015-11-17T16:25:50.524350+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:274:in `require'
2015-11-17T16:25:50.524353+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/handler/thin.rb:1:in `<top (required)>'
2015-11-17T16:25:50.524356+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/handler.rb:20:in `each'
2015-11-17T16:25:50.524348+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:240:in `load_dependency'
2015-11-17T16:25:50.524357+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/handler.rb:20:in `inject'
2015-11-17T16:25:50.524365+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.3/lib/rails/commands/server.rb:75:in `start'
2015-11-17T16:25:50.524387+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.3/lib/rails/commands.rb:17:in `<top (required)>'
2015-11-17T16:25:50.524386+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
2015-11-17T16:25:50.524354+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/handler.rb:20:in `const_get'
2015-11-17T16:25:50.524391+00:00 app[web.1]:    from bin/rails:4:in `<main>'
2015-11-17T16:25:50.524354+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/handler.rb:20:in `block in get'
2015-11-17T16:25:50.524363+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.3/lib/rails/commands/server.rb:125:in `print_boot_information'
2015-11-17T16:25:50.524361+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/server.rb:290:in `server'
2015-11-17T16:25:50.524381+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:80:in `block in server'
2015-11-17T16:25:50.524385+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:75:in `server'
2015-11-17T16:25:50.524389+00:00 app[web.1]:    from bin/rails:4:in `require'
2015-11-17T16:25:50.524359+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/handler.rb:20:in `get'
2015-11-17T16:25:50.524383+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:75:in `tap'
2015-11-17T16:25:51.306312+00:00 heroku[web.1]: Process exited with status 1
2015-11-17T16:25:51.118983+00:00 heroku[web.1]: State changed from starting to crashed
2015-11-17T16:26:05.106792+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=hidden-island-1801.herokuapp.com request_id=96ba18f5-4f1f-4e78-89d1-d3751be690f2 fwd="72.231.3.138" dyno= connect= service= status=503 bytes=
2015-11-17T16:31:52.946723+00:00 heroku[slug-compiler]: Slug compilation finished
2015-11-17T16:31:52.946714+00:00 heroku[slug-compiler]: Slug compilation started
2015-11-17T16:31:52.792769+00:00 heroku[api]: Deploy 033bb79 by info@listedbyshawn.com
2015-11-17T16:31:52.792806+00:00 heroku[api]: Release v9 created by info@listedbyshawn.com
2015-11-17T16:31:52.893375+00:00 heroku[web.1]: State changed from crashed to starting
2015-11-17T16:31:54.833297+00:00 heroku[web.1]: Starting process with command `bundle exec rails server thin -p 29959 -e production`
2015-11-17T16:31:58.486880+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.1.5/lib/active_support/dependencies.rb:247:in `require': cannot load such file -- thin (LoadError)
2015-11-17T16:31:58.486903+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.1.5/lib/active_support/dependencies.rb:247:in `block in require'
2015-11-17T16:31:58.486907+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/handler.rb:20:in `block in get'
2015-11-17T16:31:58.486905+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.1.5/lib/active_support/dependencies.rb:232:in `load_dependency'
2015-11-17T16:31:58.486908+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/handler.rb:20:in `get'
2015-11-17T16:31:58.486907+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/handler.rb:20:in `const_get'
2015-11-17T16:31:58.486906+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/handler/thin.rb:1:in `<top (required)>'
2015-11-17T16:31:58.486911+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.5/lib/rails/commands/commands_tasks.rb:76:in `server'
2015-11-17T16:31:58.486905+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.1.5/lib/active_support/dependencies.rb:247:in `require'
2015-11-17T16:31:58.486910+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.5/lib/rails/commands/server.rb:64:in `start'
2015-11-17T16:31:58.486907+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/handler.rb:20:in `each'
2015-11-17T16:31:58.486909+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.5/lib/rails/commands/server.rb:112:in `print_boot_information'
2015-11-17T16:31:58.486912+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.5/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
2015-11-17T16:31:58.486912+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.5/lib/rails/commands.rb:17:in `<top (required)>'
2015-11-17T16:31:58.486913+00:00 app[web.1]:    from bin/rails:4:in `require'
2015-11-17T16:31:58.486908+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/handler.rb:20:in `inject'
2015-11-17T16:31:58.486913+00:00 app[web.1]:    from bin/rails:4:in `<main>'
2015-11-17T16:31:58.486911+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.5/lib/rails/commands/commands_tasks.rb:81:in `block in server'
2015-11-17T16:31:58.486909+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/server.rb:268:in `server'
2015-11-17T16:31:58.486911+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.5/lib/rails/commands/commands_tasks.rb:76:in `tap'
2015-11-17T16:31:58.499347+00:00 app[web.1]: Exiting
2015-11-17T16:31:59.050411+00:00 heroku[web.1]: State changed from starting to crashed
2015-11-17T16:31:59.050411+00:00 heroku[web.1]: State changed from crashed to starting
2015-11-17T16:31:59.060355+00:00 heroku[web.1]: Process exited with status 1
2015-11-17T16:32:01.066955+00:00 heroku[web.1]: Starting process with command `bundle exec rails server thin -p 57333 -e production`
2015-11-17T16:32:05.735743+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.1.5/lib/active_support/dependencies.rb:247:in `require': cannot load such file -- thin (LoadError)
2015-11-17T16:32:05.735756+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.1.5/lib/active_support/dependencies.rb:247:in `block in require'
2015-11-17T16:32:05.735758+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.1.5/lib/active_support/dependencies.rb:232:in `load_dependency'
2015-11-17T16:32:05.735758+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.1.5/lib/active_support/dependencies.rb:247:in `require'
2015-11-17T16:32:05.735759+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/handler/thin.rb:1:in `<top (required)>'
2015-11-17T16:32:05.735760+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/handler.rb:20:in `const_get'
2015-11-17T16:32:05.735760+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/handler.rb:20:in `block in get'
2015-11-17T16:32:05.735761+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/handler.rb:20:in `each'
2015-11-17T16:32:05.735763+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/handler.rb:20:in `inject'
2015-11-17T16:32:05.735764+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/handler.rb:20:in `get'
2015-11-17T16:32:05.735765+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/server.rb:268:in `server'
2015-11-17T16:32:05.735765+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.5/lib/rails/commands/server.rb:112:in `print_boot_information'
2015-11-17T16:32:05.735766+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.5/lib/rails/commands/server.rb:64:in `start'
2015-11-17T16:32:05.735768+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.5/lib/rails/commands/commands_tasks.rb:81:in `block in server'
2015-11-17T16:32:05.735768+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.5/lib/rails/commands/commands_tasks.rb:76:in `tap'
2015-11-17T16:32:05.735770+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.5/lib/rails/commands/commands_tasks.rb:76:in `server'
2015-11-17T16:32:05.735772+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.5/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
2015-11-17T16:32:05.735774+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.5/lib/rails/commands.rb:17:in `<top (required)>'
2015-11-17T16:32:05.735775+00:00 app[web.1]:    from bin/rails:4:in `require'
2015-11-17T16:32:05.735777+00:00 app[web.1]:    from bin/rails:4:in `<main>'
2015-11-17T16:32:05.756217+00:00 app[web.1]: Exiting
2015-11-17T16:32:06.623851+00:00 heroku[web.1]: Process exited with status 1
2015-11-17T16:32:06.640663+00:00 heroku[web.1]: State changed from starting to crashed
2015-11-17T16:33:32.518991+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=hidden-island-1801.herokuapp.com request_id=eb68e24a-6c42-4ed5-a769-a0b83bf2430a fwd="72.231.3.138" dyno= connect= service= status=503 bytes=
2015-11-17T16:51:11.373470+00:00 heroku[api]: Deploy ad0279d by info@listedbyshawn.com
2015-11-17T16:51:11.373470+00:00 heroku[api]: Release v10 created by info@listedbyshawn.com
2015-11-17T16:51:11.577642+00:00 heroku[slug-compiler]: Slug compilation started
2015-11-17T16:51:11.577653+00:00 heroku[slug-compiler]: Slug compilation finished
2015-11-17T16:51:12.500357+00:00 heroku[web.1]: State changed from crashed to starting
2015-11-17T16:51:14.664864+00:00 heroku[web.1]: Starting process with command `bundle exec rails server thin -p 31700 -e production`
2015-11-17T16:51:16.956013+00:00 app[web.1]: /app/bin/bundle: line 3: syntax error near unexpected token `('
2015-11-17T16:51:16.956021+00:00 app[web.1]: /app/bin/bundle: line 3: `ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)'
2015-11-17T16:51:17.929349+00:00 heroku[web.1]: State changed from starting to crashed
2015-11-17T16:51:17.929349+00:00 heroku[web.1]: State changed from crashed to starting
2015-11-17T16:51:17.926872+00:00 heroku[web.1]: Process exited with status 2
2015-11-17T16:51:20.741615+00:00 heroku[web.1]: Starting process with command `bundle exec rails server thin -p 6840 -e production`
2015-11-17T16:51:23.184902+00:00 app[web.1]: /app/bin/bundle: line 3: syntax error near unexpected token `('
2015-11-17T16:51:23.184913+00:00 app[web.1]: /app/bin/bundle: line 3: `ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)'
2015-11-17T16:51:24.178529+00:00 heroku[web.1]: Process exited with status 2
2015-11-17T16:51:24.189642+00:00 heroku[web.1]: State changed from starting to crashed
2015-11-17T16:51:34.709173+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=hidden-island-1801.herokuapp.com request_id=1aa74752-0743-4574-a4ef-934d3787d8f8 fwd="72.231.3.138" dyno= connect= service= status=503 bytes=
Shawns-MacBook-Air-2:blog Shawn$

here is my gem file
source 'https://rubygems.org'
ruby '2.2.1'

gem 'rails', '4.1.5'
gem 'sass-rails', '~> 4.0.3'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'devise', '~> 3.3.0'

group :development, :test do
    gem 'sqlite3'
    gem 'spring'
end

group :production do
    gem 'pg'
    gem 'rails_12factor'
end

group :doc do
    gem 'sdoc', '~> 0.4.0'
end

Guys seriously any help with this would be greatly appreciated as I am just starting out with ruby on rails and its been a legit 3 days I've been trying to figure this out
thanks in advanced

A: Here's the error in your logs:
2015-11-17T16:25:50.524318+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:274:in `require': cannot load such file -- thin (LoadError)

Just add the following to your gem file:
group :production do
  gem 'pg'
  gem 'rails_12factor'
  gem 'thin' # added
end


text:
Q: custom created method error: "is not a function" I have a list of hero-buttons with a custom animation created in button.component.ts. At the beginning, they are inactive. When I press one of then, the selected one should turn active. For this, I created a field in hero.ts called state and a function called toggleState() where I change the state. But when I press the button, I receive the error:

EXCEPTION: Error in http://localhost:3000/app/button.component.js class ButtonComponent - inline template:4:10 caused by: self.context.$implicit.toggleState is not a function

My guess is that I can't create a custom method like I did here. But I'm new in Angular2 so I can't really tell it. What did I do wrong? I played enough "Where's Wally?" with my code and still I can't find anything.
button.component.ts:
import { Component, Input, OnInit, trigger, state, style, transition, animate
} from '@angular/core';

import { Hero } from './hero';
import { HeroService } from './hero.service';

@Component({
    moduleId: module.id,
    selector: 'button-collection',
    template: `
      <button *ngFor="let hero of heroes"
          [@heroState]="hero.state"
          (click)="hero.toggleState()">
        {{hero.name}}
      </button>
    `,
    styleUrls: ['heroes.component.css'],
    animations: [
        trigger('heroState', [
            state('inactive', style({
                backgroundColor: '#e1e1e1',
                transform: 'scale(1)'
            })),
            state('active', style({
                backgroundColor: '#dd1600',
                transform: 'scale(1.1)'
            })),
            transition('inactive => active', animate('100ms ease-in')),
            transition('active => inactive', animate('100ms ease-out'))
        ])
    ],
})
export class ButtonComponent implements OnInit {
    heroes: Hero[];

    constructor(private heroService: HeroService) {

    }

    ngOnInit(): void {
        this.heroService.getHeroes()
        .then(heroes => this.heroes = heroes);
    }
}

hero.ts:
export class Hero {
    id: number;
    name: string;
    state: string;

    constructor() {
        this.state = 'inactive';
    }

    public toggleState(): void{
        this.state = (this.state === 'active' ? 'inactive' : 'active');
    }
}

A: Your service most probably only returns plain objects, meaning they don't have the member methods of the Hero class.
You need to explicitly create new Hero() objects to have the toggleState() method available on the hero object.

A: If you cast JSON to a TypeScript class, all is happening is that you indicate to the static analysis it can safely assume the value is of that class; that doesn't actually change the JSON value at all (i.e it doesn't make it an instance of that  class).
What you want is probably How do I cast a JSON object to a typescript class or Cast JSON object to TypeScript class instance

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get enum.values() from class that containing it class Clazz{
    public enum MyEnum{
        Hello, World
    }
}

With class Clazz, how do I get MyEnum.values() ?
An example of the usage is :
Class unknownClass = getSomeClass();

How to get MyEnum.values() from unknownClass?

A: You can do Clazz.MyEnum.values() to access the Enum or you can directly import MyEnum in your other classes import com.in.Clazz.MyEnum becuase MyEnum is public.
To get MyEnum constant via reflection, but if MyEnum is accessible then there is no need to use reflection. You can do it in following way,
Class<?> clazz = Clazz.class;//You are getting dynamically
Class<?> enumClass = clazz.getDeclaredClasses()[0];//assuming at index 0
Enum<?>[] enumConstants = (Enum<?>[]) enumClass.getEnumConstants();
System.out.println(enumConstants[0]);

OUTPUT
Hello

A: The answer is here:
Method method = parameterIDClass.getMethod("values");
Enum<?>[] enums = (Enum<?>[])method.invoke(null);


text:
Q: Launch Setting activity then create a dialogue In my app I'd like to send the user to the device setting then create a dialogue asking him to enable something. the problem is the dialogue is always created in my app not the setting activity. I'm trying to make it look like this.
launch setting activity:
Intent overLay = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
startActivity(overLay);

and creating a dialogue:
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

dialog.dismiss();
}
});
alertDialog.show();

I've already tried using a new thread but it didn't work. the only thing that kind of works is a toast but not a dialogue.


text:
Q: Alternative to CrashPlan I use CrashPlan to take frequent backups of my Minecraft server, it's great for getting restores at certain points in time before events have occurred. I only need to backup to a local disk so is there an alternative to this program without paying for online storage?

A: CrashPlan is a free program.
You can install and use it without paying anything.
You only need to pay if you use the CrashPlan Central destination.


text:
Q: Make type deeply writable Is it possible to transform a typescript object type deeply writable, but also remove readonly type operator from array types?
Similar to this, but - as I mentioned - also remove readonly from array types.
// if initial type is:
interface InitialType {
  readonly field: string;
  readonly array: readonly { readonly arraySubfield: string; }[];
  readonly obj: {
    readonly objSubfield1: string;
    readonly objSubfield2: readonly string[];
  };
}

// then the result type would be:
interface ResultType {
  field: string;
  array: { arraySubfield: string }[];
  obj: {
    objSubfield1: string;
    objSubfield2: string[];
  };
}

// achieved by doing this:
type ResultType = Writable<InitialType>;

A: Here ya go, a deep writable type that handles way too many things:
type Writable<T> =
    // check for things that are objects but don't need changing
    T extends ((...args: any[]) => any) | Date | RegExp
        ? T
        : T extends ReadonlyMap<infer K, infer V> // maps
            ? Map<Writable<K>, Writable<V>> // make key and values writable
            : T extends ReadonlySet<infer U> // sets
                ? Set<Writable<U>> // make elements writable
                : T extends ReadonlyArray<unknown> // is an array or tuple?
                    ? `${bigint}` extends `${keyof T & any}` // is tuple
                        ? { -readonly [K in keyof T]: Writable<T[K]> }
                        : Writable<T[number]>[] // is regular array
                    : T extends object // is regular object
                        ? { -readonly [K in keyof T]: Writable<T[K]> }
                        : T; // is primitive or literal value

Essentially it's this:
type Writable<T> = T extends object ? { -readonly [K in keyof T]: Writable<T[K]> } : T;

but it handles a lot more things correctly. Things like (and only) arrays dates, functions, regex, maps, sets, tuples, readonly maps, and readonly sets.
Playground


text:
Q: numpy beginner: writing an array using numpy.savetxt I have a numpy histogram that I would like to output as a tab-delimited text file. My code is below:
targethist = np.histogram(targetlist, bins=ilist)
print targethist
np.savetxt('ChrI_dens.txt',targethist,delimiter='\t')

targetlist and ilist are long lists of integers. I get the following output:

(array([0, 0, 0, ..., 0, 0, 0]), array([       1,    10000,    20000,
  ..., 15060000, 15070000, 15072422])) Traceback (most recent call
  last):   File "target_dens_np.py", line 62, in
      np.savetxt('ChrI_dens.txt',targethist,delimiter='\t')   File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/site-packages/numpy/lib/npyio.py",
  line 979, in savetxt
      fh.write(asbytes(format % tuple(row) + newline)) TypeError: float argument required, not numpy.ndarray

It seems that the histogram array has been created, but I have done something wrong in the np.savetxt() line. I have read the documentation, but don't understand why any of the arguments in this function would be expecting a float. Where have I gone wrong?

A: I think that the problem is that the second argument to savetxt must be "array-like".  Your input is not "array-like".  e.g.
print (len(targethist[0]))
print (len(targethist[1]))

Notice the lengths aren't the same?  If the lengths were the same, numpy could convert it to a single 2-D array and everything would be fine, but it can't do the conversion so it fails.
This works
np.savetxt('stuff.dat',(targethist[0],targethist[1][1:]),delimiter='\t')

But I've truncated your data ;).  You'll need to decide what you want to do to work around this one.
I must admit, the error message here is quite cryptic.


text:
Q: Need to copy lines from one text to another based on a key item I am trying to copy lines from one text file to another which contains a key item in it (For example: "2011"). The following are the lines that are present in my source text.

PensonReport: 1/11/2010 11:14:21 AM, Index and length must refer to a location within the string.
  Parameter name: length, Sub ProcessDateHeader_BeforePrint, ReportRequestID: 24614361, DALBATCHDEV01
ReportRequest: 8/16/2011 10:02:26 AM, Procedure or function 'prcEXT602' expects parameter '@CorrespondentOfficeID', which was not supplied., Sub ExecuteStoredProc, ReportRequestID: 49474706, DALBATCHDEV01

The problem with my code is that it is not able to identify the EOL and is printing the whole of it.
Note: each new line starts from string ReportRequest.
How do I do this?

A: You will want to start with StreamReader, and have it open your first file.
Then use a StreamWriter to write the info out.
Next couple a while loop together with the streamwriter to look at each line and then you should be able to use an.
My C# syntax may be off leave a comment if I have something really off please.
string line;
using (StreamReader reader = new StreamReader("file.txt"))
using (StreamWriter writer = new StreamWriter("newfile.txt"))
//Use a while loop that reads each line until there are none left
while ((line = reader.ReadLine()) != null
{
         line = reader.ReadLine();
         if (line.contains("your string here"))
         then writer.WriteLine();
}

EDIT: Added code to better answer question
        string line;
        String Report = "ReportRequest";
        using (StreamReader reader = new StreamReader("file.txt"))
        using (StreamWriter writer = new StreamWriter("newfile.txt"))

            while (reader.ReadLine() != null)
            {
                if (reader.ReadLine().StartsWith(Report))
                {
                    //writes/starts a new line beginning with ReportRequest
                    writer.WriteLine(line);
                }
                else {
                    //appends info to same line (beginning with a space)
                    writer.Write(" " + line);
                }
                }

A: If each line starts with "ReportRequest" use
string[] splits = mybigstring.Split("ReportRequest");

If this is what you're asking for ?

A: Maeby try use something like this:
string[] lines = File.ReadAllLines("oldFile.txt")
    .Where(s => s.Contains("your_text")).ToArray();
File.WriteAllLines("newFile", lines);


text:
Q: ListView and Data Models - Blackberry I'm developing for the Blackberry 10.
I'm attempting to save and load a JSON data model into a listview in my app. It loads up initially via a couple lines of C++ in the app.cpp file before switching control to the QML file. However, I don't know how to save new cells into this JSON database. I don't know how to reload the ListView after I save. Finally, I don't know the restrictions regarding what I can and cannot save in a JSON database. Can anyone offer some assistance? Should I even be using a JSON model or should it be a QML or even XML? Thanks for all your help.

A: Some more information about what you are doing here would be helpful in order to provide an answer. JSON is a format used to contain and represent objects in a string, it is not a database.  Typically working with a ListView requires creating a ListModel that contains your data and is rendered by the ListView.  When working with a ListModel you have access to a variety of functions as documented at http://harmattan-dev.nokia.com/docs/library/html/qt4/qml-listmodel.html . It is not clear from your question what you are actually doing though I would suggest posting your code to make everything clear.


text:
Q: iOS 5 sdk issue with mutable arrays Hello I created a app on iOS 4.3.3 and than downloaded Xcode 4.2.1 and iOS sdk 5. It's a navigation-based application and it has a mutable array for the tableview but it won't create any strings for the array, so i added an object to array in the viewdidload but it is not working! So i added NSlog to the objects in my array and it says null! What should i do?
Here's the viewdidload:
    - (void)viewDidLoad
    {
    [super viewDidLoad];
    self.soldc = [NSMutableArray arrayWithCapacity:0];
    self.color = [NSMutableArray arrayWithCapacity:0];
    appdelegate = (yard_sale_managerAppDelegate *)[[UIApplication sharedApplication]          delegate];
    appdelegate.object = self;
    NSMutableArray *loadi = [[NSMutableArray alloc]initWithCapacity:0];
    self.items = loadi;
    self.sold = [NSMutableArray arrayWithCapacity:0];
    self.prices = [NSMutableArray arrayWithCapacity:0];

    alert = [[UIAlertView alloc] initWithTitle:@"Add product" message:@"Enter your   product name and price." delegate:self cancelButtonTitle:@"Add" otherButtonTitles:@"Cancel",   nil];
    [alert addTextFieldWithValue:@"" label:@"name"];
    [alert addTextFieldWithValue:@"" label:@"price"];
    add = [alert textFieldAtIndex:0];
    add.keyboardType = UIKeyboardTypeAlphabet;
    add.keyboardAppearance = UIKeyboardAppearanceAlert;
    add.autocapitalizationType = UITextAutocapitalizationTypeWords;
    add.autocorrectionType = UITextAutocorrectionTypeNo;
    add2 = [alert textFieldAtIndex:1];
    add2.keyboardType = UIKeyboardTypeNumberPad;
    add2.keyboardAppearance = UIKeyboardAppearanceAlert;
    add2.autocapitalizationType = UITextAutocapitalizationTypeWords;
    add2.autocorrectionType = UITextAutocorrectionTypeNo;
    NSLog(@"%i", [color count]);
    alert.tag=1;
    self.resa = [[UIAlertView alloc] initWithTitle:@"Sale results" message:@"temple" delegate:self cancelButtonTitle:@"Close" otherButtonTitles: nil];
    self.items = [NSMutableArray arrayWithContentsOfFile:[self itemsp]];
    self.prices = [NSMutableArray arrayWithContentsOfFile:[self pricesp]];
    self.sold = [NSMutableArray arrayWithContentsOfFile:[self soldp]];
    self.soldc = [NSMutableArray arrayWithContentsOfFile:[self soldcp]];
    self.color = [NSMutableArray arrayWithContentsOfFile:[self colorsp]];
    if ([self.soldc count]==0) {

    }
    //self.soldc = [NSMutableArray arrayWithContentsOfFile:[self soldcp]];
    self.color = [NSMutableArray arrayWithContentsOfFile:[self colorsp]];
    [loadi release];
    self.resa.tag = 2;
    [self.items addObject:@"chair"];
    [self.prices addObject:@"30"];
    [self.color addObject:@"0"];
    NSLog(@"%@",self.items);
}

If you need more information tell me!
This is the log:
2012-01-08 21:31:13.409 yard sale manager[1152:f803] 0
2012-01-08 21:31:13.411 yard sale manager[1152:f803] (null)

edit: read this its important!!!!!
a lot of people didn't notice that piece of code:
        [self.items addObject:@"chair"];
        [self.prices addObject:@"30"];
        [self.color addObject:@"0"];
        NSLog(@"%@",self.items);

A: This line
self.color = [NSMutableArray arrayWithCapacity:0];

instantiates and assigns an empty array, you then do not add anything to it therefore the 0 count.
Then this line
self.items = [NSMutableArray arrayWithContentsOfFile:[self itemsp]];

is probably the cause. Does [self itemsp] return a valid file path that points to a file that can be parsed into an NSArray.
There are also a lot of other issues with this code.

Update
This line
self.items = [NSMutableArray arrayWithContentsOfFile:[self itemsp]];

must be returning nil.
Confirm by adding this line straight after it
NSLog(@"%@", self.items);

How can I make this assumption
The reason I am making this assumption is because you are getting (null). When you call addObject: on nil you will get nil returned and it is a no-op. As you can see from this snippet
NSMutableArray *myArray = nil;

[myArray addObject:@"Test"];

NSLog(@"%@", myArray);

// => 2012-01-08 20:54:04.708 Untitled[4199:707] (null)

Just because myArray holds a pointer to an NSMutableArray it does not mean that you actually have one.
Therefore the last time you assign to self.items is in:
self.items = [NSMutableArray arrayWithContentsOfFile:[self itemsp]];

which means [NSMutableArray arrayWithContentsOfFile:[self itemsp]] is returning nil

A: Given that NSLog(@"%@",self.items); prints (null) it follows that the self.items NSMutableArray is never created. The only way that could happen is if
self.items = [NSMutableArray arrayWithContentsOfFile:[self itemsp]];

returns nil, that is does not read anything, probably because there is nothing at the path.
NSLog self.items right after the statement:
self.items = [NSMutableArray arrayWithContentsOfFile:[self itemsp]];

If you are trying to write to the app bundle that won't work, you need to write a directory such as the sandboxed Documents directory.


text:
Q: Usage of CompletableFuture's exceptionally method in Kotlin I'm trying to handle CompletableFuture exceptions in Kotlin, but I'm not able to figure out how to supply the appropriate parameters. So, for example, I have:
CompletableFuture.runAsync { "sr" }
  .exceptionally{e -> {}}
but then the compiler complains Cannot infer type parameter T.
How do I fix this?

A: Quite a tricky case which becomes tricky because of some Kotlin magic :)
The direct solution to your problem would be the following code:
CompletableFuture.runAsync {"sr"}
   .exceptionally({e -> null})

The detailed explanation goes here:
The runAsync method accepts a Runnable which means after execution it will return Void. The function passed to exceptionally method must match the generic parameter of the CompletableFuture so in this particular case, you need to help a compiler by returning null explicitly.
So the following will compile without problems:
CompletableFuture.runAsync {"sr"}
 .exceptionally({null})

CompletableFuture.runAsync {}
 .exceptionally({null})

In the first case, the "sr" String will simply be ignored and not returned since the runAsync accepts a Runnable.
You probably wanted to do something like:
 CompletableFuture.supplyAsync {"sr"}
   .exceptionally({"sr_exceptional"})

or:
CompletableFuture.supplyAsync {"sr"}
  .exceptionally({e -> "sr_exceptional"})


text:
Q: Some code not executing when program is reset I am working on a match color game. After the guesses are completed the initialize function is called, which resets the program. After the first set of guesses, when the initialize function is called again, code below the initialize function (two setTimeouts), that asks the user where a color is does not fire again. Thanks for the help.
html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>HTML 5 Boilerplate</title>

    <link rel="stylesheet" href="styles.css">

Where is:

Score: 0

    <button type="button" id="btn">Restart</button>

css
body {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    height: 100vh;
}

.container {
    height: 100vh;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.question {
    position: absolute;
    height: 100vh;
    width: 100%;
    display: none;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.questionbox {
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid black;
    background-color: red;
    height: 400px;
    width: 600px;
    color: white;
    font-size: 33px;
}

.container-box {
    width: 600px;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    height: 400px;
}

.colorbox {
    display: flex;
    height: 200px;
    width: 200px;
    border: 1px solid black;
    box-sizing: border-box;

}

.hide {
    background-color: grey !important;
}

.open {

    border: 40px white;
    cursor: default;
  }
  .button {
      width: 100vw;
      display: flex;
      flex-direction: row;
      justify-content: center;
  }
  #btn {
      display: flex;
      position: absolute;
      bottom: 50px;
      justify-content: center;

      text-align: center;

  }
  .score-container {
      display: flex;
      position: absolute;
      width: 100vw;
      justify-content: center;
      bottom: 100px;
  }

  .border {
      border: 8px solid #66ff00 !important;
  }
  .border-red {
    border: 8px solid #EE4B2B !important;
}

javascript
let colors = ["red", "yellow", "blue", "green", "orange", "purple"],
    $fullbox = $('.container'),
    $popup = $('.question'),
    gamecolor = [],
    $restart = $('#btn'),
    clicks = 0,
    guessColor = [],
    score = 0,
    guess;

window.onload = initialize();
// initialize board
function initialize () {
    clicks = 0;
    $('.colorbox').removeClass('border');
    $('.colorbox').removeClass('border-red');
    $('.colorbox').each(function () {
    $('body').css("pointer-events", "none");
    $('.colorbox').removeClass('hide');
     $(this).css("border", "2px solid black");
     let randColor = colors[Math.floor(Math.random() * colors.length)];
     $(this).css("background-color", `${randColor}`);
     setTimeout(hide, 3000);
    })
}

function hide() {
    $('.colorbox').each(function () {
    $(this).addClass('hide');
    $('body').css("pointer-events", "auto");
    $('.colorbox').css("pointer-events", "auto");
    })
}
//restart
$('#btn').on('click', () => {
    initialize();
})

setTimeout(() => {
    $popup.css('display', 'flex');
    guessColor = colors[Math.floor(Math.random() * colors.length)];
    $('.questionbox').find('p').after(`<span>  ${guessColor}?</span>`);
}, 2500)

setTimeout(() => {
    $popup.css('display', 'none');
    $('body').css("pointer-events", "auto");
}, 6000)

$('.container').on('click', '.colorbox', function () {
    console.log($(this));
    $(this).css("pointer-events", "none");
    clicks++;
    guess = $(this)[0].style.backgroundColor;
    console.log(guess);
    $(this).removeClass('hide');
    console.log(guessColor);
    console.log(guess);
    if (guess === guessColor) {
        score;
        score++;
        $('#score').html(score);
        $(this).addClass('border');
    } else {
        $(this).addClass('border-red');
        // $(this).css("border", "4px solid red");
    }
    if (clicks >= colors.length) {
        setTimeout(initialize, 800);
        $('body').css("pointer-events", "none");
    }
    console.log($(this));

});

A: If you mean the timeouts aren't firing again, you need to put them within initialize()'s scope. Otherwise they are one-time only.
function initialize () {
    clicks = 0;
    $('.colorbox').removeClass('border');
    $('.colorbox').removeClass('border-red');
    $('.colorbox').each(function () {
    $('body').css("pointer-events", "none");
    $('.colorbox').removeClass('hide');
     $(this).css("border", "2px solid black");
     let randColor = colors[Math.floor(Math.random() * colors.length)];
     $(this).css("background-color", `${randColor}`);
     setTimeout(hide, 3000);
    });

    setTimeout(() => {
        $popup.css('display', 'flex');
        guessColor = colors[Math.floor(Math.random() * colors.length)];
        $('.questionbox').find('p').after(`<span>  ${guessColor}?</span>`);
    }, 2500)

    setTimeout(() => {
        $popup.css('display', 'none');
        $('body').css("pointer-events", "auto");
    }, 6000)
}


text:
Q: Why: a relative adverb, a conjunction ... or both? I am not familiar with the idea that an adverb can function as a conjunction at the same time. Here are a couple of sentences that are confusing me.

This is the reason why she left him.

...and

He was transferred to New York, where he was promoted to a higher level.

The relative adverbs why, where, when, and how seem to introduce a clause. Therefore, can they also be called conjunctions? If yes, would I be right in assuming that relative adverbs can function as conjunctions at the same time?

A: श्री गणेशाय नमः
The problem here is that parts of speech (adverb, conjunction, pronoun, etc.) are being used as labels to classify words as "being" one and only one part of speech, and that this categorization seems to be directed by faulty definitions.
Parts of speech are uses of words, and in English almost any word can be used in a number of such ways. Definitions of such use categories are just summaries, and not directions to be followed.

So, first of all, it is entirely possible for any English word to "be" more than one part of speech,  depending on the context that word appears in.

In this case, the wh-words that have adverbial meanings
       (temporal: when; locative: where; purpose/cause: why; manner/means: how)
are indeed used to introduce clauses, like many adverbs; but this doesn't make them conjunctions.
Conjunctions are one special class of words with special grammar.
When, where, why, and how belong, however, to a different special class of words, with equally special grammar. In fact, they constitute one subclass of this special class.
Most of the other wh-words (what, which, who) refer to nouns, so they're called pronouns --
    either interrogative pronouns (because they're used to introduce question clauses)
    or relative pronouns (because they're also used to introduce relative clauses).

Second, then, it's quite common for something other than a conjunction to "introduce clauses". Complementizers introduce complement clauses (including embedded wh-question complements), adverbs introduce adverbial clauses, etc. The traditional definitions don't go nearly far enough; they're rough guides, no more.

These are also the proper terms for the wh-words with adverbial senses. They came originally from Indo-European oblique noun cases like Locative and Instrumental, and they were used in much the same way as any other interrogative or relative pronoun, to introduce clauses.
Since they don't refer to nouns, however, clauses that they introduce have adverbial restrictions.
Relative clauses, for instance, must modify a noun, but if the relative pronoun is where, the noun it modifies has to be place, or a synonym, or some other word that refers to a place. Similarly, relatives headed by when must modify nouns referring to a point or length of time; the time when itself is most common.
Why and how are even more restricted.
How itself cannot be used at all as a relative pronoun, even if it's modifying the right noun:

*

*I don't like how he did that.

*I don't like the way he did that.
but not

**I don't like the way how he did that.
Why relative clauses must modify the noun reason. Synonyms don't work.

*

*I'm unclear on the reason why he did that.

**I'm unclear on the purpose why he did that.

**I'm unclear on the intention why he did that.
Essentially, the phrase the reason why has become frozen.
There's a lot more, but I forbear.

A: Generally question words can be used for relative clauses and for subordinated question clauses:
1 Where have you found it?
2 the place where I found it
3 He asked me where I had found it.

A: Subordinating Conjunctions vs. Relative Pronouns & Relative Adverbs.
A subordinate or depending clause is joined with a main clause by :
 (1) subordinating conjunctions and
 (2) relative pronouns/adverbs.
It must be noted that relative pronouns/adverbs and subordinating conjunctions are different even though both of them introduce a depending clause.
Relative pronouns act as the subject/object of the dependent clause. Relative adverbs modify the verb of the dependent clause. At the same time, both the relative pronouns and relative adverbs qualify the antecedents (a noun or a pronoun in the main clause) :
Relative pronouns : who, whom, whose, which, that..
This is the boy who stood first in the exam.
Relative pronouns (who) is the subject of the depending clause and qualifies its antecedent "the boy" in the main clause.
Relative adverbs : When, Where, Why.
Adverbial meanings of the relative adverbs :
When >> temporal,
Where >> locative,
Why >> cause/purpose
"I know the time when he went there."
"I know the place where he lives."
"I know the reason why he went there."
Here, the relative adverbs, 'when', 'where' and 'why' modify the verbs of the depending clause and qualify the antecedents 'the time', 'the place' and 'the reason' respectively.
But  "The reason why" is redundant and unnecessary. "The way how" is INCORRECT. How means 'the way'.
I know the way he did it.
Or, I know how he did it.
Here, the subordinate clause is a noun clause, and 'how' acts as a subordinating conjunction.
But subordinating conjunctions are merely followed by the subject of the depending clause. In other words, subordinating conjunctions only introduce the depending clauses.
For example,
I know that he is honest.
You will pass if you study hard.
He failed the exam because he was idle. etc.

THE SUBORDINATE CLAUSE IN YOUR 1ST SENTENCE IS A DEFINING RELATIVE CLAUSE, AND "WHICH" IS A RELATIVE ADVERB.
THE SUBORDINATE CLAUSE IN YOUR 2ND SENTENCE IS A NON-DEFINING RELATIVE CLAUSE, AND "WHERE" IS A RELATIVE ADVERB TOO.


text:
Q: Are there any larger data types for strings in Alfresco? I'm working with a custom content model and I want to have a custom text field that serves the purpose of a description for the document. I've run into a problem with this field, because it seems I can't have a d:text property with more than 1024 characters.
Is there another property type that allows me to go over this limit? I'm using the content model to describe PDF documents, and these do not always have OCR performed on them, so I need the description field to make them searchable by Alfresco.

A: d:text length depends on your database table. So try to increase that and you should be fine.

A: It is very simple, to set a bigger limit, than 1024 characters, to a attribute which is from the type "d:text". You must modify the file custom-config-model.xml which you can find in folder ALFRESCO_HOME/tomcat/shared/classes/alfresco/web-extensions.
In the config from your node-type you must write something like in the following example:
    <config evaluator="node-type" condition="your:model">
        <forms>
            <form>
                <field-visibility>
                    ...
                    <show id="your:attribute" />
                    ...
                </field-visibility>
                <appearance>
                    ...
                    <field id="your:attribute">
                        <control template="/org/alfresco/components/form/controls/textarea.ftl">
                            <control-param name="maxLength">40000</control-param>
                        </control>
                    </field>
                    ...
                </appearance>
            </form>
        </forms>
    </config>

The fist thing you do with that code is:

*

*You show the attribute

*You make the textfield to a template which is called textarea (much better for a text or something)

*you set the maximal length of the attribute to 40.000 characters (which should be enough)
If you don't want the textfield as textarea delete the template attribute from the control section.

After this manipulation you can save strings with up to 40.000 characters in this attribute.
Hope I could help you!


text:
Q: Hide vertical scrollbar in lwc lightning datatable How to hide vertical scrollbar in lwc lightning datatable. I have enabled lazy loading.
I tried with height, but when there are less records, vertical scrollbar is not coming.
But it didnt solve the issue of hiding it when there are more records.
Please suggest any solution for this. Because this is standard one, its getting hard to enhance.
<div style="overflow: scroll-hidden; height:300px">
     <template  if:true={loadedData}>
            <c-sld-lightning-datatable scroll-hidden key-field="account" data={acclist} columns={columns}
                        enable-infinite-loading={isLoaded}
                        onloadmore={loadMoreData}
                        sorted-by={sortBy}
                        onchildexpand={childrowexpand}
                        onchildcollapse={childcollapse}
                        default-sort-direction={defaultSortDirection}
                        sorted-direction={sortDirection}
                        onsort={handleSortdata}
                        hide-checkbox-column="true"
                        onrowaction={moreRowAction}
                        >
            </c-sld-lightning-datatable>
        </template>
        </div>

A: If you want to preserve the ability to scroll, but hide the scrollbars, you can do that with CSS. Keep in mind this is not a good idea for accessibility because a scrollbar is an affordance that lets users know they can scroll in the first place. See an example of this CSS in action on this W3Schools example. You should be able to find several more examples online if you search for "hide scrollbars css".
overflow-y and overflow-x as well as overflow (for both x & y axes) tell the browser to allow scrolling to see overflowed content. scrollbar-width and the prefixed attributes below for different browsers then allow you to hide the scroll bars.
.myclass {
    overflow-y: scroll; /* Tells the browser to treat `overflow` content as scrollable */
    -ms-overflow-style: none;  /* IE and Edge */
    scrollbar-width: none;  /* Firefox */
}

.myclass::-webkit-scrollbar {
     display: none; /* WebKit browsers, like Chrome and Safari */
}


text:
Q: What does "DUNKIN DOUGH" mean? DUNKIN DOUGH
It was in a comic book typed in capital and in the book there was a part talking about riddles in English (American English).
There was a plump man having a large sum of money and this was written on piece of paper pasted on the wall in the picture. It was meant to teach the reader the meaning of the words "Dough" and "Nut" through the compound word Doughnut.

The riddle was: "Who is a doughnut?"
And the answer was: "A man crazy for money."

A: DUNKIN DOUGH is an allusion to the global chain of doughnuts-and-coffee shops Dunkin' Donuts.
The joke arises because dough is an old US colloquialism for money and a nut is a crazy person, or one who is madly fond of something.


text:
Q: Stalled data step in SAS I am a novice SAS user and am trying to run a data step on a data set with 198 rows and 1611 columns.  I don't think I am doing anything particularly elaborate in the data step, but it never completes it.  I would really appreciate if someone could point out if/where there is a problem in my code.  Thank you!
DATA merged2;
    set merged;
    Q1_rec_activity=.;
        IF (.< PA <150) THEN Q1_rec_activity=0;
        IF (. < PA >=150) THEN Q1_rec_activity=1;
    IF (PA_Q3 == 8) THEN PA_Q3=0;
    IF (PA_Q3 == 9) THEN PA_Q3=9999;
    PA_calc_activity=.;
        IF (. < PA_Q3 < 9999) and (. < PA_Q4) THEN PA_calc_activity=PA_Q4*PA_Q3;
        IF (PA_Q3==9999) THEN PA_calc_activity=9999;
    LABEL AGE='Age'
            DEM_1='Birth Year'
            DEM_2='Gender'
            DEM_3='Marial status'
            DEM_4='Hispanic/Latino'
            DEM_5='Race'
            DEM_7='Educational attainment'
            DEM_8='Employment status'
            DEM_10='Work schedule'
            DEM_11='Coworkers'
            DEM_12='Health insurance'
            DEM_14='Income'
            MODULE='Module'
            TobScreen_1='Qualtrics 1 smoke cigarettes'
            TOB_Q1='CHART tobacco module smoke cigarettes'
            TobScreen_3='Qualtrics 1 smoke cigars, cigarillos, or filtered cigars'
            TOB_Q3='CHART tobacco module smoke cigars, cigarillos, or filtered cigars'
            Exercise_Time='Qualtrics 1 minutes of moderate activity'
            PA_Q4='CHART PA module minutes of moderate activity'

    RUN;

A: Because you're missing a semicolon at the end of your label statement, SAS sees RUN as a part of the label statement.  As such it never encounters a step boundary (a RUN, QUIT, DATA, or PROC statement, typically), and thus never actually compiles and runs your code.
As Reeza pointed out in comments, you also have some errors in your code.  == is incorrect in SAS; single equal signs work for both equality and assignment.  If you prefer to have two different symbols, you can use eq for equality (though you still need to use = in some option and parameter contexts).


text:
Q: TypeError: Object # has no method 'forEach' mongodb I am trying to copy a document from one collection to another using MongoDB and nodejs in visual studio. Here's what I am trying to do:
var newcollection = db.get('mynewdata');
var oldcollection = db.get('myusercollection');
var userName = req.body.username;

oldcollection.find({ "username" : userName }).forEach(function (docs) {
     newcollection.insert(docs);
});

On the Mongo website it says that collection.find() should return a cursor which should be able to use the forEach() method.  However, it's not returning a cursor object and forEach doesn't seem to be defined for whatever its returning.
I get the error from the subject line that says: TypeError: Object #<Promise> has no method 'forEach'
Any ideas as to why it is giving me this error?

A: Try this:
oldcollection.find({ "username" : userName }).exec(function(err, results){
    if(err){
        throw err
    } else {
        results.forEach(function(docs){
            newcollection.insert(docs)
        })
    }
});

I think your problem is the response from the query is an object. This method works for me.

A:
On the Mongo website

That may be the case with the core mongo API, but not the Node.js module.
But also, make sure you're using the right version of the Node library (and the official one too).


text:
Q: Ionic 3 popover to cant add label or span tag I used Ionic 3 for my university  project, I getting some issue , i added  this code part headding: 'SOMETEXT <ion-label class="special-txt">$100 </ion-label>    to but its out put showing like this SOMETEXT <ion-label class="special-txt">$100 </ion-label>
cant change on the color  for .special-txt and always shown from the out put  component

.ts
doAlertPayment() {
        let options = {enableBackdropDismiss: true};
        let alrt = this.popoverCtrl.create(AlertsystemPage, {
            type: '1',
            headding: 'SOMETEXT <ion-label class="special-txt">$100 </ion-label>

            subHeadding: '',
            alertMessage: this.master.language.getLanguageLabel('paymentValidPeriod'),
            positiveBtnText: this.master.language.getLanguageLabel('confirmPayment'),
            negativeBtnText: '',
            responseData: '0',
            cssClass: 'custom-popover'
          },
          options);

        alrt.onDidDismiss(data => {
          if(data){
            this.showQRCode = true;
          }
          console.log("Action completed!");
        });

        alrt.present(); // present on center

    }}

css
.custom-popover .special-txt {color: #f44336;}


text: Q: Laravel API login with JWT authentication token storage I'm creating a mobile/app and i'm using the Laravel framework. For the API login i'm using JWT auth. This works fine but I have a few questions about the storage of the token. At the moment i'm sending the token in the header. But when I switch pages the headers are gone. Should I keep the token in the header or is it better to save it in a Laravel database sessions. Is there a way to keep the token in the header when i switch to another function? Hope someone can help me out, been thinking for days about this.


text:
Q: $X$ Hausdorff space, $Y \subseteq X$ compact $\implies $ Y closed
Suppose $X$ is a hausdorff Space and $Y \subseteq X$ compact. Then $Y$
  must be closed

My Attempt: We need to find an open set $O$ such that $O \subseteq X \setminus Y$, then $Y$ is closed. Let us take an open coven $\mathcal{O}$ of $Y$. Since $Y$ is compact, we can find a finite subcover $\mathcal{O}' = \{ O_1, ... , O_n \} $ such that all $O_i $ are open in $X$ and $Y \subseteq \bigcup_{i=1}^{n} O_i $ Here I am stuck. Can I assume all these $O_i$ are disjoint since $X$ is hausdorff ? And pick one of them (the one that lies outsite $Y$) Therefore showing $Y$ is closed? Can someone help me? thanks

A: No, you need to show that $X\setminus Y$ is open. No matter what $Y$ is, there's always at least one open subset of $X\setminus Y$, namely, $\varnothing$.
You're on the wrong track altogether, because you've not seen how to make use of the fact that $X$ is Hausdorff. One way to show that $X\setminus Y$ is open is to show that each point of $X\setminus Y$ has an open nbhd disjoint from $Y$, so let $x\in X\setminus Y$. $X$ is Hausdorff, so for each $y\in Y$ there are open sets $U_y$ and $V_y$ such that $x\in U_y$, $y\in V_y$, and $U_y\cap V_y=\varnothing$. Clearly $\{V_y:y\in Y\}$ is an open cover, so there is a finite $F\subseteq Y$ such that $\{V_y:y\in F\}$ covers $Y$. Can you see how to use this fact to find an open nbhd of $x$ that is disjoint from $Y$?


text:
Q: Bootstrap Carousel on top of a background image Im trying to make a bootstrap carousel (BS4) function within a div (content-left) that contain a background-image of an iPhone wireframe. So that the images slide within the iPhone wireframe illustrating how it would work on the actual device. I can display the background image successfully without the carousel, but not without it. Any thoughts on what I need to change?
The green wireframe is what I want to display in the background. While the carousel should change the images in the gray box.

HTML:

    .content-left {
      float: left;
      height:496px;
      width: 260px;
      background-image: url(/images/iPhoneX_wireframe-260x496.jpg);
       -o-background-size: cover;
      -moz-background-size: cover;
      -webkit-background-size: cover;

    }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>

                Previous

                Next


text:
Q: ¿Cómo hacer consultas en múltiples tablas con Hibernate HQL? Dado los pojos (Clases) que pongo a continuación, ¿cómo se haría la Query siguiente?
la Query
    SELECT pagina.NombrePagina, user_rol.User_id FROM user_rol
    INNER JOIN rol_pagina ON rol_pagina.Rol_id = user_rol.roles_id
    INNER JOIN pagina ON pagina.id = rol_pagina.listaWeb_id
    WHERE user_rol.User_id = 1 AND pagina.NombrePagina = 'mani.jsp'

Pagina.class
       @Entity
public class Pagina {

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)//Para generar números
  autoincrementados
  private int id;
  private String NombrePagina;

  public Pagina() {
    super();

  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getNombrePagina() {
    return NombrePagina;
  }

 public void setNombrePagina(String nombrePagina) {
    NombrePagina = nombrePagina;
 }

}

User.class
@Entity

public class User {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)//Para generar números autoincrementados
private int id;
private String usuario;
private String pass;
private String mail;
@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER) //eager = carga ansiosa
private List<Rol>roles = new ArrayList<>();

public User() {
    super();
    // TODO Auto-generated constructor stub
}

public User(int id, String usuario, String pass, String  mail) {
    super();
    this.id = id;
    this.usuario = usuario;
    this.pass = pass;
    this.mail = mail;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getUsuario() {
    return usuario;
}

public void setUsuario(String usuario) {
    this.usuario = usuario;
}

public String getPass() {
    return pass;
}

public void setPass(String pass) {
    this.pass = pass;
}

public String getMail() {
    return mail;
}

public void setMail(String mail) {
    this.mail = mail;
}

public List<Rol> getRoles() {
    return roles;
}

public void setRoles(List<Rol> roles) {
    this.roles = roles;
}

}

Rol.class
  public class Rol {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)//Para generar números autoincrementados
private int id;
private String rol;
@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER) //eager = carga ansiosa
private List<Pagina>listaWeb = new ArrayList<>();

public Rol() {
    super();
this.rol = "user";
}

public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}

public String getRol() {
    return rol;
}

public void setRol(String rol) {
    this.rol = rol;
}

public List<Pagina> getListaWeb() {
    return listaWeb;
}

public void setListaWeb(List<Pagina> listaWeb) {
    this.listaWeb = listaWeb;
}

}

El motivo por el que no lo se hacer es que, en la BBDD tengo la tabla pagina,user,rol, user_rol y rol_pagina.
Pero en hibernate usas los pojos para hacer las querys,
¿cómo accedes a esas 2 ultimas tablas?
Ejemplo de una consulta mia
"Consulta para validar un user al logearse"
  public boolean validation(User u) {

    boolean bOk = true;

    Session session = HibernateUtil.getSessionFactory().openSession();
    String queryString = "FROM User WHERE usuario = (:condicion) AND pass =(:condicion2)";

    try {
        Query hqlQuery = session.createQuery(queryString);
        hqlQuery.setParameter("condicion", u.getUsuario());
        hqlQuery.setParameter("condicion2", u.getPass());
        u = (User) hqlQuery.getSingleResult();
    } catch (NoResultException e) {
        // TODO Auto-generated catch block
   //           e.printStackTrace();

        bOk = false;
    }

    return bOk;
}

A: Tienes que usar hql (Hibernate Query Language). Basandome solamente en tu query pude hacer esto:
String queryHQL="SELECT new Map(p.nombrePagina, ur.id) FROM User_rol as ur
    INNER JOIN Rol_pagina as rp ON rp.id = ur.id
    INNER JOIN Pagina as p ON p.id = rp.listaWeb_id
    WHERE ur.User_id =:param1 AND p.nombrePagina =:param2 ";
Session session=sessionFactory.getCurrentSession();
Query consultaHQL = session.createQuery(queryHQL);
consultaHQL.setParameter("param1", 1);
consultaHQL.setParameter("param2","mani.jsp");
ArrayList<Map> respuestaHQL=(ArrayList<Map>) consultaHQL.list();

En hql le haces consultas a las clases y es indispensable que a cada clase le pongas alias. Ej. mi.paquete.User_rol as ur aunque hql puede omitir el paquete User_rol as ur.
Cuando llamas a un campo pones el nombre de la variable y esta automaticamente llama al metodo set como en: p.nombrePagina o en ur.user_id.
Tambien como es este el caso solo regresas pares clave/valor lo cual es idoneo para crear un Map de java desde hibernate new Map(...). Al final hibernate lo regresa todo en una lista de mapas en esta consulta:
ArrayList<Map> respuestaHQL=(ArrayList<Map>) consultaHQL.list();

Y respondiendo a los comentarios, si puedes ejecutar sql nativo desde Hibernate, pero no se recomienda a menos que el HQL o Criteria sean muy lentos. Pero debes estar consiente de que si haces esto la multiplataforma (respecto a bases de datos) de hibernate se pierde. Esto se hace llamando a session.createSQLQuery(SQLnativo);


text:
Q: rollover an image hyperlink to become an text line I found this useful html as answer to a question about rollover image to text by renocor (rollover a text hyperlink to become an image)

Hyper Text

but i needed to achieve the opposite effect. So i inverted span with image it partially works. Meaning that instead of the image i see the text but the problem is that the image doesn't disappear but shifts just below the text.
Any suggestions?
Thanks
.changeable span
{
    display: none;
}
.changeable:hover image
{
    display: none;
}
.changeable:hover span
{
    display: inline-block;
}
</style>
Hyper Text

A: Check the


text:
Q: Recoger valor de Gtk Dialog con Python Veréis, estoy haciendo un indicador para Ubuntu y quería implementar una ventana de Preferencias. Puesto que no tengo idea de Python, tras bastante esfuerzo y mucha lectura de documentación he conseguido crear una pequeña ventana tal que así:

Hasta ahí todo correcto. Ahora he conseguido recibir los valores del switch y mostrarlos por consola como "on" y "off".
Aquí llega mi problema, que no sé definir. Esto es lo que tengo de código.
def __init__(self):
    [...]
    label11 = Gtk.Label('Autoarranque:')
    label11.set_alignment(0, 0.5)
    table11.attach(label11, 0, 1, 0, 1, xpadding=5, ypadding=5)
    self.switch1 = Gtk.Switch()
    self.switch1.connect("notify::active", self.on_switch_activated)
    self.switch1.set_active = True
    table11.attach(self.switch1, 1, 2, 0, 1,
                   xpadding=5,
                   ypadding=5,
                   xoptions=Gtk.AttachOptions.SHRINK)
    [...]

def on_switch_activated(self, switch1, gparam):
    if switch1.get_active():
        state = "on"
        return state
    else:
        state = "off"
        return state
    print("Switch ", state)

def close_ok(self):
    stat = on_switch_activated(self, switch1, gparam)
print(stat)

Pues al lanzar esto me devuelve un error dentro del close_ok que dice NameError: global name 'on_switch_activated' is not defined. ¿No se supone que está definido? Si alguien me lo puede explicar se lo agradecería.
¡Un saludo!

A: Lo que parece que te pasa es que on_switch_activated es un método, no una función global (falta la definición de clase). El acceso a los método y atributos se ha de realizar a través de la instancia, que normalmente se pasa como argumento llamado self:
def close_ok(self):
    stat = self.on_switch_activated(self.switch1, self.gparam)
    print(stat)

Desconozco si gparam era o no atributo de la instancia.


text:
Q: Pointer To Char Array (cin.get & cout) Just to refresh my concept I'm working on parallel arrays. One is used to store integer data and the other one for char data i.e GPA.
The problem compiles like a charm but the result is not correct, it displays the Student IDs correctly but not the GPA.

*

*The simple cin works fine

*I don't really know how to use cin.get and cin.getline using pointers.

*In function enter I want to get the two-character-long string (plus one terminating null character).

Code listing:
#include <iostream>
#include <cstring>
using namespace std;

void enter(int *ar, char *arr, int size);
void exit(int *a, char *yo, int size);

int main()
{
   const int id = 5;
   const char grade = 5;
    int *student = new int[id];
    char *course = new char[grade];
    cout << "\n";

    enter(student, course, 5);
    exit(student, course, 5);

}

void enter(int *ar, char *arr, int size)
{
    for(int i = 0; i < size; i ++)
    {
        cout << "Student ID: " << i+1 << "\n";
        cin >> *(ar+i);
        cin.ignore();
        cout << "Student Grade: " << i+1 << "\n";
        cin.get(arr, 3);
    }
}

void exit(int *a, char *yo, int size)
{
    for(int i = 0; i < size; i ++)
    {
        cout << "ID And Grade Of Student #" << i+1 << ":";
            cout << *(a+i) << "\t" << *(yo+j) << endl;
    }
}

A: You are attempting to use part of the C++ language, but not embrace it entirely.  There is no need for you to manage memory (at all) to solve this problem.  Additionally, it would be much better to solve it using the standard language features:
struct Info
{
    int StudentId;
    std::string Grade; // this could easily be stored as an int or a char as well
};

int main()
{
    const std::vector<Info>::size_type SIZE_LIMIT = 5;
    std::vector<Info> vec(SIZE_LIMIT);
    for (std::vector<Info>::size_type i = 0; i < SIZE_LIMIT; ++i)
    {
        std::cout << "Enter a Student ID:  ";
        std::cin >> vec[i].StudentId;
        std::cout << "Enter a Grade:  ";
        std::cin >> vec[i].Grade;
    }

    std::for_each(vec.begin(), vec.end(), [&](const Info& i)
    {
        std::cout << "Student ID:  " << i.StudentId << ", Grade:  " << i.Grade << std::endl;
    });

    return 0;
}

Which can very easily be converted to account for more than 5 (e.g. virtually infinite) by adding an overload for std::istream& operator>>(std::istream&, Info&) and changing the for-loop to a std::copy operation.
If you absolutely want to keep your hands tied behind your back, you should at least make the following changes:
const unsigned int CLASS_SIZE = 5;
const unsigned int GRADE_SIZE = 5;
int student[CLASS_SIZE];
char course[CLASS_SIZE][GRADE_SIZE] = {};

// initialize course grades to empty strings, if you don't use the = {} above
for (unsigned int i = 0; i < CLASS_SIZE; ++i)
{
    memset(course[i], 0, GRADE_SIZE);
}

// ...

// use your constants for your sizes
enter(student, course, CLASS_SIZE);
exit(student, course, CLASS_SIZE);

// ...

// NOTE:  you should check to make sure the stream is in a good condition after each input - I leave the error checking code for you to implement
cout << "Student ID: ";
cin >> ar[i];
cout << "Student Grade: ";
cin >> arr[i]; // also note:  since you are not using std::string, this can overflow!  careful!

// ...

cout << "ID And Grade Of Student #" << i+1 << ":" << a[i] << "\t" << yo[i] << endl;


text:
Q: I get this error when I try to load the Maps extension. How can I fix it? The error message is:
 MapsRegistration::onRegistration' is not callable in /var/lib/mediawiki/includes/registration/ExtensionRegistry.php:

A: To resolve an error like this, you'd need to update the dependencies of the
"composer.lock" file. So, run composer update, and reboot Ubuntu. It should fix the issue.


text:
Q: Responsive Layout - Content Breaks I have a page layout with the following html structure:

test 1

test 2

test 3

Using the following css, I wanted to make a simple, responsive layout:
.row {
    width: 100%;
    display: block;
    padding-left: 1.25%;
    padding-right: 1.25%;
    margin: 0 auto 15px auto;
}
.col3 {
    width: 30%;
    display: inline-block;
    margin: 0 1.25%;
    border: none;
}

Why is it when I shrink my page to 30% of the width of my screen, the last column drops down underneath the other rows?
Is there something im not accounting for? I would have thought it would have just continued to get narrower and narrower. What causes it to create a content break, and drop down a row.
Screenshots:

A: It's from display: inline-block. If you float your columns to the left they will work as expected.
When you use display: inline-block spaces/returns etc between the elements that have inline-block applied to them will be taken into account and rendered. You can think of it as adding a single space between each inline-block element.
This is the main downside of using display: inline-block over floats in my humble opinion.
.col3 {
    float: left;
    width: 30%;
    margin: 0 1.25%;
    border: none;
}

You could also remedy this by doing the following if you wanted to continue using display: inline-block but they're hackerish. I would advise against either of these solutions.
no space between elements

test 1

test 1

test 1

comments between elements

test 1

test 1

test 1

A: Your problem lies with the lines
.col3 {
    ..
    width:30%;
    margin: 0 1.25%;
    ..
}

As width is 30% of the row, but while you are narrowing it down, the margin is actually getting wider with respect to the row, its a common thing which happens to inline-block display type.
If you drop the margin line, or simply change the width of the margin to
margin: 0 1%;

it would be fixed.
No need to worry about fixing inline-blocks, or having to deal with its downsides.


text:
Q: Changing a Frame from an original window to another I have this function that is generating a button every time another function is called and placing the new button into a new window. I've successfully implemented this code into my main program except for one part, the buttons will not generate in any other window except my main window. The code is a little bit longer, so I apologize.
import tkinter as tk
from pathlib import Path

def window2():
    editor = tk.Toplevel()
    editor.title("Window 2")

def add_buttons(*items):
    for item in items:
        auto_button = tk.Button(button_frame, text=item)
        auto_button.grid(column=1)

def get_items(path):
    if path.exists():
        with open(path, "r") as f:
            data = f.read().strip().splitlines()
            return data
    return []

def save_items(path, items):
    with open(path, "w") as f:
        f.write("\n".join(items))

def submit():
    global items

    # get the text and append it to our global list of button text
    text = entry.get()
    items.append(text)

    # create the button
    add_buttons(text)

    # save the list of items
    save_items(path, items)

root = tk.Tk()
button_frame = tk.Frame(root)
entry = tk.Entry(root)
submit = tk.Button(root, text="Submit", command=submit)

entry.grid(row=0, column=1)
submit.grid(row=1, column=0, columnspan=2)
button_frame.grid(column=1)

window2_btn = tk.Button(root, text="Take me to window 2", command=window2).grid(row=2, column=0,)

# initialize our list of buttons from a file
path = Path("buttons.txt")
items = get_items(path)
add_buttons(*items)

root.mainloop()

I've tested this in 3 different programs now, all with the same pattern of the button properly operating in the main startup window, but won't allow me to call the function to operate in a different window as seen above in button_frame = tk.Frame(window). The code above is almost verbatim Bryan Oakley's, credit to him, I went back into the code sample he sent me to show my minimal with the same error. Each time this function is called it gives a undefined (window in this exmaple) error. I know this can't be a hard fix but for the love of me I haven't be able to figure it out.

A: Here is the complete script. This code works!
from pathlib import Path
import tkinter as tk

def window2():
    window.deiconify()
    window.lift()
    window.title("Window 2")
    window.focus_force()

def add_buttons(*items):
    for item in items:
        auto_button = tk.Button(button_frame, text=item)
        auto_button.grid(column=1)

def get_items(path):
    if path.exists():
        with open(path, "r") as f:
            data = f.read().strip().splitlines()
            return data
    return []

def save_items(path, items):
    with open(path, "w") as f:
        f.write("\n".join(items))

def submit():
    global items

    # get the text and append it to our global list of button text
    text = entry.get()
    items.append(text)

    # create the button
    add_buttons(text)

    # save the list of items
    save_items(path, items)

root = tk.Tk()
window = tk.Toplevel()

button_frame = tk.Frame(window)
entry = tk.Entry(root)
submit = tk.Button(root, text="Submit", command=submit)

entry.grid(row=0, column=1)
submit.grid(row=1, column=0, columnspan=2)
button_frame.grid(column=1)

window2_btn = tk.Button(root, text="Take me to window 2", command=window2).grid(row=2, column=0,)

# initialize our list of buttons from a file
path = Path("buttons.txt")
items = get_items(path)
add_buttons(*items)

root.mainloop()


text:
Q: Is it possible to override WebRTC connection timeout? I have implemented WebRTC calls in my project, When the internet got disconnected then WebRTC throws a disconnected state immediately and Closed/Failed state after 10/15 secs.
Can I override these 10/15 secs timeout to 30secs?
Is it possible?


text:
Q: Stop floating elements next to Bootstrap rows from affecting alignment I have a div element whose children are Bootstrap rows, and am trying to float an element to the right of these (as a sibling element to one of the rows). The issue is that, when rendered, the rows that end up to the left of the floating element are misaligned.
It seems to be something to do with the interplay between floats, negative margins, and flexbox, but I've been unable to work out what exactly.
Ideally, I would like a CSS-only fix for this issue, and/or an explanation for why this is happening.
Thanks!
A minimal example that illustrates the problem:

body {
  font-family: system-ui;
  text-align: center;
}

.row {
  text-align: left;
  border-top: solid black 1px;
  border-bottom: solid black 1px;
  background-color: red;
}

.main {
  margin-left: 15vw;
  margin-top: 40px;
  margin-bottom: 40px;
  width: 70vw;
}

.align-right {
  float: right;
  width: 300px;
  padding-left: 30px;
  background-color: green;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.

    I am a floating div, I am a floating div, I am a floating div, I am a floating div, I am a floating div, I am a floating div, I am a floating div, I am a floating div, I am a floating div, I am a floating div, I am a floating div, I am a floating div

      A very small paragraph.

      A slightly larger paragraph than the last.

      It is a long established fact that divs can float.

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.

Edit: To clarify - I would like for the floating content to vertically span a variable number of rows depending on its size, not to be confined to a separate column alongside one (or any specific number) of these rows. This is because I have no guarantee of the exact layout, content or sizes of each element, since in my case the HTML is generated from varying content stored in our CMS.
Something like this image is what I'm looking for, where each paragraph is inside the following elements:

    {paragraph}

And where the paragraphs to the side of the floated div are not slightly left-indented.

A: I've provided two solutions below because the question is ambiguous about whether the floated element should span entire rows or partial paragraphs.
Note that I've removed several of your style rules which are redundant with Bootstrap. Color, spacing and other utilities are available with the library.
A Nested Row
It seems like simply adding a nested row with any number of columns provides a solution. It's a bit of a pattern violation to set something next to a grid row. It's better to work with the grid system, which may mean nested rows and columns. How you set width is up to you.

body {
  font-family: system-ui;
  text-align: center;
}

.main {
  margin-left: 15vw;
  margin-top: 40px;
  margin-bottom: 40px;
  width: 70vw;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

      I'm a full-width column in a top-level row.

          I'm a left column in a nested row inside a nested column. I can have any number of nested rows below me.

          I'm another left column in a nested row.

          I'm a third left column in a nested row.

      I am a right column in a top-level row. I could also contain a nested row, but I really don't need one yet.

      I'm a full width column in a top-level row.

      I'm another full width column in a top-level row.

An Interior Float
If all you're after is to float a media element, for example, then it should be inside the column. Generally speaking all content should be inside a column (or other standard layout structure).

body {
  font-family: system-ui;
  text-align: center;
}

.main {
  margin-left: 15vw;
  margin-top: 40px;
  margin-bottom: 40px;
  width: 70vw;
}

.figure {
  width: min-content; /* makes figcaption text wrap naturally */
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo.

I'm a floated box. I could also be embedded in a paragraph.

Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo.

Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo.

Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo.

Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo.

Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo.


text:
Q: Work and Time problem for proof If $a_1$ men and $b_1$ boys can complete a work in $x$ days, while $a_2$ men and $b_2$ boys can complete the same work in $y$ days, then
$$\frac{\text{1 day work of 1 man}}{\text{1 day work of 1 boy}} = \frac{yb_2 - xb_1}{xa_1 - ya_1}
$$
Please help me out in proving this equation.

A: So you have two linear equations: in the following $s$ will denote the "amount of work" of one man per day and $t$ will denote the "amount of work" of one boy per day.
\begin{align}
a_1\cdot s &+ b_1 \cdot t = x, \\
a_2\cdot s &+ b_2 \cdot t = y.
\end{align}
Using Cramer's rule we get that
$$
s=\frac{x\cdot b_2 - y\cdot b_1}{a_1\cdot b_2-a_2\cdot b_1}, \quad
t=\frac{x\cdot a_2 - y\cdot a_1}{a_1\cdot b_2-a_2\cdot b_1}.
$$
What you are looking for is then simply
$$
\frac{s}t =\frac{x\cdot b_2 - y\cdot b_1}{x\cdot a_2 - y\cdot a_1}.
$$

A: Formula -
(A men + B boys) $\times$ Number of days they work together = (C men + D boys) $\times$ Number of days they work together
$(a1 + b1) × x = (a2 + b2) × y$
$a1\cdot x + b1 \cdot x = a2\cdot y + b2 \cdot y$
$(a1\cdot x - a2 \cdot y)$ men = $(b2\cdot y - b1 \cdot x)$ boys
$\frac{\text{1 men}}{\text{1 boy}} = \frac{(b2\cdot y - b1 \cdot x)}{(a1\cdot x - a2 \cdot y)}$


text:
Q: Can I inherit a Command class from ICommand rather than have multiple instances of ICommand on one class? It seems much neater to me to implement a command in a class that represents that command, and derives from ICommand. This way I can also export and import commands in an MEF composite application.
Is this possible, or feasible? Is there a known pattern for accomplishing this?

A: I'm not sure how well this answers your question, since I don't know much about MEF.
There is no need to have direct references to command instances on your class, but you do need some way of presenting a binding source that returns one to a view. You can build a menu by binding a MenuItem's ItemsSource to a property that returns a dynamically generated IEnumerable of commands, for example.
You could also use a value converter to get a command on-demand for some arbitrary identifier:
<Button Command="{Binding Path=CommandId, Converter={StaticResource CommandConverter}}" />

Or pass the identifier directly from XAML through Binding.Source:
<Button Command="{Binding Source=DesiredCommand, Converter={StaticResource CommandConverter}}" />

In this case the string "DesiredCommand" would be passed to the converter.


text:
Q: Is it compulsory to learn about Data Structures if you want to be a Java/C++ programmer? So do I really need to learn about them ? Isn't there an interesting way to learn about stacks, linked lists, heaps, etc ? I found it a boring subject.
**While posting this question it showed some warning. Am I not allowed to post such a question ? Admins please clarify and I will delete it :/
Warning :: The question you're asking appears subjective and is likely to be closed.
okay..I get it
So what is THE best way to learn them ? What book do I refer ? What website ?

A: I would go even so far as to say that most of programming revolves around manipulating data structures, it is the foundation of computing after all: you get some data, you process it, you possibly give output. All the data usually reside in data structures and choosing inappropriate structures will have the bigger impact the bigger the project.

A: As you get more experience you will find that algorithms and datastructures are invaluable to your day-to-day development, and actually pretty interesting.
By learning about them now you will learn:

*

*Which data structure is appropriate for which context, i.e. when to use a single-linked list, when to use a stack, when to use a queue, when to use a tree

*Which algorithms are appropriate for which purpose, such as tree depth-first search or breadth-first search.

*Space and time complexity of algorithms, for example why is a quicksort sometimes the best solution, and sometimes heapsort.

*Overall it'll teach you the beginnings and fundamentals of computer science, even if you never have to implement a stack again you'll know the kind of thought and consideration that goes into it.  If you then ever have to implement your OWN data structure (and chances are you will, quite often), you will know what to do and what not to do.

A: It's compulsory to learn about data structures if you want to be a programmer. Data structures are your bread-and-butter - if you don't understand things like the behavior, uses, and run-time complexity ('big-O') of at least the basic structures (arrays, linked lists, stacks, queues, trees (binary / n-ary, self-balancing varietes), hash-tables, heaps, graphs) and the algorithms that run on them (insert / locate / delete), you won't know which is appropriate to use under what circumstances.
Every trade has its tools; these are ours. Data structures are the most basic underpinnings of almost any algorithm that you're going to learn. Unless you want to be a cargo cult programmer, you need to understand how they work.
Whether or not there are interesting ways to learn about them is a separate question entirely... :)

A: If you want to be a successful programmer, data structure is a must. How will you program if you don't know data structures and algorithms?

A: Whether you like it or not, all programming is built around data structures. You may never have to write one, but you will have to choose which one to use many times. It is not really a requirement to programming in general, but if you want to excel in the field, understanding of the basics is a must.
Anyone can build a shed without knowledge of materials or construction techniques. You can even work in a house placing bricks and mortar under the orders of someone else, but if you want to build a house yourself, you do need to understand materials and techniques.
Data structures are the programming materials. Algorithms are techniques. Will you use data structures? You will use the simplest ones in a daily basis, each so often you will need to solve a problem where an specific data structure is required, and while you may manage not to build your own bricks, you will need to understand whether you need bricks or a concrete wall for your purposes.

A: If you want some evidence for the importance of data structures, take a look at the Google hiring process.  Whatever you think about Google as a company, there is no denying that they have some very good people working for them.  Their interview process is setup to determine the candidates knowledge of data structures and algorithms.  Because when it comes down to it, that is what is at the core of programming, no matter what language you are working in or what domain you are programming for.
If you are planning a career as a professional programmer, you need to know the fundamentals, not just how to crank out code that "works".  Otherwise, your just playing.

A: Is it compulsory to learn about arithmetic to be an engineer?

A: If you take the attitude of "is it compulsory" with regards to any of the building blocks of programming languages, you're probably not cut out to be a coder. Regardless of "compulsory" or not, you should always be looking for new concepts to learn and seeing if it'll improve your coding style/standard.
But in answer to your question: yes.

A: I'd say it's compulsory at some point in your development to have a firm grasp. I'm not necessarily sure the standard Data Structures course is the best way to learn. Sometimes, the best way to learn them is "I have problem X. For some reason, it's taking my algorithm a long time to solve X. How can I make this faster?"
One book I'd highly recommend is Programming Pearls. It has some really good analyses, backed by a lot of examples of where the real-world motivations for the solutions came from. It presents the problems in an interesting manner, and never teaches by giving you a laundry list of data structures.

A: It should be, yes...

A: Yes 99% of books on Data Structures are boring and exercises contrived. They feel like they are just making up problems that server no practical purpose :(
This book is the one exception to the rule I've come across. You will have a naive but working RPG game by the end of the book:
Data Structures for Game Programmers
Read the above book and you will solve your chicken and egg problem and see you really can't do much without data structures after all.

A: Well, this may sound a little awkward but I wouldn't say it is COMPULSORY to learn Data Structures to be a - regular- developer. Seriously! Of courser if you study then hard it will give you a lot of insights and knowledge on several programming aspects and that's always good. But compulsory ... well, I think it is just too much. VERY GOOD would be enough.
Let me explain why. It is not that often, for today, to write Data Structures code because - let's face it - it would be RE-writing, RE-inventing what we already know for so many years! What I would say it is COMPULSORY is to study just the general theory of them and the APIs/libraries that are already commonly in use (and tested and optimized) like the Collections API in Java. You must know by heart the differences between a List and a Set (in Java for instance) and their capabilities and proper usage but you don't need to know exactly HOW they are implemented - checking every private method and attribute - to deal with most common, day to day, coding problems. You will do just fine without all the "guts" of Data Structures for the general stuff. We face different challenges now.
But don't get me wrong - neither think I am crazy or naive! Off course there are situations that you will need to implement yourself some sort of custom data structure (maybe your own BalancedBinaryTreeMap!). You got to be prepared for everything.
I am just arguing about being compulsory or not. Again, I don't think is compulsory but it is indeed very good.
Cheers.

A: I suppose you could learn programming without learning a whole lot about data structures or algorithms. To make an equivalent example, think of it like if a carpenter knew how to build things, but didn't know about measurements and such. Would he be able to get a career in carpentry? Possibly, but let's say he needed to know the exact material he would need to complete a project. He'd probably get fired because he doesn't know what sort of material or measurements to use.
So with data structures and algorithms, you can say it's the ability to give exact measurements of an application and knowing what sort of performance you'll get out it.

A: Like a musician learning scales, data structures are part of the tools of the software trade. Sure you can work as a programmer without the knowledge but you're handicapping yourself. If I'm interviewing two people for a position and one of them understands and uses structures and the other can't even explain what a stack is, my choice is pretty clear.
If you want to be judged to be a competent, employable programmer, you need to learn your craft.

A: Is it compulsory to learn them?
No, you can program without them, just as it's not compulsory to break your code into functions.
That being said, if you want to be an effective programmer that can write at least decent code without getting your car egged by your coworkers, you want to at least be able to make a decent selection of library classes.
Every programmer should understand the tradeoff between a LinkedList and an Array, or why binary searches and binary trees are useful for sorted data. This isn't just about performance - it's about correctness too since you can't just put anything into a tree set.
Does it mean that you need to know how to implement your own AVL tree, build super-smart data structures, etc.? Not necessarily. It's a matter of how much you want to know what's going on "beneath the hood" and whether your tasks necessitate it.
I'm not a big fan of deep data structure and algorithms questions in interviews because the vast majority of developers don't need to implement these things, just to use library stuff.  I prefer to ask job related questions in interviews. However, accept that if you don't learn those things you would face a tougher battle to get other jobs.

A: No body should force you to learn anything you don't want to learn.
If you're the type of person that is compelled to be the best that he/she can be at what he/she does, and you love what you do for a living, you'll learn everything there is to know on your own accord.

@happysoul: You should ask yourself WHY learning data structures bore you. Also, it would help if you also identify what DOESN'T bore you.
If you at least love to learn about algorithms, I'm sure we can all suggest a perfect marriage of the two that would be exciting to learn!
My recommendation for best algorithm/data structure combo for the most fun learning experience: graphs.


text:
Q: I'm missing an Ajax parameter, but I'm passing it & the browser is confirming this In a nutshell, I'm getting an error for not passing a parameter, but I am passing it. Below is what I've tried to do & the code.
My jQuery Ajax
var id = this.id;

    var viewd = JSON.stringify({
        'company': id,
        'seen':true,
        'viewCount':0,
        'email':false
    });

    $.ajax({
        type: 'POST',
        url: '/WebServices/usageAjax.asmx/addView',
        data: viewd,
        dataType: "json"
    });

The code it's calling
[WebMethod]
public void addView(string company, bool seen, int viewCount, bool email)
{
        userManager um = new userManager();
        string user = um.id;
        um.addUsage(user, company, seen, 0, email);
}

Which returns this error:

System.InvalidOperationException: Missing parameter: company.    at
System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection
collection)    at
System.Web.Services.Protocols.UrlParameterReader.Read(HttpRequest
request)    at
System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at
System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

Despite chrome clearly stating a value is being passed:

A: Add contentType: 'application/json; charset=utf-8' to your Ajax Request:
 $.ajax({
    type: 'POST',
    url: '/WebServices/usageAjax.asmx/addView',
    data: viewd,
    dataType: "json",
    contentType: 'application/json; charset=utf-8' // <= Add this
});