text:
Q: Python dataframe value did not change at all I wanna change specific cell value in dataframe type.
When i specific string type entered in the index, the specific cell value is changed.
But, i enter string variable in the index, they didn't change at all.
For example,
if target in self.confusion_mat.index:
        if prediction in self.confusion_mat.columns:
          self.confusion_mat.loc[target, prediction] = 99
          self.confusion_mat.loc['abnormaluterinebleeding', 'abnormaluterinebleeding'] = 99
print(self.confusion_mat)

and result is below
sdconfusion mat size =  (663, 663)
depression depression
=================!!!!!===============
                           abnormaluterinebleeding  ...  zollinger ellisonsyndrome
abnormaluterinebleeding                         99  ...                          0
abortion                                         0  ...                          0
acetaminophenoverdose                            0  ...                          0
aciallipoatrophy                                 0  ...                          0
acialwrinkles                                    0  ...                          0
...                                            ...  ...                        ...
women oxybutynin                                 0  ...                          0
xerostomia                                       0  ...                          0
yellowfeverprophylaxis                           0  ...                          0
zenshoulde                                       0  ...                          0
zollinger ellisonsyndrome                        0  ...                          0

[663 rows x 663 columns]

i don't know why statement 'self.confusion_mat['cough', 'cough'] = 99' change the cell value, but 'self.confusion_mat[target, prediction] = 99' when target = 'cough' prediction = 'cough' does not change
at all cell value.
is there any mistake in my conception?
the same test code is below
target_name = 'condition3'
target_label = df_test[target_name].unique()
target_label.sort()
confusion_mat = pd.DataFrame(index=target_label, columns=target_label)
confusion_mat = confusion_mat.fillna(0)
print(confusion_mat)

for index in range(0, 10):
  example = df_train.iloc[index]
  tmp_result = predictConditionSum(lemlem(example['review']))
  tmp_result = sorted(tmp_result.items(), key = lambda item : item[1], reverse=True)

  if (len(tmp_result) == 0):
    continue

  prediction = tmp_result[0][0]
  target = example[target_name]

  confusion_mat.loc[target, prediction] = 99
confusion_mat.loc['abnormaluterinebleeding','abnormaluterinebleeding'] = 99
print(confusion_mat)

--------------------------------result---------------------------------------

                           abnormaluterinebleeding  ...  zollinger ellisonsyndrome
abnormaluterinebleeding                          0  ...                          0
abortion                                         0  ...                          0
acetaminophenoverdose                            0  ...                          0
aciallipoatrophy                                 0  ...                          0
acialwrinkles                                    0  ...                          0
...                                            ...  ...                            ...
    women oxybutynin                                 0  ...                          0
xerostomia                                       0  ...                          0
yellowfeverprophylaxis                           0  ...                          0
zenshoulde                                       0  ...                          0
zollinger ellisonsyndrome                        0  ...                          0

[663 rows x 663 columns]
                       abnormaluterinebleeding  ...  zollinger     ellisonsyndrome
abnormaluterinebleeding                         99  ...                          0
abortion                                         0  ...                          0
acetaminophenoverdose                            0  ...                          0
aciallipoatrophy                                 0  ...                          0
acialwrinkles                                    0  ...                          0
...                                            ...  ...                            ...
    women oxybutynin                                 0  ...                          0
xerostomia                                       0  ...                          0
yellowfeverprophylaxis                           0  ...                          0
zenshoulde                                       0  ...                          0
zollinger ellisonsyndrome                        0  ...                          0

[663 rows x 663 columns]


text:
Q: How to differentiate whether user is coming from FB app or the standalone app I've a rails application that acts as a Facebook app as well as a standalone app. Now I need to differentiate from where the user is accessing the app.
What's the easiest and sure-shot way to do this?

A: The http Referer [sic] field.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Facing error while upgrading to angular 8 from angular 7 facing CSS,SCSS errors I want to upgarde angular 7 to angular 8
When serve application facing issue in terminal
Module build failed (from ./node_modules/sass-loader/lib/loader.js):

    @include transition(opacity .2s);
         ^
      Mixin transition is missing argument $type.
      in /home/webelight-pc/www/thunder-school/src/assets/sass/scss/core/_horizontal-timeline.scss (line 12, column 11)
ERROR in multi ./node_modules/ngx-toastr/toastr.css ./src/assets/css/prism.min.css ./node_modules/sweetalert2/dist/sweetalert2.min.css ./node_modules/ngx-ui-switch/ui-switch.component.css ./src/assets/css/wizard.css ./src/assets/css/quill.snow.css ./src/assets/css/quill.bubble.css ./src/assets/css/hopscotch.css ./node_modules/nouislider/distribute/nouislider.min.css ./node_modules/angular-calendar/scss/angular-calendar.scss ./node_modules/dragula/dist/dragula.css ./node_modules/@swimlane/ngx-datatable/release/index.css ./node_modules/@swimlane/ngx-datatable/release/assets/icons.css ./node_modules/@swimlane/ngx-datatable/release/themes/material.css ./node_modules/angular2-multiselect-dropdown/themes/default.theme.css ./src/assets/css/demo.css ./src/assets/sass/app.scss ./node_modules/intl-tel-input/build/css/intlTelInput.css ./src/styles.css
Module not found: Error: Can't resolve '/home/webelight-pc/www/thunder-school/node_modules/@swimlane/ngx-datatable/release/assets/icons.css' in '/home/webelight-pc/www/thunder-school'
ERROR in multi ./node_modules/ngx-toastr/toastr.css ./src/assets/css/prism.min.css ./node_modules/sweetalert2/dist/sweetalert2.min.css ./node_modules/ngx-ui-switch/ui-switch.component.css ./src/assets/css/wizard.css ./src/assets/css/quill.snow.css ./src/assets/css/quill.bubble.css ./src/assets/css/hopscotch.css ./node_modules/nouislider/distribute/nouislider.min.css ./node_modules/angular-calendar/scss/angular-calendar.scss ./node_modules/dragula/dist/dragula.css ./node_modules/@swimlane/ngx-datatable/release/index.css ./node_modules/@swimlane/ngx-datatable/release/assets/icons.css ./node_modules/@swimlane/ngx-datatable/release/themes/material.css ./node_modules/angular2-multiselect-dropdown/themes/default.theme.css ./src/assets/css/demo.css ./src/assets/sass/app.scss ./node_modules/intl-tel-input/build/css/intlTelInput.css ./src/styles.css
Module not found: Error: Can't resolve '/home/webelight-pc/www/thunder-school/node_modules/@swimlane/ngx-datatable/release/index.css' in '/home/webelight-pc/www/thunder-school'
ERROR in multi ./node_modules/ngx-toastr/toastr.css ./src/assets/css/prism.min.css ./node_modules/sweetalert2/dist/sweetalert2.min.css ./node_modules/ngx-ui-switch/ui-switch.component.css ./src/assets/css/wizard.css ./src/assets/css/quill.snow.css ./src/assets/css/quill.bubble.css ./src/assets/css/hopscotch.css ./node_modules/nouislider/distribute/nouislider.min.css ./node_modules/angular-calendar/scss/angular-calendar.scss ./node_modules/dragula/dist/dragula.css ./node_modules/@swimlane/ngx-datatable/release/index.css ./node_modules/@swimlane/ngx-datatable/release/assets/icons.css ./node_modules/@swimlane/ngx-datatable/release/themes/material.css ./node_modules/angular2-multiselect-dropdown/themes/default.theme.css ./src/assets/css/demo.css ./src/assets/sass/app.scss ./node_modules/intl-tel-input/build/css/intlTelInput.css ./src/styles.css
Module not found: Error: Can't resolve '/home/webelight-pc/www/thunder-school/node_modules/@swimlane/ngx-datatable/release/themes/material.css' in '/home/webelight-pc/www/thunder-school'
ERROR in ./node_modules/ngx-quill/fesm2015/ngx-quill.js
Module not found: Error: Can't resolve 'quill' in '/home/webelight-pc/www/thunder-school/node_modules/ngx-quill/fesm2015'

A: The transition function have two parameters
@include transition(cssProperty, animationDuration transitionFunction);
the transition function is not mandatory it's ease by default
in your case it could be something like
@include transition(opacity, 2s);

or
@include transition(opacity, 2s ease-in);

the complete list of transition function is :

*

*ease

*linear

*ease-in

*ease-out

*ease-in-out

*step-start

*step-end

*steps(int,start|end)

*cubic-bezier(n,n,n,n)

more sample can be found : https://www.w3schools.com/cssref/css3_pr_transition.asp

A: @include transition(opacity, .2s ease-out);


text:
Q: generate views from meta data using STRING_AGG function I want to generate the DDL for views from a table of meta data. Since every value for my_column_name maps to a single short_column_names the order is important. If they are both sorted by their individual columns the external name for the column will not match the internal name in the select statement. Other than concatenating a number in and removing to later, how can I sort both columns the same way?
To be more specific. I am creating a table to map the long SQL Server names to shorter names that I can query from Oracle. I am using Oracle 11.2.0.4, which has a limit of 30 characters for column and table names. The table and column names in the SQL Server instance that I am using can be as much as 128 characters. Hence, I need to create an updatable view to allow Oracle processes to query and update the SQL Server tables directly across a DB Link which is already setup.
CREATE TABLE [dbo].[column_mapping](
    [my_schema_name]          [varchar](128) NOT NULL,
    [table_name]              [varchar](128) NOT NULL,
    [my_column_name]          [varchar](30)  NOT NULL,
    [short_column_name]       [varchar](30)  NULL,
    [sql_server_data_type]    [varchar](30)  NULL,
PRIMARY KEY CLUSTERED
(  [my_schema_name] ASC,
    [table_name]     ASC,
    [my_column_name] ASC ) ) ON [PRIMARY]
GO

INSERT INTO dbo.column_mapping
       ( my_schema_name,        table_name, my_column_name,  short_column_name )
VALUES ( 'DBO',                 'COMPANY',  'NUMBER',        'CLIENTCODE' );

INSERT INTO dbo.column_mapping
       ( my_schema_name,        table_name, my_column_name,  short_column_name )
VALUES ( 'DBO',                 'COMPANY',  'ACTIVE_STATUS', 'CLIENTSTATUS' );

INSERT INTO dbo.column_mapping
       ( my_schema_name,        table_name, my_column_name,  short_column_name )
VALUES ( 'DBO',                 'COMPANY',  'LONG_NAME',     'FULLDESCRIPTION' );

INSERT INTO dbo.column_mapping
       ( my_schema_name,        table_name, my_column_name,  short_column_name )
VALUES ( 'DBO',                 'COMPANY',  'SHORT_NAME',    'SHORTDESCRIPTION' );

INSERT INTO dbo.column_mapping
       ( my_schema_name,        table_name, my_column_name,  short_column_name )
VALUES ( 'DBO',                 'COMPANY',  'SOURCE_ID',     'SOURCE_ID' );

INSERT INTO dbo.column_mapping
       ( my_schema_name,        table_name, my_column_name,  short_column_name )
