text:
Q: Retrieving and displaying data from oracle database First of all, I would like to THANK YOU for stopping by and spending your precious time for looking at my problem.
I have 2 different tables within an Oracle Database.
The first table holds metadata about the columns present in the other table. Think of the first (COL_TAB) table as a custom version of the ALL_TAB_COLS which comes by default with Oracle.
COL_TAB
----------------------------------------------
| TABLE_NAME | COL_NAME   | COL_DESC         |
----------------------------------------------
| TABLE1     | TAB1_COL_2 | TABLE 1 COLUMN 2 |
| TABLE1     | TAB1_COL_4 | TABLE 1 COLUMN 4 |
| TABLE1     | TAB1_COL_3 | TABLE 1 COLUMN 3 |
| TABLE1     | TAB1_COL_5 |                  |
| TABLE1     | TAB1_COL_1 | TABLE 1 COLUMN 1 |
----------------------------------------------

TABLE1
--------------------------------------------------------------------
| TAB1_COL_3      | TAB1_COL_1    | TAB1_COL_5     | TAB1_COL_2    |
--------------------------------------------------------------------
| TAB1_COL3_DATA1 | TAB1_COL1_DAT | TAB1_COL5_DAT2 | TAB1_COL2_DAT |
| TAB1_COL3_DATA2 | TAB1_COL1_DAT | TAB1_COL5_DAT1 | TAB1_COL2_DAT |
| TAB1_COL3_DATA3 | TAB1_COL1_DAT | TAB1_COL5_DAT3 | TAB1_COL2_DAT |
--------------------------------------------------------------------

I want to display the data as 2 different outputs:
FIRST OUTPUT:
------------------------------------------------------------------------------------------------
| TABLE 1 COLUMN 3 | TABLE 1 COLUMN 1 | TAB1_COL_5       | TABLE 1 COLUMN 2 | TABLE 1 COLUMN 4 |
------------------------------------------------------------------------------------------------

-> In case, if the COL_DESC is blank or null, then the COL_NAME needs to be displayed in the output.
-> "TABLE 1 COLUMN 3" AND "TABLE 1 COLUMN 1" always need to be displayed as 1st and 2nd column followed by the rest of the columns.
-> In case, if any column defined within the COL_TAB table isn't being used in TABLE1, then such a column needs to be displayed at the last column in the output,
for example, the TAB1_COL_4 isn't being used in TABLE1, so it is being displayed in the last.
SECOND OUTPUT:
------------------------------------------------------------------------------------------------
| TAB1_COL3_DATA1  | TAB1_COL1_DAT    | TAB1_COL5_DAT2   | TAB1_COL2_DAT    |                  |
| TAB1_COL3_DATA2  | TAB1_COL1_DAT    | TAB1_COL5_DAT1   | TAB1_COL2_DAT    |                  |
| TAB1_COL3_DATA3  | TAB1_COL1_DAT    | TAB1_COL5_DAT3   | TAB1_COL2_DAT    |                  |
------------------------------------------------------------------------------------------------

-> The order of the COLUMNS in the SECOND OUTPUT needs to be in sync with the order of columns as displayed within in the FIRST OUTPUT.
I did try the below query for displaying the FIRST OUTPUT, but it isn't working (I'm sure it's not correct):
SELECT NVL(COL_DESC, COL_NAME) AS COL_TEXT
FROM COL_TAB
WHERE TABLE_NAME = 'TABLE1'
PIVOT(MIN(COL_TEXT)
FOR COL_TEXT IN (SELECT COL_NAME FROM COL_TAB WHERE TABLE_NAME = 'TABLE1'));

In case, if anything isn't clear please do let me know. I would try my best to explain it again. Thanks again for your help in advance.

A: You can get the column description/names - in a deterministic order - with something like:
select coalesce(ct.col_desc, ct.col_name)
from col_tab ct
left join user_tab_columns utc
on utc.table_name = ct.table_name and utc.column_name = ct.col_name
where ct.table_name = 'TABLE1'
order by utc.column_id, ct.col_name;

