text:
Q: Receiving an undefined result from an HTTP POST Request in an Angular DataFactory I am new to Angular.js and trying to use factory for sending data via http post request. I am getting this error Cannot read property 'success' of undefined here is my code...
<!DOCTYPE html>
<html ng-app="myApp">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body>
    <div ng-controller="myCtrl">

    </div>

    <script>
        var app = angular.module('myApp', []);

        app.factory('DataFactory', ['$http', function($http) {
            return {
                setData: function(stud) {
                    return
                    $http({
                        method: 'POST',
                        url: 'http://www.w3schools.com/jquery/demo_test_post.asp',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        data: stud
                    });

                }
            }

        }]);

        app.controller('myCtrl', function($scope, DataFactory) {

            var stud = {
                name: "Alex",
                city: "Berlin"
            };

            DataFactory.setData(stud).then(function(response) {
                    console.log(response);
                })
                .catch(function(err) {
                    console.error(err)
                })
                .finally(function() {
                    console.log("Finished the chain");
                });
        });
    </script>

</body>

</html>

The error I am getting is at line DataFactory.setData(stud).success... any help much appreciated...

A: So the docs state:
var promise = someAsyncMethodCall();
promise.then(function(greeting) {
  alert('Success: ' + greeting);
}, function(reason) {
  alert('Failed: ' + reason);
});

See the bottom, there are 2 functions to pass to the then function. So your code is:
DataFactory.setData(stud).then(function(response) {
     console.log(response);
}, function (err) {
     console.error(err)
});

The $q library is what $http uses under the hood.
See the promise api.
There are these methods:

then(successCallback, errorCallback, notifyCallback) – regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected.
This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback (unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chaining). It also notifies via the return value of the notifyCallback method. The promise cannot be resolved or rejected from the notifyCallback method.
catch(errorCallback) – shorthand for promise.then(null, errorCallback)
finally(callback, notifyCallback) – allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information.

So to further your code, you could do:
DataFactory.setData(stud).then(function(response) {
    console.log(response);
})
.catch(function (err) {
    console.error(err)
})
.finally(function () {
    console.log("Finished the chain");
});

--- EDIT ---
For completeness, there was another error that @Duncan said, that is the line break:
app.factory('DataFactory', ['$http', function($http) {
    return {
        setData: function(stud) {
            return
            $http({
                method: 'POST',
                url: 'http://www.w3schools.com/jquery/demo_test_post.asp',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                data: stud
            });

        }
    }

}]);