VALUES ( 'DBO',                 'COMPANY',  'SOURCE_SYSTEM', 'SOURCE_SYSTEM' );

COMMIT;

My query
SELECT my_schema_name, my_table_name,
     STRING_AGG( my_column_name,  ',' ) WITHIN GROUP (ORDER BY my_column_name ASC) AS my_column_names,
     STRING_AGG( short_column_name,     ',' ) WITHIN GROUP (ORDER BY my_column_name ASC) AS short_column_names
FROM [dbo].[my_column_mapping]
GROUP BY my_schema_name, my_table_name
ORDER BY 1,2;

A: You can use a CTE to produce an ordering id column and use that to control order:
;WITH CTE AS (
    SELECT ROW_NUMBER() OVER (ORDER BY my_column_name) AS [Order],
        my_schema_name, table_name, my_column_name,  short_column_name
    FROM #column_mapping
)

SELECT my_schema_name, table_name,
    STRING_AGG(my_column_name, ', ') WITHIN GROUP (ORDER BY [Order] ASC) AS my_columns,
    STRING_AGG(short_column_name, ', ')  WITHIN GROUP (ORDER BY [Order] ASC) AS short_column_names
FROM CTE
GROUP BY my_schema_name, table_name

Produces this result:
my_schema_name  |   table_name  |   my_columns                                                              |   short_column_names
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
DBO             |   COMPANY     |   ACTIVE_STATUS, LONG_NAME, NUMBER, SHORT_NAME, SOURCE_ID, SOURCE_SYSTEM  |   CLIENTSTATUS, FULLDESCRIPTION, CLIENTCODE, SHORTDESCRIPTION, SOURCE_ID, SOURCE_SYSTEM

Because the CTE defines an order id for each record, when we order by this column in the STRING_AGG() function we will always get the matching column names.

A: I tried you example and added a join to the schemas, all_objects, and all_columns views. I was then able to add column_id and use that with the STRING_AGG function. Even though I used column_id in the ORDER BY on top, I did not get that order by with the column_id column and the STRING_AGG function. So as a_horse_with_no_name mentioned, in the version of SQL Server I am using, pre SQL Server 2017, the STRING_AGG function won't work. I need to do a nested loop to get the column names turned into a comma delimited list. Thanks anyway.


text:
Q: PostgreSQL - CREATE EXTENSION without warning In my migration script I am installing unaccent extension.
I use:
CREATE EXTENSION IF NOT EXISTS unaccent;

It runs fine, but it spawns warning if the extension is already installed.
Warnings:
extension "unaccent" already exists, skipping

The script runs fine, but it breaks my flyway migration because the message is returned from migration. Is there any way how to check if the extension is already installed and avoid the message.

A: In order to omit those warnings, you need to tune down client_min_messages = ERROR


text:
Q: Email sending in laravel 5.3 I an using this code in laravel 5.3 for sending email. But it says undefined variable $email, while i have defined the variable already.
This is my code.
       $user->save();
         if (!empty($user->save())) {
            $email = 'ppriyadarshi49@gmail.com';
            $mail = Mail::send('email_page', ['verification_key' => $verification_code], function($message) {
            $message->from('prince.priyadarshi@fluper.com', 'Verify');
            $message->to($email)
            ->subject('Verify your email address');
            });
            return view('for_company');

          }

And the error is    Undefined variable: email

A: Your are missing use() in closure function as:
   $user->save();
     if (!empty($user->save())) {
        $email = 'ppriyadarshi49@gmail.com';
        $mail = Mail::send('email_page', ['verification_key' => $verification_code], function($message) use($email) {
        $message->from('prince.priyadarshi@fluper.com', 'Verify');
        $message->to($email)
        ->subject('Verify your email address');
        });
        return view('for_company');

      }


text:
Q: D3 Brush coordinates under CSS transform scale D3 brush does not function properly under css transform scale.   When svg is under div element, and div element is transformed using CSS scale, the brush operation shows wrong coordinates.
To demonstrate this case, here is the jsFiddle.
It is simple modification from Bostock's Brushable Network example.
What I did was simply putting SVG in the div element and made div element zoom 50% using CSS transform scale(0.5).  And the brushing coordinates are not updating because of zooming.
#test {
transform: scale(0.5);
}

Thanks.
Deok

A: If you use an svg based transform:
transform="scale(0.5)"

Then it'll play nice with the brush:
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

svg = svg.append("g")
    .attr("transform","scale(0.5)");

Updated fiddle.
To fix the calculations you need two things.
1.) Scale the extent rect opposite the div:
.extent {
   transform: scale(2);
}

2.) Fix the extent calculations:
   .on("brush", function() {
      var extent = d3.event.target.extent();
      node.classed("selected", function(d) {
        return extent[0][0] <= d.x && d.x < extent[1][0] &&
               extent[0][1] <= (d.y/2) && (d.y/2) < extent[1][1]; // scale y opposite div transform
      });
   });

New example here.

A: If you use CSS transform you should apply it to all the classes that related by nodes:
 .node {
  stroke: #fff;
  stroke-width: 1.5px;
  transform: scale(0.5);
 }

 .node .selected {
        stroke: red;
  }

.link {
   stroke: #999;
     transform: scale(0.5);
  }

.brush .extent {
  fill-opacity: .1;
  stroke: #fff;
  shape-rendering: crispEdges;
  transform: scale(0.5);
}

When you add transform: scale(0.5); you can brush all the node. Try from left to right over node position.
 var width = 960,height = 500;
  var svg = d3.select("#body").append("svg")
        .attr("width", width)
        .attr("height", height);

    graph.links.forEach(function(d) {
        d.source = graph.nodes[d.source];
        d.target = graph.nodes[d.target];
    });

    var link = svg.append("g")
        .attr("class", "link")
        .selectAll("line")
        .data(graph.links)
        .enter().append("line")
        .attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    var node = svg.append("g")
        .attr("class", "node")
        .selectAll("circle")
        .data(graph.nodes)
        .enter().append("circle")
        .attr("r", 4)
        .attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });

    var brush = svg.append("g")
        .attr("class", "brush")
        .call(d3.svg.brush()
            .x(d3.scale.identity().domain([0, width]))
            .y(d3.scale.identity().domain([0, height]))
            .on("brush", function() {
                var extent = d3.event.target.extent();
                node.classed("selected", function(d) {
                    return extent[0][0] <= d.x && d.x < extent[1][0]
                        && extent[0][1] <= d.y && d.y < extent[1][1];
                });
            }));

Complete jsfiddle here.


text:
Q: Connect to SQL Server database from a docker container I have docker for windows installed on my machine. There is a console application targeting .net core 1.0.0 that tries to access a SQL Server database running on a different VM. I can ping the VM running SQL Server from my machine.
When I try to run the console application using dotnet run from the command prompt on my machine it works fine. But when the same application is run inside a docker container I get a message

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: TCP
  Provider, error: 40 - Could not open a connection to SQL Server)

I tried using
docker run --add-host sqldemo:<VM running sql server ip here>

but that made no difference.

A: Assumptions

*

*Microsoft SQL Server 2016

*Windows 10 Anniversary Update

*Windows Containers

*ASP.NET Core application

Add a SQL user to your SQL database.

*

*In MS SQL expand the database

*Right click on 'Security / Logins'

*Select 'New Login'

*Create a user name and password.

*Assign a 'Server Role(s)'...I used sysadmin since I'm just testing

*Under 'User Mapping' I added my new user to my database and used 'dbo' for schema.

Change SQL Authentication to allow SQL Server Authentication Mode
Right click on your database, select 'Properties / Security / Server Authentication / SQL Server and Windows Authentication Mode' radio button.  Restart the MS SQL service.
Update your appsettings.json with your new user name and password
Example
"ConnectionStrings": {
        "DefaultConnection": "Server=YourServerName;Database=YourDatabaseName;MultipleActiveResultSets=true;User Id=UserNameYouJustAdded;Password=PassordYouJustCreated"
},

Make sure you remove Trusted_Connection=True.
Create a Docker file
My example Docker file
FROM microsoft/dotnet:nanoserver
ARG source=.
WORKDIR /app
EXPOSE 5000
EXPOSE 1433
ENV ASPNETCORE_URLS http://+:5000
COPY $source .

Publish Application
Running from the same location as the Docker file in an elevated PowerShell
dotnet publish

docker build bin\Debug\netcoreapp1.0\publish -t aspidserver

docker run -it  aspidserver cmd

I wanted to run the container and see the output as it was running in PowerShell.
Once the container was up and running in the container at the command prompt I kicked off my application.
dotnet nameOfApplication.dll

If everything went to plan one should be up and running.

A: You can run a docker container with network settings set to host. Such a container will share the network stack with the docker host and from the container point of view, localhost (or 127.0.0.1) will refer to the docker host.
docker run --net=host ...

Then you should get the SQL Server database from inside the docker container as you do from your host.

A: as in this answer
SQL Server instance string connection in Linux Docker
According to Saurabh Singh from Microsoft:

The Instance name support is available in v 1.1 of .Net Core. In v1.0
  of .Net Core, Instance names are not supported on OS other than
  Windows.

So I don't think you can connect from .Net Core 1.0 running on Linux to an SQL Server using instance name.
Your choices seem to be:

don't use instance name
wait for .Net Core 1.1 (planned for "Fall 2016")
use pre-release version of .Net Core 1.1


text:
Q: using hammer.js create a touchdrag side drawer I just started playing around with hammer.js which is fantastic btw, but I am having trouble doing what I am looking for. I am trying to create a touchdrag drawer which will move up to a certain point if dragged open. I have written this so far...
$(function () {
    var mb = $('#mainbody');

    Hammer(mb).on("dragleft dragright", function (ev) {
        ev.gesture.preventDefault();
        var deltaX = ev.gesture.deltaX;

        if (deltaX > 150) {
            deltaX = 150;
        }
        $(mb).attr('style', 'transform:translate3d(' + deltaX + 'px,0,0);');

    });
})

...however, when my element stops to the 150px mark, as soon as I touch drag to restore it, it resets my translate to 0 and starts from there instead of where I left it. I have tried studying the hammer.js examples, but I am not that advanced to parse the code and write my own. Any help is appreciated!


text:
Q: WP-CLI command to update all plugins and core fails when executed from cron I have the following WP-CLI command to update all plugins and core. It seems to fail when being executed from cron (other cron commands work):
0 0 * * 0 for dir in /var/www/html/*/; do cd "$dir" && wp plugin update --all --allow-root; wp core update --allow-root; done

I tried to run it manually (did so after a manual update from GUI after a period without updates), I got the following for all sites:
Success: Plugin already updated.
Success: WordPress is up to date.

Why would the command fail on cron?
I tried to debug this by letting the command run each minute (* * * * *) and checking the output (cron output usually goes to /var/mail/root).
/var/mail/root output:
Subject: Cron <root@machine_name> for dir in /var/www/html/*/; do cd "$dir" && wp plugin update --all --allow-root; wp core update --allow-root; done
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/root>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=root>
Message-Id: <20170723050601.E8FBF3EF4F@machine_name>
Date: Sun, 23 Jul 2017 05:06:01 +0000 (UTC)

