text:
Q: send socket c ctrl+c behavior I'm witting an application based on a server and various client but I'm having a problem with the send command.
Whenever I do ctrl+c on the client side the send operation kills the thread which is in and the process running (in order to have multiple clients I set a thread to which one).
If the client ends (doing the close socket) properly the server doesn't die, but when I use the ctrl+c combination on the client both exit.
What can I do to prevent send command to have this behavior?
Thanks in Advance

A: Let me summarize what I believe your problem is: Whenever you are hitting ctrl+c to close the client, the server exits. And you want this behavior to be handled, in a way that the server does not crash as above. If this is true, kindly read on, I think I may be able to shed some light on the actual issue, it does not really have much to do with using (or not using) a proper signal handle.
When you are closing the client using ctrl+c, OS will stop the client process and close all the sockets opened by it. As part of that, a FIN will be sent to the server.
Please review your code. I believe you would have written the code in a way that it is blocked in a read() call from the socket with the client concerned. Now, when the FIN sent above reaches the server side socket, this read will return with a value of 0.
If your code does not check for this condition and tries to write something back to the client, ultimately (I skip few steps that happen intermediately) it will receive a SIGPIPE. This will cause your server to crash.
If the above scenario is true, you have 2 way outs:
1. check for read() returning 0 and gracefully continue.
2. install a signal handler for SIGPIPE.
I prefer the 1st method, btw.

A: Check out beej's guide to signals.  You need to catch and handle the signal for CTRL+C, which is SIGINT (Terminal interrupt signal).

A: In order to close the socket connection and properly terminate your client program on ctrl-c, you may need to provide an appropriate signal handler for SIGINT.  This is accomplished using the signal() or preferably, sigaction() functions.
This question and its answers may be of interest: How should I close a socket in a signal handler?
On your server program, you should be checking for errors on every function involving the socket such as accept() or recv()/read() by checking the function's return value.  If the return value from the function indicates an error (usually -1), look at errno.  The value of errno should provide some indication as to the nature of the error and allow the error case to be handled appropriately.  This should help you to better handle the condition where the connection is lost when the client application terminates unexpectedly.


text:
Q: Windows 7 random black screen when idle Occasionally, when I'm away from my computer for about 5 minutes, the computer screen will go black and all USB devices (keyboard/mouse) will lose power. Attempting to move the mouse or pressing keys does not 'wake up' the computer.
This only started happening a few days ago but I'm not sure what changes I did could have caused this and I uninstalled programs (one by one) I installed before it started happening, but still having the same issue.
The one thing I noticed different about my computer since it started happening is i've been getting random survey popups from www.insightexpress.com.
I ran Microsoft Security Essentials scan, it picked up some Java related malware, I removed it but still the same issue. I'm running MBAM right now and will run SAS after.
Edit: I just updated drivers for motherboard and video card and ran virus scans, still having the same issue.

A: How are you waking up your computer when it goes to sleep (black screen)?
Temperature can cause your problem, as can several other things, but since temperature is easy to monitor, I'll make two recommendations on temp monitoring:

*

*http://www.alcpu.com/CoreTemp/
and a program which supplies much more info about other matters but which is a convenient program from temp monitoring is:

*

*http://www.piriform.com/speccy
Both of these programs are free. I've used both ,and in fact, coretemp is running at this very moment on this machine.
Following is info on POWERCFG which you run from an elevated command prompt:
Devices which you can enable/disable wake
POWERCFG –DEVICEQUERY WAKE_PROGRAMMABLE

Example:
C:\>powercfg -devicequery wake_programmmable
Realtek PCIe FE Family Controller
HID-compliant mouse (004)
TOSHIBA Software Modem

Enable a programmable device to wake your machine
POWERCFG –DEVICEENABLEWAKE <devicename>

Example:
C:\>powercfg -deviceenablewake "TOSHIBA Software Modem"

List of all devices which can wake your machine
powercfg –devicequery wake_armed

Example:
C:\>powercfg -devicequery wake_armed
HID-compliant mouse (004)
TOSHIBA Software Modem

More information for you

*

*WIN, type DEVMGMT.MSC

*This will bring up the device manager.

*Now go down the tree till you find Universal Serial Bus Controllers.

*Take a look at each and every one of the USB Root Hub entries.

*Right-click on the USB Root Hub entry.

*choose Properties

*Power Management tab

*UNCHECK Allow the computer to turn off this device to save power.

A: My tower is a Coolermaster HAF 932 and the problem was with the front-panel.
It seems there's some wiring issues that causes any type of static to trigger something in the motherboard.
It turns out that when I would walk away from my computer and pass by my tower (within inches) the computer screen goes black. I only assumed the issue happened when it was idle because I never looked back immediately after I left my computer.
I was able to reproduce the issue by just moving my hand in front of the front-panel which caused the black screen.
I called Coolermaster and they replaced the front-panel and it works fine.

A: check your power option (right click on desktop -> go to screen saver tab -> press power option bottom )

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use loops to instantiate and render objects/shapes using JavaScript and Canvas Using Javascript and canvas, I'm trying to create a loop that will instantiate a new "ball" (a circle that comes on screen) and also add it to an array and if possible reprint it to the canvas. I want the loop to repeat 20 times, adding 20 objects/"balls" to the array, and also rendering it to the canvas. Right now what I have, or as far as I have been able to figure out, is how to manually instantiate a new ball, store it in an array, and render it. I haven't been able to figure out how to properly incorporate the loop to do it for me. Any advice will help, thank you.
let ball1;
let ball2;

let balls=[];

function setup() {
  createCanvas(800, 600);
  ball1=new Ball();
  ball2=new Ball();
}

function drawBackground() {
  background(80);
}

function draw() {
  drawBackground();

  balls.push(ball1);
  balls.push(ball2);
  balls[0].render();
  balls[1].render();
}

class Ball{
  constructor(){
    this.size=random(25,75);
    //colors
    this.r=random(0,255);
    this.g=random(0,255);
    this.b=random(0,255);

    //position
    this.xpos=random(20,780);
    this.ypos=random(20,580);
  }

  render(){
    fill(this.r,this.g,this.b);
    ellipse(this.xpos, this.ypos, this.size,this.size);
  }

}

A: You can use a for loop and populate an array of "balls". You can call whatever method each instance of class Ball has from the array.

let balls = [];

function setup(number_of_balls) {
  createCanvas(800, 600);
  for (let i=0; i<number_of_balls; i++){
    balls.push(new Ball())
  }
}

function createCanvas(w, h) {
  console.log('canvas created!')
}

function draw(number_of_balls) {
  for (let i=0; i<number_of_balls; i++){
    balls[i].render()
  }
}

class Ball{
  constructor(){
    // construct the ball
  }
  render(){
    console.log('ball rendered')
  }
}

// initialize
setup(20)
draw(20)


text:
Q: Fast query to do normalization on SQL data I have some data that I want to normalize. Specifically I'm normalizing it so I can process the portions getting normalized without having to worry about duplicates. What I'm doing is:
INSERT INTO new_table (a, b, c)
    SELECT DISTINCT a,b,c
    FROM old_table;

UPDATE old_table
SET abc_id = new_table.id
FROM new_table
WHERE new_table.a = old_table.a
  AND new_table.b = old_table.b
  AND new_table.c = old_table.c;

First off, it seems as if there should be a better way of doing this. It seems that the inherent process of finding the distinct data could produce a list of the members that belong to it. Second, and more important, the INSERT takes a couple and the UPDATE takes FOREVER (I don't actually have a value for how long it takes yet because it's still running). I'm using postgresql. Is there a better way of doing this (perhaps all in one query).

A: This is my other answer, extended to three columns:
        -- Some test data
CREATE TABLE the_table
        ( id SERIAL NOT NULL PRIMARY KEY
        , name varchar
        , a INTEGER
        , b varchar
        , c varchar
        );
INSERT INTO the_table(name, a,b,c) VALUES
 ( 'Chimpanzee' , 1, 'mammals', 'apes' )
,( 'Urang Utang' , 1, 'mammals', 'apes' )
,( 'Homo Sapiens' , 1, 'mammals', 'apes' )
,( 'Mouse' , 2, 'mammals', 'rodents' )
,( 'Rat' , 2, 'mammals', 'rodents' )
,( 'Cat' , 3, 'mammals', 'felix' )
,( 'Dog' , 3, 'mammals', 'canae' )
        ;

        -- [empty] table to contain the "squeezed out" domain {a,b,c}
CREATE TABLE abc_table
        ( id SERIAL NOT NULL PRIMARY KEY
        , a INTEGER
        , b varchar
        , c varchar
        , UNIQUE (a,b,c)
        );

        -- The original table needs a "link" to the new table
ALTER TABLE the_table
        ADD column abc_id INTEGER -- NOT NULL
        REFERENCES abc_table(id)
        ;
        -- FK constraints are helped a lot by a supportive index.
CREATE INDEX abc_table_fk ON the_table (abc_id);

        -- Chained query to:
        -- * populate the domain table
        -- * initialize the FK column in the original table
WITH ins AS (
        INSERT INTO abc_table(a,b,c)
        SELECT DISTINCT a,b,c
        FROM the_table a
        RETURNING *
        )
UPDATE the_table ani
SET abc_id = ins.id
FROM ins
WHERE ins.a = ani.a
AND ins.b = ani.b
AND ins.c = ani.c
        ;

        -- Now that we have the FK pointing to the new table,
        -- we can drop the redundant columns.
ALTER TABLE the_table DROP COLUMN a, DROP COLUMN b, DROP COLUMN c;

SELECT * FROM the_table;
SELECT * FROM abc_table;

        -- show it to the world
SELECT a.*
        , c.a, c.b, c.c
FROM the_table a
JOIN abc_table c ON c.id = a.abc_id
        ;

Results:
CREATE TABLE
INSERT 0 7
CREATE TABLE
ALTER TABLE
CREATE INDEX
UPDATE 7
ALTER TABLE
 id |     name     | abc_id
----+--------------+--------
  1 | Chimpanzee   |      4
  2 | Urang Utang  |      4
  3 | Homo Sapiens |      4
  4 | Mouse        |      3
  5 | Rat          |      3
  6 | Cat          |      1
  7 | Dog          |      2