The break between return and $http({ is causing an error. So it needs to look like this:
app.factory('DataFactory', ['$http', function($http) {
    return {
        setData: function(stud) {
            return $http({
                method: 'POST',
                url: 'http://www.w3schools.com/jquery/demo_test_post.asp',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                data: stud
            });

        }
    }

}]);

A: $http returns a Promise. you need to use .then() to register a callback on success.
The more general form is .then(successFn, failFn)

A: Your problem is in the function setData():
                return
                $http({
                    method: 'POST',
                    url: 'http://www.w3schools.com/jquery/demo_test_post.asp',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    data: stud
                });

That is two statements: return just returns from the function, then the call to $http() is additional code that is never reached.
Be careful where you put line breaks in Javascript, move the $http({ up to the previous line.
Oh, and as others have said, using .success on the result from $http calls is deprecated, switch to using the normal promise methods instead.

A: Is it just markdown or do you have  a newline between return and $http? If you return there, $http becomes unreachable. Functions can be below the return, since they are registered before code execution.
So you should write it like
return $http({...})
instead of
return
$http({...})


text:
Q: question related to linear algebra Let $V$ be a finite dimensional real vector space and let $f$ and $g$ be non-
zero linear functionals on $V$. Assume that $ker(f)$ is contained in  $ker(g)$. Which of the following statements are true?
a. $ker(f) = ker(g)$
b. $f = ag$ for some real number  $a$ not equal to $0$
c. The linear map $A : V \rightarrow  \mathbb R^2$ defined by
$Ax = (f(x),g(x))$ for all $x \in V$ , is onto.

A: Recall that if $T:V\to W$ is a linear map, the rank and nullity of $T$ are defined as
$$
\DeclareMathOperator{rk}{rk}\rk T =\dim\DeclareMathOperator{im}{im}\im T \qquad
\DeclareMathOperator{nul}{nul}\nul T =\dim\ker T
$$
respectively. Also recall that the rank-nullity theorem states that
$$
\rk T+\nul T=\dim V
$$
You are given two linear maps $f,g:V\to\Bbb R$ such that
$$
\ker f\subseteq\ker g\tag{1}
$$
Note that $\rk f>0$ since $f$ is nonzero. Since $\im f$ is a subspace of $\Bbb R$  and $\dim\Bbb R=1$ it follows that $$\rk f=1\tag{2}$$ Similarly $$\rk g=1\tag{3}$$
Now, the rank-nullity theorem implies
$$
\rk f+\nul f=\rk g+\nul g\tag{4}
$$
Combining (2), (3), and (4) gives
$$
\nul f=\nul g\tag{5}
$$
Finally, (1) and (5) imply $\ker f=\ker g$. This proves (a) in the affirmative.
Can you construct a few examples to test the validity of (b)? Solving (c) should be simple once you understand the above proof of (a).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to join two datasets using java in a way like left outer join in SQL I am new to java world. I have two data sets with me. I need to make a single data set with all the details joined together, as in SQL left outer join.
First Data Set ( Java List )

Second Data Set (Java List)

The Output I am expecting ( Java List )

Can you guide me how to achieve this using lists, streams or any other data structure in java. I am planning to implement this in a AWS Lambda function which has to be written using java.

A: This has already been discussed here. Basically, you should be using map operation to achieve this using Java Stream API


text:
Q: Springboot Rest api request timeout or cancel if the request is not processed in certain period of time I am trying to implement request timeout in Springboot Mongodb application. The flow is like  this.Send startCctv request to server. The server starts the cctv and update the database field "Status" to true. Then i will call one more api say getCctvStatus() to poll the DB and check for the status field every minute. If this field is not updated to true within 10 minutes, the original request startCctv should be cancelled or timedout.
Here is the skeleton code:
//Controller class
@PostMapping("/startCctv.on/{id}")
public ResponseEntity startCctv(@PathVariable String cctvId){
  //call to service class
  startCctv(cctvId);
}

//Service class
public void startCctv(String cctvId) {
sendReqToMainServer(cctvId);
    // main server starts the cctv for the given cctvId and updates the database field "status" to true.
}

//API to check the DB "status" field. The below api should poll the DB and check the "status"
// field every minute.
public boolean checkCctvStatus(String cctvId) {
    //DB query to get the status of cctv
    return cctvRepository.getCctvStatus(cctvId);
}

//If the status is not updated to true within 10 minutes, cancel the original request
// ie startCctv and send message to the client/user as request timed out.

Can anyone help me to achieve this !?
Thanks in advance!!!


text:
Q: Cloudformation Modules cfn submit doesn't support different profile credential I m starting to learn Cloudformation Modules,
When I run cfn submit to register the module, it will go to my AWS default credentials
And I m not able to run cfn submit --profile $profile_name?
it shows this below
cfn: error: unrecognized arguments: --profile  $profile_name

And I use -h to check it looks like currently doesn't have this arguments support?
cfn submit --help
usage: cfn submit [-h] [-v] [--dry-run] [--endpoint-url ENDPOINT_URL] [--region REGION] [--set-default] [--role-arn ROLE_ARN | --no-role]

This sub command uploads the resource type to CloudFormation. Projects can be created via the 'init' sub command.

optional arguments:
  -h, --help            show this help message and exit
  -v, --verbose         Increase the output verbosity. Can be specified multiple times.
  --dry-run             Package the project, but do not submit.
  --endpoint-url ENDPOINT_URL
                        CloudFormation endpoint to use.
  --region REGION       AWS Region to submit the resource type.
  --set-default         If registration is successful, set submitted version to the default.
  --role-arn ROLE_ARN   Role ARN that CloudFormation will use when invoking handlers.
  --no-role             Register the type without an explicit execution role (Will not be able to invoke AWS APIs).

I m wondering how to create modules if I have multiple accounts and I want to use profile this options.
Thanks for any help!


text:
Q: How can I count multiple columns in a query with a row for each column count? I have a table that looks like this:
CREATE TABLE [dbo].[Phrase]
(
    [PhraseId]     UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
    [English]      NVARCHAR (250)   NOT NULL,
    [p1]           BIT              DEFAULT ((0)) NOT NULL,
    [p2]           BIT              DEFAULT ((0)) NOT NULL,
    [p3]           BIT              DEFAULT ((0)) NOT NULL,

    PRIMARY KEY CLUSTERED ([PhraseId] ASC),

    CONSTRAINT [FK_PhrasePhraseChapter]
        FOREIGN KEY ([ChapterId])
        REFERENCES [dbo].[PhraseChapter] ([PhraseChapterShortId])
);

What I would like to do is to get a count of p1, p2 and p3 so the output looks something like:
p1  100
p2  200
p3  23

Note that in this case the first row would mean that there were 100 rows in the Phrase table that had p1 set to a value of 1. Hope this makes sense.
I know I could do this simply with three columns but I need a row output of just two string columns like above. Can anyone give me a suggestion as to how I could achieve this?

A: Use a union:
select 'P1' as ColToCount,
       count(distinct P1) as Counted
from MyTable
where 1=1 -- replace with any criteria
union all
select 'P2' as ColToCount,
       count(distinct P2) as Counted
from MyTable
where 1=1 -- replace with any criteria
union all
select 'P3' as ColToCount,
       count(distinct P3) as Counted
from MyTable
where 1=1 -- replace with any criteria

This is only really good if you only have a few different things to count

A: You can use UNPIVOT, like so:
SELECT  myColumn ,
        NoOfTrue
FROM    ( SELECT    [p1] = COUNT(CASE WHEN [p1] = 1 THEN 1 END) ,
                    [p2] = COUNT(CASE WHEN [p2] = 1 THEN 1 END) ,
                    [p3] = COUNT(CASE WHEN [p3] = 1 THEN 1 END)
          FROM      Phrase
        ) d UNPIVOT
    ( NoOfTrue FOR myColumn IN ( [p1], [p2], [p3] ) ) piv;

A: Perhaps by using case and sum:
SELECT sum(case when p1 = 1 then 1 end) as p1Count,
       sum(case when p2 = 1 then 1 end) as p2Count,
       sum(case when p3 = 1 then 1 end) as p3Count
FROM Phrase

A: simplest way is:
select 'p1' p, sum(p1) countp
from Phrase
union all
select 'p2', sum(p2)
from Phrase
union all
select 'p3', sum(p3)
from Phrase;

Note using sum for a bit field can do all that you want.
A bit field can have (0-1-null) values and sum will add null values as 0;


text:
Q: Simplify with Assumptions Sqrt[(expr)^2] While trying to simplify expressions in the form Sqrt[(expr)^2] when expr>0 I noticed a peculiar behavior that was not resolved with code from this Q&A.
Simplify[Sqrt[(x - y + a b c)^2], x - y + a b c > 0]

Abs[a b c + x - y]

When I remove any of the a, b, c, x or y it returns the result without the Abs:
Simplify[Sqrt[(x - y + b c)^2], x - y + b c > 0]

b d + x - y

I loose faith when I meet such behavior with Mathematica :-(
Even though
Simplify[Sqrt[expr^2], expr > 0] /. expr -> (x - y + a b c)

does fix the first issue how could I simplify this:
Simplify[Sqrt[(x - y + a ^2 b^2 c^2)^2], x > y]

Anyway, can anybody explain why this happens and propose a way to fix it for general expressions?

A: It would appear that you can increase the number of assumptions variables that Mathematica will handle by altering a system option:
SetSystemOptions["SimplificationOptions" -> {"AssumptionsMaxNonlinearVariables" -> 5}]

Simplify[Sqrt[(x - y + a b c)^2], x - y + a b c > 0]
(* a b c + x - y *)

Simplify[Sqrt[(x - y + a^2 b^2 c^2)^2], {x > y, {a, b, c} ∈ Reals}]
(* a^2 b^2 c^2 + x - y *)

A: It is since Mma does not know, what among x,y,a,b and c is positive and negative and, therefore, which their combination should be chosen, x-y+abcor y-x-abc. If you tell it, say, like this:
    Simplify[Sqrt[(x - y + a b c)^2], {x - y + a b c > 0, x > 0, a > 0,
  b > 0, c > 0, y < 0}]

it will return the expected result:
(*   a b c + x - y  *)

Later edit. To address your question below. No, it is not right. Let us see:
The inequality x - y + a b c > 0has a lot of solutions depending on the signs of all these parameters:
 Reduce[x - y + a b c > 0]

(*   (a | b | y) \[Element]
  Reals && ((x <=
      y && ((c <
          0 && ((b < 0 && a > (-x + y)/(b c)) || (b > 0 &&
             a < (-x + y)/(b c)))) || (c >
          0 && ((b < 0 && a < (-x + y)/(b c)) || (b > 0 &&
             a > (-x + y)/(b c)))))) || (x >
      y && ((c <
          0 && ((b < 0 && a > (-x + y)/(b c)) ||
           b == 0 || (b > 0 && a < (-x + y)/(b c)))) ||
       c == 0 || (c >
          0 && ((b < 0 && a < (-x + y)/(b c)) ||
           b == 0 || (b > 0 && a > (-x + y)/(b c)))))))   *)

A: Mathematically speaking, you are trying to specify a branch of the square-root function by an irrelevant assumption.  This can lead to totally bogus results.  Somewhat simplifying: Just because 9>0 does not mean that -3  is not also a square-root of 9.  Yeah, yeah some people think that Sqrt[explicit_positive_real] must mean the positive root. But it doesn't generalize, say to cube roots (etc).  Choosing a branch cut is independent of the sign of the radicand, mathematically. Math works that way.


text:
Q: Search file 1 in file 2 I need to go through an audio stream of 30 minutes and look for another 30 seconds of audio which is within the first audio. Example: I have a file of 30 seconds and file 2, the recorded broadcast (30 mins.) And i want to find the start position of file 1 in file 2.
Understand?
Excuse my English.
Any help will be important
Thanks

A: I think the answer depends on the source of the longer audio stream.  If the longer stream contains the exact image of the shorter one (for example, if it was created by an audio editor with access to the original) then you have a simple string search problem and many answers exist, like Boyer-Moore.
If however, the original was decoded and re-encoded (i.e: you are testing to see if some guy used part of your band's mp3 in his youtube video), then you've got a much more difficult problem.
I'd probably try to solve it in the frequency domain - Generate a 'signature' of the file 1 based on a sequence of smallish FFT windows, then doing a best-fit against FFTs from file 2.   I have no idea how well this would work.

A: I work at a radio station. Radio is recorded 24 hours per day in blocks of 30 minutes each. I want to look for a 30-second commercial that was played in the programming of Radio. I use the BASS library to write. My idea is to cut an audio sample of 30 seconds and go through the blocks of 30 minutes looking for similarities audio of 30 seconds (commercial)
I really need it
Thanks


text:
Q: What is a good ASP.NET MVC detailed error page example I looked through a bunch of other questions looking for an awesome example of a detailed error page layout and did not find anything.  I am sure many people have made this before.
Requirements
 * Must show exception information (type, stack trace)
 * Should show form values if possible
 * Should show what area/controller/action caused the issue
The best I have come up with is:
@model System.Web.Mvc.HandleErrorInfo
@{ViewBag.Title = "Error";}

Sorry, an error occurred while processing your request.

Please copy and paste this entire page in an email to
Me
along with any other information you can provide so we can
get this fixed ASAP!

@if (Model != null) {

@Model.Exception.GetType().Name

        thrown in @Model.ControllerName @Model.ActionName

Details

        @Model.Exception.ToString()

}

A: Why ask them to email you the error, many people including myself would never send you an email. Use something like ELMAH to automatically email you on unhandled exceptions and display a friendly error page.
http://code.google.com/p/elmah/
If you want to get feedback from your users when an error occurs, you can have a textbox and ask them to give you information as to what they were doing when they landed on the error page, this does seem to work well, it shows that you're being pro-active in trying to solve the solution. Be sure to say something to let them know that you have been notified, but you're looking for additional information to keep the error from happening again in the future


text:
Q: Create mongoDB Session with Socket.io connection only I need to create a session on MongoDB when the socket connection start, I have the following code:
var express = require('express');
var session = require('express-session');
var sharedsession = require("express-socket.io-session");

var MongoDBStore = require('connect-mongodb-session')(session);

var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

var store = new MongoDBStore({
  uri: 'CONNECTION TO MONGODB',
  collection: 'sessions',
    connectionOptions: {
    useNewUrlParser: true
  }
});

// Catch errors
store.on('error', function(error) {
  console.log(error);
});

let sessionConfig = require('express-session')({
  secret: 'This is a secret',
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week
  },
  store: store,
  httpOnly: false,
  resave: true,
  saveUninitialized: true
});

app.use(sessionConfig);

io.use(sharedsession(sessionConfig, {
  autoSave:true
}));

app.get('/', function(req, res) {
  res.send('Test');
});

io.on('connection', (socket) => {
  console.log('a user connected');
  console.log('socket.handshake',socket.handshake.session);
  console.log(socket.handshake.xdomain);
  console.log("A USER LOGGED IN WITH ID: ", socket.request.user);

  // Accept a login event with user's data
  socket.on("login", function(userdata) {
    socket.handshake.session.userdata = userdata;
    socket.handshake.session.save();
  });

  socket.on("logout", function(userdata) {
    if (socket.handshake.session.userdata) {
      delete socket.handshake.session.userdata;
      socket.handshake.session.save();
    }
  });

});

http.listen(3001, () => {
  console.log('listening on *:3000');
});

server = app.listen(3000);

If I access to , the session is created successfully in MongoDB, I understand that the configuration with express is ok, and the Socket Share that session correctly when I try to connect from the same domain.
The problem is, that I have a mobile app with ionic v4, that only access from a socket connection and the session is never created on MongoDB.
Any thoughts?
UPDATE 1:
I try to add passport.socketio to get a proper way to add authentication to my app, and the output of this code, is Not Session found, its right, the socket connection never add the session to the MongoDB:
var express = require('express');
var session = require('express-session');
var sharedsession = require("express-socket.io-session");
let passport = require('passport');
let passportSocketIo = require("passport.socketio");
let cors = require('cors')

var MongoDBStore = require('connect-mongodb-session')(session);

var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

var store = new MongoDBStore({
  uri: 'MONGO DB STRING CONNECTION',
  collection: 'sessions',
    connectionOptions: {
    useNewUrlParser: true
  }
});

// Catch errors
store.on('error', function(error) {
  console.log(error);
});

app.use(cors());
app.use(passport.initialize());
app.use(passport.session());

let config = {
  passport : passport,
  secret: 'This is a secret',
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week
  },
  store: store,
  httpOnly: false,
  resave: true,
  saveUninitialized: true,
  success:      onAuthorizeSuccess,  // *optional* callback on success - read more below
  fail:         onAuthorizeFail
};

let sessionConfig = require('express-session')(config);
app.use(sessionConfig);

io.origins('*:*');

io.use(sharedsession(sessionConfig, passportSocketIo.authorize(config)));

app.get('/', function(req, res) {
  res.send('Test');
});

io.on('connection', (socket) => {
  console.log('a user connected');
  console.log('socket.handshake',socket.handshake.session);
  console.log(socket.handshake.xdomain);
  console.log("A USER LOGGED IN WITH ID: ", socket.request.user);

  // Accept a login event with user's data
  socket.on("login", function(userdata) {
    socket.handshake.session.userdata = userdata;
    socket.handshake.session.save();
  });

  socket.on("logout", function(userdata) {
    if (socket.handshake.session.userdata) {
      delete socket.handshake.session.userdata;
      socket.handshake.session.save();
    }
  });

});

http.listen(3001, () => {
  console.log('listening on *:3000');
});

server = app.listen(3000);

function onAuthorizeSuccess(data, accept){
  console.log('successful connection to socket.io');
  // accept(); //Let the user through
}

function onAuthorizeFail(data, message, error, accept){

  console.log("Errror",error);

  if(error) accept(new Error(message));
  console.log('failed connection to socket.io:', message);
  // accept(null, false);
}

A: Try
//Before io.on('connection....
io.engine.generateId = (req) => {

//Try to get the cookie out from
//req.rawHeaders and return it
//so the socket ID will equal to the session Id

});

//The connection event
io.on('connection', socket => { ....

//You can then do a mongoose search query using the socket Id here to match the user in the db


text:
Q: Is it possible to return value from jQuery popup modal dialog using window.opener I use jQuery UI to make the dialog box. How can I get the return value when the dialog box is open? If I use window.open then I know that I can get the return value by window.opener.
Supposedly a modal dialog box will open when I clicked a button. Then return a value because I want to put condition so the page can be reload if the dialog box does not open.I have tried this method but it does not work:
$('#button').click(function (){
        if ($('#dialog').dialog('open')){
        // do something
        };
});

Also I only want the return value if the dialog box is open not when click any button in the dialog.Thanks in advance !


text:
Q: Ubuntu 20.04 stuck on boot screen I recently bought a brand new DELL OptiPlex 7080 and set up windows 10 and ubuntu 20.04 togather (dual boot).
Ubuntu and windows booted perfectly while installation. After installation, I rebooted Ubuntu and then it booted up normally.
Then, finally I changed the Date/Time, Location settings and the rebooted the PC. And this time it stucks (the loader spins, so it was not hung). I waited for 15 minutes but it doesn't work. But windows is still working perfectly. How to fix this now?


text:
Q: upload file asp.net mvc 2 i am trying to execute a task after uploading a file. After the task is finished i would like to display some info. At the moment i have an Upload action that will fire after clicking the 'Do task' button which is not good. question :I would like to just trigger the 'Sometask' action and not the Uploadaction?
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%= Html.BeginForm("Upload","Home",FormMethod.Post,new { enctype = "multipart/form-data" }) %>
<%{ %>
<%=Html.HiddenFor(model=>model.Filepath) %>
<input type="file" id="upload" name="upload" />
<button id="btnUpload">
    upload</button>
<%} %>
<button id="btnTask">
    Do Task</button>
<script type="text/javascript">
    $(document).ready(function (event) {
        $('#btnTask').click(function () {
            $.post("/Home/Sometask",
            { filePath: $("#Filepath").val() },
             function (data) {
                alert(data);
            });
            event.preventDefault;
        });
    });

</script>

    [HttpPost]
    public ActionResult Upload()
    {
        HttpPostedFileBase selectedFile = Request.Files["upload"];

        if (selectedFile.ContentLength > 0)
        {
            string filePath = Path.Combine(HttpContext.Server.MapPath("\\Uploads\\")
            , Path.GetFileName(selectedFile.FileName));
            selectedFile.SaveAs(filePath);
            UploadModel model = new UploadModel();
            model.Filepath = filePath;
            return View("Index", model);
        }

        return View("Index");
    }

    public string Sometask(string Filepath)
    {
        Thread.Sleep(5000);
        return "ready";
    }

A: Is the Upload() method being called? Looking at the code, I would expect the Sometask() to be called but not the Upload() method. The jQuery code is calling .post when the button is clicked and that should eliminate the normal form posting. If Sometask() is not getting called, you many need to add [HttpPost] attribute to the Sometask() method.
Note that for security reasons files cannot be uploaded from Javascript.


text:
Q: how to get spacing between divisons

body{background-image: url(images/boy_naruto_blond_drop_stern_look_24237_1366x768.jpg);background-attachment: fixed; }
@font-face{
font-family:pagal;
    src:url("fonts/Pagal Font.ttf");}
    @font-face{
font-family:folktale;
src:url("fonts/Folktale.ttf");
}
#titl{
    font-family:folktale;
    text-align:center;
    color: aliceblue;
    font-stretch: ultra-expanded;
font-size: 40px;
    background: rgba(44,95,188,0.3);
    back

}
h1{color: rgb(255,201,14);margin-bottom: 0px;padding-bottom: 0px;border: 0px;}
sub{margin-top: 0px;padding-top: 0px;border-spacing: 0px;}
.icon{height: 150px;width: 200px;text-align: center;}
#naruto{display: table-cell;padding: 20px;background: rgba(220,199,48,0.5);}
#sasuke{display: table-cell;padding: 20px;background: rgba(81,81,255,0.5);}
#sakura{display: table-cell;padding: 20px;background: rgba(231,126,176,0.5);}
#container{display: table-row;}
#table1{display: table;margin: 50px;text-align: center;margin-left: auto;margin-right: auto;}
<!DOCTYPE html>

    <meta charset="utf-8">
<title>Home</title>
    <link type="text/css" rel="stylesheet" href="main.css">

NARUTO
never give up

NARUTO UZUMAKI

SASUKE UCHIHA

SAKURA HARUNA

i am trying to get space between the naruto sasuke and sakura blocks. I represented each div(naruto,sasuke,sakura) as table cells and enclosed these three divs in another div(display:table row) and finally in div(id=table1,display:table). please help me.

imageLink:https://drive.google.com/file/d/0B9RbEZnGFP1JUjE3N1NjZGJoUFU/view?usp=sharing

A: If I understand the issue you want a space between each block? If that so, assign a class (ie .cell) to naruto, sasuke and sakura. Then use
.cell {
  margin: 0 5px;
}

This will add a margin of 0 at the top and the bottom and a spacing of 5px on each side.
Also avoid repeating in CSS. You could merge display: table-cell;padding: 20px; and put this in your .cell class. It will be easier if you need to change the padding, for exemple ;)
Hope this helped.

A: Insert the following into #table1
border-spacing:5px; border-collapse:separate;

For more info see: https://stackoverflow.com/a/16398904/4665

body{background-image: url(images/boy_naruto_blond_drop_stern_look_24237_1366x768.jpg);background-attachment: fixed; }
@font-face{
font-family:pagal;
    src:url("fonts/Pagal Font.ttf");}
    @font-face{
font-family:folktale;
src:url("fonts/Folktale.ttf");
}
#titl{
    font-family:folktale;
    text-align:center;
    color: aliceblue;
    font-stretch: ultra-expanded;
font-size: 40px;
    background: rgba(44,95,188,0.3);
    back

}
h1{color: rgb(255,201,14);margin-bottom: 0px;padding-bottom: 0px;border: 0px;}
sub{margin-top: 0px;padding-top: 0px;border-spacing: 0px;}
.icon{height: 150px;width: 200px;text-align: center;}
#naruto{display: table-cell;padding: 20px;background: rgba(220,199,48,0.5);}
#sasuke{display: table-cell;padding: 20px;background: rgba(81,81,255,0.5);}
#sakura{display: table-cell;padding: 20px;background: rgba(231,126,176,0.5);}
#container{display: table-row;}

#table1{display: table;margin: 50px;text-align: center;margin-left: auto;margin-right: auto; border-spacing:5px; border-collapse:separate;}
<!DOCTYPE html>

    <meta charset="utf-8">
<title>Home</title>
    <link type="text/css" rel="stylesheet" href="main.css">

NARUTO
never give up

NARUTO UZUMAKI

SASUKE UCHIHA

SAKURA HARUNA

A: I took another approach and change display:table-cell; by display:inline-block;
try this code:
#naruto{display:inline-block; margin-right:10px;padding: 20px;
background: rgba(220,199,48,0.5);}
#sasuke{display:inline-block; margin-right:10px;padding: 20px;
background: rgba(81,81,255,0.5);}
#sakura{display:inline-block; margin-right:10px;padding: 20px;
background: rgba(231,126,176,0.5);}