/bin/sh: 1: wp: not found
/bin/sh: 1: wp: not found
/bin/sh: 1: wp: not found
/bin/sh: 1: wp: not found
/bin/sh: 1: wp: not found
/bin/sh: 1: wp: not found
/bin/sh: 1: wp: not found
/bin/sh: 1: wp: not found
/bin/sh: 1: wp: not found
/bin/sh: 1: wp: not found

A: Understanding this answer requires preliminary knowledge in a system administration and Linux issue named "Environment variables". Acquiring this knowledge could be done with a didactic Linux book, course, or tutor. If one explanation was bad, seek another.

The problem and the solution:
It seems to happen due to a partial utilization of the PATH environment variable, by cron.
When cron runs it has only the /usr/bin value of this variable, instead the whole set, common in Ubuntu 16.04:
/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games

What I did was to add the full location of WP-CLI to the commands (I also splitted the long one-liner command to two short commands):
From:
0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && wp plugin update --all --allow-root; done
0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && wp core update --allow-root; done

To:
0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp plugin update --all --allow-root; done
0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp core update --allow-root; done

Note the /usr/local/bin/ right before wp.
To test this works without waiting a whole day I changed the cron schedule from 0 0 * * * (in the first minute, of the first hour, in each day of month, in each month, in each day of week), to this:
* * * * *

(in each minute, in each hour, in each day of month, in each month, in each day of week).
After about 2 minutes I checked one of my websites and saw everything was updated (besides themes, which updating them isn't included in the two commands I used).


text:
Q: Mocha: Timeout on endpoint that is functional When using Mocha, supertest, and Chai, when I run the code:

const authPost = (title, endpoint, body, responseProperty, checkFirstElement = false) => {
    it(title, (done) => {
        request(app)
            .post(endpoint)
            .set({ "Authorization": `Bearer ${token}` })
            .set("Content-Type", "application/json")
            .send(body)
            .end((error, response) => {
                if (error) done(error);
                checkFirstElement ? response.body[0].should.have.property(responseProperty) : response.body.should.have.property(responseProperty);
                done();
            });
    });
}

I get the following error:
Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/drone/src/test/test.js)
          at listOnTimeout (node:internal/timers:557:17)
          at processTimers (node:internal/timers:500:7)

I initially thought it was a timeout error, but I have had it run for a long time and I cannot solve the issue.
Things I've tried:

*

*Verified that the endpoint is actually accessible

*Removing the Content-Type set statement

*Adding a .catch(done) after the request

*calling it() directly where the error was happening as opposed to calling the function and adding the JSON data directly into the function as well

Any and all help would be greatly appreciated!


text:
Q: How to report progress of a web service on windows mobile client? I have tried to implement progress reporting using a soap extension as described at the following links:
stackoverflow
codeproject
However, my "ProgressUpdate" method is not being called, and I believe that is because I haven't got an app.config file in my Windows Mobile project to tell the web service calls to be processed by the SOAP Extension. How can do it in Windows Mobile? This is the sample config file used in the article:
<?xmlversion="1.0" encoding="utf-8" ?>
<configuration>
   <system.web>
      <webServices>
         <soapExtensionTypes> <add
        type="SoapExtensionLib.ProgressExtension, SoapExtensionLib"
        priority="1"  group="High" />
         </soapExtensionTypes>
      </webServices>
   </system.web>

</configuration>

A: I figured out how to do this by adding a custom attribute to the method inside the generated proxy class. The custom attribute is derived from SoapExtensionAttribute.
I got the information at MSDN
Problem now is that I have to remember to add the attribute back in if I refresh the web service reference..............


text:
Q: UICollectionView not updated in iOS In my iPhone app I just parse the JSON from a url and save it to arrays.  After completing JSON parsing my UICollectionView should be updated with the new array values. But my UICollectionView isn't updating. Please look through my following coding
@interface SpecialPgms ()
@property (strong, nonatomic) IBOutlet UICollectionView *collecSpecial;
@end

@implementation SpecialPgms
NSMutableArray *arrTitle,*arrUrl,*arrImg;
UICollectionViewCell *cell ;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _sidebarButton.tintColor = [UIColor colorWithWhite:0.1f alpha:0.9f];
    _sidebarButton.target = self.revealViewController;
    _sidebarButton.action = @selector(revealToggle:);
    [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
    self.collecSpecial.delegate=self;
    self.collecSpecial.dataSource=self;
    [self loadJSON];
}

-(void)loadJSON{
    arrTitle=[[NSMutableArray alloc]init];
    arrUrl=[[NSMutableArray alloc]init];
    arrImg=[[NSMutableArray alloc]init];

    [pro startAnimating];

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        JSONDecoder *decoder = [JSONDecoder decoderWithParseOptions:JKParseOptionStrict];

        NSData *immutableItemList = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@"https://gdata.youtube.com/feeds/api/videos?author=jiljilmedia&v=2&alt=jsonc"]];

        NSData *data =immutableItemList;
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSData* data1 = [string dataUsingEncoding:NSUTF8StringEncoding];
        NSArray *returnedData = (NSArray *) [[[decoder objectWithData:data1] objectForKey:@"data"] objectForKey:@"items"];

        for(NSDictionary * student in returnedData){

            NSString *strTitle=[student objectForKey:@"title"];

            NSDictionary *Thumbnail=[student objectForKey:@"thumbnail"];
            NSString *strImg = Thumbnail[@"sqDefault"];
            NSDictionary *player = student[@"player"];
            NSString *strdefaultUrl = player[@"default"];
            NSString *strMobileUrl=player[@"mobile"];

            [arrTitle addObject:strTitle];
            //NSLog(@"%@",strImg);

            if(strMobileUrl.length==0){
                [arrUrl addObject:strdefaultUrl];
            }
            else{
                [arrUrl addObject:strMobileUrl];
            }
            [arrImg addObject:strImg];

        }
        [self performSelectorOnMainThread:@selector(setProgramTableView:) withObject:[NSArray arrayWithObjects: nil] waitUntilDone:YES];
    });

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return arrTitle.count;

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"Cell";

    cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
    recipeImageView.image = [UIImage imageNamed:[arrImg objectAtIndex:indexPath.row]];

    UILabel *lab = (UILabel *)[cell viewWithTag:101];
    lab.text= [arrImg objectAtIndex:indexPath.row];

    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"photo-frame.png"]];

    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
       NSLog(@"%d",indexPath.row);
}

////// JSON Parsing for video links////////////////////
- (void)setProgramTableView: (NSArray*)array
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [  self.collecSpecial reloadData];
        [  self.collecSpecial.collectionViewLayout invalidateLayout];
    });

    [pro stopAnimating];
}


text:
Q: Ansible best way to capture result from aws_s3 module if download failed and fall back to get_url? I want to use aws_s3 module and if the download failed it will fall back to get_url to download from the web,
what I use to have is using block/rescue option but i feel there is much elegant way to do it
maybe capture the error of the aws_s3 command and based on this to decide what to do
how can I improve this?
- name: download
   block:
        local_action:
         module: aws_s3
         bucket: bucket_x
         object: "foo.zip"
         dest: "/home/home/foo.zip"
         mode: get
  rescue:

      get_url:
        url_username: "xxx"
        url_password: "xxx"
        dest: "/home/home/"
        url: "http://ftp.xx/foo.zip"

this is working but I'm not sure its the best way to implement this logic
is there more elegant way to do it but not complex?
I thought about capturing the output of aws_s3 , but this can be changed over time .


text:
Q: Is this spot significant in Reflecting Cave? If you're not paying attention, there is a short hidden path in the Reflecting Cave that leads to a dead end. In this path you can find the HM for Gyro Ball, but it's at the dead end that has me curious. What is the significance of this area? If you bring a certain Pokemon or item to this spot, does something happen? It's the only area of the cave that I saw a big spot of light.

A: This dead end is the location of Alakazam's Mega Evolution stone. That is one of the stones that you can only find between 8 and 9 PM after your Mega Ring has been upgraded in the post-game.


text:
Q: Rails: Can't find assets via SCSS @import in test environment My team is using SitePrism for feature tests in a Rails 4 app, and we're currently restructuring our CSS assets in the project. One of the asset files includes a line that @imports from a subdirectory:
app/assets/stylesheets/lib/admin.scss.css:
   @import "base/base-admin";

and app/assets/stylesheets/lib/base/base-admin.scss in turn includes:
   @import "shared/reset";
   @import "shared/colors";
   @import "shared/breakpoints";
   @import "shared/grids";

This all works fine in development in the browser (I get no errors from requests to lib/admin.css, and I see the CSS rules are applied to the page correctly).
But when I run our feature tests, I get
Failure/Error: @page.load
ActionView::Template::Error:
  File to import not found or unreadable: base/base-admin.
  Load paths:
    /Users/duncanmalashock/ruby_projects/platform
    /Users/duncanmalashock/ruby_projects/platform/.bundle/gems/ruby/2.2.0/gems/bootstrap-sass-3.3.4.1/assets/stylesheets
 (in /Users/duncanmalashock/ruby_projects/platform/app/assets/stylesheets/lib/admin.scss.css)

However, none of the other assets are broken in the test environment. Why can't these be found?