(7 rows)

 id | a |    b    |    c
----+---+---------+---------
  1 | 3 | mammals | felix
  2 | 3 | mammals | canae
  3 | 2 | mammals | rodents
  4 | 1 | mammals | apes
(4 rows)

 id |     name     | abc_id | a |    b    |    c
----+--------------+--------+---+---------+---------
  1 | Chimpanzee   |      4 | 1 | mammals | apes
  2 | Urang Utang  |      4 | 1 | mammals | apes
  3 | Homo Sapiens |      4 | 1 | mammals | apes
  4 | Mouse        |      3 | 2 | mammals | rodents
  5 | Rat          |      3 | 2 | mammals | rodents
  6 | Cat          |      1 | 3 | mammals | felix
  7 | Dog          |      2 | 3 | mammals | canae
(7 rows)

A: Came up with a way to do this on my own:
BEGIN;

CREATE TEMPORARY TABLE new_table_temp (
    LIKE new_table,
    old_ids integer[]
)
ON COMMIT DROP;

INSERT INTO new_table_temp (a, b, c, old_ids)
    SELECT a, b, c, array_ag(id) AS old_ids
    FROM old_table
    GROUP BY a, b, c;

INSERT INTO new_table (id, a, b, c)
    SELECT id, a, b, c
    FROM new_table_temp;

UPDATE old_table
SET abc_id = new_table_temp.id
FROM new_table_temp
WHERE old_table.id = ANY(new_table_temp.old_ids);

COMMIT;

This at least is what I was looking for. I'll update this as to whether it worked quickly. The EXPLAIN seems to form a sensible plan, so I'm hopeful.