text:
Q: Does Visual Studio Publish to App Service feature deploys items in appsettings.json to the configuration blade in the Azure portal I am using Visual Studio 2022 to build an ASP .NET Core (v6) application.
I need to deploy and run my application on an Azure App Services instance.
I have many settings in my application's appsettings.json file. The file is included in the deployment package as shown here:

I use Visual Studio 2022 Publish feature to deploy my asp.net core application to an Azure App Services instance:

After a successful Visual Studio Publish, none of appsettings.json file settings show in the configuration blade:

Questions:
1- Is there any way Visual Studio publish feature deploy appsettings.json settings to the App Services' configuration blade?
2- Even after a successful deployment, my application does not read the settings in the appsettings.json. It seems that all ignored. I checked and on my local visual studio developer environment, my app reads  appsettings.json, but not when it is deployed to App Services. Why the deployed app ignores the appsettings.json settings?
Update 1: program.cs and appsettings.json
public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);

    builder.Logging.ClearProviders();
    builder.Logging.AddConsole();
    builder.Logging.AddAzureWebAppDiagnostics();

    // Add services to the container.
    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

    builder.Services.AddControllers();
    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();

    builder.Services.AddApplicationInsightsTelemetry();
    builder.Services.AddScoped<Framework>();

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }

    app.UseHttpsRedirection();

    app.UseAuthentication();
    app.UseAuthorization();

    app.MapControllers();

    app.Run();
}

appsettings.json could be anything. Just need to read its content with a ConfigurationManager instance like how I read them when the site is running locally in Visual Studio.

A:

*