A: This turned out to be a naming error. The suffixes on my manifest were ".scss.css", instead of ".css.scss" (which would have been correct).
The Asset Pipeline starts with the last suffix, and tries to run a process that matches it, then repeats with the next suffix in.
So the Pipeline was trying to @import a file in the wrong way (there's an @import directive in CSS and also differently behaving one in SCSS), which was leading to unexpected behavior.


text:
Q: How to convert a string to a number in the where statement I am trying to convert a string to a number. I have values stored like $4,215.35 so I want to convert that to a number so I can check if the value is greater than 50 or not.
If the value is greater than 50 then I want to update a field called first_sale_on with a time stamp.
Here is what I have done
UPDATE
    account AS m
    INNER JOIN ps_weekly_activations AS t ON t.mid = m.mid
SET
    m.first_sale_on = CAST(CONCAT(STR_TO_DATE(t.Date_First_PL_Sale, '%c/%e/%Y'), ' 00:00:00') AS datetime)
WHERE
    t.Date_First_PL_Sale IS NOT NULL
    AND CONVERT(REPLACE(REPLACE(Private_Label_Net_Sales, '$',''), ',', ''), DECIMAL(18,2) ) >= 50;

I get the following error:

"Error code 1366: Incorrect decimal value '' at row -1..

The error means that I am trying to do operation on a string in the where statement. but I am not sure why the conversion is failing here. If the convert works then the query should execute with no problems.

A: I found the problem and the solution. The problem is that there was a bad data in that table that was throwing the query off.
To solve it I have added a check print i do the arithmetic. the check will check if the value is a number or not
This my new query (I hope my answer helps someone else)
UPDATE
    account AS m
    INNER JOIN ps_weekly_activations AS t ON t.mid = m.mid
SET
    m.first_sale_on = CAST(CONCAT(STR_TO_DATE(t.Date_First_PL_Sale, '%c/%e/%Y'), ' 00:00:00') AS datetime)
WHERE
    t.Date_First_PL_Sale IS NOT NULL

AND CONCAT('', REPLACE(REPLACE(Private_Label_Net_Sales, '$',''), ',', '') *1 ) = REPLACE(REPLACE(Private_Label_Net_Sales, '$',''), ',', '')

    AND CONVERT(REPLACE(REPLACE(Private_Label_Net_Sales, '$',''), ',', ''), DECIMAL(18,2) ) >= 50;


text:
Q: C# sudoku solver Variable malfunction The problem here is, that emptyRow and emptyCol variables somehow do not tend to work and are always equal 0, even when I actually assign them values at initialization!
As well, do you see any mistakes that I could have made here?
Here's the code:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    // Declaration of Fields, used to conjoin methods
    RichTextBox[,] Grid = new RichTextBox[9, 9];
    int emptyRow, emptyCol;

    private void Form1_Load(object sender, EventArgs e)
    {
        // Creating a grid of Textboxes, for further use in a solving algorithm
        // and setting alignment to center for all boxes
        int i = 0;
        for (int row = 0; row < 9; row++)
        {
            for (int col = 0; col < 9; col++)
            {
                i++;
                Control[] foundControls = this.Controls.Find("Grid" + i.ToString(), false);
                foreach (Control currentControl in foundControls)
                {
                    if (currentControl.GetType() == typeof(RichTextBox))
                    {
                        RichTextBox currentRichTextBox = (RichTextBox)currentControl;
                        Grid[row, col] = currentRichTextBox;
                        currentRichTextBox.SelectionAlignment = HorizontalAlignment.Center;
                    }
                }
            }
        }
    }
    bool SolveSudoku()
    {
        FindUnassignedLocation();
        for (int num = 1; num <= 9; num++)
        {
            if (NoConflicts(emptyRow, emptyCol, num))
            {
                Grid[emptyRow, emptyCol].Text = num.ToString();
                return true;
            }
        }
        return false;
    }
    // Method to determine wether any fields are empty and if so, returning the first found
    bool FindUnassignedLocation()
    {
        for (int row = 0; row < 9; row++)
        {
            for (int col = 0; col < 9; col++)
            {
                if (Grid[row, col].Text == "")
                {
                    emptyRow = row;
                    emptyCol = col;
                    return true;
                }
            }
        }
        return false;
    }
    // Check if there are any conflicts in row or col or box
    bool NoConflicts(int row, int col, int num)
    {
        return !UsedInRow(row, num) && !UsedInCol(col, num) &&
            !UsedInBox(row - row % 3, col - col % 3, num);
    }
    // Check if there are any conflicts in row
    bool UsedInRow(int row, int num)
    {
        for (int col = 0; col < 9; col++)
        {
            if (Grid[row, col].Text == num.ToString())
            {
                return true;
            }
        }
        return false;
    }
    // Check if there are any conflicts in column
    bool UsedInCol(int col, int num)
    {
        for (int row = 0; row < 9; row++)
        {
            if (Grid[row, col].Text == num.ToString())
            {
                return true;
            }
        }
        return false;
    // Check if there are any conflicts in box
    }
    bool UsedInBox(int boxStartRow, int boxStartCol, int num)
    {
        for (int row = 0; row < 3; row++)
        {
            for (int col = 0; col < 3; col++)
            {
                if (Grid[row + boxStartRow, col + boxStartCol].Text == num.ToString())
                {
                    return true;
                }
            }
        }
        return false;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        SolveSudoku();
    }

}

}

A: I've found a few errors in your code:
Line:26 Control[] controlsFound = this.Controls.Find("Grid" + i.ToString(), false);
The variable controlsFound is never used. It seems to me like you should be using it in the foreach loop below.
I think your main problem is the call to FindUnassignedLocation(); It returns a bool, but you are not checking it. It should probably be:
bool SolveSudoku()
{
    if (FindUnassignedLocation())
    {
        for (int num = 1; num <= 9; num++)
        {
            if (NoConflicts(emptyRow, emptyCol, num))
            {
                Grid[emptyRow, emptyCol].Text = num.ToString();
                return true;
            }
        }
    }
    return false;
}


text:
Q: button can toggle boolean in C# trying to make button in asp.net and C# that change its text from "Show Edit" to "Hide Edit" and it will do more code in future like making text box visible and invisible so I can't use the short if statement.
first it tried to put a boolean to be like switch but it didn't worked.
if(isEditing)
{
    Button1.Text = "Show Edit";
    isEditing = false;
}
if(!isEditing)
{
    isEditing = true;
    Button1.Text = "Hide Edit";
}

this is the code inside the button method and the "isEditing" boolean is decelerated above in C# class and initialized with default value.
it is not working for some reason it just switch one time and it not change.

A: I guess you wanted to use else if or simply else instead of a second ìf where you change the isEditing to true immediately:
if(isEditing)
{
    Button1.Text = "Show Edit";
    isEditing = false;
}
else
{
    isEditing = true;
    Button1.Text = "Hide Edit";
}

You could also use:
Button1.Text = isEditing ? "Show Edit" : "Hide Edit";
isEditing = !isEditing;


text:
Q: Interrupt handler won't work on two similar machines I register an interrupt handler for my keyboard via a kernel module, the code works well on my virtualbox Linux guest Light Ubuntu 20.04 5.13.0-51-generic, the interrupt handler work as intended. However, when the same code is being run on my host operating system, Ubuntu 20.04 5.13.0-51-generic, the init function ends successfully but the interrupt handler is never called when an interrupt occurs.
request_irq(IRQ_NUMBER, keyb_handler, IRQF_SHARED, "irq_keyboard",
                        (void *)keyb_handler);

Light Ubuntu (VM) /proc/interrupts (Entry 1)
// When the module isn't loaded, it's like that
1:         56          0   IO-APIC   1-edge      i8042
// When the module is load, it's like that
1:        272          0   IO-APIC   1-edge      i8042, irq_keyboard

Ubuntu (Host) /proc/interrupts (Entry 1)
// Nothing is shown unless the module is loaded. if the module is loaded, then it's
1:        .. 0  ..  IO-APIC    1-edge      irq_keyboard

What can be the problem? I debugged the code many times on both operating system, and I know for a fact that the code is fine, hence it must be a portability issue. If any additional information is needed, lmk.

A: Note the "PC" is the original IBM PC from 1987, and its successors. Copies of the original PC copied the hardware, of course, so that the software would still work. And later editions also had to copy the hardware, so that the software would still work.
In these computers, the keyboard port was connected to an Intel 8042 computer chip which was then connected to the CPU. The 8042 chip was in charge of converting between the signals from the keyboard, and the signals to the CPU. So for example it sent an interrupt when it noticed a key was pressed. The interrupt was hard-wired to a certain pin of the interrupt controller.
Modern computers are more flexible. Everything is connected through a bus like PCIe or USB. If it was hard-wired to a keyboard controller chip to a certain interrupt pin, you could only have one keyboard, and what would be the fun in that? USB lets me plug in as many keyboards as I want.
Do you have a USB keyboard? Then your keyboard connection is most likely going through a USB bus to a USB controller chip connected to a PCIe bus connected to the processor. There is no 8042 chip involved. There might not even be an interrupt pin - the controller could use Message-Signaled Interrupts instead.
Your BIOS may have a setting for "PS/2 emulation". If this is turned on, when the operating system tries to talk to that ancient 8042 chip, the BIOS intercepts it and simulates what the 8042 would have done. Probably this is turned off, because you are using an OS newer than 20 years, which knows how to access a USB port, and doesn't need the emulation.
Meanwhile your VM simulates the 8042 chip because it's convenient, more compatible with older operating systems, etc. It might depend on how the VM is set up - there might be an option to choose between an 8042 (PS/2) or USB keyboard. Notice that Linux is using the "i8042" (intel 8042) driver.


text:
Q: Get Rad Numeric Textbox value? Here i'm going to get RAD Numeric textbox value in client side.but failed.There's no any error shown.Here i use alert for testing purpose
My code as follow,(Here i tries 2 ways )
alert($find('<%=Live_count.ClientID%>').get_textBoxValue());

alert($find('<%=Live_count.ClientID%>').get_value());

The above thing i got it from here Link

A:     function OnClientValueChanged(sender, args)
  {
logEvent(GetServerId(sender.get_id()) + ".OnClientValueChanged: Value is changed to " +   args.get_newValue());
   }

check client side demo :http://demos.telerik.com/aspnet-ajax/input/examples/programming/clientside/apievents/defaultcs.aspx
    and : http://www.telerik.com/help/aspnet-ajax/introduction.html


text:
Q: Can I create a car that powered by sound energy? If I create a car that has an ideal loudspeaker (that can emit sound with any positive real number of amplitude) on car roof then loudspeaker emit very very loud sound (sound may be complex or be pulse which has specific rhythm) , can this car move ?
I know that electromagnetic has momentum but I don't know that sound really hasn't momentum or it has ?

A: No, a car with a speaker attached will not be propelled forwards. Sound waves are longitudinal waves and do not carry mass with them as they propagate and therefore do not have any momentum. The diagram below shows how longitudinal waves can send a vibration through a material without carrying any mass. Look at the red dots, they have no net movement and therefore the sound wave has no net momentum.
The most that would happen to your car is that it would vibrate backwards and forwards as the speaker extends and retracts.

A: I disagree with Ryan's answer. A source of sound can cause acoustic streaming, which is a net flow of ambient fluid away from the source. See this demonstration. Therefore a source of sound experiences a back-thrust which can be utilised for propulsion, although it would likely be inefficient.
The picture of a vibrating medium, with no mean flow, which extends forever is correct only if the medium is non-dissipative, but any real fluid is dissipative. This gives rise to an effective body-force on the fluid given by the averaged quantity $\nabla\cdot\overline{\rho\mathbf{v}\mathbf{v}}$, in which $\mathbf{v}$ is the velocity field with zero mean corresponding to pure vibration.


text:
Q: box-shadow property makes menu overlay another div and look bad I have a menu div and below is content div. When I add box-shadow to content div, it will paint over menu div and it doesn't look good. I would like to see box-shadow being painted behind menu div.
Is there way how to achieve it?

A: Using z-index you can position the "layering" of your elements:
.menu
{
   z-index:1;
   position: relative;
}

.content
{
   z-index:0;
   position: relative;
}


text:
Q: Custom Objects Record Type Deactivations What happens when a custom objects record type is made inactive without transferring the record to another recordtype.

A: Nothing occurs to the existing data. Deactivating a record type means it can no longer be selected for new records, and existing records can no longer be changed to that record type. Existing records of that record type can still be edited without changing the record type. Upon deletion of a record type, however, all records with the affected record type must be changed to a new record type.


text:
Q: Laravel relations with multiple models I am building a blog application and I have
Post, City, Neighbourhood, SubNeighbourhood.
The relations that I have until now are between City, Neighbourhood and subNeighbourhood like follows:
subNeighbourhood belongs to Neighbourhood
Neighbourhood belongs to city