text:
Q: Is there any Portable IronPython Availabe? I have developed an application where a small part of the solution is done in ironpython, but when I am migrating to production they (client) are not giving permission to install ironpython.
I am trying to get any portable version of IronPython. So that without installing I can run IronP` code.
Please Help.

A: There is no need to MSI-install IronPython on the clients you are deploying your application to.
Just XCOPY deploy your application as well as required portions of IronPython (e.g. by grabbing a current ZIP release or getting files from your local installation).
The required files will at least include

*

*IronPython.dll,

*Microsoft.Dynamic.dll,

*Microsoft.Scripting.dll and

*Microsoft.Scripting.Metadata.dll
from the correct Platforms-subfolder (e.g. Net45).
If the python standard library is used in your python code (or needs to be available to dynamically loaded code) the Lib-folder (or a subset) has to be included as well.
Should your application be deployed via MSI or a similar mechanism just include relevant IronPython files instead of XCOPYing.


text:
Q: One large database vs several smaller databases We currently have a single large database for use in reporting. This contains multiple tables, of which only some are related.
For example, we have 5 tables for one division, 2 tables from another division, etc. Data can flow between divisions, but there is not a structural link between the tables - no foreign key relationships, no duplication of tables.
We also have some lookup tables that are used by procedures that populate a lot of the tables in each division - calendar, postcodes, that kind of thing.
Is this best as a single large database, or separated out into smaller databases with thematically linked tables?  These tables will grow, and the number of them will increase as new divisions are set up.  We will notice any degradation over time, or is this so small as to be insignificant?
Any advice or pointers on things to read are gratefully received.

A: First, define what "large" is. For the rest of your career, you're always going to be working with what you think is big data, and the volumes will keep growing. However, what seems big to you may not seem all that big to others.
Second, ask about backup/restore. Odds are, if you need to do a restore, you're going to want all of the objects restored to the same point in time. The easiest way to do that is to keep 'em in a separate database.
Finally, what's the problem you're trying to solve? Whenever you're thinking about doing something, ask about the problem you're trying to solve. Here, it sounds like you're just randomly looking for ways to use a tool (in this case, breaking data into separate databases.) Focus on the problem at hand, not new solutions. By adding solutions to a problem you don't have, you're only injecting complexity that will come back to bite you later (like at restore time.)


text:
Q: remap irregular to regular grid I'm using the remap function to map a irregular grid( 650 xyz-coordinates ) to a regular one ( 160x160 points from -5....5 step 1/160) but I can't seem to get it working. By the way the interpolation that I use is bicubic. Can someone please tell me if it's even possible to do it like this? thanks in advance.
using namespace cv;
using namespace POINTS;

std::ofstream file;
Mat src(400,3,CV_32F);
Mat dst(160,160,CV_32F);
Mat map_x;
Mat map_y;
int ind = 0;

Mat matx( 400, 1, CV_32F, &pointsx );
Mat maty( 400, 1, CV_32F, &pointsy );
Mat matz( 400, 1, CV_32F, &pointsz );

void matrixDump( const Mat* mat );
void createMatrix( Mat* mat );

int main()
{

 hconcat( matx, maty, matx );
 hconcat( matx, matz, src );

 map_x.create( 160,160, CV_32FC1 );
 map_y.create( 160, 160, CV_32FC1 );

 createMatrix( &map_x );
 createMatrix( &map_y );
 Mat T = map_y.t();
 remap( src, dst, map_x, T, CV_INTER_CUBIC, BORDER_CONSTANT, Scalar(0, 0, 0) );

 return 0;
}

void matrixDump( const Mat* mat )
{
    file.open("interpolation.txt");

    for( int i=0; i<mat->rows ; i++ )
    {
       for( int j=0; j<mat->cols;j++)
       {
           file << mat->at<float>(i,j) << " " ;
       }
    }
    file.close();
}

void createMatrix( Mat* mat )
{
   for( int i=0; i<mat->rows; i++)
   {
       for( int j=0; j<mat->cols; j++ )
       {
           float value = -1. + (j*2./(mat->rows-1));
           mat->at<float>(i,j) = 5. * value;
       }
   }
}

A: map_x.create( 160,160, CV_32FC1 ); is float but when you fill it you use mat.at<double>(i,j) = 5. * value; . I don't know if it solve your problem, but it should be corrected.


text:
Q: docker swarm how to get all container ip using dns? I create two service, service-a(3 replies) and service-b(5 replies).
They are in micro overlay network.
I want to get all container ip from dns.
# docker run --rm --network micro alpine nslookup service-a

But only get one ip. Is there has anyway to get all IPs address of some service using dns?

A: Use tasks.<service-name> to get all containers belonging to particular service.

A: You can use docker inspect to get the virtual IP of a service:
NETWORK_ID=$(docker network ls -q --no-trunc --filter name=micro) && docker service inspect service-a -f "{{range \$i, \$value := .Endpoint.VirtualIPs}} {{if eq \$value.NetworkID \"$NETWORK_ID\" }}{{$value.Addr}}{{end}}{{end}}"

This one line command finds the network ID then use it in a docker inspect to get only the services virtual IPs in this network, using the -f (format) parameter


text:
Q: Is there a way to update embedded entities in onetomany relation Each time I update (patch) House with collection of WorkingHours, it erase old collection. I wonder if there is an approach to force system recognize new entities and already persistant ones within the collection
#[ORM\Entity]
#[ApiResource(
    collectionOperations: [
        'post' => [
            'denormalization_context' => ['groups' => ['create:house']],
        ],
    ],
    itemOperations: [
        'get',
        'patch' => [
            'denormalization_context' => ['groups' => ['update:house']],
        ],
    ],
)]
class House
{
    ...
    #[ORM\OneToMany(mappedBy: 'house', targetEntity: WorkingHours::class, cascade: ['persist'], orphanRemoval: true)]
    #[Groups(['create:house', 'update:house', 'read:house'])]
    private Collection $workingHours;

    /**
     * @return Collection<int, WorkingHours>
     */
    public function getWorkingHours(): Collection
    {
        return $this->workingHours;
    }

    public function addWorkingHour(WorkingHours $workingHour): self
    {
        if (!$this->workingHours->contains($workingHour)) {
            $this->workingHours->add($workingHour);
            $workingHour->setHouse($this);
        }

        return $this;
    }

    public function removeWorkingHour(WorkingHours $workingHour): self
    {
        if ($this->workingHours->removeElement($workingHour)) {
            // set the owning side to null (unless already changed)
            if ($workingHour->getHouse() === $this) {
                $workingHour->setHouse(null);
            }
        }

        return $this;
    }

here is the other related class
#[ORM\Entity]
#[UniqueEntity(
    fields: ['weekDay', 'house'],
    errorPath: 'weekDay',
)]
class WorkingHours
{
    ...
    #[ORM\ManyToOne(inversedBy: 'workingHours')]
    #[ORM\JoinColumn(nullable: false)]
    private ?House $house = null;

    #[ORM\Column(type: Types::SMALLINT)]
    #[Groups(['create:house', 'update:house', 'read:house'])]
    #[Assert\NotBlank]
    private ?int $weekDay = null;

    // getters/setters are ok

I can assume that can be done in custom controller, but there might be some attributes to specify or so


text:
Q: devise_token_auth omniauth JSON response? I have a Rails 5 site which consists of 2 parts:

*

*Admin area

*API-only client area

I'm using Devise for both parts and https://github.com/lynndylanhurley/devise_token_auth gem for the API frontend.
The problem is about using the omniauth authentication. When I omniauth authenticate into the admin area - everything is ok - I get back some successful HTML-response.
But the problem is that I'm getting the same HTML-response in the API-area - but I need some JSON-response - not HTML one.
Here is my code:
config/routes.rb
Rails.application.routes.draw do

    devise_for :users, controllers: { sessions: 'users/sessions', :omniauth_callbacks => 'users/omniauth_callbacks' }

    namespace :api do

        mount_devise_token_auth_for 'User', at: 'auth', controllers: { sessions: 'api/users/sessions', :omniauth_callbacks => 'api/users/omniauth_callbacks' }

    end
end

app/models/user.rb
class User < ApplicationRecord

  # Include default devise modules.
  devise :database_authenticatable, :registerable,
          :recoverable, :rememberable, :trackable, :validatable,
          :omniauthable,
          :omniauth_providers => [:facebook, :vkontakte]

  include DeviseTokenAuth::Concerns::User

  devise :omniauthable

  def self.from_omniauth_vkontakte(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      user.email = auth.extra.raw_info.first_name.to_s + "." + auth.extra.raw_info.last_name.to_s + '@vk.com'
      user.password = Devise.friendly_token[0,20]
    end
  end

end

app/controllers/users/omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

  def vkontakte
    @user = User.from_omniauth_vkontakte(request.env["omniauth.auth"])

    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, :kind => "Vkontakte") if is_navigational_format?
    else
      session["devise.vkontakte_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

end

config/initializers/devise.rb
Devise.setup do |config|

  config.omniauth :facebook, ENV["FACEBOOK_APP_ID"], ENV["FACEBOOK_APP_SECRET"], provider_ignores_state: true

  config.omniauth :vkontakte, ENV["VKONTAKTE_APP_ID"], ENV["VKONTAKTE_APP_SECRET"]

end

Gemfile
gem 'omniauth'
gem 'omniauth-facebook'
gem 'omniauth-vkontakte'

Gemfile.lock
devise (4.3.0)
devise_token_auth (0.1.42)

Here's my log:
Started GET "/api/auth/vkontakte" for 127.0.0.1 at 2017-06-20 17:34:23
+0300
Started GET "/omniauth/vkontakte?namespace_name=api&resource_class=User" for
127.0.0.1 at 2017-06-20 17:34:23 +0300
I, [2017-06-20T17:34:23.237270 #15747]  INFO -- omniauth: (vkontakte) Request phase initiated.
Started GET "/omniauth/vkontakte/callback?code=0b8446c5fe6873bb12&state=52254649eb899e3b743779a1a4afc0304f249a6dd90b4415" for 127.0.0.1 at 2017-06-20 17:34:23 +0300
I, [2017-06-20T17:34:23.672200 #15747]  INFO -- omniauth: (vkontakte) Callback phase initiated. Processing by Users::OmniauthCallbacksController#vkontakte as */*   Parameters: {"code"=>"0b8446c5fe6873bb12", "state"=>"52254649eb899e3b743779a1a4afc0304f249a6dd90b4415"}

I guess that the problem is about a so-called "callback" url. I don't understand where it is set. It is obvious from the log that at the end of the auth process the GET "/omniauth/vkontakte/callback..." query is called. And probably it is called always - no matter if I initiated the oath sequence from admin or api client area.
I use Chrome Postman to make the API query http://localhost:3000/api/auth/vkontakte - and I get the HTML-response back ("successful login etc.") - but I need surely some JSON-response.
Is there a way to dynamically change the callback path depending on some precondition?
Is the callback query somewhat different depending on from where the oath procedure was initiated?
EDIT1:
This is not a single problem here unfortunately. Looks like the oauth is simply not implemented in the https://github.com/lynndylanhurley/devise_token_auth gem. So, even if I succeed to switch the oauth login procedure to the JSON way - how do I login the user the devise_token_auth-way - generating 3 tokens etc...? The app/controllers/users/omniauth_callbacks_controller.rb needs to be totally reimlemented.

A: You can render json from your OmniauthCallbacksController based on some extra parameter provided when your request a connection from the API for example.
These extra parameters will be availables in this hash request.env["omniauth.params"].
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

  def vkontakte
    @user = User.from_omniauth_vkontakte(request.env["omniauth.auth"])

    if @user.persisted?
      sign_in @user, :event => :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, :kind => "Vkontakte") if is_navigational_format?

      if request.env["omniauth.params"]["apiRequest"]
        render status: 200, json: { message: "Login success" }
      else
        redirect_to after_sign_in_path_for(@user)
      end
    else
      session["devise.vkontakte_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

end

You can this extra parameters by calling the auth helper with additional parameters, they will be passed to your OmniauthController : user_vkontakte_omniauth_authorize_path(api_request: true) (Or whatever your route helper is)

A: I ended up implementing my own oauth callback procedure - instead of using one from the devise_token_auth gem.
The devise_token_auth gem does contain the oauth authentication - but it appears to be not working properly.
Here are my code changes:
config/routes.rb
Rails.application.routes.draw do

    devise_for :users, controllers: { sessions: 'users/sessions', :omniauth_callbacks => 'users/omniauth_callbacks' }

    namespace :api do

        mount_devise_token_auth_for 'User', at: 'auth', controllers: { sessions: 'api/users/sessions'}

    end
end

app/controllers/users/omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  include DeviseTokenAuth::Concerns::SetUserByToken

  def vkontakte
    @user = User.from_omniauth_vkontakte(request.env["omniauth.auth"])

    namespace_name = request.env["omniauth.params"]["namespace_name"]

    if @user.persisted?

      if namespace_name && namespace_name == "api"

        @client_id = SecureRandom.urlsafe_base64(nil, false)
        @token     = SecureRandom.urlsafe_base64(nil, false)

        @user.tokens[@client_id] = {
          token: BCrypt::Password.create(@token),
          expiry: (Time.now + DeviseTokenAuth.token_lifespan).to_i
        }
        @user.save

        @resource = @user # trade-off for "update_auth_header" defined in "DeviseTokenAuth::Concerns::SetUserByToken"

        sign_in(:user, @user, store: false, bypass: false)

        render json: @user

      else

        sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
        set_flash_message(:notice, :success, :kind => "Vkontakte") if is_navigational_format?

      end

    else
      session["devise.vkontakte_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

end

The inclusion of include DeviseTokenAuth::Concerns::SetUserByToken provides 5 auth headers in response:
access-token →BeX35KJfYVheKifFdwMPag
client →96a_7jXewCThas3mpe-NhA
expiry →1499340863
token-type →Bearer
uid →376449571

But the response still lacks these headers (available at a common sign-in):
Access-Control-Allow-Credentials →true
Access-Control-Allow-Methods →GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Origin →chrome-extension://aicmkgpgakddgnaphhhpliifpcfhicfo
Access-Control-Max-Age →1728000

I don't know whether they are important and if yes - how to provide them.
PS The same identical approach works with Facebook too.


text:
Q: Detect TFS Build vs. Visual Studio build Is it possible to detect whether or not the current build is executing from Visual Studio rather than an automated build with TFS without creating a separate solution configuration? I'm wondering if I can exclude certain Post Build Events if the build is running on TFS 2013, but if possible I would like to avoid a whole separate configuration.

A: You do not need to edit the CSProj file: just use CMD.EXE syntax in Visual Studio Post-Build events
You can test if running inside Visual Studio
IF "$(BuildingInsideVisualStudio)"=="true" (
  …
)

or inside TFS Build (2013 or later)
IF "$(TF_BUILD)"=="True" (
  …
)

See the discussion a
TFS 2010 Build Automation and post-build event and Team Foundation Build environment variables.

A: It is possible, and I finally found out how:

*

*Unload the project in question, that has a PostBuildEvent defined.

*Edit the .csproj file.

*Locate the PostBuildEvent XML element, and add a Condition attribute like the following:
<PostBuildEvent Condition="'$(BuildingInsideVisualStudio)' == 'true'">
At this point the PostBuildEvent will only execute when built with Visual Studio.
This answer and other answers to that question were helpful.
This particular property is briefly mentioned on this MSDN page as well.


text:
Q: Highlight cell border color when click, change back when click to others I have the code below:

function highlight(cell){
  cell.style.borderColor = "red";
 }

 function originalColor(cell){
  cell.style.borderColor = "black";
 }
td{
  cursor: pointer;
 }

 Cell 1
 Cell 2
 Cell 3

 Cell 4
 Cell 5
 Cell 6

 Cell 7
 Cell 8
 Cell 9

It will highlight the border to red when click, when click to the other cell, it suppose change back to black color, but it doesn't work, I try onmouseup, onmouseover, it doesn't work as what I want.
The technique I'hv tried is using tabindex, it works; but that can highlight one cell, if I try to select 2 cells at the same time, it doesn't work. Anyone can help?

A: After your clarifying comment, if I understand correctly, you want to highlight a cell when you click it, and remove the highlighting if you choose to by clicking another element. If not, please clarify again. If that's indeed the case though, then the following code will work by traversing up the DOM to the parent table, then iterating through all the cells and taking appropriate action:

function toggleBorderColor(c) {
    cells = c.parentElement.parentElement.getElementsByTagName('td');
    for (var i in cells) {
       var cell = cells.item(i);
       cell.style.borderColor = (cell != c) ? "" : "red";
    }
}
td {
 cursor: pointer;
}

 Cell 1
 Cell 2
 Cell 3

 Cell 4
 Cell 5
 Cell 6

 Cell 7
 Cell 8
 Cell 9

A:

    var redNow = 1;
    function highlight(cell) {
        redNow == 1 ? redNow = 0 : redNow.style.borderColor = "black";
        redNow = cell;
        cell.style.borderColor = "red";
    }
    td {
      cursor: pointer;
     }

        Cell 1
        Cell 2
        Cell 3

        Cell 4
        Cell 5
        Cell 6

        Cell 7
        Cell 8
        Cell 9


text:
Q: How to know the array reference value stored in memory? I am looking for a reference of the array that we assign
sup.
array = [1,2,3,4]

array1 = array
array2 = array

now, array1 and array2 hold ref. of the array so my question is how to know that this 2 array holds which object reference? in a value ? in a pointer? memory location?


text:
Q: Noether nomalization theorem Noether Normalization theorem
For finitely generated $k$-algebra $A$, there is a polynomial ring $k[x_1,x_2,\cdots ,x_d]$ over which $A$ is finite.
I want to know the specific geometric background of it. It's easy to know that the homomorphism from the polynomial ring to $A$ implies a morphism from a variety whose coordinates ring is $A$ to a linear subspace of some affine space. But where to find the reflection of finite?


text:
Q: Introduce NA in a value text exist into two columns Having a df like this:
df_in <- data.frame(x = c('x1','x2','x3','x4'),
                    col1 = c('http://youtube.com/something','NA','https://www.yahooexample.com','https://www.yahooexample2.com'),
                    col2 = c('www.youtube.com/searcht', 'http://www.bbcnews2.com?id=321','NA','https://google.com/text'))

What kind of grep should I implement in order to check col1 and col2 and if "youtube" phrase exist in both columns in the same row replace it with NA.
Example of expected output
> df_in <- data.frame(x = c('x1','x2','x3','x4'),
+                     col1 = c('NA','NA','https://www.yahooexample.com','https://www.yahooexample2.com'),
+                     col2 = c('NA', 'http://www.bbcnews2.com?id=321','NA','https://google.com/text'))
> df_in
   x                          col1                           col2
1 x1                            NA                             NA
2 x2                            NA http://www.bbcnews2.com?id=321
3 x3  https://www.yahooexample.com                             NA
4 x4 https://www.yahooexample2.com        https://google.com/text

A: Another option is to use rowSums with sapply and grepl:
df_in[rowSums(sapply(df_in, grepl, pattern = 'youtube')) > 1, 2:3] <- 'NA'

which gives:

> df_in
   x                          col1                           col2
1 x1                            NA                             NA
2 x2                            NA http://www.bbcnews2.com?id=321
3 x3  https://www.yahooexample.com                             NA
4 x4 https://www.yahooexample2.com        https://google.com/text

A: you can try a tidyverse solution:
library(tidyverse)
df_in %>%
  unite(a,starts_with("col")) %>%
  mutate(a=ifelse(str_count(a,"youtube")>1, "NA_NA", a)) %>%
  separate(a, c("col1","col2"), "_")
   x                          col1                           col2
1 x1                            NA                             NA
2 x2                            NA http://www.bbcnews2.com?id=321
3 x3  https://www.yahooexample.com                             NA
4 x4 https://www.yahooexample2.com        https://google.com/text

In base R I would do:
df_out <- df_in
df_out[,-1] <-  t(apply(df_in[,-1], 1, function(x){
      tmp <- grepl("youtube",x[1]) + grepl("youtube",x[2])
      if(tmp > 1) rep("NA",2) else x

  }
    ))
df_out
   x                          col1                           col2
1 x1                            NA                             NA
2 x2                            NA http://www.bbcnews2.com?id=321
3 x3  https://www.yahooexample.com                             NA
4 x4 https://www.yahooexample2.com        https://google.com/text

The idea is to count the occurrence of "youtube". If there are n=2 per row, replace the entries with NA otherwise leave them as they are.

A: Not an improvement on @Jaap's answer, but an alternative:
df_in[do.call(`&`,lapply(df_in[,2:3], grepl, pattern = "youtube")), 2:3] <- 'NA'


text:
Q: Can D and H form an 'in materials' version of the electromagnetic tensor? In analogy to the electromagnetic tensor, with the components defined as the electric field $E$ and magnetic field $B$ as such:
$F^{ab} = \begin{bmatrix}
0 & -E_x/c & -E_y/c & -E_z/c \\
E_x/c & 0 & -B_z & B_y \\
E_y/c & B_z & 0 & -B_x \\
E_z/c & -B_y & B_x & 0
\end{bmatrix}$
Can one form a relativistic tensor from the electric displacement field $D$ and magnetizing field $H$ like so:
$\bar{F}^{ab} = \begin{bmatrix}
0 & -D_x/c & -D_y/c & -D_z/c \\
D_x/c & 0 & -H_z & H_y \\
D_y/c & H_z & 0 & -H_x \\
D_z/c & -H_y & H_x & 0
\end{bmatrix}$
and thus obtain an "electromagnetic tensor" that can be easily used to handle the effects of fields in materials?
Since $D = \epsilon_0 E + P$ and $H = \frac{1}{\mu_0}B - M$, this is equivalent to asking if $P$ and $M$ can be used to form a relativistic tensor.

A: Yes, you can form such a tensor with $D$ and $H$ but it is not as useful and natural as the tensor with $E$ and $B$ because $E$ and $B$ are the actual physical fields that naturally transform into each other by Lorentz transformations.
On the other hand, you may declare that $D$ and $H$ transform into each other by the Lorentz transformations but it is not too useful because these fields are only useful to describe fields inside a material, and the presence of this material spontaneously breaks the Lorentz symmetry, anyway.
This is related to some recent questions on this server about electrodynamics of moving media. $D$ and $H$ are normally used, together with the well-known equations they satisfy, only in the rest frame of a material. If the material is moving, the whole analysis has to be redone. To be sure that we do it right, we should return to the actual $B$ and $E$ field and if we define new ones to simplify our life, we shouldn't guess the equations for these new fields: we should derive them from the equations for the vacuum fields $E,B$ and the actual charge densities and currents, including the bound ones.
The resulting Maxwell's equations for a medium, which include $B,E,D,H$, are not Lorentz-covariant, anyway - because the material picks a preferred frame. To introduce new fields $D,H$ is just a bookeeping device to simplify some calculations - and it only works nicely in the medium's rest frame.

A: I'm not 100% sure, but I think the answer is yes. Here's my reasoning.
The physical effects of $\mathbf{P,M}$ result from the bound charges and currents they produce: $\rho_b=-\nabla\cdot{\bf P}$ and ${\bf J}_b=\nabla\times{\bf M}$. I'd expect $j\equiv (\rho_b,{\bf J}_b)$ to transform as a 4-vector (after all, they are "real" charges and currents). If you define an antisymmetric tensor $P^{\mu\nu}$ out of $\mathbf{P,M}$ in the natural way, then the definitions of $\rho_b,{\bf J}_b$ reduce to $j^\mu={P^{\mu\nu}}_{,\nu}$. If $P^{\mu\nu}$ is covariant, then $j^\mu$ is automatically covariant.
That's just a plausibility argument, not a proof, but I find it pretty convincing. Let me see if I can tighten up the argument a bit. In the local rest frame of the matter, define $P^{\mu\nu}$ to be the tensor built out of $\mathbf{P,M}$ in the natural way. In any other frame, define $P^{\mu\nu}$ via Lorentz transformations. Finally, define $j^\mu={P^{\mu\nu}}_{,\nu}$. Then the four-vector $j$ gives the correct bound charges and currents in the rest frame, and hence (since everything's covariant) it gives the correct bound charges and currents in all frames. Everything that matters about $\mathbf{P,M}$ is contained in the bound charges and currents, so we're done.
The correct answer is presumably contained in Landau & Lifschitz, Electrodynamics of Continuous Media, which I've never read. If what's in there contradicts what I've said, then I'm sure that they're right and I'm wrong.

A: The answer is "yes". One has
\begin{equation}
\bar{F}^{ab} = \bar{\epsilon}_{abcd} F^{cd}
\end{equation}
where
\begin{equation}
\bar{\epsilon}^{0i0j} = \epsilon^{ij}
\end{equation}
and
\begin{equation}
\bar{\epsilon}^{ijpq} = (1/\mu)^{kr}
\end{equation}
up to a factor $c$ here and there :-) .
Here $i,j,k$ and $p,q,r$ are spatial indices such that $\hat{k}=\hat{i}\times\hat{j}$ and $\hat{r}=\hat{p}\times\hat{q}$.
See A.O. Barut, Electrodynamics and Classical Theory of Fields and Particles.


text:
Q: Mysql(version 5.6) hierarchy query all parents when nodes have more than one parent I've searched a lot to find my answer, the most related one is Finding all parents in mysql table with single query (Recursive Query)
The answer is great, but I found that this solution is not working when one node has more than one parent. Table like this:
id, node_id, parent_id
 1,       1,         2
 2,       2,         3    <-----
 3,       2,         4    <-----
 4,       4,         5
 5,       5,         6
 6,       6,         7

Notice that the line 2 and line 3, the node which has node_id=2 has more than one parent.
The answer mentioned above will only return parent id of 2, 3, 4 when node_id=1, which is not true. (Should be 2, 3, 4, 5, 6, 7)


text:
Q: Visibility IIF statement rdlcreports I have a report with a textfield "copy" in it. This should be hidden when my dataset field "isPrinted" is false.
So i tried this one under the expression of the hidden option of the textfield property:
=IIf(First(Fields!isPrinted.Value , "DataSet1")=false)

Obviously im doing something wrong, but I have no idea what.
Anyone who would be so kind to help me in the right direction here ?

A: Hidden is expecting a result to return TRUE if you want it hidden.  The IIF() is typically
IIF( some condition, return this if true, return this if false ).

So, if you want the label HIDDEN, you probably want to remove the IIF().  If the "isPrinted.Value" is a boolean, you MIGHT just be able to do based on something like
=First(Fields!isPrinted.Value, "DataSet1")

or (! logical NOT) if the reverse
=!First(Fields!isPrinted.Value, "DataSet1")


text:
Q: In Eclipse, the changes of my source code have no effect I have a strange problem in Eclipse Helios. When I alter my source code, my changes have no effect. Even if I alter the code in a way that looks uncompilable, it still can be run.
It seems that Eclipse keeps its state somewhere in the background while I edit and save my sources and commit them to svn.
I don't know what setting to look up or what else to do. I'd be glad to receive any help.

A: I was having the same problem while running a Maven project in Spring Tool Suit (which is based on Eclipse). I needed to clean and build the maven project every time to make the STS detect the new changes (what is obviously a slow and inefficient process).
So my solution was:
Pressing Alt+F5 and check Force update of Snapshots/Releases

A: As mentioned before verify your Build Automatically option in Project->Build Automatically, then clean the project so your changes will be compiled again.

A: Note : Please try this only if you have run out of other options in this thread.
So Just in case the other options like clean/rebuild listen in the other answers, do not address the problem do the following,
Close eclipse
Go to the project folder on the hard drive.
Delete the .metadata file and restart eclipse and revisit the workspace.
The class path and libraries will be re validated and the project fresh built.

A: In the Project menu, verify that Build Automatically is checked.

A: Just go to "Project->Build Automatically" and check it that's all

A: Try (re)building or saving first.

A: This is on Eclipse (Kepler).
Simple "Hello World" in Java where changes to text in println where not reflected in console when doing a run or relaunch (Build automatically was checked). When doing a second relaunch ( or saving the .java file 1st) it always showed the changes to the println.
Kristian

A: Try doing some minor changes in the JSP file. Sometimes your Tomcat server contains old cache files which it uses even if you CLEAN BUILD your project. Bringing updates in the JSP files helps Tomcat deploy the JSP file with modifications rather than using the old cache files. I faced a similar problem which was resolved the same way. Thanks to
Latest changes are not reflected in servlet (tomcat)

A: This is an old post but I had a similar issue recently which was not resolved by deleting the jar or building it. In Eclipse I tried the following:
Window --> Preference --> LIB --> Expand it and delete the jar (which is to be replaced).

This will delete the reference from the project. After that I just added it back using:
Properties --> Java Build path --> Libraries and adding the jar.

A: It's possible that you have copied the previous code from an old class  but that class-name is still same, then this file will be using the old class.
Make sure you changed the class name also..
I hope this could solve the problem.

A: Your operating system simply does not allow modifying a file while it is in use, so the compilation fails. The compiler can't remove the old executable and place a new one. Because of this, save the code and restart Eclipse, build, and run again

A: This most probably occurs when the meta data related to the workspace is corrupted. Simple solution would be to create an entirely new folder as workspace and import the project into this new workspace.
This is after you have tried all the clean build, rebuild etc.. :)


text:
Q: Can not clear cache memory in Universal Imageloader ImageGridFragment Am trying to display images in grid view from web-server using UniversalImageLoader. That code working fine. but main problem is when am seeing grid view second time it display previous URL image. Am trying this code to clear cache
    ImageLoader.getInstance().clearMemoryCache();
    ImageLoader.getInstance().clearDiscCache();

but not work.Here is my full code
public class ImageGridFragment extends AbsListViewBaseFragment {

public static final int INDEX = 1;
String description="";
 ArrayList<String> img = new ArrayList<String>();

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fr_image_grid, container, false);

    listView = (GridView) rootView.findViewById(R.id.grid);

    Bundle bundle = this.getArguments();

    description = bundle.getString("description");
    String[] separated= description.split(",");
    img.clear();
    for(int i=0;i<separated.length;i++)
    {
    img.add(separated[i]);
    }

    ImageGalleryFragment.imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()));
    ImageLoader.getInstance().clearMemoryCache();
    ImageLoader.getInstance().clearDiscCache();
    ((GridView) listView).setAdapter(new ImageAdapter(getActivity()));
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          //  Toast.makeText(getActivity().getApplicationContext(), String.valueOf(position), Toast.LENGTH_LONG).show();

           // startImagePagerActivity(position);
            ImageLoader.getInstance().clearMemoryCache();
            ImageLoader.getInstance().clearDiscCache();
            Intent intent = new Intent(getActivity(), SimpleImageActivitya.class);
            intent.putExtra(Constants.Extra.FRAGMENT_INDEX, ImagePagerFragment.INDEX);
            intent.putExtra("description", description);
            startActivity(intent);
        }
    });
    return rootView;
}

private  class ImageAdapter extends BaseAdapter {

   String[] IMAGE_URLS =  img.toArray(new String[img.size()]);

    private LayoutInflater inflater;

    private DisplayImageOptions options;

    ImageAdapter(Context context) {
        inflater = LayoutInflater.from(context);

        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_stub)
                .showImageForEmptyUri(R.drawable.ic_empty)
                .showImageOnFail(R.drawable.ic_error)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
    }

    @Override
    public int getCount() {
        return IMAGE_URLS.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        View view = convertView;
        if (view == null) {
            view = inflater.inflate(R.layout.item_grid_image, parent, false);
            holder = new ViewHolder();
            assert view != null;
            holder.imageView = (ImageView) view.findViewById(R.id.image);
            holder.progressBar = (ProgressBar) view.findViewById(R.id.progress);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }

        ImageLoader.getInstance()
                .displayImage(IMAGE_URLS[position], holder.imageView, options, new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String imageUri, View view) {
                        holder.progressBar.setProgress(0);
                        holder.progressBar.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                        holder.progressBar.setVisibility(View.GONE);
                    }

                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        holder.progressBar.setVisibility(View.GONE);

                    }
                }, new ImageLoadingProgressListener() {
                    @Override
                    public void onProgressUpdate(String imageUri, View view, int current, int total) {
                        holder.progressBar.setProgress(Math.round(100.0f * current / total));
                    }
                });

        return view;
    }
}

static class ViewHolder {
    ImageView imageView;
    ProgressBar progressBar;
}}


text:
Q: Custom keyboard shortcuts I want my app to support keyboard shortcuts. Many devices, such as Asus Transformer have external keyboard which has Ctrl key (available on API Level 11). I've made some code, to check if Ctrl key works in emulator:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if(Build.VERSION.SDK_INT>10 &&
        event.getAction()==KeyEvent.ACTION_DOWN &&
        event.isCtrlPressed()){
    String actionType="NONE";
    final int keyCode = event.getKeyCode();
    switch(keyCode){
    case KeyEvent.KEYCODE_C:
        actionType = "COPY";
        break;
    case KeyEvent.KEYCODE_V:
        actionType = "PASTE";
        break;
    case KeyEvent.KEYCODE_X:
        actionType = "CUT";
        break;
    case KeyEvent.KEYCODE_R:
        actionType = "REFRESH";
        break;
    case KeyEvent.KEYCODE_A:
        actionType = "SELECT ALL";
        break;
    }
    Toast.makeText(ctx, actionType, Toast.LENGTH_SHORT).show();
    return true;
    }
    return super.dispatchKeyEvent(event);
}

Unfortunately it doesn't work in emulator and I can't check it on real hardware.
I have two questions:
1. Would it work on device like Asus Transformer?
2. Why Ctrl key does not work in emulator?
EDIT: I tried to find an answer or solution to my problem, but neither Google nor SO helped.

A:
1. Would it work on device like Asus Transformer?

I've checked on my Asus Transformer TF101 with physical keyboard (standard docking station from Asus) and your code works fine. I think you can use it without problems.

2. Why CTRL key does not work in emulator?

Looking at the list of buttons that can be mapped (for example using emulator -keyset) I don't think that current version of emulator supports direct Ctrl key mapping, so you're out of luck here.


text:
Q: Visual Studio Code - file icon color After updating to VS Code 1.46.1. I see 2 diffs. color of .js files. There is no code change in any of the files then why 1 js file icon is yellow and others are orange. What's the meaning of these 2 different colors?

This is the default theme which is auto-enabled after installation.

A: If I look at the file name closely, All files with extension *.test.js looks orange and the other js file looks yellow. This is vs code way to differentiate the type of files. vs code knows and tries to show the difference between normal js file and .test.js files. Although we can write test cases in any js files but *.test.js files are special test cases file.
Also, check this link https://code.visualstudio.com/api/working-with-extensions/testing-extension
It says the *.test.js files have access to the VS Code API.


text:
Q: forgetting the : on a command line while installing devise So I was supposed to type this "rails generate devise:install" in the terminal. instead I typed "rails generate devise install". Does it make a difference? What should I do to repair it if there is something wrong.
I hope I'm not wasting anyone's time with a stupid question; however I've spent the better part of the past 4 months being thwarted by semi-colons that should have been colons, devastated by missing commas and heart-broken by single spelling errors. I've gotten into the habit of thinking every letter and character counts.
Thanks!

A: Yes, there's a difference. When you run rails generate devise install you're telling Devise to configure devise for model called install because here's config syntax from Devise's README:

In the following command you will replace MODEL with the class name
  used for the application's users (it's frequently User but could also
  be Admin). This will create a model (if one does not exist) and
  configure it with the default Devise modules. The generator also
  configures your config/routes.rb file to point to the Devise
  controller.
$ rails generate devise MODEL

To undo the changes just run rails destroy devise install and run it properly (with colon) after.

A: In general programs which get called from the command line parse arguments by spaces.  Rails generators are programs which generate code for your project.  They take command line arguments.  Let's see how this works in your case:
rails generate #takes the name of generator as its 1st argument
rails generate devise #tells generate to lookup the devise namespace

# the next single argument `devise:install` is parsed by generator and
# calls the install task. The colon is use by [Rake][1] to call tasks within namespace
rails generate devise:install

# As already mentioned in previous answer and in devise docs
# here install is not a sub task but an argument passed to the devise task
rails generate devise user # this is typically the model devise would use


text:
Q: How to anotate ServiceWorker with flow? I'm trying to get 100% code coverage with flow but I'm stuck with anotating my ServiceWorker. It is not throwing any errors, but all self.addEventListener(...) are marked as uncovered. For example in:
self.addEventListener("install", (event) => {
  console.log("Event: Install");

  event.waitUntil(
    //Open the cache
    caches
      .open(cacheName)
      .then((cache) => {
        //Adding the files to cache
        return cache.addAll(filesToCache).then(() => {
          console.log("All files are cached.");
          return self.skipWaiting(); //To forces the waiting service worker to become the active service worker
        });
      })
      .catch((err) => {
        console.log(err);
      })
  );
});

Even if I do something like let a = self flow will show this line as uncovered.
I tried changing self to this but that didn't help either :(
Does anyone have an idea how to fix this?


text:
Q: Yet another STL tree Quite a funny question I have.
I am working now on the HTML parser and I was using vector <HTMLTag> for all my input purposes which seemed quite fine and fast for creating tree.
In another application I need to edit HTML structure and now inserting or reordering of the elements would be extremely painful using vector so I decided to switch to more tree-like structure.
I read a few articles on trees and their implementation and I was thinking of std::map for this purpose.
Something like this:
std::map< element, *child_map >
So when I thought of inserting a tag somewhere in between and having them all ordered by some key (e.g. unique integer id) I still have a problem to update all keys in a branch after insertion.
for example:
1:SCRIPT
2:HEAD
3:BODY

When I want to insert new element "SCRIPT" after the HEAD I will need to increment Body Key to 4 and have something like this:
1:SCRIPT
2:HEAD
3:SCRIPT
4:BODY

Seems a bit cumbersome to me. Am I missing something?
As an alternative I thought of doing list<pair<>> implementation instead. Thus sorting is not determined by a key and I can add elements anywhere without any extra updates.

A: I would make the child set a member of the element and use std::list:
class Element {
/* ... */
  std::list<boost::shared_ptr<Element> > children;
/* ... */
};

That said, you might want to look into using an existing DOM library instead of rolling your own. For example, you could use htmlcxx.

A: List< pair > would work well to simulate any form of tree structure such as what you're trying to do:
list< pair< "html", list > would let you store an arbitrary number of children as well as control the order of objects in the child list.
Have fun walking this tree.


text:
Q: Zend Framework - Best Way To Autoload From /Application/Api Folder I'm trying to autoload Classes from within a folder contained in the application itself.
E.G.
/Application
    |->Models
    |->Custom
      |->Object.php

Is this the best way to do it (from bootstrap.php)?

public function _initAutoLoad()
{
    $resourceLoader = new Zend_Loader_Autoloader_Resource(array(
        'basePath'  => APPLICATION_PATH,
        'namespace' => '',
        'resourceTypes' => array(
                'custom' => array(
                    'path'      => 'custom/',
                    'namespace' => 'Custom',
                ))
    ));
}

Meaning from within any controller, I can call:

$object = new Custom_Object();

A: If you're not intending to prefix the class names with the application namespace (default Application), I'd simply put this stuff in library, eg
library/
    Custom/
        Object.php -> class Custom_Object

then add your Custom namespace to the autoloader in configuration (application.ini)
autoloadernamespaces[] = "Custom_"

If your class represents some kind of service, you could use the built-in Service resource type which is automatically autoloaded
application/
    services/
        Object.php -> class Application_Service_Object

A: Looks like the solution I had is the best... I can find anyways...


text:
Q: What string should I pass to java.lang.Long.parseLong() to return a NaN? I unfortunately cant use expressions like Long.Nan as the string is actually a return value from a different C module. Is there a string I can pass to parseLong() to return an NaN ?

A: There is no Long.NaN -- you are confused.
For Double.NaN, how about this:
public double myParseDouble(String s)
{
   double result;
   try
   {
      result = Double.parseDouble(s);
   }
   catch (NumberFormatException nfe)
   {
      result = Double.NaN;
   }
   return result;
}

(edit: and the obvious approach is to pass in any string that is an invalid double, e.g. the empty string or NaN)

A: There is no such thing as Long.NaN, which makes sense when you consider that every bit pattern within long represents a valid integer within the range of [Long.MIN_VALUE, Long.MAX_VALUE].
You might consider trying to get the bit pattern of Double.NaN instead.

A: Long.Nan? That doesn't exist in Java. You only have Long.MIN_VALUE and Long.MAX_VALUE
"Nan" as argument to Double.parseDouble(String) gives Double.NaN as value if that is what you want.

A: java.lang.Long represent 64-bit signed integral value, while NaN is introduced only in floating-point computations. That being said there is no special string return Long NaN, but you can for instance use:
double notANumber = java.lang.Double.NaN;

A: Java only has a concept of NaN for floating point datatypes, not integer ones such as Long.


text:
Q: Changing the "Upload failed" Message I would like to change the "Upload failed" message to one returned from my server-side processing.
I can see the message I want in the onError callback but I'm not sure how to used that instead of the default message.
Thoughts, examples or further reading advice welcome (new here).

A: The implementation of what you're trying to do depends on whether you are using Fine Uploader Basic/Core or Regular/UI. This is because UI mode offers some extra goodies for displaying error messages and such.
A few properties/options that may benefit you:
Fine Uploader Basic/Core mode

*

*text.defaultResponseError

Message sent to the onError callback if no specific information about the error can be determined. This is used if the server indicates failure in the response but does not include an "error" property in the response and the error code is 200 (XHR only)

var uploader = new qq.FineUploaderBasic({
    /* ... */
    text: {
        defaultResponseError: "Oh noes! Upload fail."
    }
});

The documentation on 'text'

Fine Uploader Regular/UI mode

*

*failedUploadTextDisplay.mode option

Valid values are "default" (display the text defined in failUploadText next to each failed file), "none" (don't display any text next to a failed file), and "custom" (display error response text from the server next to the failed file or Blob).

*failedUploadTextDisplay.responseProperty option

The property from the server response containing the error text to display next to the failed file or Blob. This is ignored unless mode is "custom".

var uploader = new qq.FineUploader({
    /* ... */
    text: {
        defaultResponseError: "Oh noes! Upload fail."
    },
    failedUploadTextDisplay: {
        mode: 'custom',              // Display error responses from the server.
        responseProperty: 'errorMsg' // Default is 'error', change this to match the
                                     // property that contains the error message from
                                     // your server
    }
});

The documentation on failedUploadTextDisplay

A: For people who still use FineUploaded and above does not work, that is because the key is not changed to failUpload.
Usage for a custom message on UI end would be
text: {
  failUpload: 'Your upload faile message goes here
},

More details can be found here - https://docs.fineuploader.com/branch/master/upgrading-to-4.html
If you want to display the server-side message, you can do it the below way:
failedUploadTextDisplay {
  mode: 'custom',
  responseProperty: 'server side error key goes here'
}

If you wish to completely remove it, i.e, not show the message below file if file upload has failed, use below
failedUploadTextDisplay {
  mode: 'none'
}


text:
Q: Linking a library which is compile time linked to another library I have a binary1 which is compile time linked to another library1.so
To add some functionality I have created library2.so which uses libas_sdk.so.
Functionality in library2.so works only if dlopen(libas_sdk.so) is success, else it returns normally and does other work.
Now library1.so has to use library2.so if required and use the new functionality.
I have tried multiple compile and link options but getting ldd or unresolved symbol errors.
Please suggest.

A: dlopen() will return success, if the lib is already linked in.
Because library1.so has to use library2.so, you need to link both of them to binary1. (-llibrary1 -llibrary2)
From your question seems, that library2.so links in libas_sdk.so runtime. It happens probably when you call its some init_library2() or some function with some configuration data.
I think the problem is not with your linking, but with your binary1. This initialization of library2 (or library1) is what you do too early, or too late. IMHO your binary1 should be linked with a simple -llibrary1 -llibrary2 .


text:
Q: How do I extract dates from .rtf in R I have articles in .rtf from which I want to extract the dates. The article looks like this:

The first line is the title, followed by a blank line. Then it lists the following, each on its own line:

*

*The number of words

*The date

*The news agency

*The news agency's acronymn

*The language

*Copyright information

I have tried the following code but it doesn't seem to work. Seems like the problem is in the one to extract the date.
##First I read the file using this code:
htmlText <- read_file(paste("/Users/adhyantarahma/Desktop/Factiva-20190905-0316.rtf"))

##then I removed new lines tags
removeNewLines <- gsub("\n"," ",htmlText)

##and I changed " to ' in text
cleanLines <- gsub("\"", "'", removeNewLines)

print(cleanLines)

##the relevant part of cleanLines look like this
#\\ 347 words\\ 9 April 2016\\ FARS News Agency\\ FARSNA\\ English\\

##then I used this to extract date
date <- str_extract_all(htmlText, "words \\d{1,2} [A-Z][a-z]+ \\d{4}")[[1]]

But it doesn't seem to pick up the date. When I run it, it always says that there is no character.
What should I do so that I can pick up the date?

A: I'm just following your solution and turning it into a solution with slight modification.
library(readr)
library(stringr)
htmlText <- read_file("Factiva-20190905-0316.rtf")

# -------------------------------------------------------------------------
              # output -- htmlText
# [1] "347 words\n9 April 2016\nFARS News Agency\nFARSNA\nEnglish\n"

# -------------------------------------------------------------------------

#replace "\n" with a space
removeNewLines <- gsub("\n"," ",htmlText)

# -------------------------------------------------------------------------
            # output -- removeNewLines
# [1] "347 words 9 April 2016 FARS News Agency FARSNA English "

# -------------------------------------------------------------------------

       # extract the date from removedNewLines
my_date <- str_extract_all(removeNewLines, "\\d{1,2} [A-Z][a-z]+ \\d{4}")[[1]]
        # output -- my_date
#[1] "9 April 2016"

# -------------------------------------------------------------------------


text:
Q: Using an iPhone as FIDO2 hardware token? There are many FIDO2 security hardware tokens on the market that allow password-less login on web sites e.g. on your PC. For example from YubiKey, FEITIAN, ePass...
These token communicate for example via NFC with the PC. But I don't want to use an extra token, when I have my iPhone which could do the job as well.
Is it possible to use an iPhone as a FIDO2 hardware token instead of those tiny hardware FIDO2 tokens? Is this possible with a plain iPhone running iOS 14.6 or do I need a special app so that the iPhone could act as authenticator?
I am aware that this would not work for authentication of web site in Safari on the iPhone, I only want the iPhone for FIDO2 authentication of my PC.


text:
Q: How to load primefaces dialog in selenium? i am trying to load primefaces dialog inside selenium test as follows:
-the primefaces code:
   <p:commandLink id="iam_interested1" styleClass="iam_interested"
   oncomplete="signUpDialog.show()"
   actionListener="#{leadsBean.initSaveAction()}"
   update=":betasignup">
   I'm interested
   </p:commandLink>

-the generate code for above primefaces code is:
<a id="headerForm:iam_interested1" href="#" class="ui-commandlink ui-widget iam_interested" onclick="PrimeFaces.ab({source:'headerForm:iam_interested1',update:'betasignup',oncomplete:function(xhr,status,args){signUpDialog.show();}});return false;">
                            I'm interested
                        </a>

the selenium code:
    @Test
    public void test() throws InterruptedException {
        driver.get("http://localhost:8080/MyApp/index.xhtml");
        WebElement dialogLink = driver.findElement(By
                .className("iam_interested"));
        dialogLink.click();
        String currentWindowHandle = driver.getWindowHandle();
        String popupWindowHandle  =  getPopupWindowHandle(driver,dialogLink);
        driver.switchTo().window(popupWindowHandle);
        (new WebDriverWait(driver, 5)).
        until(ExpectedConditions.elementToBeClickable(By.className("ui-dialog-titlebar-close")));
        driver.findElement(By.className("ui-dialog-titlebar-close")).click();
        driver.switchTo().window(currentWindowHandle);

    }

    String getPopupWindowHandle(WebDriver driver, WebElement element) {

        String popupHandle = null;
        int maxTimeToWait = 5000;
        int timeInterval = 1000;
        int timeElasped = 0;
        int attempt;

        // get all the window handles before the popup window appears
        Set<String> beforePopup = driver.getWindowHandles();

        // click the link which creates the popup window
        element.click();
        System.out.println("element clicked");

        attempt = 1;
        while (timeElasped < maxTimeToWait) {

            // get all the window handles after the popup window appears
            Set<String> afterPopup = driver.getWindowHandles();

            // remove all the handles from before the popup window appears
            afterPopup.removeAll(beforePopup);

            // there should be only one window handle left
            if (afterPopup.size() == 1) {
                System.out.println("Popup window found");
                popupHandle = (String) afterPopup.toArray()[0];
                break;
            }

            try {
                Thread.sleep(timeInterval);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            timeElasped = timeInterval * attempt;
            attempt++;
        }
        if (popupHandle.isEmpty() || popupHandle == null) {
            System.out.println("No Popup Window found");
        }

        return popupHandle;

    }

but the  dialog doesn't load, and instead i get the exception:
org.openqa.selenium.interactions.MoveTargetOutOfBoundsException: Element cannot be scrolled into view:http://localhost:8080/MyApp/betasignup_index.xhtml#
    Command duration or timeout: 40 milliseconds
    Build info: version: '2.33.0', revision: '4ecaf82108b2a6cc6f006aae81961236eba93358', time: '2013-05-22 12:00:17'
    System info: os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_25'
    Session ID: 1ff0ca5a-5906-412f-b2a7-6e170a7d8932
    Driver info: org.openqa.selenium.firefox.FirefoxDriver
    Capabilities [{platform=XP, databaseEnabled=true, cssSelectorsEnabled=true, javascriptEnabled=true, acceptSslCerts=true, handlesAlerts=true, browserName=firefox, browserConnectionEnabled=true, nativeEvents=true, webStorageEnabled=true, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=21.0}]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:191)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:554)
        at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268)
        at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:79)
        at com.motivosity.selenium.HomeTest.addingOneUser(HomeTest.java:32)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
        at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:80)
        at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:47)
        at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69)
        at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:49)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
        at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
        at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
        at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
        at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
        at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:103)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
        at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
        at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:355)
        at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:66)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:724)

please advise how to resolve it.

A: Issue was that the generated <a> component has multiple generated classes beside the declared one, so when i tried to get the link element by id instead, and do normal click, everything works fine:
WebElement dialogLink = driver.findElement(By
                .id(dialogLinkId));
        dialogLink.click();


text:
Q: Ansible win_package gets stuck forever when installing PowerShell 7 MSI I'm trying to install the PowerShell7-MSI-package via Ansible. During execution it seems that Ansible is stuck (at least for about 45 minutes ...). For the installation I'm using the win_package module. I also found this SO question which unfortunately has no answer.
The host I'm trying to install to is:
OS Name:                   Microsoft Windows 10 Enterprise
OS Version:                10.0.19042 N/A Build 19042

Ansible version:
ansible 2.9.16
  config file = /etc/ansible/ansible.cfg
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Aug 24 2020, 17:57:11) [GCC 8.3.1 20191121 (Red Hat 8.3.1-5)]

Playbook:
---
# tasks file for common

- name: Create temp directory
  win_file:
    path: "{{ ansibleRemoteTemp }}"
    state: directory
- name: Copy Powershell package
  win_copy:
    src: ../files/PowerShell-7.1.0-win-x64.msi
    dest: "{{ ansibleRemoteTemp }}/PowerShell-7.1.0-win-x64.msi"
- name: Install PowerShell 7
  win_package:
    product_id: '{8B34F593-C5DF-47D9-AD0E-23D579F6D83E}'
    path: "{{ ansibleRemoteTemp }}/PowerShell-7.1.0-win-x64.msi"
    state: present
    arguments: ' /package PowerShell-7.1.0-win-x64.msi /quiet ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=1 ENABLE_PSREMOTING=1 REGISTER_MANIFEST=1'

The arguments are based on this learn.microsoft.com link.
Here is my Ansible output:
...

TASK [common : Copy Powershell package] *************************************************************************************************************************************************************************
ok: [server_14] => {
    "changed": false,
    "checksum": "517a93072f1f3d2d82b4634a506a84a808f63de2",
    "dest": "C:/Users/ansibletestuser/AppData/Local/Temp/playbookPackages/PowerShell-7.1.0-win-x64.msi",
    "operation": "file_copy",
    "original_basename": "PowerShell-7.1.0-win-x64.msi",
    "size": 99663872,
    "src": "../files/PowerShell-7.1.0-win-x64.msi"
}

TASK [common : Install PowerShell 7] ****************************************************************************************************************************************************************************

HERE WE ARE STUCK


text:
Q: convert early binding to late binding without changing object type This seems like a simple question but I after chasing forums for several hours I think it might be impossible.
I often want to convert a  program from early binding to late binding.  Usually,  it is a vba, visual basic for applications, program that runs under Excel 2010 and windows 7 pro.
For discussion purposes, let's pretend it is the following.
Sub EarlyBind()
   ' use IDE > Tools > references > and select "Microsoft Internet Controls"
     Dim shellWins1 as shdocvw.shellwindows
Line1:      Set shellWins1 = New SHDocVw.ShellWindows
      MsgBox TypeName(shellWins1) ' this will display "IShellWindows"
      ' other code that expects to be working with an IshellWindows object …..
 End Sub

In my experience, converting such a program to late binding is sometimes hard.
For instance, I found some forums that suggest I change it to
Set shellwins1 = createobject("Shell.applicaton")

But that creates a IShellDispatch5 object, not an IshellWindows object.  That means I have to change other code to accommodate the new object type.  And, of course I have to test that other code for subtle differences.
So, my goal is to find a general solution that will allow me to rewrite "Line1" to create the CORRECT object type with late binding. I also wish to avoid the need setting a reference to "Microsof Internet Controls.  In other words, I want the code to look like this:
    Sub LateBind()
Dim shellWins1 as object

Line1:      Set shellWins1 = createobject("xxxxxx.yyyyyy").zzzzzz

 MsgBox TypeName(shellWins1) ' this should display "IShellWindows"

  …..  other code that expects to be working with an IshellWindows object …..

End Sub

I know how to use the vba IDE to find the dll associated with the object.  In this case the dll is Library SHDocVw  C:\Windows\SysWOW64\ieframe.dll.
I have installed OleView and can find the associated IshellWindows "magic numbers" for the  clsId, TypeLib, and Inteface (for instance the interface is 85CB6900-4D95-11CF-960C-0080C7F4EE85).
But, I don't know how to convert them into a program id that can be used in line1 in the sample code posted above.
I hope someone here can help.
------ With MeHow's help, I now have the answer! ------
To switch 'set myObj = new xxxx.yyyyy' to late binding for arbitrary object types
Change  set myObj = new xxxx.yyyyy
into    set myObj = CreateObject("xxxx.yyyyy")

Very often that will work.
But, in the some cases, (e.g. "shDocVw.ShellWindows.")  it gives error 429 ActiveX component cannot be created.
When that occurs I AM COMPLETELY OUT OF LUCK.  It is impossible to use late binding with that EXACT object class. Instead I must find a substitute class that does approximately the same thing.  (e.g. "Shell.Application").

A: Your short answer is
IShellWindows is an interface.
It

Provides access to the collection of open Shell windows.

Therefore

Take a look at the CreateObject() method.
Note:

Creates and returns a reference to a COM object. CreateObject cannot
  be used to create instances of classes in Visual Basic unless those
  classes are explicitly exposed as COM components.

IShellWindows is not exposed as a COM component so that's why there is no way to say CreateObject("SHDocVw.IShellWindows")

When you open your registry (regedit) and search for a key type in IShellWindows. If you find anything that means you've found your Prog ID and if you don't find anything it means that nothing like IShellWindows is registered as a prog Id therefore it would make sense to assume that you can't late bind IShellWindows

A: I bumped into your question trying to find something for myself. But I don't know if you have tried the following -
Set shellwins1 = createobject("Shell.Application")
MsgBox TypeName(shellWins1.Windows)

This answers your question for datatype. It prints IShellWindows for me. I'm not sure though if it could actually solve your purpose for latebinding meaning if this would be the object required though the datatype is what you need.
So, I would advise you to give it a try.

A: There is a slightly better approach outlined at https://www.experts-exchange.com/questions/28961564/How-to-find-the-class-id-of-an-arbitrary-object-Example-Set-x-CreateObject-New-1C3B4210-F441-11CE-B9EA-00AA006B1A69.html#a41743468.


text:
Q: "no route to host" / "host is down" cycle I'm working on an application that uses UDP-broadcast for discovery. For what it's worth, I'm using ZeroMQ's pure-java implementation project, JeroMQ (but I don't think this is germane to the problem).
I've noticed something strange when I run the application on my Mac -- It will send the broadcast once per second a few times without issue, and then I will get a NoRouteToHost exception, followed by 15-25 seconds of SocketException with the message "host is down". Then the broadcast will go through for another 4-10 seconds. The exact number of successes and failures in the cycle fluctuates a bit, but it's always roughly 5 successes followed by roughly 20 failures.
I have also observed this pattern by using the OSX native ping utility targeting any address on my subnet that doesn't respond to icmp (including [/24 subnet].255) -- A handful of "request timeout" responses (as expected) followed by exactly one "No route to host" and then a couple dozen "host is down" messages. Eventually I get another half-dozen timeouts without connection errors and the cycle repeats.
I observe this behavior on a conventional Access Point 802.11 network, and also an ad-hoc wifi network.
This issue does not happen from a Debian VM or from a Raspberry Pi running Raspbian Stretch.
OSX version 10.13.4
I've looked around online some with no success, perhaps because I'm having trouble phrasing the question?


text:
Q: Are Microsoft SQL Server "Express" editions free to develop on? Am I able to develop a software for free on Microsoft SQL Server 2005/2008 Express edition databases?

A: Yes, here is a relevant faq.
You are free to redistribute your applications commercially...

A: Yes, SQL Server Express is free to develop on, free to use, free to ship to your customers - FREE all around! :-)
In addition to MicTech's list of limitations, SQL Server Express is (at this time) 32-bit only.
As for the 4 GB limitation for the database, this is per database, so you can easily have several databases in SQL Server Express on the same machine - each up to 4 GB in size. And in SQL Server Express 2008, the data stored in the FILESTREAM filegroup (BLOBs stored on disk) is not considered for this limit.
Marc

A: Yes, You can.
But Express version have few limitations

*

*SQL Server use only one CPU at a time

*Maximum memory is 1GB

*Database size limit is 4GB

And you can redistribute SQL Server, but you must register for that at Microsoft.
UPDATE - SQL Server 2008 R2
Database size limit is 10GB

A: Wrong Answer: As far as I know, you are free to develop in any Microsoft Express Edition as long as you do not redistribute the code commercially.
EDIT: I swear I read a license a while ago which said you couldn't.  They must have changed it on me, either that or I'm thinking of the license for my student edition.  Sorry about that.
Another Edit: Just clarifying, my original answer was completely wrong, I got my MS licenses confused.  As far as I know from reading the licenses last night, you can develop to your hearts content with Microsoft Express Edition software.


text:
Q: mybatis create/update database on application startup? Is present some configuration properties for mybatis in order to create/update database on application startup like does "hibernate.hbm2ddl.auto" ?

A: Well,  The MyBatis Migration Tool might meet your needs, it sounds a little different than Hibernate though.


text:
Q: jquery error, Uncaught TypeError: Cannot use 'in' operator to search for 'scrollLeft' in undefined when  ABC  is loaded,
How to remove this (in fadeout effect)
I tried
view.html
    <%if notice %>
      <span class = "notice"><%= flash[:notice] %> </span>
    <% end %>

<script>

<script>

$( "span.notice" ).ready(function() {
  $( this ).fadeOut( 1000, function() {
    $( this ).remove();
  });
});
</script>

I received error message that
Uncaught TypeError: undefined is not a function
jquery-1.10.2.js:6820 Uncaught TypeError: Cannot use 'in' operator to search for 'display' in undefine

How to I fix it?

A: $( "span.notice" ).ready( ? I don't think so. The DOM can be ready, but you can't listen for a HTML element to be. Just remove this, and also the double <script> opening.
<script>
$( "span.notice" ).fadeOut( 1000, function() {
    $( this ).remove();
});
</script>

A: Try below code.
$( document ).ready(function() {
      $( 'span.notice').fadeOut( 1000, function() {
        $('span.notice').remove();
      });
});

You can not use ready on "span.notice".. so you need to use dom element and on dom ready you need to fadout and then remove your span. Please make sure you have added necessary jquery files in proper manner.


text:
Q: Error when outputting an image inside an embed with canvas | Discord.js So I have been getting this error when outputting an image using canvas (Node Module). Can anyone help?
embed.image.url: Could not interpret "{'name': 'welcome-image.png'}" as string.

I think this may be the issue here
const attachment = new Discord.MessageAttachment(canvas.toBuffer(), 'welcome-image.png');
console.log("Testing 2")
let embed = new Discord.MessageEmbed()
  .setAuthor(member.tag)
  .setImage(attachment)
  .setFooter(client.config.footer)
  .setColor(client.config.color)
console.log("Testing 3")
return wChannel.send(embed);

If anyone could help me out here and try remove that error it would be greatly appreciated

A: I beleive this has the answer to your question. The way I do it with canvas is like this:
var attachment = new Discord.MessageAttachment(canvas.toBuffer(), `image_name.png`)
const embed = new Discord.MessageEmbed()
  .setAuthor(member.tag)
  .setFooter(client.config.footer)
  .attachFiles([attachment])
  .setImage(`attachment://image_name.png`)
  .setColor(client.config.color)