*Is there any way Visual Studio publish feature deploy appsettings.json` settings to the App Services' configuration blade?

The deployed appsettings.json  file will be available in KUDU Debug Console.
In your Azure App Service => Advanced Tools => Go => Debug Console => cmd => site => wwwroot.

*

*Or even you can open the KUDU with the below URL

https://YourAppServiceName.scm.azurewebsites.net/

*

*Configuration section will not display the setting which are in appsettings.json file. It is used to override the available settings from appsettings.jsonfile.

*The values which you want to override and the new values which you want to add after deployment must be set in the Application Settings in portal.

*The key name must be same in both appsettings.json and Configuration => Application Settings.

My  sample appsettings.json :
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "MyVal": "Local Connection"
  },
  "AppSettings": {
    "MySettings": "Local Settings"
  }
}

Code to retrieve values from appsettings.json
var MyAppSettings = builder.Configuration.GetSection("AppSettings");
var LocalAppset = MyAppSettings.GetValue<string>("MySettings");

OR
var MyAppSettings1 = builder.Configuration.GetValue<string>("AppSettings:MySettings");

Index.cshtml
@page
@model IndexModel
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

Configuration value for 'AppSettings': @Configuration["AppSettings:MySettings"]

*

*I have deployed the app and able to read the values from the deployed code.

Initial Values

Overridden Values


text:
Q: Properties and columns difference in GEE feature collections What the difference between columns and properties in Google Earth Engine feature collections?
When I build a new feature collection with a property directly in the code editor, when I print it I do not see "properties" but only "columns" and "features". Instead, when I open a feature collection which I have as an asset I see "properties","columns" and "features" as three different parts of the the feature collections. Where "columns" are the fields from the shapefile that I imported as asset.
So, why "properties" are added in a feature collections imported as asset?
And what's the difference between "properties" and "columns"?

A: First, it's important to understand that a feature collection is, itself, a sort of feature — or in the lesser-known terminology of the API, an "element". Thus, like any other feature (or an image or image collection), the collection itself can have properties, which are completely separate from properties of features within the collection.
As an example, suppose you have uploaded your own table (feature collection) asset from a CSV file: properties of features come from the rows of the CSV file, but properties of the collection come from filling out the "Properties" section of the upload dialog.
When you're writing code, collection.set("pname", "pvalue") will add a property on a collection; collection.map(function (feature) { return feature.set("pname", "pvalue"); }) will add a property on each feature of the collection.

When you print or evaluate a feature collection, you may see:

*

*properties: Properties attached to the collection itself, not the features.

*features: The features in the collection, each of which has its own properties.

*columns: The names and types of properties which every feature in the collection has.
columns information is only sometimes available; in particular, it is typically present for feature properties in collections loaded from assets (tables) and typically not present for properties you've added within the computation via .map() over the collection or other such operations.
If a property name is listed in columns, then you can expect that every feature in the collection has that property. If not listed, there may or may not be such a property on each feature.


text:
Q: how can I control the signal in two always block I am trying to write initial LCD module. I didn't finish letter writing part. When I'm creating that part, there is small problem in my code. I can't write data in two always blocks. When I do that , Xilinx says ERROR: counter signal is connected to multiple drivers., comment language is Turkish but it's not important.
I just want to know how I can reset and increment counter reg to increase in always *(posedge CLK or posedge RESET) block and reset the counter reg in always *@ block?
/*

 Wait 45ms.
 Write 0x38, wait 4.1ms.
 Write 0x38, wait 100us.
 Write 0x38, wait 40us.
 Write 0x38, wait 40us.
 Write 0x0F, wait 40us. (Display ON, Cursor ON, Blinking ON)
 Write 0x01, wait 1.64ms. (Clear display)
 Write 0x06, wait 40us. (Entry Mode Set, Auto-Increment, No Shift)
 Write LETTER_PRINTED
*/
//////////////////////////////////////////////////////////////////////////////////
module LCD_Baslangic(
    input CLK,
    input RESET,
     input wire [7:0] LETTER_PRINTED, //letter to be printed
    output wire LCD_E,
     //output wire LCD_RW,
    output wire LCD_RS,
    output wire [7:0] LCD_DATA
    );
        //Başlangıç değerleri
    reg [7:0] sampled_LCD_DATA = 8'd0;
    reg sampled_LCD_E = 0;
    reg sampled_LCD_RS = 0;
    //reg sampled_LCD_RW = 0;

    reg [19:0] counter = 20'd0 ; // 83.3 ns göre hesaplandı.
    //En yüksek bekleme süresi 45ms olduğu için counter 10000011111111111111
    //dönmesi demek,540671 kez dönmesi demektir.

    reg [19:0] precomp_delay = 20'd0;
    reg flag_45ms = 0, flag_function_is_set = 0;

    localparam t_45ms = 540000; // beslenme delayı
    localparam t_4_1ms = 54000;  //
   localparam t_1_64ms = 19680; // Clear Display komutun işleme cycle
   localparam t_100us = 1200;
    localparam t_40us = 480;
    localparam t_40_80ns = 1;
    localparam t_240ns = 3;

    localparam [3:0]
                        starting_state                          = 4'd0, // 45ms Beklenen kısım
                        reset_state                                 = 4'd1,
                        write_state                                 = 4'd2, // İlk Write State
                        data_delay_state                            = 4'd3, // 80ns bir bekleme yapıyoruz. Yazılan data garanti olsun diye
                        enable_high_state                       = 4'd4, // Enable ın 1 oldugu durum bu state 240ns korunur.
                        oneclock_delay_state                    = 4'd5, // 240ns den sonra 10 ns bir bekleme gerçekleşir.Fakat FPGA kartımız en 83.3 ns clock üretebildiği için en az bir clock sağlıyabilirz.
                        precompiler_delay_state                 = 4'd6, // yapılan işleme göre LCD gerçekleştirme süresidir
                        check_isthereanywritingdata_state   = 4'd7, // yapilacak başka bir işlem varsa write state'e geri döner, yoksa bir state atlar
                        infinity_state                              = 4'd8; // Programın sona erdiği yer.

    reg [4:0] substate = 5'd0;
    reg [3:0] state_reg = 4'd0;
    reg [3:0] state_next = 4'd0;

    always @(posedge CLK or posedge RESET)
        begin
            if (RESET)
                begin
                    state_reg <= reset_state;
                    counter      <= 20'd0;
                end
            else
                begin
                    state_reg   <= state_next;
                    counter       <= counter + 20'd1;
                end
        end

    always @*
        begin
            state_next = state_reg;
            case (state_reg)
                starting_state:
                        begin
                            if (counter == t_45ms)
                                begin
                                        counter = 20'd0;
                                        state_next = write_state;
                                        flag_45ms = 1;
                                end
                        end
                    reset_state:
                        begin
                            if (RESET == 0)
                                begin
                                    if (flag_45ms == 1) // Demekki ilk durum gerçekleşmiş
                                        begin
                                            if (flag_function_is_set == 0) // Fonksiyonlarda gönderilmemiş
                                                state_next = write_state;
                                            else
                                                state_next = infinity_state;
                                        end
                                    else
                                        state_next = starting_state;
                                end
                            else
                                state_next = reset_state;
                        end
                    write_state:
                        begin
                                case (substate)
                                        5'd0:
                                            begin
                                                sampled_LCD_DATA = 8'h38;
                                                precomp_delay = t_4_1ms;
                                                sampled_LCD_RS = 0;
                                            end
                                        5'd1:
                                            begin
                                                sampled_LCD_DATA = 8'h38;
                                                precomp_delay =  t_100us;
                                                sampled_LCD_RS = 0;
                                            end
                                        5'd2:
                                            begin
                                                sampled_LCD_DATA = 8'h38;
                                                precomp_delay = t_40us;
                                                sampled_LCD_RS = 0;
                                            end
                                        5'd3:
                                            begin
                                                sampled_LCD_DATA = 8'h38;
                                                precomp_delay = t_40us;
                                                sampled_LCD_RS = 0;
                                            end
                                        5'd4:
                                            begin
                                                sampled_LCD_DATA = 8'h0F; // Display ON, Cursor On, Blinking On
                                                precomp_delay = t_40us;
                                                sampled_LCD_RS = 0;
                                            end
                                        5'd5:
                                            begin
                                                sampled_LCD_DATA = 8'h01; // Clear Display
                                                precomp_delay = t_1_64ms;
                                                sampled_LCD_RS = 0;
                                            end
                                        5'd6:
                                            begin
                                                sampled_LCD_DATA = 8'h06; // Entry Set, Auto-Increment,No Shift
                                                precomp_delay = t_40us;
                                                sampled_LCD_RS = 0;
                                            end
                                        default:
                                            sampled_LCD_DATA = sampled_LCD_DATA;
                                    endcase
                                state_next = data_delay_state;
                        end
                    data_delay_state: // Data Oluşum Delayı
                        begin
                            if (counter >= t_40_80ns)
                                begin
                                    state_next = enable_high_state;
                                    counter = 20'd0;
                                    sampled_LCD_E = 1; // Enable High olur
                                end

                        end
                    enable_high_state: // 240ns Enable High durumunu korur.
                        begin
                            if (counter == t_240ns)
                                begin
                                    state_next = oneclock_delay_state;
                                    counter = 20'd0;
                                    sampled_LCD_E = 0; // 10 ns bekleme yapalım
                                end
                        end
                    oneclock_delay_state:
                        begin
                            if (counter >= t_40_80ns)
                                    begin
                                        state_next = precompiler_delay_state; // bir clock 83.3 lük bekleme yapar,
                                                                                //yani 10 ns lik bir delay anca en az
                                                                                //bir clock yaparak uyarlanabilir.
                                        counter = 20'd0;
                                    end
                            else
                                counter = counter + 20'd1;
                        end
                    precompiler_delay_state: // Pre Compiler Delay.
                        begin
                            if (counter == precomp_delay)
                                begin
                                    counter = 20'd0;
                                    precomp_delay = 20'd0;
                                    state_next = check_isthereanywritingdata_state;
                                end
                            else
                                counter = counter + 20'd1;
                        end
                    check_isthereanywritingdata_state: //
                        begin
                            if (substate == 5'd6)
                                begin
                                    state_next = infinity_state; // yapilacak işlemler bittiyse öbür state e geç
                                    flag_function_is_set = 1;
                                end
                            else
                                begin
                                    substate = substate + 3'd1;
                                    state_next = write_state;
                                end
                        end
                    infinity_state:
                        state_next = state_reg ; // durumunu korur.Program sona erer.
                endcase
        end

    assign LCD_E = sampled_LCD_E;
    //assign LCD_RW = sampled_LCD_RW;
    assign LCD_RS = sampled_LCD_RS;
    assign LCD_DATA [7:0] = sampled_LCD_DATA [7:0];

A: You're counter signal has multiple drivers and considered to be
an error.
Here is an example that demonstrates the error and will not work:
always @(posedge clk) begin
   counter <= some_signal;
end

always @* begin
   counter <= another_signal;
end

To reset the counter flip-flop, you might need to declare another
combinational circuit to reset the counter. The same with incremeting.
reg reset_counter;
reg increment_counter;

always @(posedge CLK or posedge RESET)
    begin
        if (RESET)
            begin
                state_reg <= reset_state;
                counter      <= 20'd0;
            end
        else
            begin
                state_reg   <= state_next;
                if (reset_counter) begin
                   counter <= 0;
                end
                else if (increment_counter) begin
                   counter       <= counter + 20'd1;
                end
            end
    end

Then add reset_counter and increment_counter in your combinational logic block.
always @*
  begin
     state_next = state_reg;
     reset_counter = 0;
     increment_counter = 0;

Finally, change the occurence of counter = 20'd0; to
reset_counter = 1;
The same is through with counter = counter + 20'd1;.
Change this line to increment_counter = 1.
I modified the code for you. (Note that I separated state_reg
and counter registers to improve readability and make it
easier to debug).
module LCD_Baslangic(
                     input             CLK,
                     input             RESET,
                     input wire [7:0]  LETTER_PRINTED, //letter to be printed
                     output wire       LCD_E,
                     //output wire LCD_RW,
                     output wire       LCD_RS,
                     output wire [7:0] LCD_DATA
                     );
   //Başlangıç değerleri
   reg [7:0]                           sampled_LCD_DATA = 8'd0;
   reg                                 sampled_LCD_E = 0;
   reg                                 sampled_LCD_RS = 0;
   //reg sampled_LCD_RW = 0;

   reg [19:0]                          counter = 20'd0 ; // 83.3 ns göre hesaplandı.
   //En yüksek bekleme süresi 45ms olduğu için counter 10000011111111111111
   //dönmesi demek,540671 kez dönmesi demektir.

   reg [19:0]                          precomp_delay = 20'd0;
   reg                                 flag_45ms = 0, flag_function_is_set = 0;

   localparam t_45ms = 540000; // beslenme delayı
   localparam t_4_1ms = 54000;  //
   localparam t_1_64ms = 19680; // Clear Display komutun işleme cycle
   localparam t_100us = 1200;
   localparam t_40us = 480;
   localparam t_40_80ns = 1;
   localparam t_240ns = 3;

   localparam [3:0]
     starting_state                          = 4'd0, // 45ms Beklenen kısım
     reset_state                                 = 4'd1,
     write_state                                 = 4'd2, // İlk Write State
     data_delay_state                            = 4'd3, // 80ns bir bekleme yapıyoruz. Yazılan data garanti olsun diye
     enable_high_state                       = 4'd4, // Enable ın 1 oldugu durum bu state 240ns korunur.
     oneclock_delay_state                    = 4'd5, // 240ns den sonra 10 ns bir bekleme gerçekleşir.Fakat FPGA kartımız en 83.3 ns clock üretebildiği için en az bir clock sağlıyabilirz.
     precompiler_delay_state                 = 4'd6, // yapılan işleme göre LCD gerçekleştirme süresidir
     check_isthereanywritingdata_state   = 4'd7, // yapilacak başka bir işlem varsa write state'e geri döner, yoksa bir state atlar
     infinity_state                              = 4'd8; // Programın sona erdiği yer.

   reg [4:0]                           substate = 5'd0;
   reg [3:0]                           state_reg = 4'd0;
   reg [3:0]                           state_next = 4'd0;
   reg                                 reset_counter;
   reg                                 increment_counter;

   always @(posedge CLK or posedge RESET)
     begin
        if (RESET)
          begin
             state_reg <= reset_state;
          end
        else
          begin
             state_reg   <= state_next;
          end
     end

   always @(posedge CLK or posedge RESET)
     begin
        if (RESET)
          begin
             counter      <= 20'd0;
          end
        else
          begin
             if (reset_counter) begin
                counter <= 0;
             end
             else if (increment_counter) begin
                counter       <= counter + 20'd1;
             end
          end
     end

   always @*
     begin
        state_next = state_reg;
        reset_counter = 0;
        increment_counter = 0;
        case (state_reg)
          starting_state:
            begin
               if (counter == t_45ms)
                 begin
                    // counter = 20'd0;
                    reset_counter = 1;
                    state_next = write_state;
                    flag_45ms = 1;
                 end
            end
          reset_state:
            begin
               if (RESET == 0)
                 begin
                    if (flag_45ms == 1) // Demekki ilk durum gerçekleşmiş
                      begin
                         if (flag_function_is_set == 0) // Fonksiyonlarda gönderilmemiş
                           state_next = write_state;
                         else
                           state_next = infinity_state;
                      end
                    else
                      state_next = starting_state;
                 end
               else
                 state_next = reset_state;
            end
          write_state:
            begin
               case (substate)
                 5'd0:
                   begin
                      sampled_LCD_DATA = 8'h38;
                      precomp_delay = t_4_1ms;
                      sampled_LCD_RS = 0;
                   end
                 5'd1:
                   begin
                      sampled_LCD_DATA = 8'h38;
                      precomp_delay =  t_100us;
                      sampled_LCD_RS = 0;
                   end
                 5'd2:
                   begin
                      sampled_LCD_DATA = 8'h38;
                      precomp_delay = t_40us;
                      sampled_LCD_RS = 0;
                   end
                 5'd3:
                   begin
                      sampled_LCD_DATA = 8'h38;
                      precomp_delay = t_40us;
                      sampled_LCD_RS = 0;
                   end
                 5'd4:
                   begin
                      sampled_LCD_DATA = 8'h0F; // Display ON, Cursor On, Blinking On
                      precomp_delay = t_40us;
                      sampled_LCD_RS = 0;
                   end
                 5'd5:
                   begin
                      sampled_LCD_DATA = 8'h01; // Clear Display
                      precomp_delay = t_1_64ms;
                      sampled_LCD_RS = 0;
                   end
                 5'd6:
                   begin
                      sampled_LCD_DATA = 8'h06; // Entry Set, Auto-Increment,No Shift
                      precomp_delay = t_40us;
                      sampled_LCD_RS = 0;
                   end
                 default:
                   sampled_LCD_DATA = sampled_LCD_DATA;
               endcase
               state_next = data_delay_state;
            end
          data_delay_state: // Data Oluşum Delayı
            begin
               if (counter >= t_40_80ns)
                 begin
                    state_next = enable_high_state;
//                    counter = 20'd0;
                    reset_counter = 1;
                    sampled_LCD_E = 1; // Enable High olur
                 end

            end
          enable_high_state: // 240ns Enable High durumunu korur.
            begin
               if (counter == t_240ns)
                 begin
                    state_next = oneclock_delay_state;
//                    counter = 20'd0;
                    reset_counter = 1;
                    sampled_LCD_E = 0; // 10 ns bekleme yapalım
                 end
            end
          oneclock_delay_state:
            begin
               if (counter >= t_40_80ns)
                 begin
                    state_next = precompiler_delay_state; // bir clock 83.3 lük bekleme yapar,
                    //yani 10 ns lik bir delay anca en az
                    //bir clock yaparak uyarlanabilir.
//                    counter = 20'd0;
                    reset_counter = 1;
                 end
               else
                 increment_counter = 1;
//                 counter = counter + 20'd1;
            end
          precompiler_delay_state: // Pre Compiler Delay.
            begin
               if (counter == precomp_delay)
                 begin
                    //counter = 20'd0;
                    reset_counter = 1;
                    precomp_delay = 20'd0;
                    state_next = check_isthereanywritingdata_state;
                 end
               else
//                 counter = counter + 20'd1;
                 increment_counter = 1;
            end
          check_isthereanywritingdata_state: //
            begin
               if (substate == 5'd6)
                 begin
                    state_next = infinity_state; // yapilacak işlemler bittiyse öbür state e geç
                    flag_function_is_set = 1;
                 end
               else
                 begin
                    substate = substate + 3'd1;
                    state_next = write_state;
                 end
            end
          infinity_state:
            state_next = state_reg ; // durumunu korur.Program sona erer.
        endcase
     end

   assign LCD_E = sampled_LCD_E;
   //assign LCD_RW = sampled_LCD_RW;
   assign LCD_RS = sampled_LCD_RS;
   assign LCD_DATA [7:0] = sampled_LCD_DATA [7:0];


text:
Q: Conditional average of values in a row, depending on data qualifiers I hope you're all doing well.
So I've been working with Excel my whole life and I'm now switching to Python & Pandas. The Learning curve is proving to be quite steep for me, so please bare with me.
Day after day it's getting better. I've already managed to aggregate values, input/ouput from csv/excel, drop "na" values and much more. However, I've stumbeled upon a wall to high for me to climb right now...
I created an extract of the dataframe I'm working with. You can download it here, so you can understand what I'll be writing about: https://filetransfer.io/data-package/pWE9L29S#link
df_example
t_stamp,1_wind,2_wind,3_wind,4_wind,5_wind,6_wind,7_wind,1_wind_Q,2_wind_Q,3_wind_Q,4_wind_Q,5_wind_Q,6_wind_Q,7_wind_Q
2021-06-06 18:20:00,12.14397093693768,12.14570426940918,10.97993184016605,11.16468568605988,9.961717914791588,10.34653735907099,11.6856901451427,True,False,True,True,True,True,True
2021-05-10 19:00:00,8.045154709031468,8.572511270557484,8.499070711427668,7.949358210396142,8.252115912454919,7.116505042782365,8.815732567915179,True,True,True,True,True,True,True
2021-05-27 22:20:00,8.38946901817802,6.713454777683985,7.269814675171176,7.141862659613969,12.38239256540934,14.23146015260278,11.26704854500004,True,True,True,True,False,False,False
2021-05-05 18:20:00,0.0,0.0,0.0,0.0,0.0,0.0,0.0,False,False,False,False,False,False,False
2021-06-06 12:20:00,11.95525872119988,12.14570426940918,12.26086164116684,12.89527716859738,11.77172234144684,12.12409015586662,12.52180822809299,True,False,True,True,True,True,True
2021-06-04 03:30:00,14.72553364088618,12.72900662616056,10.59386275508178,10.96070182287055,12.38239256540934,12.07846616943932,10.58384464064597,True,True,True,True,False,True,True
2021-05-05 13:00:00,0.0,0.0,0.0,0.0,0.0,0.0,0.0,False,False,False,False,False,False,False
2021-05-24 18:10:00,17.12270521348523,16.22721748967324,14.15318916689965,19.35395873243158,17.60747853230812,17.18577813727543,17.70745523935796,False,False,False,False,True,True,True
2021-05-07 19:00:00,13.94341927008482,10.95456999345216,13.36533234604886,0.0,3.782910539990379,10.86996953698871,13.45072022532649,True,True,True,False,False,True,True
2021-05-13 00:40:00,10.70940582779898,10.22222264510213,9.043496015164536,9.03805802580422,11.53775481234347,10.09538681656049,10.19345618536208,True,True,True,True,True,True,True
2021-05-27 19:40:00,10.8317678500958,7.929683248532885,8.264301219025942,8.184133252794958,12.38239256540934,14.23146015260278,11.26704854500004,True,True,True,True,False,False,False
2021-05-09 12:00:00,10.55571650269678,7.635778078425459,10.43683108425784,7.847532146733346,8.100127641989639,7.770247510198059,8.040702032061867,True,True,True,True,True,True,True
2021-05-19 19:00:00,2.322496225799398,2.193219010982461,2.301622604435732,2.204278609893358,2.285408405883714,1.813280858368885,1.667207419773053,True,True,True,True,True,True,True
2021-05-30 12:30:00,5.776450801637788,8.488826231951345,10.98525552709715,7.03016556196849,12.38239256540934,14.23146015260278,11.26704854500004,True,True,True,True,False,False,False
2021-05-24 14:10:00,17.12270521348523,16.22721748967324,14.15318916689965,19.35395873243158,17.93466266883504,17.04697174496121,17.0739475214739,False,False,False,False,True,False,True

What you are looking at:
"n" represents the number of measuring points.

*

*First column: Timestamp of values

*Columns index 1 to "n": Average windspeed at different points, of the last 10 minutes

*Columns index "n+1" to last (-1):  Qualifies if the value of the respective point is valid (True) or invalid (False). So to the value "1_wind", the qualifier "1_wind_Q" applies

Want I'm trying to achieve:
The goal is to create a new column called "Avg_WS" which iterates through every row and calculates the following:

*

*Average of the value ranges, ONLY if the corresponding Qualifier is TRUE

Example: So if in a given row, the column "4_wind_Q" is "False", the value "4_wind" should be excluded from the average on that given row.
Extra: If all Qualifiers are "False" in a given row, "Avg_WS" should equal to "NaN" in that same row.
I've tried to use apply, but I can't figure out how to match the pairs of value-qualifier
Thnak you so much in advanced!

A: I tried using mask for this.
quals = ['1_wind_Q','2_wind_Q','3_wind_Q','4_wind_Q','5_wind_Q','6_wind_Q','7_wind_Q']
fields = ['1_wind', '2_wind', '3_wind', '4_wind', '5_wind', '6_wind', '7_wind']

df[fields].mask( ~df[quals].values ).mean( axis=1 )

# output

0     11.047089
1      8.178635
2      7.378650
3           NaN
4     12.254836
5     11.945236
6           NaN
7     17.500237
8     12.516802
9     10.119969
10     8.802471
11     8.626705
12     2.112502
13     8.070175
14    17.504305
dtype: float64

# assign this to the dataframe
df.loc[ :, 'Avg_WS' ] = df[fields].mask( ~df[quals].values ).mean( axis=1 )

mask works by essentially applying a boolean mask on each of the "fields" - the caveat is the bool mask must be the same shape as the data you are trying applying it on (i.e. must have same dimensions n x m)
mean( axis= 1 ) tells the data frame to apply the mean function across each row ( rather than column which axis=0 would imply.


text:
Q: Will an Android app only receive push notifications is the app was downloaded from the Google Play Store? (React Native Expo) I'm using Expo push notifications. Push notifications work fine in Expo Go and for apps on published to the Google Play store. But when I create an APK file and download it directly onto my Android phone, NOT through the Google Play store, the push notifications I send are not received.
Will push notifications only work for apps published to the Google Play store? Or is there a way to receive push notifications for apps downloaded directly onto an Android phone without being published to the Google Play store?

A: *

*Depending on your android version and rom you have to open the app setting's (for me long press app icon).

*Select settings

*Choose notifications

*Enable notification for this app

A: I forgot to import { Platform } from 'react-native'.
Also, I needed to upload Android server api key credentials which can be found in Firebase Console in your project settings under Cloud Messaging. Here is how to upload the server api key credentials in the terminal:
expo push:android:upload --api-key <your-token-here>

Documentation can be found here under "Uploading Server Credentials": https://docs.expo.dev/push-notifications/using-fcm/


text:
Q: My react-native application run correctly on android emulation 100% but it shown network error on physical device when I login or signup Database: MongoDB
App: react native
Node js
error: My react-native application run correctly on android emulation 100% but it shown network error on physical device when I login or signup.

A: It is because your server ( node.js ) is not hosted. To run your application in other physical devices ( except emulator ) you have to host your server because any physical phone cannot work with your machine localhost API.


text:
Q: In a stored procedure how to run a query and conditionally do something How would I do this in a stored procedure (SQL 2005):
count = select count(*) from table1 where line like '%success%'
if count > 0:
   delete from table1 where not line like '%success%'

Thanks for any help.  My google skills are really failing me today :-(

A: I would write that this way
if exist (select 1 from table1 where line like '%success%')
begin
    delete from table1 where line not like '%success%'
end

A: So if there are any rows where line is like success then delete any rows where line is not like success?
IF EXISTS (SELECT * from table1 where line like '%success%')
   delete from table1 where line NOT like '%success%'

A: I would not keep the check at all. What is the purpose of that check?
Just use the delete query along with the where clause.


text:
Q: Why pip cannot install package even having permissions for both user & system repository? When I upgrade my user's pip repository with the following command:
pip freeze --local | grep -v '^\-e' | cut -d = -f 1  | xargs pip install -U

I got the following error message:
Exception:
Traceback (most recent call last):
  File "/home/peng/.local/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/home/peng/.local/lib/python2.7/site-packages/pip/commands/install.py", line 317, in run
    prefix=options.prefix_path,
  File "/home/peng/.local/lib/python2.7/site-packages/pip/req/req_set.py", line 742, in install
    **kwargs
  File "/home/peng/.local/lib/python2.7/site-packages/pip/req/req_install.py", line 831, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "/home/peng/.local/lib/python2.7/site-packages/pip/req/req_install.py", line 1032, in move_wheel_files
    isolated=self.isolated,
  File "/home/peng/.local/lib/python2.7/site-packages/pip/wheel.py", line 346, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/home/peng/.local/lib/python2.7/site-packages/pip/wheel.py", line 330, in clobber
    os.utime(destfile, (st.st_atime, st.st_mtime))
OSError: [Errno 1] Operation not permitted: '/usr/local/lib/python2.7/dist-packages/easy_install.pyc'

However the file that triggers this error already has all permissions opened:
ls /usr/local/lib/python2.7/dist-packages/easy_install.pyc -l
-rwxrwxrwx 1 root staff 315 Jul  5 20:47 /usr/local/lib/python2.7/dist-packages/easy_install.pyc

Why pip is still unable to work on it? What has to be done to fix it?

A: I've encountered this error when running pip install by a different user than owner of python files. It's a strange (and ugly) limitation of Linux: any user with write permission can set file times to current time (touch), but only owner of file can set arbitrary times. pip/wheel is trying to set exact times, and kernel doesn't allow it.
Relevant pip issue: https://github.com/pypa/pip/issues/2125
Beta (than nuthin) solution is to change file owner or run pip as file owner user.
I am desperately looking for a better solution, please help in comments.


text:
Q: COM interop reference counting guidelines Recently I spent quite some time writing various Visual Studio Extensions projects. Even though the projects are all managed code to access the core VS services it is still necessary to work with the old style COM interfaces.
Here is an example:
var selectionTracker = (IVsMonitorSelection)serviceProvider.GetService(typeof(SVsShellMonitorSelection));
IntPtr ppHier;
uint pitemid;
IVsMultiItemSelect ppMIS;
IntPtr ppSC;
selectionTracker.GetCurrentSelection(out ppHier, out pitemid, out ppMIS, out ppSC)))

as you can see this call returns 2 pointers (ppHier and ppSC) and an object ppMIS.
The question is: how should I go about playing it nice with COM reference counting.
It is my understanding that in COM world when a method returns a pointer to an object this pointer is AddRef'ed before it is returned. Which means that to prevent the COM object leakage I have to Release them when I am done using them.
I also assume that what I am getting as an object it is already wrapped into a RCW, which will take care of reference releasing when it is finalized.
These 2 assumptions applied to the above call would mean that I have to make sure to call `Marshal.Release' on my 2 pointers, but I should not do anything about reference counting in regards to the object returned.
To rephrase my question: assuming that the COM objects I am using are playing by the COM rules, is the approach above the right way to deal with COM reference counting?