The second relation is like
City hasMany Neighbourhoods
Neighbourhood hasMany subNeighbourhoods

My problems are when I create the post. The posts table have id_city, id_neighbourhood and id_subNeighbourhood.
The questions that I have are:
If the post structure is correct? I feel like having many "id_..." is not ok.
Second issue is how do I write the relation in posts? All the columns "id_..." are having foreign keys to each corresponding table.

A: For what I can understand from your explanation the post table should have only a subneighbourhood_id field, in the Post class the relation should be:
public function subneighbourhood()
{
    return $this->belongsTo('App\Subneighbourhood');

So a Post belongs to a Subneighbourhood that belongs to a Neighbourhood that belongs to a City

A: I think a polymorphic relation will be a nice solution to your problem. (I didn't test my code or what so ever)
class Post extends Model
{
   // Can return a City or Neighbourhood or SubNeighbourhood
   public function related() {
      return $this->morphTo();
   }
}

class City extends Model
{
   public function posts() {
      return $this->morphMany(App\Models\Post::class, 'related');
   }
}

class Neighbourhood extends Model
{
   public function posts() {
      return $this->morphMany(App\Models\Post::class, 'related');
   }
}

How to use this:
Example if we have a post that's related to a city
$post = Post::find(1);
$true = ($post->related instanceof City);  // This will be true if post related to a city
$neightbourhoods = $post->related->neightbourhoods(); // All the neightbourhoods of the city

Example if we have a post that's related to a neighbourhood
$post = Post::find(2);
$true = ($post->related instanceof Neighbourhood); // This will be true if post is related to a neighbourhood
//In this case we can do
$post->neighbourhood->subNeighbourhoods(); // All the sub neighbourhoods

You can safe post easily with
$post = new Post();
$post->related = City::find(1);
$post->save();

or

$post = new Post();
$post->related = Neighbourhood::find(1);
$post->save();


text:
Q: How to create an alias of an interface from another module in typescript? I have 2 typescript files.
commons.d.ts
module "commons" {
    interface IUser {
        name:string;
    }
}

main.ts
import commons = module("commons");
class User implements commons.IUser {
    name:string;
}

Since I will use commons.User a lot in the main.ts, I want to create an alias for it. For I change the code to:
import commons = module("commons");

import UserAlias = commons.IUser;

class User implements UserAlias {
    name:string;
}

But it throws error when compiling:
E:\WORKSPACE\app\typescripts>tsc main.ts
E:/WORKSPACE/app/typescripts/main.ts(3,27): The property 'IUser'
    does not exist on value of type 'commons'
E:/WORKSPACE/app/typescripts/main.ts(3,19): A module cannot be aliased
    to a non-module type

How to fix it?

A: To create an alias for an interface, you can extend it on a local interface:
I have tested this with:
commons.ts
export interface IUser {
    name: string;
}

app.ts
import commons = module("commons");

interface userAlias extends commons.IUser {
}

class User implements userAlias {
    name: string;
}

I have changed the commons.ts slightly because when you use External Modules don't usually have a module declaration inside of them - the file is the module. The module declaration is used for internal modules.
You can read more about that in section 9.4 of the TypeScript language specification.

A: You can always alias on importing:
import { IUser as userAlias } from "commons"

Ancient question, I know, but for anyone landing here now...


text:
Q: defer final value to subclass java I have a question similar to In Java, why can't I declare a final member (w/o initializing it) in the parent class and set its value in the subclass? How can I work around? but which requires a different solution. As in the above case, I want to declare a variable to be Final in the superclass, but I want the subclass to give it the value. What makes my problem different though is that I don't want the value passed in to the subclass, I want the subclass to 'know' its value, so the above solution doesn't work for me. Then I tried to do this:
public class Superclass{
    public final int x;
    public Superclass(int x){
        this.x = x;
    }
}
public class Subclass extends Superclass{
    public Subclass(){
        x = 1;
        super(x);
    }
}

...which didn't work (the call to super() must be on the first line :/ ). But this is basically the behavior that I want. Is there a good way to do this? Thanks!

A: You could do
super(1);

so instead of setting x, you are passing the value.

A: An alternative to the one above:
class Superclass{
    public final int x;

    public Superclass(int x){
        this.x = x;
    }

    public static Superclass createNew(Integer y) {
        return new Superclass(y);
    }

    public void print() {
        System.out.println(this.x);
    }
}
class Subclass extends Superclass{
    public Subclass(int x) {
        super(process(x));
    }

    public static Integer process(Integer y) {
        if (y < 100)
            y += 100;
        return y;
    }
}

A: I don't have a java compiler handy, but you're attempting to set x = 1 twice in this code.
x = 1;

And
super(x); //==> this.x = x

Do as @Kal said and do super(1), as x = 1 won't work.


text:
Q: Grouping by commas I want to accomplish the following:
ID  serviceaccess
11  Value1
11  Value2
11  Value3
22  Value2
22  Value1
22  Value1

ID
11 value1, value2, value3
22 value2, value1, value1

But I can't use stuff STUFF(( because my system doesn't support it.
This link doesn't really help. I have tried everything so far, but ran out of ideas. Thanks
SQL Server : GROUP BY clause to get comma-separated values
Thought about this, but doest' work. Please help:
WITH RecurRanked ( dbid, rnk, serviceaccess)
             AS (
                SELECT t.t1.dbid, t.t1.rnk, t.t2.serviceaccess || ', ' || t.t1.serviceaccess
                FROM t.t1
                INNER JOIN t.t2  ON t.t1.dbid = RecurRanked.dbid AND t.t1.rnk = RecurRanked.rnk + 1)
SELECT dbid, MAX(serviceaccess)
FROM RecurRanked
GROUP BY dbid;

    SELECT t.t1.dbid, t.t1.rnk, t.t2.serviceaccess || ', ' || t.t1.serviceaccess
                FROM t.t1
                INNER JOIN t.t2  ON t.t1.dbid = t.t2.dbid AND t.t1.rnk = t.t2.rnk + 1


text:
Q: Pulling links to all documents that have a column "XXXX" in sharepoint I have a site collection in which there are lot of sites, and each site has a number of documents which are tagged as "XXX" in a particular column. Now, if I have to pull links to all documents in the site collection that are tagged "XXX" and display them in a list, how do I go about it? I mean how do I start it?

A: Do you have any knowledge with JavaScript ? Because you could use it to do this kind of task...
For example with SPServices you can get all the sites:
$().SPServices({
  operation: "GetAllSubWebCollection",
  completefunc: function(xData, Status) {
    $(xData.responseXML).find("Webs > Web").each(function() {
      var $node = $(this);
      getDocuments( $node.attr("Title") );
    });
  }
});

Then with SharepointPlus (because the syntax is easier but you can still use SPServices) you can get the documents:
function getDocuments(site) {
  $SP().list("My Document List", site).get({fields:"Title",where:"My_x0020_Column = 'XXX'"}, function(data) {
    for (var i=data.length; i--;) console.log(data[i].getAttribute("Title"))
  })
}

Of course at this point, instead of console.log you should inject the link into your webpage.
It's just a very basic example of what you could do.


text:
Q: Rails: change column name and not value in where clause How could I change the column name in the argument of a where clause? Something like this is what I'm after:
def self.filter_by_time(datetime)
  where('? < ?', datetime, Time.now)
end

Thanks!

A: def self.filter_by_time(datetime)
  where("#{datetime} < ?", Time.now)
end

A: You can try this:
def self.filter_by_time(datetime)
  where("datetime < ?", Time.now)
end


text:
Q: Tag placing with amsmath I'm using amsmath and its \tag command to tag equations. I remember having a situation where I liked having the tag on the left better than on the right. So I gave my class (which is report btw) the leqno options. Now, however, I find myself wanting to revert to reqno. However, I fear actually removing leqno will make the above mentioned situation look worse. I found that the solution in Switch between leqno and reqno options (of amsmath) in the same document does not work with equation:
\documentclass{report}
\usepackage[leqno]{amsmath}

\makeatletter
\newcommand{\leqnomode}{\tagsleft@true}
\newcommand{\reqnomode}{\tagsleft@false}
\makeatother
\begin{document}

\begin{align}
  f(x) &= ax^2 + bx + c \\
  g(x) &= dx^2 + ex + f
\end{align}

\reqnomode

\begin{align}
  f(x) &= ax^2 + bx + c \\
  g(x) &= dx^2 + ex + f \tag{e}
\end{align}

\begin{equation}
  a^2+b^2=c^2.\tag{1}
\end{equation}

\leqnomode

\begin{equation}
  -\Delta\phi=4\pi k\rho.\tag{2}
\end{equation}

\end{document}

Output:

The first equation should still be in \reqnomode (alias \tagsleft@false) from the second align, yet the tag is on the left. How do I solve the problem without using an align or such which are for multiline display and would therefore be out of place on a single one-line equation?

A: \documentclass{report}

\usepackage[leqno]{amsmath}

\makeatletter
\newcommand{\leqnomode}{\tagsleft@true\let\veqno\@@leqno}
\newcommand{\reqnomode}{\tagsleft@false\let\veqno\@@eqno}
\makeatother
\begin{document}

\begin{align}
  f(x) &= ax^2 + bx + c \\
  g(x) &= dx^2 + ex + f
\end{align}

\reqnomode

\begin{align}
  f(x) &= ax^2 + bx + c \\
  g(x) &= dx^2 + ex + f \tag{e}
\end{align}

\begin{equation}
  a^2+b^2=c^2.\tag{1}
\end{equation}

\leqnomode

\begin{equation}
  -\Delta\phi=4\pi k\rho.\tag{2}
\end{equation}

\end{document}


text:
Q: Ошибка в хроме: Error in event handler for extension.onRequest: undefined Сегодня целый день непонятная и ранее невидимая мной ошибка в хроме -

Error in event handler for
extension.onRequest: undefined
extensions::event_bindings:383

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>

Text

Что это такое и как с этим бороться?
A: Ошибка в расширении вашего браузера.
Конструкция extension.onRequest устарела.
Вместо нее рекомендуется использовать runtime.onMessage

Отключайте расширения по одному, пока не найдете проблемное.


text:
Q: Firebase query from 2 nodes cards

    cars
    -- idcars
        -- type:
        -- age:
        -- user: iduser

    users
    -- iduser
     -- username
     -- usermail

    ads
    -- iduser
     -- ads1 : idcars
     -- ads2 : idcars

With this structure how it's possible to retrieve all ads for a user together with their own data?
Example:
ads1:
type: golf
age:2

I'm completely new with Firebase

A: This should be what you need to get the authenticated user and then you can use this model to just retrieve the whole ads branch filtering through it to have everyones ads detail (if you want)
let userID = FIRAuth.auth()?.currentUser?.uid
ref.child("ads").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in

  // Get user value
  let value = snapshot.value as? NSDictionary // This gets the whole ad branch with all the users ad data
  let adsValue = value?["ads1"] as? String ?? "" // This is the specific value of 'ads1' node

  // ...
  }) { (error) in
    print(error.localizedDescription)
}