COALESCE(CT.COL_
----------------
TABLE 1 COLUMN 3
TABLE 1 COLUMN 1
TAB1_COL_5
TABLE 1 COLUMN 2
TABLE 1 COLUMN 4

Pivoting those rows to columns would need to be done dynamically.
You can also generate a dynamic query to get the data in the same order in a similar way.
This uses SQL*Plus (or SQLcl, or SQL Developer) bind variable ref cursors to get the two outputs, and uses a table name defined within the block; but could easily be adapted to be a procedure that is passed the table name and have out parameters for the ref cursors:
var rc1 refcursor;
var rc2 refcursor;

declare
  l_table_name varchar2(30) := 'TABLE1';
  l_stmt varchar2(4000);
begin
  select 'select '
    || listagg('''' || coalesce(ct.col_desc, ct.col_name) || '''',  ',')
         within group (order by utc.column_id, ct.col_name)
    || ' from dual'
  into l_stmt
  from col_tab ct
  left join user_tab_columns utc
  on utc.table_name = ct.table_name and utc.column_name = ct.col_name
  where ct.table_name = l_table_name;

  dbms_output.put_line(l_stmt);

  open :rc1 for l_stmt;

  select 'select '
    || listagg(coalesce(utc.column_name, 'null') || ' as ' || ct.col_name,  ',')
         within group (order by utc.column_id, ct.col_name)
    || ' from ' || l_table_name
  into l_stmt
  from col_tab ct
  left join user_tab_columns utc
  on utc.table_name = ct.table_name and utc.column_name = ct.col_name
  where ct.table_name = l_table_name;

  dbms_output.put_line(l_stmt);

  open :rc2 for l_stmt;

end;
/

Running the block gets dbms_output of the statements just for debugging, but might be of interest:
select 'TABLE 1 COLUMN 3','TABLE 1 COLUMN 1','TAB1_COL_5','TABLE 1 COLUMN 2','TABLE 1 COLUMN 4' from dual
select TAB1_COL_3 as TAB1_COL_3,TAB1_COL_1 as TAB1_COL_1,TAB1_COL_5 as TAB1_COL_5,TAB1_COL_2 as TAB1_COL_2,null as TAB1_COL_4 from TABLE1

and then you can print the ref cursors (again, client-specific behaviour):
print rc1

'TABLE1COLUMN3'  'TABLE1COLUMN1'  'TAB1_COL_ 'TABLE1COLUMN2'  'TABLE1COLUMN4'
---------------- ---------------- ---------- ---------------- ----------------
TABLE 1 COLUMN 3 TABLE 1 COLUMN 1 TAB1_COL_5 TABLE 1 COLUMN 2 TABLE 1 COLUMN 4

print rc2

TAB1_COL_3      TAB1_COL_1    TAB1_COL_5     TAB1_COL_2    TAB1_COL_4
--------------- ------------- -------------- ------------- ----------
TAB1_COL3_DATA1 TAB1_COL1_DAT TAB1_COL5_DAT2 TAB1_COL2_DAT
TAB1_COL3_DATA2 TAB1_COL1_DAT TAB1_COL5_DAT1 TAB1_COL2_DAT
TAB1_COL3_DATA3 TAB1_COL1_DAT TAB1_COL5_DAT3 TAB1_COL2_DAT

Those 2 columns are common across all the tables.

In that case you can use a case expression to extend the ordering logic:
         within group (order by case ct.col_name
                                  when 'TAB1_COL_3' then 1
                                  when 'TAB1_COL_1' then 2
                                  else 3 end,
                                utc.column_id, ct.col_name)

which then gets:
'TABLE1COLUMN3'  'TABLE1COLUMN1'  'TAB1_COL_ 'TABLE1COLUMN2'  'TABLE1COLUMN4'
---------------- ---------------- ---------- ---------------- ----------------
TABLE 1 COLUMN 3 TABLE 1 COLUMN 1 TAB1_COL_5 TABLE 1 COLUMN 2 TABLE 1 COLUMN 4

TAB1_COL_3      TAB1_COL_1    TAB1_COL_5     TAB1_COL_2    TAB1_COL_4
--------------- ------------- -------------- ------------- ----------
TAB1_COL3_DATA1 TAB1_COL1_DAT TAB1_COL5_DAT2 TAB1_COL2_DAT
TAB1_COL3_DATA2 TAB1_COL1_DAT TAB1_COL5_DAT1 TAB1_COL2_DAT
TAB1_COL3_DATA3 TAB1_COL1_DAT TAB1_COL5_DAT3 TAB1_COL2_DAT

or possibly using the description instead of the name, depending on whether it's the name or description that stays the same (hard to guess from the example).

It would be really great if you could show up how pivoting can be done dynamically.

it isn't really needed here in the end, and is more complicated than the listagg I used above; but you could do something like;
  select '
select * from (
  select row_number()
           over (order by case ct.col_name
                            when ''TAB1_COL_3'' then 1
                            when ''TAB1_COL_1'' then 2
                            else 3
                          end,
                          utc.column_id, ct.col_name) as pos,
         coalesce(ct.col_desc, ct.col_name) as name
  from col_tab ct
  left join user_tab_columns utc
  on utc.table_name = ct.table_name and utc.column_name = ct.col_name
  where ct.table_name = :tab
)
pivot (max(name) as col for (pos) in ('
|| listagg(level, ',') within group (order by level)
|| '))'
  into l_stmt
  from dual
  connect by level <= (select count(*) from col_tab where table_name = l_table_name);

  dbms_output.put_line(l_stmt);

  open :rc1 for l_stmt using l_table_name;

which gets output showing the generated dynamic query as:
select * from (
  select row_number()
           over (order by case ct.col_name
                            when 'TAB1_COL_3' then 1
                            when 'TAB1_COL_1' then 2
                            else 3
                          end,
                          utc.column_id, ct.col_name) as pos,
         coalesce(ct.col_desc, ct.col_name) as name
  from col_tab ct
  left join user_tab_columns utc
  on utc.table_name = ct.table_name and utc.column_name = ct.col_name
  where ct.table_name = :tab
)
pivot (max(name) as col for (pos) in (1,2,3,4,5))

and result set as:
1_COL            2_COL            3_COL            4_COL            5_COL
---------------- ---------------- ---------------- ---------------- ----------------
TABLE 1 COLUMN 3 TABLE 1 COLUMN 1 TAB1_COL_5       TABLE 1 COLUMN 2 TABLE 1 COLUMN 4

You could use the column names for the pivot instead of the pos, it would just make it even harder to read I think, as you'd need to include quotes around them.


text:
Q: SELECT value and INSERT it INTO a new row? I want to select BlockHash value from the last row in the table pow and insert it into BlockLastHash in the new row, How can I do that?
I tried this code:
 connection.query("SELECT `BlockHash` FROM `pow` ORDER BY id DESC LIMIT 1", (err, res) => {
     if(err) throw err;

     connection.query("INSERT INTO `pow` (`BlockData`, `BlockHash`, `BlockLastHash`, `dataid`) VALUES ('"+blockdata+"', '"+hash+"', '"+res+"' , '"+id+"') ", (err, res2) => {
         if(err) throw err;
         console.log("1 Block inserted");
     });
 });

The output in BlockLastHash is [object Object]
How to solve this?
Thanks in advance

A: The results object supports multiple rows returned and multiple fields for each row; you need to tell it what you want to get from the result.  Try:
res[0].BlockHash

In addition to err and res, a fields object is also available that describes what fields are returned.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Posição de componentes com bootstrap Tenho uma dúvida bem simples, não consigo posicionar elementos na horizontal com Bootstrap, como ficaria o código HTML com Bootstrap, igual dessa imagem?

Vejam que tem o label, e ao lado o radioGroup, e abaixo outro radiobutton e ao lado textbox e label novamente, como ficaria exatamente esse código?
Sempre fica tudo abaixo do outro quando coloco.

A:             <form class="form-inline" role="form"  method="POST">

Ends:

                <input type="radio" name="group1" id="group1" class="radio" value="Never"> Never

                <input type="radio" name="group1" id="group1" class="radio" value="After"> After
                <input type="text" name="texto2" id="texto2">
                occurrences

                <input type="radio" name="group1" id="group1" class="radio" value="On"> On
                <input type="text" name="texto2" id="texto2">

        </form>

Você pode fazer como no código acima e acrescentar uma div com a class="row" para cada linha que deseja criar um form com a class="form-inline" que faz com que todos os elementos fiquem em uma só linha.


text:
Q: Setting a periodic request to a Pythonanywhere server I'm a bit new regarding coding and specially setting up servers and interacting with them. To learn, I wanted to practice how to interact with a remote server periodically. I took as an example the server https://darwincubansalsa.pythonanywhere.com/book_lesson, which accepts bookings once every week at a specific hour.
Aim:

*

*To set a recurring process that sends a request to the https://darwincubansalsa.pythonanywhere.com/book_lesson domain every Sunday at 22:00 with the details of the booking.

Once I know a good way to set up the process I'll get into the details of the POST request. But first I would like to know what is the best option to set up a server for this simple task. I could think of using a free version of Pythonanywhere or even GitHub actions in a recurring manner. Setting up the server locally in my computer would not be the preferred way, given that they may be turned off during the opening window for requests.
Thank you in advance, everyone.


text:
Q: Connecting two identical mosfets in series
I'm required to prove the above claim. I've written a few equations in my attempt to prove that and some of them obviously might not make sense.Could you tell me please if I'm in the right direction or do I have to come up with an entirely different approach ?  Here is my attempt :


text:
Q: Phone Gap In APP Browser I am adding the Phonegap in app browser because I have some links in my app and when they are launched using the iPhone you can't return to the app (a common problem I believe).
I have tried to add the in app browser but it doesn't seem to work.
This is what I have done.
Added a Config.xml to the root of the app. This is my Config.xml file.
    <?xml version="1.0" encoding="UTF-8" ?>
    <widget xmlns   = "http://www.w3.org/ns/widgets"
    xmlns:gap   = "http://phonegap.com/ns/1.0"
    id          = "com.phonegap.my.example"
    versionCode = "10"
    version     = "1.0.0" >

  <!-- versionCode is optional and Android only -->

  <name>Testt App APP</name>

  <description>
    This is a test app.
  </description>

  <author href="http://www.mywebaddress.co.uk"          email="email@mywebaddress.co.uk">
    My Name
  </author>

  <gap:plugin name="org.li8.inappbrowser" version="0.1" />

</widget>

In the page with the link I have added the cordova.js ref
<script type="text/javascript" src="cordova.js"></script>

Does this need to be in certain order (before or after Jquery ref). Do I need to include this file in my program or does phonegap automatically include it?
I have tried 2 types of link:
var ref = window.open('http://twitter.com', '_blank', 'location=yes');

and
window.open('http://www.facebook.com', '_system');

Neither seem to work.
Am I missing somthing?
Thanks in advance!

A: Ok managed to solve it.
I noticed that none of the plugins tab wasn't showing any installed plugins. So I deleted the config.xml and stated again. The plugin then showed up and it works ok now. The only difference I can see it that I renamed the config file config.xml as opposed to Config.xml.


text:
Q: How to fix 'updating a comment sent me to the wrong route' I am building an app and I have a device user controller, for login with scaffold of Comment and Post. My problem is that when I update a comment and hit the button update it send me to the route http://localhost:3000/publicaciones/1/comentarios when I have tell it in the controller to send me to http://localhost:3000/publicaciones/1.
The create and delete thought send me to the correct routes
mensajes controller
before_action :set_comentario, only: [:show, :edit, :update, :destroy]
  before_action :set_publicacione, only: [:new, :create, :destroy, :show]

  # GET /comentarios
  # GET /comentarios.json
  def index
    @comentarios = Comentario.all
  end

  # GET /comentarios/1
  # GET /comentarios/1.json
  def show
  end

  # GET /comentarios/new
  def new
    @comentario = Comentario.new
  end

  # GET /comentarios/1/edit
  def edit
  end

  # POST /comentarios
  # POST /comentarios.json
  def create
    @comentario = Comentario.new(comentario_params)
    @comentario.publicacione_id = @publicacione.id
    @comentario.user_id = current_user.id
    respond_to do |format|
      if @comentario.save
        format.html { redirect_to publicacione_path(@publicacione), notice: 'Comentario was successfully created.' }
        format.json { render :show, status: :created, location: @comentario }
      else
        format.html { render :new }
        format.json { render json: @comentario.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /comentarios/1
  # PATCH/PUT /comentarios/1.json
  def update
    respond_to do |format|
      if @comentario.update(comentario_params)
        format.html { redirect_to publicacione_path(@comentario.publicacione_id), notice: 'Comentario was successfully updated.' }
        format.json { render :show, status: :ok, location: publicacione_path(@comentario.publicacione_id) }
      else
        format.html { render :edit }
        format.json { render json: @comentario.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /comentarios/1
  # DELETE /comentarios/1.json
  def destroy
    @comentario.destroy
    respond_to do |format|
      format.html { redirect_to publicacione_path(@comentario.publicacione_id), notice: 'Comentario was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_comentario
      @comentario = Comentario.find(params[:id])
    end

    def set_publicacione
      @publicacione = Publicacione.find(params[:publicacione_id])
    end
    # Never trust parameters from the scary internet, only allow the white list through.
    def comentario_params
      params.require(:comentario).permit(:contenido, :puntaje_reputacion, :user_id, :publicacione_id)
    end
end

publicaciones controller
class PublicacionesController < ApplicationController
  before_action :set_publicacione, only: [:show, :edit, :update, :destroy]
  # GET /publicaciones
  # GET /publicaciones.json
  def index
    @publicaciones = Publicacione.all
  end

  # GET /publicaciones/1
  # GET /publicaciones/1.json
  def show
  end

  # GET /publicaciones/new
  def new
    @publicacione = Publicacione.new
  end

  # GET /publicaciones/1/edit
  def edit
  end

  # POST /publicaciones
  # POST /publicaciones.json
  def create
    @publicacione = Publicacione.new(publicacione_params)

    respond_to do |format|
      if @publicacione.save
        format.html { redirect_to @publicacione, notice: 'Publicacione was successfully created.' }
        format.json { render :show, status: :created, location: @publicacione }
      else
        format.html { render :new }
        format.json { render json: @publicacione.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /publicaciones/1
  # PATCH/PUT /publicaciones/1.json
  def update
    respond_to do |format|
      if @publicacione.update(publicacione_params)
        format.html { redirect_to @publicacione, notice: 'Publicacione was successfully updated.' }
        format.json { render :show, status: :ok, location: @publicacione }
      else
        format.html { render :edit }
        format.json { render json: @publicacione.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /publicaciones/1
  # DELETE /publicaciones/1.json
  def destroy
    @publicacione.destroy
    respond_to do |format|
      format.html { redirect_to publicaciones_url, notice: 'Publicacione was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_publicacione
      @publicacione = Publicacione.find(params[:id])
    end

    def set_comentarios
      @comentarios = Comentario.all
    end
    # Never trust parameters from the scary internet, only allow the white list through.
    def publicacione_params
      params.require(:publicacione).permit(:titulo, :contenido, :descripcion, :puntaje_reputacion, :user_id, :curso_id)
    end
end

confit/routes
Rails.application.routes.draw do
  resources :publicaciones do
    resources :comentarios
  end
  resources :cursos
  resources :eventos
  resources :sala_de_estudios
  devise_for :users
  resources :campus
  resources :users, only: [:show, :edit, :update]
  root 'campus#index'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

edit view

Editing Comentario

<%= render 'form', comentario: @comentario %>

<%= link_to 'Show', publicacione_comentario_path%> |
<%= link_to 'Back', publicacione_path(@comentario.publicacione_id) %>

Form view
<%= form_with(model: @comentario, url: publicacione_comentarios_path, local: true) do |form| %>
  <% if comentario.errors.any? %>

<%= pluralize(comentario.errors.count, "error") %> prohibited this comentario from being saved:

      <% comentario.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

    <%= form.label :contenido %>
    <%= form.text_field :contenido %>

    <%= form.label :puntaje_reputacion %>
    <%= form.text_field :puntaje_reputacion %>

    <%= form.submit %>

<% end %>

When I click it send me to http://localhost:3000/publicaciones/1/comentarios
but http://localhost:3000/publicaciones/1 was expected

A: You have nested routes
resources :publicaciones do
  resources :comentarios
end

You can abandon them.
resources :publicaciones
resources :comentarios

Also you can use shallow
resources :publicaciones do
  resources :comentarios, shallow: true
end

A: Since you have nested resources, you need to set the Publicacione object on the form:
<%= form_with(model: @comentario, url: publicacione_comentarios_path(@publicacione), local: true) do |form| %>

Then, in the controller, you need to set @commentario based on @publicacione, and redirect_to publicacione_path(@publicacione):
  def update
    respond_to do |format|
      if @comentario.update(comentario_params)
        format.html { redirect_to publicacione_path(@publicacione), notice: 'Comentario was successfully updated.' }
        format.json { render :show, status: :ok, location: publicacione_path(@comentario.publicacione_id) }
      else
        format.html { render :edit }
        format.json { render json: @comentario.errors, status: :unprocessable_entity }
      end
    end
  end

  private

    def set_comentario
      @comentario = @publicacione.comentarios.find(params[:id])
    end

A: This
<%= form_with(model: @comentario, url: publicacione_comentarios_path, local: true) do |form| %>

Is correct for new/create but for edit/update it should be...
<%= form_with(model: @comentario, url: publicacione_comentario_path(@publicacione, @comentario), local: true) do |form| %>

If you don't want to have different forms for the two conditions (and I don't blame you) use the format...
form_with(model: @comentario, url: [@publicacione, @comentario], local: true)

...and then the form_with helper method will generate the correct path.


text:
Q: After update of either npm, or ng-packagr, publish tries to use incorrect package name and version After migration to Node@16.14.2, NPM@8.5.0 and Angular@13 I am not able to publish package generated by ng-packager to npm repository.
package.json:
{
"name": "@me/ng13",
"version": "1.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"packagr": "ng-packagr -p ng-package.json",
"publish": "npm publish dist"
},
"private": true,
"dependencies": {
"@angular/animations": "~13.3.0",
"@angular/common": "~13.3.0",
"@angular/compiler": "~13.3.0",
"@angular/core": "~13.3.0",
"@angular/forms": "~13.3.0",
"@angular/localize": "~13.3.0",
"@angular/platform-browser": "~13.3.0",
"@angular/platform-browser-dynamic": "~13.3.0",
"@angular/router": "~13.3.0",
"@progress/kendo-angular-buttons": "^8.0.0",
"@progress/kendo-angular-common": "^3.0.0",
"@progress/kendo-angular-dialog": "^7.1.2",
"@progress/kendo-angular-l10n": "^4.0.0",
"@progress/kendo-angular-popup": "^5.0.0",
"@progress/kendo-angular-tooltip": "^4.0.1",
"@progress/kendo-licensing": "^1.0.2",
"@progress/kendo-theme-default": "^5.0.0",
"rxjs": "~7.5.0",
"tslib": "^2.3.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "~13.3.7",
"@angular/cli": "~13.3.7",
"@angular/compiler-cli": "~13.3.0",
"@types/jasmine": "~3.10.0",
"@types/node": "^12.11.1",
"jasmine-core": "~4.0.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.1.0",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "~1.7.0",
"typescript": "~4.6.2",
"ng-packagr": "^13.3.1"
},
"description": "This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 13.3.7.",
"author": "me",
"license": "MIT"
}

After ng-packagr -p ng-package.json I can see correct package.json with expected version, but after npm publish dist there is some weird information about the package:
npm run publish
> @me/ng13@1.0.0 publish
> npm publish dist

npm notice
npm notice package: dist@0.1.2
npm notice === Tarball Contents ===
npm notice 13B   .npmignore
npm notice 200B  HISTORY.md
npm notice 7B    README.md
npm notice 1.4kB bin/dist.js
npm notice 1.8kB lib/dist.js
npm notice 602B  package.json
npm notice 4.5kB test/dist.test.js
npm notice 89B   test/fixtures/copyright.js
npm notice 199B  test/fixtures/input.js
npm notice 289B  test/fixtures/out/input.copyright.js
npm notice 229B  test/fixtures/out/input.copyright.min.js
npm notice 199B  test/fixtures/out/input.js
npm notice 139B  test/fixtures/out/input.min.js
npm notice 20B   test/mocha.opts
npm notice === Tarball Details ===
npm notice name:          dist
npm notice version:       0.1.2
npm notice filename:      dist-0.1.2.tgz
npm notice package size:  2.7 kB
npm notice unpacked size: 9.7 kB
npm notice shasum:        8898629cc251297e36d1354a9a9598619aba5b1a
npm notice integrity:     sha512-TmsZfJybRs3IZ[...]frqZyuqkz/sOQ==
npm notice total files:   14

So I am wondering why name and version in publish step are incorrect and how could I fix it?

A: So after all these upgrades instead of npm publish dist I should use npm publish ./dist


text:
Q: XPS from FlowDocument Rendering bug in Images This will be little longer post
Goal
Render XPS document from FlowDocument while maintaining original Images (no transformation)
Existing Scenarios

*

*Image is added correctly (keeps format), but only first one. Cache is then broken, only 1 image is embedded in XPS and used for all images

*All images are added and correct, but converted to PNG.
Difference occurs based on commenting / uncommenting of single line in method GetImage (see comments)
Minimal showcase / problem recreation code
Imports System.Windows.Documents
Imports System.Windows.Documents.Serialization
Imports System.Windows.Xps.Packaging
Imports System.Windows.Xps
Imports System.IO
Imports System.IO.Packaging
Imports System.Windows.Markup
Imports System.Windows.Media.Imaging
Imports System.Windows.Media
Imports System.Windows.Controls

Module Module1

    Sub Main()

        Render()

    End Sub

    Sub Render()

        Using image1 = IO.File.OpenRead("image1.jpg"),
            image2 = IO.File.OpenRead("image2.png"),
            file = IO.File.Create("asdf.xps"),
            pack = Package.Open(file, FileMode.Create),
            d As New XpsDocument(pack)

            Dim writer As XpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(d)
            Dim xpsVisWriter As SerializerWriterCollator = writer.CreateVisualsCollator()

            Dim x As New FlowDocument
            x.PageWidth = 100
            x.ColumnWidth = x.PageWidth

            Dim s As New Section
            DirectCast(x, IAddChild).AddChild(s)
            s.BreakPageBefore = True

            Dim p As New Paragraph()
            DirectCast(s, IAddChild).AddChild(p)

            Dim i As New Image
            DirectCast(p, IAddChild).AddChild(i)
            i.Source = GetImage(image1)

            Dim i2 As New Image
            DirectCast(p, IAddChild).AddChild(i2)
            i2.Source = GetImage(image2)

            Dim paginator = DirectCast(x, IDocumentPaginatorSource).DocumentPaginator
            Dim pageIndex As Integer = 0

            While Not paginator.IsPageCountValid OrElse paginator.PageCount > pageIndex
                Dim page As DocumentPage = paginator.GetPage(pageIndex)

                xpsVisWriter.Write(page.Visual)
                pageIndex += 1
            End While

            xpsVisWriter.EndBatchWrite()

        End Using

    End Sub

    Function GetImage(stream As Stream) As ImageSource

        Dim result As ImageSource = BitmapFrame.Create(
            stream,
            BitmapCreateOptions.PreservePixelFormat Or BitmapCreateOptions.IgnoreImageCache,
            BitmapCacheOption.None)

        'If this Line Runs, scenario 2 occures, otherwise scenario 1
        'result = BitmapFrame.Create(result)

        Return result

    End Function

End Module

I no longer have any idea what to do with this. All possible cache enabling / disabling was tried.

A: I have not done any visual basic, but I ran into similar problem with c#.  Try returning a BitmapImage instead of ImageSource in your GetImage method. Using PngBitmapDecoder, MemoryStream, FlowDocument, XPSDocument to Preview Images


text:
Q: Imageview position not behaving as expected I' using full screen and locking to portrait. In the manifest:
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:screenOrientation="portrait"

In the layout I have an imageview and two buttons:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
    android:id="@+id/imageView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"/>
<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />
<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />
</LinearLayout>

At the start I load my own image into the imageview:
imageView = (ImageView) findViewById(R.id.imageView1); //from .xml
Drawable newPhoneImage;
newPhoneImage = getResources().getDrawable(R.drawable.phone_on);
imageView.setImageDrawable(newPhoneImage);

On both my emulators this shows the image at the top of screen as expected.
I then draw up a bitmap and replace the Image:
sBitmap = Bitmap.createBitmap(557, 580,Config.ARGB_8888);
//draw the bimap image
BitmapDrawable nimage;
nimage = new BitmapDrawable(sBitmap);
imageView.setImageDrawable(nimage);

On the large emulator(WVGA800 400x800) the image is at the top as expected.
On the small emulator(QVGA 240x320) and on my phone(240x320) the image is 35 pixels down from the top.
Why are they different?
I can scroll the image up:
imageView.scrollTo(0, 35); //this will put image at top

How can I find this value? Nothing like this will work:
int offset = imageView.getTop();// it just = height of image

Any help would be appreciated.

A: It's because your image is too big for the screen.
Setting android:adjustViewBounds="true" in the XML may help.
Also, you may try getting the screen width and using it:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
Bitmap.createBitmap(width, width/557*580,Config.ARGB_8888);

To create an image of the correct size. Try settings both of these things at the same time.
On another note, you can just:
imageView = (ImageView) findViewById(R.id.imageView1); //from .xml
imageView.setImageResource(R.drawable.phone_on);

To simplify the code a little bit.


text:
Q: If $\sum_n\|x_n-x_{n-1}\|^2<\infty$, is $(x_n)$ Cauchy? Let $(E,d)$ be a metric space and $(x_n)_{n\in\mathbb N}\subseteq E$. We can easily show that if $(\varepsilon_n)_{n\in\mathbb N}\subseteq[0,\infty)$ is summable and $$d(x_n,x_{n+1})\le\varepsilon_n\;\;\;\text{for all }n\in\mathbb N,\tag1$$ then $(x_n)_{n\in\mathbb N}$ is Cauchy.
Now let $H$ be a Hilbert space, $(x_n)_{n\in\mathbb N_0}\subseteq H$ and $h_n:=x_n-x_{n-1}$. Assume $(h_n)_{n\in\mathbb N}$ is orthogonal and $\sum_{n\in\mathbb N}\left\|h_n\right\|_H^2<\infty$.

Are we able to conclude that $(x_n)_{n\in\mathbb N}$ is Cauchy?

We cannot apply the former result for general metric spaces, since we've only got $\sum_{n\in\mathbb N}\left\|h_n\right\|_H^{\color{red}2}<\infty$. On the other hand, this implies that $(h_n)_{n\in\mathbb N}$ is summable. Is this enough to obtain that $(x_n)_{n\in\mathbb N}$ is Cauchy?

A: Yes. Let $\varepsilon>0$ and find $n_0\in\mathbb{N}$ such that $\sum_{j=n_0+1}^\infty\|h_j\|^2<\varepsilon^2$. Now let $m>n\ge n_0$. We have $x_m-x_n=x_m-x_{m-1}+x_{m-1}-x_{m-2}+\dots+x_{n+1}-x_n=\sum_{j={n+1}}^{m}h_j$. Therefore
$$\|x_n-x_m\|^2=\bigg\|\sum_{j=n+1}^mh_j\bigg{\|}^2=\sum_{j=n+1}^m\|h_j\|^2\le\sum_{j=n_0+1}^\infty\|h_j\|^2<\varepsilon^2$$
so $\|x_n-x_m\|<\varepsilon$.


text:
Q: Overlapping the Excel Application By Recently Opened Application - C# In my VSTO Excel AddIn Application Facing an issue with window overlapping by recently opened window at the time of displaying alert box.
In below screen shot if I click on OK button Excel application is minimized and some other (Recently Opened) window is opened.
But I still want to be in parameters window, just want to close alert box only.


text:
Q: How to delete singleton instance from separate module before system killed running threads I have a C++ Windows (compiled with Visual Studio 2019) program that uses shared libraries. A shared library uses a singleton on a class that creates a thread. The class destructor kills the thread cleanly, so there should be no memory leak. However, I see that the destructor is being invoked after the system actually killed all running threads upon exit, so it's too late, the thread is not exited cleanly and this introduces a memory leak (and possibly other problems depending on the code being processed by the thread).
Here is a MCVE:
#include <thread>
#include <atomic>

class Single
{
public:
    static Single& GetInstance()
    {
        static Single single;
        return single;
    }

    int doSomething()
    {
        while ( !started )
            std::this_thread::sleep_for( std::chrono::milliseconds(100) );

        return 0;
    }

private:
    Single() :
        started( false ),
        continueThread( true )
    {
        thread = new std::thread( &Single::threadFunc, this );
    }
    ~Single()
    {
        continueThread = false;
        thread->join();
        delete thread;
    }

    void threadFunc()
    {
        started = true;
        while ( continueThread )
        {
            std::this_thread::sleep_for( std::chrono::milliseconds(1) );
        }
    }

    std::atomic_bool started;
    std::atomic_bool continueThread;
    std::thread* thread;
};

int main( int argc, char* argv[] )
{
    return Single::GetInstance().doSomething();
}

If this is copied to a single main.cpp file and executed, everything works fine. When ~Single is executed, in the debugger, I see the threadFunc thread is running and it gets stopped cleanly.
Now, if Single definition and implementation is moved to a separate dll. When ~Single is executed, in the debugger, I see the threadFunc thread is not running anymore (the system already stopped it) and the code can't stop in cleanly. Visual Leak Detector reports then a memory leak.
Is there any flag (in code or at compiler level) that could be set to guarantee threads are not destroyed before the singleton gets deleted?
I know I could call a deinit function manually from the main function, but at some point, the main may not even know there is singleton running a thread in the shared library it uses...the shared library itself should be able to cleanly exit.

A: No.
Multithreading, automatic cleanup, and DLL unloading are basically a huge mess on Windows once they interact.
The solution is to not have singletons, or any static lifetime variables (globals, local statics, class statics) with non-trivial destruction semantics. Make an instance of your thing in main()/WinMain(). Pass a reference to whoever needs it. Let the destructor clean it up before main exits and thus before everything gets unloaded.
Or simply ignore the memory leak. The process is exiting anyway.

A: This a common case of SUOF (Static Unitialization Order Fiasco) caused by giving up control over object instance lifetime by using static local variable. Solution is to get back control over object instance lifetime by adding a couple of initialization / uninitialization routines (probably wrapped with RAII) that will ensure that object is created before the first use and destroyed after last use but prior to dll getting unloaded / main function returning.


text:
Q: search within array for most common occurrences I have a text logfile, containing lines of data separated by " | "
for example
date | time | ip | geo-location (city) | page viewed ......

I need to find the 10 most occuring "page views" in the text file....
each log of page view is listed as:
//pageurl

as the log is on seperate lines I am presuming I would be searching for the page urls between
// [url name] \r\n

how would I code a search to list the top 10 urls and list them into an array....
for example:
$url[0]  <<this would be the most occuring url
$url[1]  <<thos would be the second most occuring url

and so on..... until I can list them up to:
$url[9]  <<which would be the 10th most common url

I am not sure how I would search between the " // " and the " \r\n "
and then convert the top 10 most common occurrences into an array...
edit: here is 2x lines of my logs, just to help even more if I can
sunday, january 22, 2012 | 16:14:36 | 82.**.***.*** | bolton | //error
sunday, january 22, 2012 | 17:12:52 | 82.**.***.*** | bolton | //videos

A: Based on the information given, here's a rather naïve approach:
/* get the contents of the log file */
$log_file = file_get_contents(__DIR__.'/log.txt');

/* split the log into an array of lines */
$log_lines = explode(PHP_EOL, $log_file);

/* we don't need the log file anymore, so free up some memory */
unset($log_file);

/* loop through each line */
$page_views = array();
foreach ($log_lines as $line) {
    /* get the text after the last pipe character (the page view), minus the ' //' */
    $page_views[] = ltrim(array_pop(explode('|', $line)), ' /');
}

/* we don't need the array of lines either, so free up that memory */
unset($log_lines);

/* count the frequency of each unique occurrence */
$urls = array_count_values($page_views);

/* sort highest to lowest (may be redundant, I think array_count_values does this) */
arsort($urls, SORT_NUMERIC);

print_r($urls);
/* [page_url] => num page views, ... */

/* that gives you occurrences, but you want a numerical
   indexed array for a top ten, so... */

$top_ten = array();
$i = 0;
/* loop through the array, and store the keys in a new one until we have 10 of them */
foreach ($urls as $url => $views) {
  if ($i >= 10) break;
  $top_ten[] = $url;
  $i++;
}

print_r($top_ten);
/* [0] => page url, ... */

** Script output: **
Array
(
    [videos] => 1
    [error ] => 1
)
Array
(
    [0] => videos
    [1] => error
)

It's not the most optimal solution, and the bigger your log file, the longer it'll take. To this end, you may be better off logging to a database and querying from that.


text:
Q: How to convert time output from SQL*Plus TIMING to a Linux TIMESTAMP? I'm getting a TIMING result from SQL*Plus query like this:
00:00:02.02

Explaining the construction of this line:
hours:minutes:seconds.hundredths

For my needs I need to convert it to a Linux timestamp (or just a number containing the SQL*Plus string converted to miliseconds or sth).
I need it to be converted in whole, even with hours.


text:
Q: How do BundleActivator, ManagedService, and my application interact on start/stop? I had a non-OSGi application.  To convert it to OSGi, I first bundled it up and gave it a simple BundleActivator.  The activator's start() started up a thread of what used to be the main() of my app (and is now a Runnable), and remembered that thread.  The activator's stop() interrupted that thread, and waited for it to end (via join()), then returned.  This all seemed to be working fine.
As a next step in the OSGiification process, I am now trying to use OSGi configuration management instead of the Properties-based configuration that the application used to use.  So I am adding in a ManagedService in addition to the Activator.
But it's no longer clear to me how I am supposed to start and stop my application; examples that I've seen are only serving to confuse me.  Specifically, here:
http://felix.apache.org/site/apache-felix-config-admin.html
They no longer seem to do any real starting of the application in BundleActivator.start().  Instead, they just register a ManagedService to receive configuration.  So I'm guessing maybe I start up the app's main thread when I receive configuration, in the ManagedService? They don't show it - the ManagedService's updated() just has vague comments saying to "apply configuration from config admin" when it is passed a non-null Dictionary.
So then I look here:
http://blog.osgi.org/2010/06/how-to-use-config-admin.html
In there, it seems like maybe they're doing what I guessed.  They seem to have moved the actual app from BundleActivator to ManagedService, and are dealing with starting it when updated() receives non-null configuration, stopping it first if it's already started.
But now what about when the BundleActivator's stop() gets called?
Back on the first example page that I mentioned above, they unregister the ManagedService.  On the second example page, they don't show what they do.
So I'm guessing maybe unregistering the ManagedService will cause null configuration to be sent to ManagedService.updated(), at which point I can interrupte the app thread, wait for it to end, and then return?
I suspect that I'm thoroughly incorrect, but I don't know what the "real" way to do this is.  Thanks in advance for any help.

A: BundleActivator (BA) and ManagedService (MS) are callbacks to your bundle. BundleActivator is for the active state of your bundle. BA.start is when you bundle is being started and BA.stop is when it is being stopped. MS is called to provide your bundle a configuration, if there is one, or notify you there is no configuration.
So in BA.start, you register your MS service and return. When MS is called (on some other thread), you will either receive your configuration or be told there is no configuration and you can act accordingly (start app, etc.)
Your MS can also be called at anytime to advice of the modification or deletion of your configuration and you should act accordingly (i.e. adjust your app behavior).
When you are called at BA.stop, you need to stop your app. You can unregister the MS or let the framework do it for you as part of normal bundle stop processing.


text:
Q: Socket.Connect with a IPv6 address throws a "Address Family Not supported" Error I am trying to do a Socket.Connect() and when the IP address that i specify is in ipv6 format, the Socket.Connect() fails with the error message :
Address family not supported by protocol family.
An address incompatible with the requested protocol was used. All sockets are created with an associated address family (that is, AF_INET for Internet Protocols) and a generic protocol type (that is, SOCK_STREAM). This error is returned if an incorrect protocol is explicitly requested in the socket call, or if an address of the wrong family is used for a socket, for example, in sendto.
However if i uncomment the code in the below snippet, then the ipv4 address would be used to connect and now the call succeeds; Note that hostadd.AddressList[0] returns a ipv6 address.
Also note that i am connecting between Windows 7 64 bit machines which both have ipv4 and ipv6 enabled;
Why does connecting using an ipv6 address throw the error? The Socket.Connect() method documents that :

If IPv6 is enabled and the
  Connect(String, Int32) method is
  called to connect to a host that
  resolves to both IPv6 and IPv4
  addresses, the connection to the IPv6
  address will be attempted first before
  the IPv4 address. This may have the
  effect of delaying the time to
  establish the connection if the host
  is not listening on the IPv6 address.is not listening on the IPv6 address.

                IPHostEntry hostadd = Dns.GetHostEntry(TimeServer);
                IPAddress ip4IP = hostadd.AddressList[0];
                //foreach (IPAddress ipAddress in hostadd.AddressList) {
                //    if (ipAddress.AddressFamily == AddressFamily.InterNetwork) {
                //        ip4IP = ipAddress;
                //        break;
                //    }
                //}
                IPEndPoint EPhost = new IPEndPoint(ip4IP, 123);

                Socket pSocket = new Socket(
                    AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                pSocket.ReceiveTimeout = 2000;
                pSocket.SendTimeout = 2000;
                pSocket.Connect(EPhost);

A: Looks like you're specifying IPv4 in your Socket() call. Did you try using InterNetworkV6 instead of InterNetwork? In my experience, (at least with C sockets) IPv6 sockets will support both IPv4 and IPv6 addresses, but IPv4 sockets will support only IPv4.


text:
Q: How to faster filter a range? I want to filter a range (9 columns and 1400 rows) by values in a column (rng01)
Application.ScreenUpdating = False
db.Rows.Hidden = False
For Each cell In rng01.Cells
If Not cell.Value = "323" Then
cell.EntireRow.Hidden = True
End If
Next cell
Application.ScreenUpdating = True

This works, but takes about 3-4 seconds.
Is there a faster way, pls ?

A: Lets see if I understand your question:  rng01 is one of the nine columns, you want to filter so that only rows where the value in rng01 = 323 are visible.
You can use AutoFilter for this.  You will need a header row above your data (but it can be blank).
rng01.AutoFilter
rng01.AutoFilter Field:=1, Criteria1:="323", VisibleDropDown:=False

If the sheet rng01 referes to already has an active AutoFilter, the first rng01.AutoFilter clears it.
Note that rng01 is one column wide.
If in fact rng01 referes to a range wider than one column, use
rng01.Columns(3).AutoFilter
rng01.Columns(3).AutoFilter Field:=1, Criteria1:="323", VisibleDropDown:=False


text:
Q: Database deployment script for SQL Server 2008 has different behaviors Using Visual Studio 2008, I have compared schemas between remote SQL Server database with  scripts hosted in a TFS server.
The goal was to generate a migration script that would update the remote database with developers latest script changes located in TFS.
The next step was to get a full backup from remote database, and restore it in my local database, and then execute the migration script in order to test it.
After small tweeks (dealing with constraints) and I have managed to execute the migration script locally and my local database (that is a copy from remote database).
The last step was to get this script and run it in remote database, but for my surprise, the script gets interrupted in a procedure:
Altering dbo.sp_my_procedure_here...
Msg 207, Level 16, State 1, Procedure sp_my_procedure_here, Line 616
Invalid column name 'code'.

Within this mentioned procedure, there is a CREATE TABLE ##TEMP (code INT), a execute command to run a SQL statement contained in a string variable for executing INSERT INTO ##TEMP VALUES (999), a SELECT @myReturnCode = code FROM ##TEMP and a DROP TABLE ##TEMP.
The statement SELECT @myReturnCode = code FROM ##TEMP is not working in the remote database. Since there is no procedure execution (this is only a script modifying database structure). Why the migration script would fire "invalid column" on the remote database?
The remote SQL Server database is version 10.0.2531
The local SQL Server database is version 10.50.2500
Both databases are set to compatibility mode for "SQL Server 2000".
The same migration script was executed in SSMS 2008.
ALTER PROCEDURE [dbo].[sp_my_procedure]
AS
SET NOCOUNT ON

CREATE TABLE ##TEMP (code INT)
DECLARE @sql Varchar(4000)

SET @sql = 'DECLARE @myReturnCode int
               SET @myReturnCode = 999
               INSERT INTO ##TEMP VALUES (@myReturnCode)'
EXEC (@sql)

IF (@@ERROR <> 0)
BEGIN
   RAISERROR('There is something wrong with insert',1,1)
   DROP TABLE ##TEMP
   RETURN -1
END
SELECT @myReturnCode = code FROM ##TEMP
DROP TABLE ##TEMP
SET NOCOUNT OFF

A: Why are you using ##global temp tables instead of #local? It is possible that when you are changing the procedure there is already a global temp table in existence with the same name - they're global so it could have been created by anyone. Use a local temp table and that problem will go away.
Also, please don't use the sp_ prefix. Stored procedures shouldn't really need to have a prefix - what is the point of adding sp_ to the beginning of every stored procedure? They still sort the same (e.g. in Object Explorer), it just makes it that much harder to find the one you're after. If you absolutely must use a prefix for some reason, pick something other than sp_.


text:
Q: Does a React Native project by default uses Javascript or Typescript? I am new to React Native development so bear with me.
When I create a new React Native project via CMD and I see the code, the .js has a lot of keywords used in TypeScript.
This not seems to be plain Javascript or I'm wrong? What I am seeing is Javascript or Typescript?
Thank you

A: To answer the question: in the App.js file (of at least > 0.52) you can see the following at the top of the file:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

The syntax you see there is Flow (like React also from Facebook), which is an alternative for Typescript (from Microsoft). Flow and React got a different syntax and are both compatible with React / React Native. Understandably though, Facebook is pushing their own Flow. It is not necessary to use it. It also works with regular javascript.

A: React native script uses JavaScript by default. Typescript files have .ts extension.
You can also user TypeScript in React Native with certain configuration. Following links will help you for this
TypeScript React Native Starter
React-native-with-typescript

A: By default you are seeing Flowtype.
Flow is great, but Typescript seems to be the direction developers are going.
If you want to use Typescript, try this:
react-native init MyApp --template typescript
Also checkout: https://medium.com/@emin93/react-native-typescript-b965059109d3


text:
Q: How can I change state of an Article with the corresponding Button in React? I'm building my first React demo.  I'd like to learn how to write a function and/or useEffect that will display an article based on which button was clicked.  I have 4 buttons always visible and I'd like to have 1 article visible depending on which one is selected.  Thanks in advance for the assistance!
Here's the setup I have so far:
import React from 'react'
import './main.css'
import mainData from './mainData'
import Button from './menuButtons'
import Article from './contentCard'

function Main() {
    const [menuProps] = React.useState(mainData.menu)
    const [buttons, setButtonActive] = React.useState(mainData.buttons)
    const [articles, setArticle] = React.useState(mainData.articles[0])

    function setActive(key) {
        setButtonActive(prevActive => {
            return prevActive.map((button) => {
                return button.key === key ? {...button, active: true} : {...button, active: false}
            })
        })
    }

    const buttonElements = buttons.map((buttonProps) => (
        <Button
            key={buttonProps.key}
            label={buttonProps.label}
            active={buttonProps.active}
            setactive={() => setActive(buttonProps.key)}
        />
    ))

    return (

{menuProps.title}

{menuProps.description}

                    {buttonElements}

            <Article
                key={articles.key}
                style={{backgroundImage: `url(${articles.img})`}}
                title={articles.title}
                description={articles.description}
            />

    )
}

export default Main

A: I wanted to share the function structure that worked for me in this scenario...
[For a little more clarification, I'm using a separate data JS file that contains the content, mainData as shown above, that gets mapped in the main.js file for both the buttons and articles.  Button keys are set in the data file with a value the same as an index]
function setButtonActive(key) {
    setActive(prevActive => {
        return prevActive.map((button, index) => {
            if (key === index) {
                setArticle(mainData.articles[index])
            }
            return button.key === key ?
                {...button, active: true} : {...button, active: false}
        })
    })
}

The site is now live so everyone can see the finished result of what I was aiming for:
https://willfranck.github.io/react-demo-travel-site/
Thanks!

A: With your state, how are you determining which button is active?
 const [buttons, setButtonActive] = React.useState(mainData.buttons)
 const [articles, setArticle] = React.useState(mainData.articles[0])

Here it looks you are mixing two concepts - setting elements as buttons and setting a button as active. I'm not sure what your mainData.buttons is, but unless you are planning on changing the buttons based on user actions, you don't need to set them in state. You've imported them, you can use them.
You should use useState for setting a button as active - how you decide to do that is ultimately up to you. The same is true of articles. How are buttons and articles related? From there, you can determine how to structure your state.


text:
Q: Vert.x unit test doesn't execute I'm new to vert.x and decided to start out light, but can't get a simple unit test to work (using maven to build). Code as follows
FileRepo.java:
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Router;

public class FileRepo extends AbstractVerticle {
  @Override
  public void start(Future<Void> fut) {
    HttpServer server = vertx.createHttpServer();
    Router router = Router.router(vertx);
    router.route("/upload").handler(routingContext -> {
      HttpServerResponse response = routingContext.response();
      response.putHeader("content-type", "text/plain");
      response.end("Hello world!");
    });
    System.out.println("Starting server!");
    server.requestHandler(router::accept).listen(8080);
    System.out.println("Server started!");
  }
}

FileRepoTest.java:
import FileRepo;
import io.vertx.core.Vertx;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(VertxUnitRunner.class)
public class FileRepoTest {
  private Vertx vertx;

  @Before
  public void setUp(TestContext context) {
    vertx = Vertx.vertx();
    System.out.println("SetUp Vertx");
    vertx.deployVerticle(FileRepo.class.getName(), context.asyncAssertSuccess());
    System.out.println("SetUp done");
  }

  @After
  public void tearDown(TestContext context) {
    System.out.println("tearDown Vertx");
    vertx.close(context.asyncAssertSuccess());
  }

  @Test
  public void testUpload(TestContext context) {
    System.out.println("testUpload");
  }
}

Result:
SetUp Vertx
SetUp done
Starting server!
Server started!
tearDown Vertx

java.util.concurrent.TimeoutException
    at io.vertx.ext.unit.impl.TestContextImpl$Step.lambda$run$0(TestContextImpl.java:112)
    at java.lang.Thread.run(Thread.java:745)

Process finished with exit code -1

Browsing http://localhost:8080/upload while waiting for the TimeoutException shows a Hello World! page, but the @Test never seem to execute. What am I doing wrong here?
Regards,
Mattias

A: The exception you are getting is because there is no acknowledgment of the server start state.
Change your Verticle to following:
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Router;

public class FileRepo extends AbstractVerticle {
    @Override
    public void start(Future<Void> fut) {
        Router router = Router.router(vertx);
        router.route("/upload").handler(routingContext -> {
            HttpServerResponse response = routingContext.response();
            response.putHeader("content-type", "text/plain");
            response.end("Hello world!");
        });
        System.out.println("Starting server!");
        vertx.createHttpServer()
                .requestHandler(router::accept)
                .listen(8080, result -> {
                    if (result.succeeded()) {
                        System.out.println("Server started!");
                        fut.complete();
                    } else {
                        System.out.println("Server start failed!");
                        fut.fail(result.cause());
                    }
                });
    }
}


text:
Q: Windows Scheduler - Script Execution Error I'm trying to set up Windows Task Scheduler to run the upload_xml.cmd script below:
Inside this script I call several other files that have FTP commands, but when I run the task scheduler I configured, it only runs until step 2. How can I solve this problem?
:Step 1
Echo step 1 - Check for xml files to process
Netsh advfirewall set allprofiles state off
Of xmls.list /f/q
Dir /s/b C:\xml\UPLOAD\*.xml xmls.list
Find /c ".xml xmls.list
If% errorlevel% equ 1 goto Exit
Echo step 1 - Files found
: Step2
Echo step 2 - run the ftp script to check if the connection exists
In10xml_connect /f/q
Ftp -s: download_connect.ftpget xx.xxx.xxx.xx
If not exist in10xml_connect goto Exit
Echo step 2 - SUCCESSFUL CONNECTION
: Step3
Echo step 3 - run the ftp script to check if you can send the files
In10xml_loader.lock /f/q
Ftp -s: download_lock.ftpget xx.xxx.xxx.xx
If exist in10xml_loader.lock goto Exit
Echo step 3 - UPLOAD CAN CONTINUE


text:
Q: Data View Web Part and Custom List Form show Attachments I have found a few ways to add attachments to a Data View Web Part, but I can only get this to work when the SharePoint:AttachmentsField is not being used anywhere else on the page.
Currently my DispForm.aspx page has a Custom List Form (display) for one List, and a Data View Web Part that filters its values based on the first List.
I am trying to get both the Custom List Form and the Data View Web Part to show attachments for both lists using SharePoint:AttachmentsField however I can only get one or the either to work.
Anybody have luck with this?

A: Looks like it is a Microsoft bug, and nothing can be done about this :(
Second AttachmentsField control on the page is always displaying this text:

["Attachments" column value]

I found that inside both controls' HTML, where is a table with static id:
<table id="idAttachmentsTable" border="0" cellSpacing="0" cellPadding="0">

So, this could be a reason for such behavour, but I'm not sure.
I tried passing to the controls all possible property values, and with no luck. And I tryed this in SharePoint 2010, and saw the same issue.
So, you should probably use another way for displaying attachments. Please, take a look at following solution:
http://www.codeproject.com/KB/sharepoint/DataViewAttachments.aspx

A: I added and modified the code from the editform to the last row in the dvwp on my custom dispform.  Had to delete the ($Pos) parameter and remove the concat function, also changed the controlmode to display.
Diplays multiple attachments on my custom dispform.
If anyone sees a weakness with this method, please let me know
thx fran

A: Bad, but this may get it working? (Iframes are the devil, but if this is short term, it may meet the requirements?)
Just iframe the data view web part and overwrite the Save button to redirect the entire page on save.
Change
<input type="button" value="Save" name="btnSave" onclick="javascript: {ddwrt:GenFireServerEvent('__commit')}" />

To
<input type="button" value="Cancel This" name="btnSave" onclick="javascript: {ddwrt:GenFireServerEvent('__redirect={/redirectparent.aspx}')}" />

RedirectParent.aspx
<script>
    self.parent.location='wherever after submit.aspx';
</script>

Alternatively, if you want to look into why you can only have one on a page, It sounds like a few things
I would make sure you account for the following:

*

*Button functionality to show/hide attachments row (not necessary)

*Linking the attachment to the new form (very important)

I would bet its an issue with the ID's not being unique if you have two on a page. Custom List Forms probably take care of this for you.


text:
Q: 'tb' referenced before assignment I use from multiprocessing.dummy import Pool in my project. The problem is that after many successful attempts (getting price), it returned UnboundLocalError: local variable 'tb' referenced before assignment.
The thing is that tb variable should be 100% assigned when it's referenced. If there is an exception, tb is assigned, otherwise, the variable d is returned and tb is not referrenced.
I can't figure out where could be the problem. I will show you my functions - you can see that variable tb, which is a traceback, has to be assigned in all situations when its referrenced:
def scan_partner(d):
    success = False
    try:
        from parser import parse_price
        resp = get_price(d.get('url'), d.get('xpath'))
        amount = resp.get('price')

    except XPathEvalError as xee:
        tb = traceback.format_exc()
        ticket_code = 'xpath'
        msg = u'XPath Error'
    except (requests.Timeout, requests.ConnectTimeout, requests.ReadTimeout):
        tb = traceback.format_exc()
        ticket_code = 'timeout'
        msg = u'Timeout'
    except requests.HTTPError:
        tb = traceback.format_exc()
        ticket_code = 'http'
        msg = u'HTTP Error'
    except decimal.DecimalException:
        tb = traceback.format_exc()
        ticket_code = 'decimal'
        msg = u'Decimal Error'
    except requests.ConnectionError:
        tb = traceback.format_exc()
        ticket_code = 'connection'
        msg = u'Connection Error'
    except Exception as e:
        tb = traceback.format_exc()
        ticket_code = 'unknown'
        msg = u'Unknown Error'
    else:
        success = True
        result = {'result': {'success': True,
                             'amount': str(amount)}}
        d.update(result)

    finally:
        if success:
            return d
        d.update({'ticket': {'tb': tb,
                             'msg': msg,
                             'ticket_code': ticket_code},
                  'result': {'success': False}})
        return d

def scan_partners_dummy_pool(dicts_list):
    repeated_results = []

    results_to_repeat = []
    for i in range(settings.ENGINE_NUMBER_OF_SCAN_REPEATS):
        pool = Pool(300)
        results = pool.map(scan_partner, dicts_list)
        pool.close()
        pool.join()
        results_to_go = []
        results_to_repeat = []
        for result in results:
            if result['result']['success']:
                results_to_go.append(result)
            else:
                if result['ticket']['ticket_code']=='timeout':
                    results_to_repeat.append(result)
                else:
                    results_to_go.append(result)
        repeated_results.extend(results_to_go)
        dicts_list = results_to_repeat
    repeated_results.extend(results_to_repeat)

    return repeated_results

The traceback:
[2017-02-11 23:33:54,470: ERROR/MainProcess] Task engineapp.tasks.scan_every_20_minutes[91c08f5d-36ad-42bc-805f-8a35c01127e6] raised unexpected: UnboundLocalError("local variable 'tb' referenced before assignment",)
Traceback (most recent call last):
  File "c:\users\milano\pycharmprojects\dropboxworkspaces\priceist_workspace\priceist_venv\lib\site-packages\celery\app\trace.py", line 240, in trace_task
    R = retval = fun(*args, **kwargs)
  File "c:\users\milano\pycharmprojects\dropboxworkspaces\priceist_workspace\priceist_venv\lib\site-packages\celery\app\trace.py", line 438, in __protected_call__
    return self.run(*args, **kwargs)
  File "C:\Users\Milano\Desktop\Projekty\FS Dropbox\Dropbox\priceist\engineapp\tasks.py", line 18, in scan_every_20_minutes
    scan_all_active_users(20)
  File "c:\users\milano\pycharmprojects\dropboxworkspaces\priceist_workspace\priceist_venv\lib\site-packages\celery\local.py", line 167, in <lambda>
    __call__ = lambda x, *a, **kw: x._get_current_object()(*a, **kw)
  File "c:\users\milano\pycharmprojects\dropboxworkspaces\priceist_workspace\priceist_venv\lib\site-packages\celery\app\trace.py", line 439, in __protected_call__
    return orig(self, *args, **kwargs)
  File "c:\users\milano\pycharmprojects\dropboxworkspaces\priceist_workspace\priceist_venv\lib\site-packages\celery\app\task.py", line 420, in __call__
    return self.run(*args, **kwargs)
  File "C:\Users\Milano\Desktop\Projekty\FS Dropbox\Dropbox\priceist\engineapp\tasks.py", line 132, in scan_all_active_users
    report = scan_user(user.id, simple_schedule)
  File "C:\Users\Milano\Desktop\Projekty\FS Dropbox\Dropbox\priceist\engineapp\tasks.py", line 123, in scan_user
    results = scan_partners_dummy_pool(partners_dicts)
  File "C:\Users\Milano\Desktop\Projekty\FS Dropbox\Dropbox\priceist\engineapp\engine\scraper.py", line 126, in scan_partners_dummy_pool
    if result['ticket']['ticket_code']=='timeout':
  File "c:\python27\Lib\multiprocessing\pool.py", line 251, in map
    return self.map_async(func, iterable, chunksize).get()
  File "c:\python27\Lib\multiprocessing\pool.py", line 567, in get
    raise self._value
UnboundLocalError: local variable 'tb' referenced before assignment

PS:
The process is a Celery periodic task.

A: You are not catching all possible exceptions, so if you get exception that is not subclass of Exception then neither except blocks nor else block will execute, but finally block will be still executed.
I would put return statement in else and move contents of finally block to main body. Then you will might able to see whatever BaseException causes trouble.


text:
Q: Get count unique values in a row in pandas Suppose I have the following data frame:
0     1        2
new   NaN      NaN
new   one      one
a     b        c
NaN   NaN      NaN

How would I get the number of unique (non-NaN) values in a row, such as:
0     1        2       _num_unique_values
new   NaN      NaN     1
new   one      one     2
a     b        c       3
NaN   NaN      NaN     0

I suppose it would be something along the lines of:
df['_num_unique_values'] = len(set(df.loc.tolist())) ??

A: Just use nunique(axis=1).
import numpy as np
import pandas as pd

data={0:['new','new','a',np.nan],
     1:[np.nan,'one','b', np.nan],
     2:[np.nan,np.nan,'c',np.nan]}
df = pd.DataFrame(data)

# print(df.nunique(axis=1))

df['num_unique'] = df.nunique(axis=1)

A: Use a list comprehension.... with set:
df['num_uniq'] = [len(set(v[pd.notna(v)].tolist())) for v in df.values]
df

     0    1    2  num_uniq
0  new  NaN  NaN         1
1  new  one  one         2
2    a    b    c         3
3  NaN  NaN  NaN         0

You could do this with stack, groupby and nunique.
# df.join(df.stack().groupby(level=0).nunique().to_frame('num_uniq'))
df['num_uniq'] = df.stack().groupby(level=0).nunique()
df

     0    1    2  num_uniq
0  new  NaN  NaN       1.0
1  new  one  one       2.0
2    a    b    c       3.0
3  NaN  NaN  NaN       NaN

Yet another option is apply and nunique:
df['num_uniq'] = df.apply(pd.Series.nunique, axis=1)
df

     0    1    2  num_uniq
0  new  NaN  NaN         1
1  new  one  one         2
2    a    b    c         3
3  NaN  NaN  NaN         0

Performance
df_ = df
df = pd.concat([df_] * 1000, ignore_index=True)

%timeit df['num_uniq'] = [len(set(v[pd.notna(v)])) for v in df.values]
%timeit df['num_uniq'] = df.stack().groupby(level=0).nunique()
%timeit df['num_uniq'] = df.apply(pd.Series.nunique, axis=1)
%timeit df['num_uniq'] = df.nunique(1)

196 ms ± 10.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
6.34 ms ± 343 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
679 ms ± 24 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
3.21 ms ± 343 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

A: A more abstract solution:
df['num_uniq']=df.nunique(axis=1)

A: It is not as fast as coldspeed's answer with set(), but you could also do
df['_num_unique_values'] = df.T.nunique()

First the transpose of df dataframe is taken with df.T and then nunique() is used to get the count of unique values excluding NaNs.
This is added as a new column to the original dataframe.
df would now be
    0   1   2   _num_unique_values
0   new nan nan 1
1   new one one 2
2   a   b   c   3
3   nan nan nan 0


text:
Q: "No such file or directory" при вызове file_get_contents Собственно, код самый примитивный:
<?php
echo file_get_contents("example.xml");
?>

Выдает No such file or directory, хотя я совершенно уверен в том, что ошибки в названии файла нету и этот файл существует с правами 777. Более того, этой функцией я не могу открыть абсолютно никакой файл, в том числе с других сайтов (В этом случае failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request; Конечно, allow_url_fopen = On).
A: https://stackoverflow.com/questions/22022194/file-get-contents-no-such-file-or-directory-php
http://php.net/manual/en/function.file-get-contents.php
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>


text:
Q: Access every other item in an array - JavaScript Is it possible for me to access every other item in an array? So basically, all items in positions 0, 2, 4, 6 etc.
Here's my code if it helps:
function pushToHash(key, value) {
    for (var t = 0; t < value.length; t++) {
    MQHash[key[t]] = value.slice(0, lineLength[t]);
    }
}

So, I need to get every other value of lineLength. I only want this for lineLength, not key. I was thinking of doing a modulus, but wasn't sure how I'd implement it. Any ideas?
Thanks in advance!

A: If you just want this with lineLength and not with key, then add a second variable and use += when incrementing:
function pushToHash(key, value) {
    for (var t = 0, x = 0; t < value.length; t++, x += 2) {
        MQHash[key[t]] = value.slice(0, lineLength[x]);
    }
}

(The power of the comma operator...)

A: You can use the index (second parameter) in the array filter method like this:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// filter out all elements that are located at an even index in the array.

let x = arr.filter((element, index) => {
  return index % 2 === 0;
})

console.log(x)
// [1, 3, 5, 7, 9]

A: How about   for (var i = 1; i < array.length; i += 2)

A: Here is a function that will truncate an array every X elements (factor).
const truncateArray = (array: any[], factor: number): any[] => {
  let lastNumber = 0;
  return array.filter((element, index) => {
    const shouldIncludeThisElement = index === lastNumber + factor ? true : false;
    lastNumber = shouldIncludeThisElement ? index : lastNumber;
    return shouldIncludeThisElement;
  });
};


text:
Q: TreeView with Two Columns JavaFX 8 I need to have an expandable nestable key value list in JavaFX 8. This is similar in functionality to a TreeTableView, but it is oriented vertically, not horizontally. In other words, the rows would be the headers not the columns for a X-Y inverted axis table. Due to the limitation of TreeTableView being horizontal, I started exploring the options of TreeView. TreeView works nicely but only has one column where I need a key value pair in each row. What I really need is something like below:

Note the foo and bar can be unique.
How can I add a second column to a TreeView?

A: This is an idea based on a custom cell factory for TreeView that creates row-like cells. A custom cell is created which contains 2 labels in a grid and some resizing behavior settings.

public class CustomTree extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        TreeView<String[]> tree = new TreeView<>();

        tree.setCellFactory(cell -> new TreeCell<String[]>() {

            private GridPane pane = new GridPane();
            private Label keyLabel = new Label();
            private Label valueLabel = new Label();
            private Border keyBorder = new Border(
                    new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, null, new BorderWidths(0.5, 0.5, 0.5, 1)));
            private Border valueBorder = new Border(
                    new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, null, new BorderWidths(0.5, 1, 0.5, 0.5)));

            {
                pane.getChildren().addAll(keyLabel, valueLabel);
                GridPane.setConstraints(keyLabel, 0, 0);
                GridPane.setConstraints(valueLabel, 1, 0);

                ColumnConstraints column1 = new ColumnConstraints();
                column1.setPercentWidth(50);
                ColumnConstraints column2 = new ColumnConstraints();
                column2.setPercentWidth(50);
                pane.getColumnConstraints().addAll(column1, column2);

                keyLabel.setBorder(keyBorder);
                valueLabel.setBorder(valueBorder);
                keyLabel.setMaxWidth(Double.MAX_VALUE);
                valueLabel.setMaxWidth(Double.MAX_VALUE);

                setPadding(Insets.EMPTY);
            }

            @Override
            public void updateItem(String[] name, boolean empty) {
                super.updateItem(name, empty);
                if (empty || name == null) {
                    setText(null);
                    setGraphic(null);
                } else {
                    keyLabel.setText(name[0]);
                    valueLabel.setText(name[1]);
                    setGraphic(pane);
                }
            }
        });

        TreeItem<String[]> root = new TreeItem<>(new String[] { "", "" });
        TreeItem<String[]> sub1 = new TreeItem<>(new String[] { "Foo", "Bar" });
        TreeItem<String[]> sub2 = new TreeItem<>(new String[] { "Foo", "Bar" });
        TreeItem<String[]> sub3 = new TreeItem<>(new String[] { "Foo", "Bar" });
        TreeItem<String[]> sub4 = new TreeItem<>(new String[] { "Foo", "" });
        TreeItem<String[]> sub5 = new TreeItem<>(new String[] { "Foo", "Bar" });
        TreeItem<String[]> sub41 = new TreeItem<>(new String[] { "Foo", "Bar" });
        TreeItem<String[]> sub42 = new TreeItem<>(new String[] { "Foo", "Bar" });
        root.getChildren().addAll(sub1, sub2, sub3, sub4, sub5);
        sub4.getChildren().addAll(sub41, sub42);

        tree.setRoot(root);

        Scene scene = new Scene(tree);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}

Note that the root must also use this cell type, though it's possible to hide the root completely using tree.setShowRoot(false);. Two shortcomings of this approach are that each cell behaves as one unit - there is no concept of columns, and that the values of the cell are given as an array, thus losing type safety. You can expand on this example yourself.
It could be possible, though a lot more work, to use a (generic) TableView or TreeTableView approach.


text:
Q: How do I set configuration for a group in Phaser 3? In my Phaser 3 game I have a group called OBS that stores all the obstacles sprites.
OBS = this.physics.add.group

I want to set the velocity of every child created from this group to a particular value say
setVelocityY=40

So every object that is in group OBS will move at velocity 40. How do I set a configuration for the group such that every object that I add to it moves at the given velocity and shares other common properties?

A: There are multiple ways to do that.

*

*using config -
You can pass PhysicsGroupConfig while creating group, and set velocityY in that config that will set velocityY of every children of that group. You can set many properties in config. Check out the docs.

*using group's methods like setVelocity or setVelocityY - if you want to set velocity after creating group you can use group's methods like setvelocityY or setVelocity.

A: You can use a for-loop to add properties to all the child elements.
Eg. if you have 3 child elements, you can do it like this:
var OBSPositions = [
    { x: 50, y: 80 },
    { x: 50, y: 480 },
    { x: 300, y: 480 }
];

OBS = this.physics.add.group;
for (var i = 0; i < OBSPositions.length; i++) {
    var OBSchild = OBS.create(
        OBSPositions[i].x,
        OBSPositions[i].y,
        'OBSsprite'
    ).setScale(0.13, 0.13);

    OBSchild.setVelocityY = 40;
}


text:
Q: Solve $e = xe^x$ I know it it seems trivial that $x = 1$, but I would like to know a more rigorous solution involving algebra. I tried solving for it, but could not come up with a proper solution.
My attempt:
$e = xe^x \implies e^{1-x} = x \implies (1-x)\ln e = \ln x \implies 1-x = \ln x \implies 1 = \ln x + x$
And at this point I got stuck.

A: The function $f(x) = xe^x$ does not have an inverse that can be expressed in terms of any finite algebraic combination of the usual functions.  The two branches that form its inverse are known as the Lambert W function(s).
The equation
$$
y = xe^x
$$
can be solved for $y$ using a numerical approach, if an approximate solution is desired.

A: Consider $f(x) = xe^x-e$. You have that $x = 1$ is a root. And: $$f'(x) = e^x + xe^x > 0,$$ for $x > 0$, so we don't have any positive roots other than $1$. If $x \leq 0$, you would have $e = \text{something negative}$, which can't happen.


text:
Q: How to change Android Things mDNS hostname (Android.local) to something else I have an IoT project that has to identify my RaspberryPI (which has Android Things OS) over the local network.
A good way to do this is by using the Multicast DNS (mDNS) that Android Things broadcasts as Android.local.
The question is: can I change the Android.local to somethingelse.local so that I dont have any conflicts ?
I know it is possible using a Linux OS, as showed here. Can I do the same on Android Things ?
Thanks in advance!

A: I know Android Things is no longer supported but still... I found solution:
You can set hostname over ADB:
adb connect x.x.x.x  # where x.x.x.x is ip address of your device
adb root
adb remount
adb shell
su
cd system
echo 'net.hostname=newHostName' >> build.prop

echo 'net.hostname=newHostName' >> build.prop  appends new line to build.prop file.. if you wish to rename again you need to remove this line before


text:
Q: Mortar + Flow with third party libraries hooked to activity lifecycle Some third party libraries use hooks into the activity lifecycle to work correctly - for instance, the Facebook SDK (https://developers.facebook.com/docs/android/login-with-facebook/).
I'm having some trouble figuring out how to reconcile this model cleanly with a single-activity flow+mortar setup.
For instance, if I want to use Facebook login as part of a login Flow (w/ FlowView/FlowOwner), but not otherwise in the activity, what's the smartest way to pull this off if you need hooks for that particular flow in onCreate, onResume, onPause, onDestroy, onSaveInstanceState, onActivityResult, etc?
It's not immediately obvious what the cleanest path is - create an observable for each lifecycle activity stage and subscribe the flow to it? Seems like that path quickly devolves to the same Android lifecycle if you're not careful. Is there a better way?
I love the single activity model, and I'd really like to keep everything managed by flow/mortar and not activities, if possible. Or am I thinking about this in a way that is fundamentally making it more difficult than it should be?

A: So I've been porting a personal app over to flow and mortar to evaluate it for businesses use. I haven't encountered a scenario where I HAD to have the entire activity lifecycle yet, but as things stand with the current version of flow (v0.4) & mortar (v0.7), this is something I think you will have to creatively solve for yourself. I've recognized this as a potential problem for myself and have put some thought of how to overcome it:
I would also like to note that I haven't actually used the Facebook SDK. You will have to choose the best method for yourself.

*

*You could post events from the activity for each Activity life cycle event. You essentially mentioned this approach using RXJava's Observables. If you really really wanted to use RXJava, you could use a PublishSubject for this, but I'd probably go with simple events from an EventBus you could subscribe to. This is probably the easiest approach.

*You could also, depending on how the Facebook SDK works, possibly inject the Facebook SDK component in the activity, and from there initialize it. Then also inject the Facebook SDK component into your view to be used. Flow and Mortar's entire system is deeply integrated into dependency injection after all? This approach is also fairly simple, but depending on how the Facebook SDK works it probably isn't the best option. If you did go this route, you'd need to heed my warning at the bottom of this post.

*This brings us to my last idea. Square had a similar problem when they needed access to an Activity's ActionBar in it's sub-views/presenters. They exposed access to the ActionBar in their sample app via something they called the ActionBarOwner.java. They then implement the ActionBarOwner interface and give an instance of itself in the DemoActivity.java. If you study how they implemented this and share it through injection, you could create a similar class. AcivityLifecycleOwner or something (the name needs work), and you could subscribe to callbacks on it from a presenter. If you decide to go down this route, and aren't careful you can easily end up with a memory leak. Any time you would subscribe to any of the events (I'd recommend you subscribe in the presenter), you'd need to make sure you unsubscribe in the onDestroy method as well. I've created a short untested sample of what I mean for this solution below.

No matter which approach you use, you'll probably need to make sure your onCreate and onDestroy methods actually come from your presenter, and not the exact events from the activity. If you are only using the sdk on a single view, the activity's onCreate has been called long before your view is instantiated probably, and the onDestroy for the Activity will be called after your view is destroyed. The presenter's onLoad and onDestroy should suffice I think, however I haven't tested this.
Best of luck!
Untested code example for solution #3:
All your presenters could extend this class instead of ViewPresenter and then override each method you wanted events for just like you would in an activity:
public abstract class ActivityLifecycleViewPresenter<V extends View> extends ViewPresenter<V>
    implements ActivityLifecycleListener {

  @Inject ActivityLifecycleOwner mActivityLifecycleOwner;

  @Override protected void onLoad(Bundle savedInstanceState) {
    super.onLoad(savedInstanceState);
    mActivityLifecycleOwner.register(this);
  }

  @Override protected void onDestroy() {
    super.onDestroy();
    mActivityLifecycleOwner.unregister(this);
  }

  @Override public void onActivityResume() {
  }

  @Override public void onActivityPause() {
  }

  @Override public void onActivityStart() {
  }

  @Override public void onActivityStop() {
  }

}

Activity Lifecycle owner that would be injected into the activity and then hooked up to the corresponding events. I purposely didn't include onCreate and onDestroy, as you presenter's wouldn't be able to get access to those events as they wouldn't be created or they would already be destroyed. You'd need to use the presenters onLoad and onDestroy methods in place of those. It's also possible that some of these other events wouldn't be called.
public class ActivityLifecycleOwner implements ActivityLifecycleListener {

  private List<ActivityLifecycleListener> mRegisteredListeners
      = new ArrayList<ActivityLifecycleListener>();

  public void register(ActivityLifecycleListener listener) {
    mRegisteredListeners.add(listener);
  }

  public void unregister(ActivityLifecycleListener listener) {
    mRegisteredListeners.remove(listener);
  }

  @Override public void onActivityResume() {
    for (ActivityLifecycleListener c : mRegisteredListeners) {
      c.onActivityResume();
    }
  }

  @Override public void onActivityPause() {
    for (ActivityLifecycleListener c : mRegisteredListeners) {
      c.onActivityPause();
    }
  }

  @Override public void onActivityStart() {
    for (ActivityLifecycleListener c : mRegisteredListeners) {
      c.onActivityStart();
    }
  }

  @Override public void onActivityStop() {
    for (ActivityLifecycleListener c : mRegisteredListeners) {
      c.onActivityStop();
    }
  }
}

Now you need to hook the lifecycle owner to the activity:
public class ActivityLifecycleExample extends MortarActivity {

  @Inject ActivityLifecycleOwner mActivityLifecycleOwner;

  @Override protected void onResume() {
    super.onResume();
    mActivityLifecycleOwner.onActivityResume();
  }

  @Override protected void onPause() {
    super.onPause();
    mActivityLifecycleOwner.onActivityPause();
  }

  @Override protected void onStart() {
    super.onStart();
    mActivityLifecycleOwner.onActivityStart();
  }

  @Override protected void onStop() {
    super.onStart();
    mActivityLifecycleOwner.onActivityStop();
  }

}

A: We haven't had a need for start and stop so far, but do have a few spots that rely on pause and resume. We use an ActivityPresenter as you suggest, but avoid any kind of universal superclass. Instead it exposes a service that interested presenters can opt in to. This kind of hookup need is why the onEnterScope(Scope) method was added. Here's the code.
First, have the activity implement this interface:
/**
 * Implemented by {@link android.app.Activity} instances whose pause / resume state
 * is to be shared. The activity must call {@link PauseAndResumePresenter#activityPaused()}
 * and {@link PauseAndResumePresenter#activityResumed()} at the obvious times.
 */
public interface PauseAndResumeActivity {
  boolean isRunning();

  MortarScope getMortarScope();
}

And have it inject the presenter and make the appropriate calls:
private boolean resumed;
@Inject PauseAndResumePresenter pauseNarcPresenter;

@Override protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  pauseNarcPresenter.takeView(this);
}

@Override public boolean isRunning() {
  return resumed;
}

@Override protected void onResume() {
  super.onResume();
  resumed = true;
  pauseNarcPresenter.activityResumed();
}

@Override protected void onPause() {
  resumed = false;
  super.onPause();
  pauseNarcPresenter.activityPaused();
}

@Override protected void onDestroy() {
  pauseNarcPresenter.dropView(this);
  super.onDestroy();
}

Now interested parties can inject a registrar interface to opt-in to pause and resume calls, without subclassing anything.
/**
 * Provides means to listen for {@link android.app.Activity#onPause()} and {@link
 * android.app.Activity#onResume()}.
 */
public interface PauseAndResumeRegistrar {
  /**
   *
Registers a {@link PausesAndResumes} client for the duration of the given {@link
   * MortarScope}. This method is debounced, redundant calls are safe.
   *
   *
Calls {@link PausesAndResumes#onResume()} immediately if the host {@link
   * android.app.Activity} is currently running.
   */
  void register(MortarScope scope, PausesAndResumes listener);

  /** Returns {@code true} if called between resume and pause. {@code false} otherwise. */
  boolean isRunning();
}

Have the client presenter implement this interface:
/**
 *
Implemented by objects that need to know when the {@link android.app.Activity} pauses
 * and resumes. Sign up for service via {@link PauseAndResumeRegistrar#register(PausesAndResumes)}.
 *
 *
Registered objects will also be subscribed to the {@link com.squareup.otto.OttoBus}
 * only while the activity is running.
 */
public interface PausesAndResumes {
  void onResume();

  void onPause();
}

And hook things up like this. (Note that there is no need to unregister.)
private final PauseAndResumeRegistrar pauseAndResumeRegistrar;

@Inject
public Presenter(PauseAndResumeRegistrar pauseAndResumeRegistrar) {
  this.pauseAndResumeRegistrar = pauseAndResumeRegistrar;
}

@Override protected void onEnterScope(MortarScope scope) {
  pauseAndResumeRegistrar.register(scope, this);
}

@Override public void onResume() {
}

@Override public void onPause() {
}

Here's the presenter that the activity injects to make it all work.
/**
 * Presenter to be registered by the {@link PauseAndResumeActivity}.
 */
public class PauseAndResumePresenter extends Presenter<PauseAndResumeActivity>
    implements PauseAndResumeRegistrar {

  private final Set<Registration> registrations = new HashSet<>();

  PauseAndResumePresenter() {
  }

  @Override protected MortarScope extractScope(PauseAndResumeActivity view) {
    return view.getMortarScope();
  }

  @Override public void onExitScope() {
    registrations.clear();
  }

  @Override public void register(MortarScope scope, PausesAndResumes listener) {
    Registration registration = new Registration(listener);
    scope.register(registration);

    boolean added = registrations.add(registration);
    if (added && isRunning()) {
      listener.onResume();
    }
  }

  @Override public boolean isRunning() {
    return getView() != null && getView().isRunning();
  }

  public void activityPaused() {
    for (Registration registration : registrations) {
      registration.registrant.onPause();
    }
  }

  public void activityResumed() {
    for (Registration registration : registrations) {
      registration.registrant.onResume();
    }
  }

  private class Registration implements Scoped {
    final PausesAndResumes registrant;

    private Registration(PausesAndResumes registrant) {
      this.registrant = registrant;
    }

    @Override public void onEnterScope(MortarScope scope) {
    }

    @Override public void onExitScope() {
      registrations.remove(this);
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;

      Registration that = (Registration) o;

      return registrant.equals(that.registrant);
    }

    @Override
    public int hashCode() {
      return registrant.hashCode();
    }
  }
}


text:
Q: Identity and Access is Missed in VS 2017 I am trying to create a WCF service which uses WIF. Following this howto I should right-click the service in Solution Explorer and select Identity and access. But I can't find that option in VS 2017.
I have found a solution for ASP.Net MVC applications here, but I am not sure if that works seamless for WCF services.
What can I do?

A: All the tooling that did this has been deprecated.
As per the article, you can build up the web.config manually. That's probably your best option.
The new way is to use OWIN. I don't know of any OWIN sample for WCF though because the new way of doing this is via web API.
WS-Fed is hardly ever used. The new way is OIDC.


text:
Q: How we can launch a JS program with this command ./prog.js? I had to launch the following code :
    var fs = require('fs');
var str = fs.readFileSync('input.txt', 'utf8');

str.replace(/^\s*[\r\n]/gm,"").split(/\s+/).forEach(function (s) {
    return console.log(
    s === 'bob'
        ? 'boy'
        : s === 'alicia'
        ? 'girl'
        : s === 'cookie'
        ? 'dog'
        : 'unknown');
});

with this command : ./prog.js
But it does not work and I found online in order to launch a JS program on a terminal we had to use this command : node prog.js.
And my internship supervisor said to me the first command it's very possible. So can you help me in order to launch my code with the first command please?


text:
Q: JS. Get part of date from string I have this string '2020-10-20'
Can i somehow get those numbers separately like this:
const [year, month, day] = '2020-10-20'.match(/\d\d\d\d/ what should i write there?)

Or any better approach exist?

A: You can split the string using a delimiter as follows
const [year, month, day] = '2020-10-20'.split("-")
then you would have year=2020 etc.

A: Using regex you can do something like this:

console.log('2020-10-20'.match(/\d+/g))

If you want to use Array.prototype.split, you can do something like this

console.log('2020-10-20'.split("-"))

A: I'll add a little bit to the above solutions. If you want to get those values as number then use the map method.

const dateString = "2020-10-12";
const [year, month, date] = dateString.split("-").map(Number);
console.log(year, month, date);

Update
By the way, If you want to learn how to do that with regex, then here's how:

const dateString1 = "2020-10-10";
const dateString2 = "2020/10/10";
const dateString3 = "2020_10_10";

const pattern = /(\d{4}).(\d{2}).(\d{2})/;
 /*
  * \d - matches digits 0 - 9
  * \d{4} - matches any 4 digits. e.g., 1234, 4587 ...
  * \d{2} - matches any 2 digits.
  * . - matches anything except new line ("\n"). For the
  * separator.
  * (anything-here) - anything inside () is called a capture
  * group.
  * and will be available in the result
  * */

 /*
  * console.log(pattern.exec(dateString2))
  * returns [ "2020/10/10", "2020", "10", "10" ]
  * now we need to slice the arrary from index 1 to 3
  * and we get [ "2020", "10", "10" ]
  * */

function parseDate(dateString) {
  // For invalid dateString we'll throw an error
  if(!pattern.test(dateString))
    throw new Error("Invalid date string");
  return pattern.exec(dateString).slice(1).map(Number);
}

console.log(parseDate(dateString1))
console.log(parseDate(dateString2))
console.log(parseDate(dateString3))

A: Or turn the string into a Date object and then return year, month and date.

var date = new Date('2020-10-20');
console.log(date);
console.log(date.getFullYear());
console.log(date.getMonth()+1); // Jaunary = 0
console.log(date.getDate());

Using the date object you also avoid problems with the leading "0" for numbers less than 10.

var date = new Date('2020-02-8'); // notice the "missing" 0 before 8
console.log(date);
console.log(date.getFullYear());
console.log(date.getMonth()+1); // Jaunary = 0
console.log(date.getDate());


text:
Q: Save File with AppendText i have a richTextbox es:
line1
line2
line3

use this for save file File.WriteAllText(name, (richTextBox1.Text));
but the file returns this line1lin2line3
is possiible to save file in this way?
line1
line2
line3

A: I suspect that for whatever reason, RichTextBox is using the Unix linebreak of just \n. Try this:
File.WriteAllText(name, richTextBox1.Text.Replace("\n", "\r\n"));

A: For writing to file:
File.WriteAllLines("my file.txt", this.richTextBox1.Lines);

for appending:
File.AppendAllLines("my file.txt", this.richTextBox1.Lines);

A: What about richTextBox1.SaveFile(file_name)?
Or richTextBox1.SaveFile(file_name, RichTextBoxStreamType.PlainText)

A: You can fetch the individual lines by using the 'Lines' property.
string[] linesintextbox = richTextBox1.Lines;
File.WriteAllLines("xyz.txt", linesintextbox);


text:
Q: What are the pros and cons of using these Multithreading Models in a Client/Server Architecture In my classes of parallel programming the teacher mentioned three models, dynamic thread creation (create threads according to demand), thread pool (create a fixed amount of threads) and mixed or hybrid (create a number of threads at first, but you can create more if the demand increases too much and then return to the previous amount of threads when demand returns to normal)
I would like if someone could elaborate on the advantages and disadvantages of each model in general terms of performance, when it is best to use one in specific, etc...

A: A quick non-academic view:
Dynamic model:

*

*Pros: uses only the number of threads needed.

*Cons: the overhead of the thread creation and deletion during the processing.  Consider also thread switching overhead, if the number of dynamic threads increases over the hardware supported limit.

*Typical use case:  handling event driven processes/sessions (e.g. I/O), where threads are frequently waiting and performance of thread creation is small compared to I/O (e.g. new incoming network connection).

Thread pool:

*

*Pros: reduces overhead of thread management to the minimum. Constant throughput ?

*Cons:  If the size of the pool is too large (compared to hardware capacity or to processing needs), there might be an unnecessary switching overhead for unused threads.

*Typical use case:  handling work processes for queued input. More here
Mixed model:

*

*can have the advantages (or the inconveniences if not careful !!) of both models. One possible approach is to size the a pool with an optimal size determined dynamically at runtime to maximize performance in view of hardware and processing needs.

*Pros & cons of hybrid models can't be analyzed in general: they must be assessed case by case.