A: In this particular scenario you would need to call Marshal.Release on the IntPtr variables otherwise they will not go away. Of course if you tell the marshaller to just use object (or a specific type) directly then you would not need to worry about it as the RCW will ensure the object is destroyed at some point in the future (i.e. when the finalizer is called in the garbage collection process).
Of course the finalizer approach could happen at a non-deterministic point in time so if the object maintains some resource which you need to get rid of you should ideally call Marshal.ReleaseComObject to decrement its reference count before the wrapper does the releasing for you.


text:
Q: How to get top account with Vault in a way that it doesn't lag? Vault is a plugin for Bukkit that is also an Economy API. It can be used to post updates to Players' money, and used as a Currency in a server.
VaultAPI is also open-sourced at Github
I'm trying to get the accounts which have the biggest amount of money, but that's not straight-forward in Vault's API.
So, what I tried to do was:

*

*Iterating through all OfflinePlayers and comparing money values

*Recovering the biggest value

Code:
double highest = 0;
OfflinePlayer topPlayer;
OfflinePlayer[] players = Bukkit.getOfflinePlayers();

for (OfflinePlayer p : players) {
    double playerAmount = econ.getBalance(p);    //Econ is Economy  instance from Vault.
    if (playerAmount > highest){
        highest = playerAmount;
        topPlayer = p;
    }
}