A: Maybe like this,
get the user id then put it in ref.child(yourString)
ref = FIRDatabase.database().reference()
    ref.child("iduser").observeSingleEvent(of: FIRDataEventType.value, with: { (snapshot) in })

A: This will require two read operations, one for the user and one for their ads. See the Firebase documentation for reading data and for querying lists.
If you're having trouble making this work, post the minimal code that reproduces the problem.


text:
Q: Maven project deployment error for ContextLoaderListener I am converting my project from ant to maven. The build process succeeded asda
com.ibm.ws.webcontainer.webapp.WebApp logError SRVE0293E: [Servlet Error]-[Failed to load listener: org.springframework.web.context.ContextLoaderListener]: java.lang.ClassNotFoundException: class java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

I have checked the project Deployment Assembly and found that Maven Dependecy in added and classpath entry. My war also contains all jars under WEB-INF/lib. Can anyone help me to resolve this.
Thanks,
Surodip


text:
Q: Error C2011 '_iobuf': 'struct' type redefinition I have problems with my code, after including dirent.h in my project, I got the error

Severity  Code    Description Project File    Line    Suppression State
Error   C2011   '_iobuf': 'struct' type redefinition    KittenProject   C:\Program Files (x86)\Windows Kits\10\Include\10.0.18362.0\ucrt\corecrt_wstdio.h   26

in the corecrt_wstdio.h file, line 26
how can I fix this? thanks in advence


text:
Q: Block web traffic from internet (public access) I just configured an NGINX instance on the Jelastic platform.
In my environment's firewall inbound rules there are now a few default rules added.
With source All. (HTTP, HTTPS, ...)
I changed the source of these firewall rules to Local LAN.
So I expect that when I go to my Jelastic public URL in my browser on my own computer, I do not get a website but I'm blocked by the firewall.
This is not happening. I do not want the website to be used from the outside. This environment will host some REST API's and workers running on the inside and only triggered by other environments I have.
Kind regards.
Roel

A: We recommend following this guide to disable access to your container (CT) from the outside: https://docs.jelastic.com/release-notes-59/#restrict-node-access-via-shared-load-balancer-slb
However, please keep in mind that you'll not be able to access this CT from another CT too.
UPDATE:
little clarification
If "Access via SLB" disabled, the nodes within the layer are inaccessible via SLB (including the Open in Browser button in the dashboard) and return the 403 "Forbidden error" instead of the intended service. Herewith, access via the private network from the other nodes of the environment, access via SSH and access via endpoints from the public network is not affected.
We also want to draw your attention to that described feature is available from the Jelastic PaaS 5.9 release


text:
Q: KeyListener not working and map overlapping character My KeyListener and the methods work, but they don't do anything. When I run the code and I try to use the arrow keys, nothing happens. I also have another problem. I'm making a game and I already did the map, but when I put the map in, the map has priority and covers my character. How would I go about fixing these?
This is the JFrame Package.
package MyGamePKG;

import java.awt.BorderLayout;

public class GameJFrame extends JFrame {

private JPanel contentPane;
private int x,y,x_vel,y_vel;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                GameJFrame frame = new GameJFrame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public GameJFrame() {

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 720, 520);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    GameJPanel Jpanel = new GameJPanel();
    Jpanel.setBounds(0, 0, 720, 480);
    contentPane.add(Jpanel);
    Jpanel.setLayout(null);

}

}

This is the JPanel.
package MyGamePKG;

import java.awt.BasicStroke;

public class GameJPanel extends JPanel implements ActionListener, KeyListener {

private int frameRate = 30;
private int x=0;
private int y=0;
private int x_vel, y_vel;
private Image map;

/**
 * Create the panel.
 */
public GameJPanel() {
    new ImageIcon(getClass().getResource("/Resources/gamemap.png"));
    gamemap = map.getImage(); //error here
    this.addKeyListener(this);
    this.setFocusable(true);
    Timer timer = new Timer(30, this);
    timer.start();

}

}

public void background()
{
    ImageIcon icon = new ImageIcon(this.getClass().getResource("/Resources/gamemap.png"));
    map = icon.getImage();
}
@Override
public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    setBackground(Color.WHITE);

    Graphics2D g2d = (Graphics2D) g;

    RenderingHints rh = new RenderingHints( RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);

    g2d.setRenderingHints(rh);

    g2d.setColor(Color.green);
    g2d.setStroke(new BasicStroke(5));

    myDrawBoxOvalsandRect(x,y,100,g2d);
    myDrawArc(x+25,y+40,50,50,550,170,g2d);
} // paintComponent
public void myDrawBoxOvalsandRect( int x, int y, int scale, Graphics my_g)
{
    my_g.setColor(Color.cyan);
    my_g.fillOval(x, y, 100, 100); //face

    my_g.setColor(Color.red);
    my_g.fillOval(x+20, y+25, 15, 15); //left eye

    my_g.setColor(Color.red);
    my_g.fillOval(x+60, y+25, 15, 15); //right eye

    my_g.setColor(Color.cyan);
    my_g.fillRect(x+25,y+100,50,80);//body

    my_g.setColor(Color.cyan);
    my_g.fillRect(x-30,y+105,55,20); //left arm

    my_g.setColor(Color.cyan);
    my_g.fillRect(x+70, y+105, 60, 20); //right arm

    my_g.setColor(Color.red);
    my_g.fillOval(x-47, y+105, 20, 20); //left hand

    my_g.setColor(Color.red);
    my_g.fillOval(x+126,y+105,20,20); //right hand

    my_g.setColor(Color.cyan);
    my_g.fillRect(x+25, y+175, 20, 50); //left leg

    my_g.setColor(Color.cyan);
    my_g.fillRect(x+55,y+175,20,50); // right leg

}
public void myDrawArc(int x, int y, int height, int width, int angle1, int angle2, Graphics my_g)
{
    my_g.setColor(Color.red);
    my_g.drawArc(x, y, 50, 50, 550, 170); //happy face
}
@Override
public void keyPressed(KeyEvent e) {
    // TODO Auto-generated method stub
    int c = e.getKeyCode();

    if(c == KeyEvent.VK_LEFT)
    {
        x_vel = -1;
        y_vel = 0;
    }
    if(c == KeyEvent.VK_UP)
    {
        x_vel = 0;
        y_vel = -1;
    }
    if( c == KeyEvent.VK_RIGHT)
    {
        x_vel = 1;
        y_vel = 0;
    }
    if( c == KeyEvent.VK_DOWN)
    {
        x_vel = 0;
        y_vel = 1;
    }
    repaint();

}
@Override
public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub
    x_vel = 0;
    y_vel = 0;
    repaint();
}
@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}
@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if(x < 0)
    {
        x_vel = 0;
        x = 0;
    }
    if(x > 720)
    {
        x_vel = 0;
        x = 720;
    }
    if(y < 0)
    {
        y_vel = 0;
        y = 0;
    }
    if(y > 480)
    {
        y_vel = 0;
        y = 480;
    }
    x = x + x_vel;
    y = y + y_vel;
    repaint();

}

}

A: You have a few problems you need to deal with

*

*You've created two sets of variable. One set in your frame, and one set in your panel. With your Keyalistener, you are only changing the values of the ones in the frame, which will have no affect on the ones in the panel.

*Updates to the UI should be done on the Event Dispatch Thread. Don't use a new thread with while(true) and Thread.sleep(). Instead use a javax.swing.Timer for animation. See more at How to Use Swing Timers. You also see a bunch of examples here and here and here and here and here and here.

*You should be using key binding for key specific actions, instead of KeyListener. See more at How to Use Key Bindings. You can also see a simple example here

Others:

*

*Why are you using a ActionListener when it is not being added to anything?

*Don't use null layouts. Learn to use LayoutManagers, and let them do the sizing and positioning for you.

*For painted panels, you should override getPreferredSize() to set a preferred size to the panel, and it will be respected when you pack() your frame (as you should, instead of setting the size)

*Don't set the background in the paint method. Do it in the constructor.

UPDATE
Here is the complete code. It works fine for me
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;

public class GameFrame extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GameFrame frame = new GameFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public GameFrame() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 720, 520);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        GameJPanel Jpanel = new GameJPanel();
        Jpanel.setBounds(0, 0, 720, 480);
        contentPane.add(Jpanel);
        Jpanel.setLayout(null);

    }
}

class GameJPanel extends JPanel implements ActionListener, KeyListener {

    private int frameRate = 30;
    private int x = 0;
    private int y = 0;
    private int x_vel, y_vel;
    private Image map;

    /**
     * Create the panel.
     */
    public GameJPanel() {
        map = new ImageIcon(getClass().getResource("/resources/gamemap.png")).getImage();
        this.addKeyListener(this);
        this.setFocusable(true);
        Timer timer = new Timer(30, this);
        timer.start();
        /*
        Thread myAnimationThread = new Thread() {
            @Override
            public void run() {
                while (true) {
                    repaint(); // Refresh the display which calls paintComponent
                    try {
                        Thread.sleep(1000 / frameRate);
                    } // try
                    catch (InterruptedException ex) {
                    }
                } // while
            } // run
        }; // Thread
        */
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        setBackground(Color.WHITE);

        Graphics2D g2d = (Graphics2D) g;

        RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        g2d.setRenderingHints(rh);

        g2d.setColor(Color.green);
        g2d.setStroke(new BasicStroke(5));

        g2d.drawImage(map, 0, 0, 720, 480, getParent());
        myDrawBoxOvalsandRect(x, y, 100, g2d);
        myDrawArc(x + 25, y + 40, 50, 50, 550, 170, g2d);
    } // paintComponent

    public void myDrawBoxOvalsandRect(int x, int y, int scale, Graphics my_g) {
        my_g.setColor(Color.cyan);
        my_g.fillOval(x, y, 100, 100); // face

        my_g.setColor(Color.red);
        my_g.fillOval(x + 20, y + 25, 15, 15); // left eye

        my_g.setColor(Color.red);
        my_g.fillOval(x + 60, y + 25, 15, 15); // right eye

        my_g.setColor(Color.cyan);
        my_g.fillRect(x + 25, y + 100, 50, 80);// body

        my_g.setColor(Color.cyan);
        my_g.fillRect(x - 30, y + 105, 55, 20); // left arm

        my_g.setColor(Color.cyan);
        my_g.fillRect(x + 70, y + 105, 60, 20); // right arm

        my_g.setColor(Color.red);
        my_g.fillOval(x - 47, y + 105, 20, 20); // left hand

        my_g.setColor(Color.red);
        my_g.fillOval(x + 126, y + 105, 20, 20); // right hand

        my_g.setColor(Color.cyan);
        my_g.fillRect(x + 25, y + 175, 20, 50); // left leg

        my_g.setColor(Color.cyan);
        my_g.fillRect(x + 55, y + 175, 20, 50); // right leg

    }

    public void myDrawArc(int x, int y, int height, int width, int angle1,
            int angle2, Graphics my_g) {
        my_g.setColor(Color.red);
        my_g.drawArc(x, y, 50, 50, 550, 170); // happy face
    }

    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub
        int c = e.getKeyCode();