text:
Q: `react-hover` npm package not in production build but working fine in development I want to make use of the npm package react-hover (here's the github link) in my project and when I develop locally in dev build it works just fine. When I run the npm run build command and serve the production version the components I want to show in the <ReactHover> object don't render on the page.
I started the project using create-react-app I serve the production version locally using the npm package serve.
I will share all the files of my project since it's nothing spectacular, here are all files on a public repo.
I haven't really been able to find this issue anywhere else so any insight would be appreciated.

A: You can simply use CSS to do that.
Define two divs, one with id="hover-selector-parent" and another with id="hover-selector-child".
Then configure your CSS file to handle the event -
#hover-selector-parent:hover~#hover-selector-child{
  display:block;
}

#hover-selector-child{
  display: none;
}


text:
Q: How to throw an annotation processing error if a class with a custom Java annotation is used I want to use an annotation processor to create an @Internal annotation which throws an error if an internal library class is used outside the library.
However, I'm not sure how to find where a class is referenced and throw an error then.
For example, with these 2 library classes:
//Implementation
@Internal
public class InternalClass implements SomeInterface {
}

//API class
public interface SomeInterface {

     static SomeInterface getInstance() {
        return new InternalClass();
     }
}

public class Test {
   public static void main(String[] args) {
      InternalClass annotated = new InternalClass(); //ERROR
      SomeInterface interface = SomeInterface.getInstance(); //FINE
    }
}