I tried iterating all acounts to find the highest amount, but it lags a lot when you have too many Players.
Is there any way to find which players have the biggest amount of money?

A: There are a few ways you can accomplish this.
First of all, you could use Essentials' UserBalanceUpdateEvent and determine if the balance is higher than the high score in the config (in which case, you update the stored value with the new value and the UUID it belongs to).
Second, you could iterate through the OfflinePlayers, but using an Asynchronous task.


text:
Q: Outputting XML on Java Servlet using PrintWriter I have used this tutorial to convert an ArrayList to XML. My code is successfully outputting XML to the Eclipse console.
Here is a snippet of my code
DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
DocumentBuilder build = dFact.newDocumentBuilder();
Document doc = build.newDocument();

Element root = doc.createElement("Properties");
doc.appendChild(root);

for(House house : house) {

    Element Details = doc.createElement("house");
    root.appendChild(Details);

    Element location = doc.createElement("location");
    location.appendChild(doc.createTextNode(house.getLocation()));
    Details.appendChild(location);

    ...

}

 // Save the document to the disk file
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();

// format the XML nicely
aTransformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");

aTransformer.setOutputProperty(
        "{http://xml.apache.org/xslt}indent-amount", "4");
aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");

DOMSource source = new DOMSource(doc);
StreamResult result =  new StreamResult(System.out);
aTransformer.transform(source, result);

Instead of outputting this XML to the Eclipse console, I would like to print out the XML on a servlet.
I have done something similar with a jsonObject, using the following code:
PrintWriter out = resp.getWriter();
...
out.print(jsonObject);
out.close();

But I can't seem to work out how to use this method to output my XML.
Please can someone point me in the right direction. Thank you

A: You should set the content type:
response.setContentType("text/xml; charset=UTF-8"); //you can set the encode you want to charset
PrintWriter out = response.getWriter();
out.print(yourXmlString);

A: You will use the response.getOutputStream() to write the XML to Servlet output.
StreamResult result =  new StreamResult(response.getOutputStream());

Preferably, you can use a Writer, the response.getWriter() can be used on StreamResult:
StreamResult result =  new StreamResult(response.getWriter());

Also, you will need to set the Content-Type header to text/html; charset=UTF-8 (and provided your encoding is indeed UTF-8).
response.setContentType("text/xml; charset=UTF-8");

I hope this helps.


text:
Q: Load->view a file based on SQL field I'm trying to load a file (a website header) depending on a preference set by a user, which is stored in a mysql db field.
This code loads the header when placed on any page:
<?php $this->load->view('header');?>

Users have an option to select/deselect the header in the preferences.
to show the header the term 'show' is saved to the cell in the database and 'hide' to hide.
I have been working this code:
<?php if(($boardDetails->showheader)):show ?>
<?php $this->load->view('header');?>
<?php endif ?>

Where 'showheader' is the database field name and 'show' is the content within it. But I keep getting errors with conflicting php code in the same file: unexpected end etc.
When I trim them up to make it viewable the header is loaded regardless of the content of the users field.
So 'show' and 'hide' both display the header.
Does anyone have a simpler way of selecting this option working with my current code?

A: Your should try something like this:
    <?php
         if(($boardDetails->showheader)=="show"){
          $this->load->view('header');
          }

    ?>


text:
Q: How to get a limited number of values from a HashMap or LinkedHashMap? Say I have a LinkedHashMap containing 216 entries, how would I get the first 100 values (here, of type Object) from a LinkedHashMap<Integer, Object>.

A: Well to start with, doing this for HashMap as per your title, doesn't make much sense - HashMap has no particular order, and the order may change between calls. It makes more sense for LinkedHashMap though.
There, I'd use Guava's Iterables.limit method:
Iterable<Object> first100Values = Iterables.limit(map.values(), 100);