        if (c == KeyEvent.VK_LEFT) {
            x_vel = -1;
            y_vel = 0;
        }
        if (c == KeyEvent.VK_UP) {
            x_vel = 0;
            y_vel = -1;
        }
        if (c == KeyEvent.VK_RIGHT) {
            x_vel = 1;
            y_vel = 0;
        }
        if (c == KeyEvent.VK_DOWN) {
            x_vel = 0;
            y_vel = 1;
        }
        repaint();

    }

    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub
        x_vel = 0;
        y_vel = 0;
        repaint();
    }

    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        if (x < 0) {
            x_vel = 0;
            x = 0;
        }
        if (x > 720) {
            x_vel = 0;
            x = 720;
        }
        if (y < 0) {
            y_vel = 0;
            y = 0;
        }
        if (y > 480) {
            y_vel = 0;
            y = 480;
        }
        x = x + x_vel;
        y = y + y_vel;
        repaint();

    }
}


text:
Q: 'Textheight' is not a member of 'System.Windows.Forms.PictureBox' I am converting an old VB6 project to .NET. In the VB6 Project .TextHeight and .TextWidth were used for a picture box object. After I migrated the project from VB6 to .NET the compiler threw the error 'Textheight' is not a member of 'System.Windows.Forms.PictureBox'
tmpX = tmpX - (p.TextWidth(tmpStr) / 2.0#)

and
tmpY = tmpY - (p.Textheight(tmpStr) / 2.0#)

What is the .NET equivalent for these?

A: This snippet gets a high for some text headed for a multiline textbox or RTF box:
       txtPrompt.Height = Convert.ToInt32(Me.CreateGraphics().MeasureString(txtPrompt.Text, txtPrompt.Font, txtPrompt.Width).Height + 15)

.MeasureString() is the function you are looking for.


text:
Q: Fill in missing data by breaking down values from one day During data recording, there are sometimes power outages and then the consumption from several days aggregates within one day and is unreasonably large.
Sample data
df<-data.frame(dayofmonth=c(5,6,7, 8, 9, 10 ,11,12,13,14),
               measurement=c(301589, 301599, 301602, NA, NA, 301637.5, 301683.8, 301693.1, 301702.9, 301713.2)) %>%
  mutate(hotwater=c(0, diff (measurement)))

ggplot (df) +
  geom_col (aes (x = factor(dayofmonth), y = hotwater))

In this specific case, data for four days require corrections and supplements
B <- (301637.5 - 301599)/4

I want the final output to look something like this:
df<-data.frame(dayofmonth=c(5,6,7, 8, 9, 10 ,11,12,13,14),
               measurement=c(301589, 301599, 301599 + B, 301599 + 2*B, 301599 + 3 * B, 301637.5, 301648.3, 301657.6, 301667.4, 301677.7)) %>%
  mutate(hotwater=c(0, diff (measurement)))

ggplot (df) +
  geom_col (aes (x = factor(dayofmonth), y = hotwater))

A: It looks like you are try to interpolate the missing values based on the last value and the next one. The zoo::na.approx() function. Based on your first df this would be:
df %>%
  mutate(measurement = zoo::na.approx(measurement),
         hotwater=c(0, diff (measurement)))

https://www.rdocumentation.org/packages/zoo/versions/1.8-10/topics/na.approx


text:
Q: how to get anaconda version from conda list anaconda I am trying to get the anaconda version here, when I run conda list anaconda
I get the following result:

I want to be able to get the value 2019.10, I am not aware how to do so, I tried to get the type of conda list anaconda to know even how to deal with it, but I get error. Is there a way I can get the version which is 2019.10 here?

A: If you just want that string then:
conda list '^anaconda$' | tail -n1 | tr -s' ' | cut -f2 -d' '

or maybe more robust
conda list -e '^anaconda$' | awk -F'=' '!/^#/ {print $2}'


text:
Q: Generating Sequence for Each Group in MySQL How to generate this sequence for MySQL?
(N.B. :- for each unique pair the sequence is generated afresh)
1,1 -- 1
1,1 -- 2
1,1 -- 3
1,2 -- 1
1,2 -- 2
1,3 -- 1
1,4 -- 1
1,4 -- 2
1,4 -- 3

A: You need the row_number function in SQL Server for MySQL
SELECT
  @row_number := CASE
    WHEN @conc_no = conc THEN
    @row_number + 1
    ELSE
    1
    END AS num,
  @conc_no := mydata.conc AS conc
FROM
  (
    SELECT
      CONCAT(num1, ",", num2) AS conc
    FROM
      table1
    ORDER BY
      num1 ASC, num2 ASC
    ) mydata

Fiddle: http://sqlfiddle.com/#!9/ad4a0/3/0

A: create a table:-
create table dummy(id varchar(100));

insert values in a table :-
insert into dummy (id) values('1,1');
insert into dummy (id) values('1,1');
insert into dummy (id) values('1,1');
insert into dummy (id) values('1,2');
insert into dummy (id) values('1,2');
insert into dummy (id) values('1,3');
insert into dummy (id) values('1,4');
insert into dummy (id) values('1,4');
insert into dummy (id) values('1,4');

run the below query:-
select id,@aaaa:=ifnull(seq,@aaaa:=@aaaa+1)as seq from(select y.id,b,seq from (select
id,@aaa:=@aaa+1 as b from dummy cross join (select @aaa:=0)a) as y  left join
(select id,a,@aa:=@aa as seq from  (select * from (select id,@a:=@a+1 as a from dummy
cross join (select @a:=0)a)as b group by id)a cross join (select @aa:=1)as d )
 as x on x.a=y.b) as z cross join  (select @aaaa:=0)a;


text:
Q: Java Drawing Multiple Squares in Same JFrame I am trying to make an animation with multiple thread. I want to paint n squares where this n comes from commend-line argument. Every square has their x-y coordinates, colors and speed. They are moving to the right of the frame with different speed, color and coordinates. Since I am using multi thread I assume I have to control each squares. So I have to store each square object in the ArrayList. However, I am having trouble with painting those squares. I can paint one square but when I try to paint multiple squares, it does not show. Here what I have done so far:
DrawSquare.java
import java.awt.Graphics;
import javax.swing.JPanel;

public class DrawSquare extends JPanel {
    public Square square;
    public DrawSquare() {
        square = new Square();
    }

    @Override
    public void paintComponents(Graphics g) {
        // TODO Auto-generated method stub
        super.paintComponents(g);

    }

    @Override
    public void paint(Graphics g) {
        // TODO Auto-generated method stub
        super.paint(g);

        g.setColor(square.getC());
        g.fillRect(square.getX(), square.getY(), square.getR(), square.getR());
    }
}

Square.java
import java.awt.Color;
import java.util.Random;

public class Square {
    private int x,y,r,s;
    private Color c;
    private Random random;

    public Square() {
        random = new Random();
        x = random.nextInt(100) + 30;
        y = random.nextInt(100) + 30;
        r = random.nextInt(50) + 20;
        s = random.nextInt(20) + 5;
        c = new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getR() {
        return r;
    }

    public int getS() {
        return s;
    }

    public Color getC() {
        return c;
    }
}

Animation.java
import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Animation extends JFrame implements Runnable {
    private JPanel panel;
    private DrawSquare square;

    public Animation() {

    }

    public static void main(String[] args) {
        Animation w = new Animation();
        DrawSquare square = new DrawSquare();
        JFrame f = new JFrame("Week 9");
        int n = Integer.parseInt(args[0]);
        f.setVisible(true);
        f.setSize(700,700);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setResizable(false);
        for(int i=0; i<n; i++) {
            f.getContentPane().add(square);
        }
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub

    }
}

A: So, starting with...
public class DrawSquare extends JPanel {
    public Square square;
    public DrawSquare() {
        square = new Square();
    }

    @Override
    public void paintComponents(Graphics g) {
        // TODO Auto-generated method stub
        super.paintComponents(g);

    }

    @Override
    public void paint(Graphics g) {
        // TODO Auto-generated method stub
        super.paint(g);

        g.setColor(square.getC());
        g.fillRect(square.getX(), square.getY(), square.getR(), square.getR());
    }
}

As general recommendation, it's preferred to put custom painting in the paintComponent method (note, there's no s at the end)
When paint is called, the Graphics context has already been translated to the component coordinate position.  This means that 0x0 is the top/left corner of the component, this also means that...
g.fillRect(square.getX(), square.getY(), square.getR(), square.getR());

is painting the rect at x + x x y + y, which will, at the very least, paint the rect in the wrong position, at worst paint it beyond the visible scope of the component.
You're also not providing any sizing hints for the component, so it's default size will be 0x0, which prevent it from been painted.

Since I am using multi thread I assume I have to control each squares.

Well, since I can't really see what's driving the animation, I imagine that when you say "multi thread" you're suggesting that each square has it's own Thread.  In this case, that's a bad idea. Let's put aside the thread synchronisation issues for a moment, more threads doesn't equate to more work you can do, at some point, it will begin to degrade the system performance.
In most cases, a single, well managed thread, is all you really need.  You also have to understand that Swing is NOT thread safe.  This means that you shouldn't update the UI (or states that the UI relies on) from outside the context of the Event Dispatching Thread.
So, while you're thread can update the position of the rects, you need to take care to ensure that they are not been painted while they are been update. Once you've updated the state, you then need to trigger a paint pass (which is trivial in of itself)

So I have to store each square object in the ArrayList.

Yep, good start

However, I am having trouble with painting those squares. I can paint one square but when I try to paint multiple squares, it does not show.

Okay, so instead of using multiple components, use one.  Run through your ArrayList within the paintComponent method of this component and paint all the rects to it.  This provides a much simpler way to manage things like bounds detection, as you have only one container to worry about.
I'd highly recommend you have a look at:

*

*Java Bouncing Ball which demonstrates many of the concepts discussed here

*Concurrency in Swing

*How to use Swing Timers

*Performing Custom Painting

*Painting in AWT and Swing


text:
Q: Get Data for ArcPad extension and python Is it possible to call the 'Get Data for ArcPad' extension using python?  If so would someone be willing to share their code?

A: Yes, it is possible. ArcPad comes with a toolbox and geoprocessing tools. There are two tools that might be of interest, the ArcPad Checkout and the ArcPad check in. If you export them to py you will learn their arcpy parameters and variables.
    arcpy.ArcPadCheckout_ArcPad("", "", "", "", "", "", "", The_full_path_and_name_of_the_AXF)


text:
Q: Voice Recognition stops listening after a while i am using android speech recognizer and it stops listening after few seconds? What can be the solution?

A: set startistening at End or Error
@Override
public void onEndOfSpeech(){
System.out.println("End");
if(error != -1){
sr.startListening(intent);
}
}
@Override
public void onError(int error){
if(error != -1){
sr.startListening(intent);
}
}


text:
Q: Count of binary matrices that avoids a certain sub-matrix What is the number of $n$ by $m$ zero-one matrices that avoid a $2$ by $2$ sub-matrix of all ones?
For the motivation, I'm trying to generate nontrivial examples of differential posets, which are locally finite, ranked, and equipped with a $\mathbb Z$-linear operator $Ux = \sum_{y \gtrdot x} y$.
By restricting to $R_n$, the set of elements of rank $n$, we get a map $U_n: \mathbb Z[R_n] \to \mathbb Z[R_{n+1}]$ ($\mathbb Z[R_n]$ is the free vector space with basis vectors indexed by elements in $R_n$.)  The main condition differential posets satisfy is $U_n^t U_n - U_{n-1} U_{n-1}^t = I$, which is called the differential condition.
Since knowing $U$ give complete information about the poset, I'm trying to recursively generate $U_n$--given $U_{n-1}$, figure out all the matrices $U_n$ that satisfies the differential condition above.  It turns out that the differential condition forces $U_n$ to avoid a $2$ by $2$ sub-matrix of all ones.  I'd like to be able to use this fact to prune my search space (which is frickin huge), but it might be more trouble than it's worth, and hence I'm asking the question.
Also, if anyone knows a better way to generate all such differential posets, I'd love to know.
EDIT: By avoid, I mean when you restrict to two rows and two columns, you get all 1s.  Answers to the other question are still good to know though!

A: Seth Pettie has done some fascinating work on this topic and generalizations. In his setting, the goal is to upper bound the number of 1s in a 0-1 matrix that excludes a particular submatrix pattern. Your specific example (if restricted to the case of m=n) is the problem he denotes as Ex($P_5$, n) in this paper, in which he mentions earlier work by Furedi and Hajnal giving an upper bound of $O(n^{3/2})$ for the total number of ones.
While the number of ones doesn't answer your question directly, it gives an upper bound. I don't know how precise you need your answer to be, but this might help.

A: This looks like it will be a difficult question to answer in general, but here's the answers for $m \in \{2,3\}$.  Let N(m,n) be the number of m by n (0,1)-matrices without a 2 by 2 all-1 submatrix.
Let A=00 B=01 C=10 D=11.  Then any n by 2 (0,1)-matrix counted by N(2,n) is equivalent to a word of length n on the alphabet {A,B,C,D} without two D's.  Hence \[N(2,n)=n \cdot 3^{n-1}+3^n.\]  The first term counts when there is a D in the word, the other term counts without any D's.  See: http://www.oeis.org/A006234
Now let A=000 B=001 C=010 D=011 E=100 F=101 G=110 H=111.  Then any (0,1)-matrix counted by N(2,n) is equivalent to a word of length n without (a) two D's (b) two F's (c) two G's (d) two H's or (e) an H and one of D, F or G.  Hence \[N(3,n)=n \cdot 4^{n-1}+\sum_{i=0}^{3} {3 \choose i} (n)_i 4^{n-i}\] where $(n)_i=n(n-1)\cdots(n-i+1)$.  The first term is the number of words containing H.  The sum counts the terms without any H:  First we choose i of D, F or G, and place them in the word.  The remaning letters must be A, B, C or E.

A: It is worth to mention that if we forbid also $2\times 2$ submatrices of all zeros, then there will be no such matrices as soon as $m,n\geq 5$.
In other words, every binary $5\times 5$ matrix contains a $2\times 2$ submatrix consisting of all ones or all zeros.

A: For the case when $m = n$, these appear to have been computed as this sequence in Sloane.  I don't know how they were computed, though; I found the sequence by solving the cases $m = n = 1$, $m = n = 2$, $m = n = 3$ by hand and searching.


text:
Q: Is there way to use javascript to sychronize the server file with yours? So that if i change a div with :
 <form>
Datum: <input type="text" id="datum">
</form>

This is a dummy text

Replace it!

Is it possible  to change it on the server right away instead of your local browser?
So not get reset with F5 Reload? And without using cookies?


text:
Q: Why does not Warble include .class files in war file? when I warble my project, it doesn't include .class files to war file.
My config/warble.rb file is like that:
Warbler::Config.new do |config|
  config.features = %w(compiled executable)
  config.dirs << "bin"
  config.dirs << "public"
  config.includes = FileList["Rakefile"]
  config.executable = ["rake", "bin/rake"]
end

It was compiled yesterday but not compile and include for now. Also when I run warble compiled, it just rm .class files.

A: I was using warble gem '1.4.0' and updated to '1.4.2' it solved my problem.


text:
Q: Parsing URL through Python I need to parse
http://www.webpagetest.org/breakdown.php?test=150325_34_0f581da87c16d5aac4ecb7cd07cda921&run=2&cached=0
If you view source of the above url you will find
Expected Output:
fvRequests= css
fvRequests=7

A: The idea is to locate the script with BeautifulSoup and use regular expression pattern to find the the fvRequests.setValue() calls and extract the value of the third argument:
import re

from bs4 import BeautifulSoup
import requests

pattern = re.compile(r"fvRequests\.setValue\(\d+, \d+, '?(\w+)'?\);")

response = requests.get("http://www.webpagetest.org/breakdown.php?test=150325_34_0f581da87c16d5aac4ecb7cd07cda921&run=2&cached=0")
soup = BeautifulSoup(response.content)

script = soup.find("script", text=lambda x: x and "fvRequests.setValue" in x).text
print(re.findall(pattern, script))

Prints:
[u'css', u'7', u'flash', u'0', u'font', u'0', u'html', u'14', u'image', u'80', u'js', u'35', u'other', u'14']

You can go further and pack the list into a dict (solution taken from here):
dict(zip(*([iter(data)] * 2)))

which would produce:
{
    'image': '80',
    'flash': '0',
    'js': '35',
    'html': '14',
    'font': '0',
    'other': '14',
    'css': '7'
}

A: import re
import urllib2

if __name__ == "__main__":
    url = 'http://www.webpagetest.org/breakdown.php?test=150325_34_0f581da87c16d5aac4ecb7cd07cda921&run=2&cached=0'

    # http request
    response = urllib2.urlopen(url)
    html = response.read()
    response.close()

    # finding values in html
    results = re.findall(r'fvRequests\.setValue\(\d+, \d+, \'?(.*?)\'?\);', html)
    keys = results[::2]
    values = results[1::2]

    # creating a dictionary
    output = dict(zip(keys, values))

    print output


text:
Q: Search a secure way to connect to my remote server I actually realise a project on Android Studio. To get the data, I put the URL path of my csv file with the format : ftp://login:password@IP/path_File.
   But I guess this is not secure. How can I secure that ? I did some research. Some people say to put the password in configuration file but I don't see what this changes. It's important because with these informations, people can directly read the csv file and I don't want that.
   Please can you guide me to secure that ? Thanks for your help.
   Have a nice day.


text:
Q: mapcat using map and concat In order to better understand mapcat I took an example:
user>  (mapcat #(list % %) [1 2 3])
(1 1 2 2 3 3)

And tried to reproduce what the doc describes using, on purpose, map and concat :
user> (doc mapcat)
clojure.core/mapcat
([f & colls])
  Returns the result of applying concat to the result of applying map
  to f and colls.  Thus function f should return a collection.

By doing this:
user>  (concat (map #(list % %) [1 2 3]))
((1 1) (2 2) (3 3))

However as you can see it doesn't work.  I can however use reduce like this but don't know if it's correct:
user>  (reduce #(concat %1 %2) (map #(vec (list % %)) [1 2 3]))
(1 1 2 2 3 3)

The above works but I don't know if it's a correct way to recreate, using map and concat, what mapcat does.
Basically I'd like to understand of mapcat works under the hood.
What is going on and how can I access the source of mapcat? (I'm using Emacs + nrepl)

A: user=> (source mapcat)
(defn mapcat
  "Returns the result of applying concat to the result of applying map
  to f and colls.  Thus function f should return a collection."
  {:added "1.0"}
  [f & colls]
    (apply concat (apply map f colls)))
nil
user=>

The reason reduce also works is because it is effectively:
(concat (concat '(1 1) '(2 2)) '(3 3))

apply, as used in the source code, expands to:
(concat '(1 1) '(2 2) '(3 3))

In your initial attempt with concat:
  user=> (map #(list % %) [1 2 3])
  ((1 1) (2 2) (3 3))
  user=> (concat (list '(1 1) '(2 2) '(3 3)))
  ((1 1) (2 2) (3 3))
  user=> (concat [1])
  (1)

You can see that if you call concat with a single argument, it returns that argument.

A: concat is a variadic function i.e it can take n parameters where each parameter is a sequence of value i.e the signature becomes (defn concat [& lst]]). Whereas in your example you are calling concat with a single argument assuming that concat take a seq of seq of values to be concatenated and thats why you get the result i.e the same list of list is returned back.
(apply concat(apply map #(list % %) [1 2])) wont work.
(apply map #(list % %) [[1 2]]) or (apply map #(list % %) [1 2] []) will work.
This is because apply expects the last parameter to be a sequence of values and each item in that sequence of values will be passed as a parameter to the applied function. In your case of apply being failed the call will expand to (map #(list % %) 1 2) which is wrong and the error message also shows it that it cannot convert long to sequence as map need sequences as parameters.


text:
Q: Python understanding threading and race condition Trying to clarify my understanding of threading.
To my understanding, when the GIL isn't released manually (e.g. time.sleep), the OS assigns it to threads randomly right? If so, how come no race condition ever occurs here? I've re-run the code many times and the ending value logged (last line) is always 5.
I would've thought that at some of the runs, some threads would have gotten a local_copy before another thread updated self.value, leading to a race condition. Furthermore, doesn't this mean that the threads run synchronously since each thread waits for the previous thread to write self.value = local_copy ?
My thought process is that the OS has some process of identifying a read-write process of a shared attribute, and so assigns GILs to threads in a way that prevents any race condition from happening.
class FakeDatabase:
    def __init__(self):
        self.value = 0

    def update(self, name):
        logging.info("Thread %s: starting update", name)
        local_copy = self.value
        local_copy += 1
        self.value = local_copy
        logging.info("Thread %s: finishing update", name)

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    database = FakeDatabase()
    with futures.ThreadPoolExecutor() as executor:
        for i in range(5):
            executor.submit(database.update, i)
    logging.info(f'Ending value is {database.value}')

A: You only do one increment per thread, and the increment is a relatively short part, so it's likely that the increments don't overlap. If I make each thread increment a million times with
        for _ in range(10**6):
            local_copy = self.value
            local_copy += 1
            self.value = local_copy

then I do see it happen (Try it online!):
INFO:root:Thread 0: starting update
INFO:root:Thread 1: starting update
INFO:root:Thread 2: starting update
INFO:root:Thread 3: starting update
INFO:root:Thread 4: starting update
INFO:root:Thread 4: finishing update
INFO:root:Thread 0: finishing update
INFO:root:Thread 3: finishing update
INFO:root:Thread 2: finishing update
INFO:root:Thread 1: finishing update
INFO:root:Ending value is 1745053

A: Python's threading with CPU bound tasks like in your example case above behaves effectively in synchronous fashion under the hood, the real benefit of threads in Python is with I/O bound tasks like waiting for something from the network or disk.
Although pretty old, this is an excellent talk about this