How would I do that?
public class InternalProcessor extends AbstractProcessor {

    @Override
    public boolean process(final Set<? extends TypeElement> annotations,
                           final RoundEnvironment roundEnv) {
        //What goes in here?
    }
}

A: Without hackery, this is rather difficult. You get access to a few things:

*

*You get 'mirror objects' that let you programmatically query signatures of stuff being compiled. Signatures is the class name, what it extends, the fields, the types of those fields, the constructors and the methods, and the types and names of the parameters, their throws clauses, their return types, and any annotations in any signature. But you do not get anything to inspect the body of that method.

*You get the ability to read arbitrary source files under compilation, as raw bytes.

*You get the ability to write arbitrary files out, including new source files (which then get processed and compiles in a 'rounds' system). Notably you don't get the ability to modify code in existing files.

*You get the ability to emit error and warning nodes on any signature or annotation.

Note how you just can't do it easily then: You want access to method bodies which you don't get. Your only option is to open all the source files, throw them through a java parser (which java doesn't ship with; you have various options but they all have downsides. javac's is complete and open source but restrictively licensed and not all that easily traversed. They also change that API every other minute. ecj's is complete, permissively licensed open source, and fast, with a much more stable API, but that API is deplorably designed and badly documented. All other java parsers are incomplete, in the sense that no serious project uses it and thus you should expect that various language constructs that javac and ecj can handle will crash such a parser. They also tend to have bad error recovery so one weird or new construct used anywhere in a source file means that entire file just errors out for you and there's no analysis you can perform.
To make matters even more complicated, there's the notion of incremental compilation. When you edit a file, and save, Just that file gets recompiled, the rest isn't touched. This is a big deal: I can modify a source file and start using '@Internal' marked stuff in it, and then run compilers (IDEs run them as you save), and that @Internal annotation does not trigger anything because no code with it is being compiled (instead, code that uses a class so marked is being compiled). APs can just trigger on any compilation regardless of annotations, so you're not completely out of luck on this regard, but you need to process everything and scan all used types.
What you want to do is therefore a crazy complicated project that an expert java programmer will need more than a week to put together at least. Your job would entail:

*

*Immediately accepting massive slowdowns in compilation; parsing is 90% of any compile run and you need to do so at least twice, and you probably need to either accept even more slowdowns or build a complicated caching system.

*Figuring out a java parser (java is a very complicated language, hence so are these parsers), in order to analyse the code the way you want to.

*Then write this project once you've written a 'framework' that parses and caches the ASTs for everything that you see fly on by as an annotation processor.

Taking a step back, just preventing access to certain methods: Module systems such as OSGi and java's module-info aim to do that too, it sounds like you want to badly reinvent some wheels. Maybe just use an existing module system?


text:
Q: MySQL Merge Two SELECT Queries With CASE On One Table I want to merge two queries into one full query. I would need the two queries to group on one aggregate field (MFG).  I would assume you use a JOIN but it is on the same table and with a CASE so I'm not sure how that could even work.
1ST QUERY (2015)
SELECT
    CASE
        WHEN ITEM LIKE '%1%' THEN 'MFG1'
        WHEN ITEM LIKE '%2%' THEN 'MFG2'
        WHEN ITEM LIKE '%3%' THEN 'MFG3'
        ELSE ''
    END AS MFG,
    SUM(COST) AS Cost2015
FROM
    table
WHERE
    TRANS_DATE BETWEEN '2015-12-01' AND '2015-12-31'
GROUP BY MFG

2ND QUERY (2014)
SELECT
    CASE
        WHEN ITEM LIKE '%1%' THEN 'MFG1'
        WHEN ITEM LIKE '%2%' THEN 'MFG2'
        WHEN ITEM LIKE '%3%' THEN 'MFG3'
        ELSE ''
    END AS MFG,
    SUM(COST) AS Cost2014
FROM
    table
WHERE
    TRANS_DATE BETWEEN '2014-12-01' AND '2014-12-31'
GROUP BY MFG

DESIRED RESULT
MFG  |  Cost2015  |  Cost2014
MFG1 |   1500     |     0
MFG2 |   1000     |    1200
MFG3 |     0      |    3600
     |    100     |     15

A: You can use CASE in SUM()
SELECT
    CASE
        WHEN ITEM LIKE '%1%' THEN 'MFG1'
        WHEN ITEM LIKE '%2%' THEN 'MFG2'
        WHEN ITEM LIKE '%3%' THEN 'MFG3'
        ELSE ''
    END AS MFG,
    SUM(CASE WHEN TRANS_DATE BETWEEN '2014-12-01' AND '2014-12-31' THEN COST ELSE 0 END) AS Cost2014,
    SUM(CASE WHEN TRANS_DATE BETWEEN '2015-12-01' AND '2015-12-31' THEN COST ELSE 0 END) AS Cost2015
FROM
    TABLE
WHERE
    TRANS_DATE BETWEEN '2014-12-01' AND '2015-12-31'
GROUP BY MFG