or
// Or whatever type you're interested in...
Iterable<Map.Entry<Integer, Object>> firstEntries =
    Iterables.limit(map.entrySet(), 100);

You can then create a list from that, or iterate over it, or whatever you want to do.

A: You can do:
Map<Integer, Object> records;
List<Entry<Integer, Object>> firstHundredRecords
    = new ArrayList<Entry<Integer, Object>>(records.entrySet()).subList(0, 100);

Although note that this will copy all the entries from the map.

A: To copy only the records you need with using a library.
Map<Integer, Object> records;

List<Entry<Integer, Object>> firstHundredRecords = new ArrayList<>();
for(Entry<Integer, Object> entry : records.entrySet()) {
    firstHundredRecords.add(entry);
    if (firstHundredRecords.size()>=100) break;
}

A: Ugly One-Liner
This ugly one-liner would do (and return a ArrayList<Object> in the question's case):
Collections.list(Collections.enumeration(lhMap.values())).subList(0, 100)

This would work for a HashMap as well, however HashMap being backed by a HashSet there's not guarantee that you will get the first 100 values that were entered; it would work on other types, with similar limitations.
Notes:

*

*relatively unefficient (read the Javadoc to know why - though there's worse!),

*careful when using views (read the Javadoc to know more),

*I did mention it was ugly.

Step-By-Step Usage Example
(as per the OP's comment)
Map<Integer, Pair<Double, SelectedRoad>> hashmap3 =
  new LinkedHashMap<Integer, Pair<Double, SelectedRoad>>();

// [...] add 216 elements to hasmap3 here somehow

ArrayList<Pair<Double,SelectedRoad>> firstPairs =
  Collections.list(Collections.enumeration(hashmap3.values())).subList(0, 100)

// you can then view your Pairs' SelectedRow values with them with:
//  (assuming that:
//    - your Pair class comes from Apache Commons Lang 3.0
//    - your SelectedRoad class implements a decent toString() )
for (final Pair<Double, SelectedRoad> p : firstPairs) {
    System.out.println("double: " + p.left);
    System.out.println("road  : " + p.right);
}

A: Write a loop which uses a Iterator.next() 100 times, and then stops.
I was going to say something about NavigableMap and SortedMap - but their interfaces are defined in terms of keys, not indexes. But they may be useful nevertheless, depending on what your actual underlying problem is.

A: You can use counter. Your foreach loop will exit when your counter reached 100.


text:
Q: Is it possible to insert fingerprint in php having oracle sql developer? <?php

   include '../conexao_oracle.php';

   $db = $pdo;
   $db->beginTransaction(); // Essential!
   $mimetype = 'image/jpeg';
   $funcionario_id = 10;
   $stmt = $db->prepare(
       "INSERT INTO foto (mimetype, binario, funcionario_id) ".
       "VALUES (:mimetype, EMPTY_BLOB(), :funcionario_id) ".
       "RETURNING binario INTO :binario");
   $stmt->bindParam(':mimetype', $mimetype);
   $stmt->bindParam(':binario', $blob, PDO::PARAM_LOB);
   $stmt->bindParam(':funcionario_id', $funcionario_id);
   $blob = fopen('fotos/10.jpg', 'rb');
   $stmt->execute();
   $pdo->commit();

we save image through this this in blob if it is possible to store fingerprint in database then what is the best solution for this?


text:
Q: is this use of eval in a node server a bad idea? I want to create an object dynamically in node. To do that i used a code like this.
Is this use of eval in a node server a bad idea?
var a1 = require(./a1.js),
    a2 = require(./a2.js),
    ...
    aN = require(./aN.js);

    function createObj(pObjName, pObjValue){
        var tmp = new eval(pObjName)(pObjValue);
        //where pObjName is a1 or a1 or .... or aN
    }

A: From what you're showing, there's no need to use eval:
const Classes = {
  a1 : require('./a1'),
  a2 : require('./a2'),
  ...
};

function createObj(pObjName, pObjValue){
  var tmp = new Classes[pObjName](pObjValue);
  ...
}

A: Seems like you want to create objects with a set of properties?
You might want to look at the Object.create()-method

A: If you want to save yourself the time of declaring all of those dependencies, you could even write a function without using eval that handles the case even more efficiently:
function createObj(pObjName, pObjValue) {
  var tmp = new (require('./' + pObjName))(pObjValue);
  // ...
}

Please note that this is only safe if createObj() is guaranteed to be invoked with a pObjName that is what you expect, otherwise you'll need to validate it first, possibly something like this:
function createObj(pObjName, pObjValue) {
  if (!/^a\d$/.test(pObjName)) {
    throw new TypeError('invalid name')
  }

  var tmp = new (require('./' + pObjName))(pObjValue);
  // ...
}


text:
Q: How Can I Remove This White Box Behind This HighCharts Sparkline (Code and Picture Included) In the code provided below, you can see that I have a list of data series all with Data and a Name, and for each series in that list, I am trying to create a highcharts sparkline.  The data for the sparkline is bound using KnockoutJS. However, there is this pesky white background square that I can't figure out how to remove (pictured below).
var highChartsFunction = $(function () {
            Highcharts.SparkLine = function (a, b, c) {
                var hasRenderToArg = typeof a === 'string' || a.nodeName,
                    options = arguments[hasRenderToArg ? 1 : 0],
                    defaultOptions = {
                        chart: {
                            renderTo: (options.chart && options.chart.renderTo) || this,
                            borderWidth: 0,
                            type: 'area',
                            backgroundColor: '#eeeeee',
                            width: 120,
                            height: 50,
                            style: {
                                overflow: 'visible'
                            },
                            skipClone: true
                        },
                        title: {
                            text: ''
                        },
                        credits: {
                            enabled: false
                        },
                        xAxis: {
                            labels: {
                                enabled: false
                            },
                            title: {
                                text: null
                            },
                            startOnTick: false,
                            endOnTick: false,
                            tickPositions: []
                        },
                        yAxis: {
                            endOnTick: false,
                            startOnTick: false,
                            labels: {
                                enabled: false
                            },
                            title: {
                                text: null
                            },
                            tickPositions: [0]
                        },
                        legend: {
                            enabled: false
                        },
                        tooltip: {
                            enabled: false
                        },
                        plotOptions: {
                            series: {
                                animation: false,
                                lineWidth: 1,
                                marker: {
                                    enabled: false
                                },
                                states: {
                                    hover: {
                                        enabled: false
                                    }
                                },
                                fillOpacity: 0.25,
                                color: "#2aabb2"
                            },
                        },
                    };

                options = Highcharts.merge(defaultOptions, options);

                return hasRenderToArg ?
                        new Highcharts.Chart(a, options, c) :
                        new Highcharts.Chart(options, b);
            };

            var $tds = $('div[data-sparkline]');

            function doChunk() {
                var i,
                    len = $tds.length,
                    $td,
                    stringdata,
                    data,
                    chart;

                for (i = 0; i < len; i += 1) {
                    $td = $($tds[i]);
                    stringdata = $td.data('sparkline');
                    data = $.map(stringdata.split(','), parseFloat);
                    chart = {};
                    $td.highcharts('SparkLine', {
                        series: [{
                            data: data,
                            pointStart: 1
                        }],

                        chart: chart
                    });
                }
            }
            doChunk();
        });

Here is the html behind the sparklines:

And finally, the picture of the output:

Is there anyway to remove this white square? I've tried all of the background attributes and the borders and nothing seems to work.  Whenever I add this into JFiddle, the charts look just fine and do not have the white square, so I cannot recreate the issue there in order to isolate it.  Thank you in advance for any help you can give!

A: Hard as there isn't a live example. Try the below though:
ul,
ul li  {
 padding: 0px !important;
margin:0px !important;
}


text:
Q: Gearman Cannot connect to server Does anyone have any idea what could be causing this problem in Gearman?

PHP Warning:  GearmanClient::doBackground():
  gearman_connection_flush:could not connect

I am trying to connect to another server to run a gearman task and I am using the PECL PHP Gearman package.

A: It's an old question, but for anyone who encounters this: your Gearman daemon may not be running. Do gearmand -d to set up the daemon first, then start your worker process, then finally run the client code.


text:
Q: Is there a way to do a reverse "code generation" in jooq? I use jooq (version 3.5.3) in one of my projects and I am quite happy with it. Now I came across the situation that it would be nice to check if a table in the database is available and, if that's not the case, create it.
That would come in handy when I'm installing my software on a new system and I could just take care of table creation automatically.
My initial idea was to use:
DSLContext create = DSL.using(conn, SQLDialect.POSTGRES);
for (Table<?> t : Public.PUBLIC.getTables()) {
    create.createTable(t);
}

However, it does nothing since it lacks the .execute(). But that is apparently only possible if at least one .column() is added. If I do
create.createTable(t).column("foo", SQLDataType.INTEGER).execute();

it works, and creates the table, but (naturally) only with one column called foo.
So, the question is: Is there a lazy way to just create the table in the database that it fits to the generated code, or do I have to use a more manual approach for that?

A: The main reason and motivation for jOOQ to originally support DDL statements is precisely what you have in mind, and is described in this feature request here:

*

*https://github.com/jOOQ/jOOQ/issues/3160
In fact, the motivation is slightly different. While jOOQ doesn't encourage you use its DDL for actual schema creation (because of the lack of support for storage clauses, and other vendor-specific features), it will be useful nonetheless for generating test schemas that are somewhat equivalent to the original production schema.
As of jOOQ 3.6, the supported DDL statements are still far from complete to help you re-generate your schema, which is why #3160 is still not implemented. You will have to write some glue code yourself, e.g. (still incomplete, but to give you an idea):
for (Table<?> t : Public.PUBLIC.getTables()) {
    CreateTableAsStep<?> a = create.createTable(t);
    CreateTableColumnStep b = null;

    for (Field<?> f : t.fields())
        if (b == null)
            b = a.column(f, f.getDataType());
        else
            b = b.column(f, f.getDataType());

    b.execute();
}


text:
Q: flyway how to use placeholder in insert query inside SQL file Application.properties
TM_ESCALATION_QUALIFICATION=SHIFT_LEADER

Application.java
@Value( "${TM_ESCALATION_QUALIFICATION}" )
String escalationQualification;

@Bean
InitializingBean printConfigurations(DataSource datasource) {
    return () -> {
            Flyway flyway = new Flyway();
            flyway.setDataSource(datasource);
            flyway.getPlaceholders().put( "ESCALATION_QUALIFICATION", escalationQualification );
            flyway.migrate();
    };
}

SQL file
insert into tm_qualification (ID, NAME, DELETABLE) values (sys_guid(), ${ESCALATION_QUALIFICATION}, 0);

Above is working when I use file with default extension, but getting below error when I make file as .sql extension.
ERROR
org.flywaydb.core.api.FlywayException: No value provided for placeholder expressions: ${ESCALATION_QUALIFICATION}.  Check your configuration!
    at org.flywaydb.core.internal.util.PlaceholderReplacer.checkForUnmatchedPlaceholderExpression(PlaceholderReplacer.java:101)
    at org.flywaydb.core.internal.util.PlaceholderReplacer.replacePlaceholders(PlaceholderReplacer.java:78)
    at org.flywaydb.core.internal.dbsupport.SqlScript.<init>(SqlScript.java:79)....

A: From the web, suggestions are to use
flyway.placeholderReplacement=false
Which only worked after upgrading to > flyway 4.0.3 (spring boot latest uses ooold version)
Another thing that worked is use a bogus placeholder prefix and that did the trick...
flyway.placeholderPrefix=$$$-bogus-$$$


text:
Q: Alternative to Thread.Sleep in windows Form apart from Timer I am using Thread.Sleep in windows form C#. using which results in Not responding of Form.
Using Timer is also not serving my purpose.
Sample Code:
if(......)    // There are many if with difrent components and many Thread.sleep
{
      button.visible=true;
      Thread.sleep(1000);
      GotoMeasurementMode(3000);
      Thread.sleep(3000);
      query(device.Text);
      Thread.sleep(7000);
      StopMeasurement();
      Thread.sleep(4000);
 }

Using above Code results in form irresponsiveness. Using Timer gonna result in Nested Timers. and Not fessable in my case.
Please tell me an alternative in windows form. Want the specific pause between commands.

A: The easiest option is to use this model:
public async void button1_Click(object sender, EventArgs args)
{
    if(condition)
    {
        button.visible=true;
        await Task.Delay(1000);
        GotoMeasurementMode(3000);
        await Task.Delay(3000);
        query(device.Text);
        await Task.Delay(7000);
        StopMeasurement();
        await Task.Delay(4000);
    }
}

If you don't have access to C# 5.0 you can do this in 4.0.  You'll need to start with your own Delay method, as one doesn't exist in .NET 4.0:
public static Task Delay(int milliseconds)
{
    var tcs = new TaskCompletionSource<bool>();
    var timer = new System.Threading.Timer(o => tcs.SetResult(false));
    timer.Change(milliseconds, -1);
    return tcs.Task;
}

Using that we can now write:
Delay(1000)
    .ContinueWith(t => GotoMeasurementMode(3000), TaskScheduler.FromCurrentSynchronizationContext())
    .ContinueWith(t => Delay(3000)).Unwrap()
    .ContinueWith(t => query(device.Text), TaskScheduler.FromCurrentSynchronizationContext())
    .ContinueWith(t => Delay(7000)).Unwrap()
    .ContinueWith(t => StopMeasurement(), TaskScheduler.FromCurrentSynchronizationContext())
    .ContinueWith(t => Delay(4000)).Unwrap();

That is pretty similar to the code that the first snippet will be compiled into, but clearly that first one is much prettier, so you should use it if at all possible.
If we go back to C# 3.0 then we lose access to the Task, this means that we're back to using timers and callbacks.  We'll start with this simple helper method to handle managing the task for us:
public static void ExecuteIn(int milliseconds, Action action)
{
    var timer = new System.Windows.Forms.Timer();
    timer.Tick += (s, e) => { action(); timer.Stop(); };
    timer.Interval = milliseconds;
    timer.Start();
}

Then we can just nest calls to this:
ExecuteIn(1000, () =>
{
    GotoMeasurementMode(3000);
    ExecuteIn(3000, () =>
    {
        query(device.Text);
        ExecuteIn(7000, () => StopMeasurement());
    });
});

While it's possible to re-create a Task in C# 3.0 (it doesn't leverage any of the 4.0 language features) and there are existing libraries that do that, that would be somewhat more involved.

A: Put the above code in a background thread, that way it won't block the UI thread. Assuming your methods in between the waits require UI access, they can use Control.BeginInvoke to make an update on the UI thread.

A: you should consider a BackgroundWorker.
Currently only the .NET framework 4.5 supports the async-await mechanism.
if you're looking at solution backward compatible you should check out this link on CodeProject.
the Background worker will execute your tasks asynchronously in a separate thread context for long running process, keeping your UI responsiveness,
Hope it helps


text:
Q: Returning Data From 2 Tables and Filtering Out Information I am trying to Join 2 tables based on WorkCentres. In the one table the field is called LWorkCentre, in the other table it is called WorkCentre.
I have done a Full Outer Join to join these two tables. Then I want to return overtime hours based on the overtime work centres. So where the overtime WorkCentre is applicable then return the runtime hours otherwise return 0.
This is how I have written the view however, it isn't returning any values.
Please Help I don't know where I am going wrong.
SELECT DISTINCT
dbo.PrjJobHierDet.JobEstimate AS CONTRACT,
dbo.PrjContMaster.ContractDesc1 AS CONTRACT_NAME,
dbo.WipJobPost.TrnDate AS DATE,
dbo.WipJobPost.LWorkCentre AS WORKCENTRE,
dbo.WipJobPost.LWorkCentreDesc AS WORKCENTRE_DESC,
dbo.WipJobPost.Hierarchy1 AS SECTION,
dbo.WipJobPost.Hierarchy2 AS HIER,
dbo.WipJobPost.LEmployee AS EMPLOYEE_ID,
dbo.BomEmployee.Name AS EMPLOYEE_NAME,
dbo.WipJobPost.LRunTimeHours AS HOURS_WORKED,
dbo.BomEmployee.MtdActProdHours AS PRODUCTION_HOURS,
dbo.BomEmployee.MtdNonProdHours AS STANDING_TIME_HOURS,
dbo.BomEmployee.StdHrsPerMonth AS BUDGETED_HOURS,
CASE
   WHEN LWorkCentre = 'CCOTAR' THEN LRunTimeHours
   WHEN LWorkCentre != 'CCOTAR' THEN 0
   WHEN LWorkCentre = 'CCOTWI' THEN LRunTimeHours
   WHEN LWorkCentre != 'CCOTWI' THEN 0
   WHEN LWorkCentre = 'CCOTPM' THEN LRunTimeHours
   WHEN LWorkCentre != 'CCOTPM' THEN 0
   WHEN LWorkCentre = 'CCOTLA' THEN LRunTimeHours
   WHEN LWorkCentre != 'CCOTLA' THEN 0
   WHEN LWorkCentre = 'CCOTSA' THEN LRunTimeHours
   WHEN LWorkCentre != 'CCOTSA' THEN 0
   WHEN LWorkCentre = 'CCOTSU' THEN LRunTimeHours
   WHEN LWorkCentre != 'CCOTSU' THEN 0
   WHEN LWorkCentre = 'ELOTAD' THEN LRunTimeHours
   WHEN LWorkCentre != 'ELOTAD' THEN 0
   WHEN LWorkCentre = 'ELOTCA' THEN LRunTimeHours
   WHEN LWorkCentre != 'ELOTCA' THEN 0
   WHEN LWorkCentre = 'ELOTDE' THEN LRunTimeHours
   WHEN LWorkCentre != 'ELOTDE' THEN 0
   WHEN LWorkCentre = 'MAOTFA' THEN LRunTimeHours
   WHEN LWorkCentre != 'MAOTFA' THEN 0
END AS Overtime
FROM dbo.PrjJobHierDet
INNER JOIN  dbo.WipJobPost
   ON dbo.PrjJobHierDet.JobEstimate = dbo.WipJobPost.Job
INNER JOIN dbo.PrjContMaster
   ON dbo.PrjContMaster.Contract = dbo.WipJobPost.Job
INNER JOIN dbo.BomEmployee
   ON dbo.BomEmployee.Employee = dbo.WipJobPost.LEmployee
FULL OUTER JOIN dbo.BomWorkCentre
   ON dbo.WipJobPost.LWorkCentre = BomWorkCentre.WorkCentre

A: Based on the query, it only makes sense that there isn't any data joinable in your inner joins.
These two tables are joining on the same field, should they be?
 INNER JOIN  dbo.WipJobPost
    ON dbo.PrjJobHierDet.JobEstimate = dbo.WipJobPost.Job
 INNER JOIN dbo.PrjContMaster
    ON dbo.PrjContMaster.Contract = dbo.WipJobPost.Job

Without knowing how else your data is structured, try switching your inner joins to LEFT OUTER JOINs to figure out why it isn't joining properly


text:
Q: Perl - How to set key based on column header when converting from xlsx to perl hash I have a xlsx that im converting into a perl hash

Name
Type
Symbol
Colour

JOHN
SUV
X
R

ROB
MPV
Y
B

JAMES
4X4
Y
G

Currently, I can only set the hash superkey to the column wanted based on column array. I cant seem to figure out how to choose based on column header.
use Data::Dumper;

use Text::Iconv;
my $converter = Text::Iconv->new("utf-8", "windows-1251");

use Spreadsheet::XLSX;

my $excel = Spreadsheet::XLSX->new('file.xlsx', $converter);

foreach my $sheet (@{$excel->{Worksheet}}) {
if ($sheet->{Name} eq "sheet1"){

my %data;

for my $row ( 0 .. $sheet-> {MaxRow}) {
if  ($sheet->{Cells}[0][$col]->{Val} eq "Symbol"){
    my $super_key = $sheet->{Cells}[$row][$col]{Val};

}
    my $key       = $sheet->{Cells}[$row][0]{Val};
    my $value = $sheet->{Cells}[$row][2]{Val};
    my $value2= $sheet->{Cells}[$row][3]{Val};
    $data{$super_key}->{$key}->{$value}=${value2};
}

print Dumper \%data;

}}

The outcome i get is,
$VAR1 = {
          '' => {
                  'JOHN' => {
                             'SUV' => R

I would like to have;
$VAR1 = {
          'X' => {
                  'JOHN' => {
                             'SUV' => R

`

A: You are missing use strict; in your perl script. If you had it, you would have seen your error yourself
Defining the $super_key with my in your If-clause, makes this variable lose scope as soon as you exit it.
And using a variable $col without defining it doesn't work either.
Better (and probably working) is:
for my $row ( 0 .. $sheet-> {MaxRow}) {
    my $super_key;
    foreach my $col (0 .. 3) {
        if  ($sheet->{Cells}[0][$col]->{Val} eq "Symbol"){
            $super_key = $sheet->{Cells}[$row][$col]{Val};
        }
    }
    my $key       = $sheet->{Cells}[$row][0]{Val};
    my $value = $sheet->{Cells}[$row][2]{Val};
    my $value2= $sheet->{Cells}[$row][3]{Val};
    $data{$super_key}->{$key}->{$value}=${value2};
}