text:
Q: Using Environment Variables for connecting to RDS mysql database from php YII application running on docker container I am running few docker container on aws ecs, All running on php Yii application.
the apps needs to connect to AWS RDS database. currently the databasename, host,username and password is hardcoded in the file "main-local.php"
  'components' => [
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=dbinstancename.xxxxx.region.rds.amazonaws.com;dbname=xxxxxxx',
        'username' => 'xxxxxxxx',
        'password' => 'xxxxxxxx',
        'charset' => 'utf8',
    ],

I know its not best practice to hardcode the database details in the docker container.  I can pass environment variables into the docker at run time such that "DB_HOST","DB_NAME", "DB_USER","DB_PASSWORD" with the corresponding values.  I can see the same details inside the docker container typing the command "env"
How can this be used in the main-local.php? can we directly substitute the db details in the code with the env variables? Is this something to be done from the developers end?

A: To add env support you may use this extension https://github.com/vlucas/phpdotenv
Simply install it
composer.phar require vlucas/phpdotenv

Create .env file. It should be in .gitignore and not accessed from web. If you are using basic or advanced templates put it with yii.bat into the project root. Also you may create .env.example with empty variables.
YII_DEBUG=1
YII_TRACE_LEVEL=3
YII_ENV=dev

Then add it to your index.php like this
require_once __DIR__ . '/protected/vendor/autoload.php';

$factory = new Dotenv\Environment\DotenvFactory([
    new Dotenv\Environment\Adapter\EnvConstAdapter(),
]);
// Specify path to directory with .env file here (for advanced you should up twice)
\Dotenv\Dotenv::create(__DIR__ . DIRECTORY_SEPARATOR . '/../', null, $factory)->load();

defined('YII_DEBUG') or define('YII_DEBUG', (bool) $_ENV['YII_DEBUG']);
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', $_ENV['YII_TRACE_LEVEL']);
defined('YII_ENV') or define('YII_ENV', $_ENV['YII_ENV']);

I recommend to use only EnvConstAdapter. Cause $_SERVER variable get logged and getenv() some time has empty values on concurrency requests.
Small improvement for bool, null and empty strings. Add this before $factory instantiation and use env() instead $_ENV.
if (!function_exists('env')) {
    /**
     * Gets the value of an environment variable.
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    function env($key, $default = null)
    {
        if (!isset($_ENV[$key])) {
            return $default;
        }

        $value = $_ENV[$key];

        switch ($value) {
            case 'true':
            case '(true)':
                return true;
            case 'false':
            case '(false)':
                return false;
            case 'empty':
            case '(empty)':
                return '';
            case 'null':
            case '(null)':
                return null;
            default:
                return $value;
        }
    }
}


text:
Q: Check for (.csv or .dat) file extension among multiple files and if not send alert to the user I am new to SSIS,
Every 30 mins I will receive a single file or multiple files in the Source Directory
I need to loop through these files and check if it has a .csv or .dat extension:

*

*If it is not: send alert to the user.

*If it is: execute the package

EDIT : I have tried;
Main()
{
    try
    {
        string[] filenames;
        filenames = Directory.GetFiles(@"C:Input_Data\");
        string FileExtension = Path.GetExtension("filenames");
        if (FileExtension == ".DAT" && FileExtension == ".csv")
            Dts.Variables["FileExist"].Value = 1;
    }
    catch
    {
        Dts.Variables["FileExist"].Value = 0;
    }

    Dts.TaskResult = (int)ScriptResults.Success;
}

But even if the file exist with .dat extension, it is returning 0 and sending the alert.

A: Perhaps you meant to write...
if (FileExtension == ".DAT" || FileExtension == ".csv")

Otherwise it would never evaluate to true.
Also you probably want a loop of some kind, your current structure is trying to access all the files at once (and not even quite doing that)
filenames = Directory.GetFiles(@"C:\Input_Data\");
foreach(string filename in filenames)
{
    string FileExtension = Path.GetExtension(filename);
    if (FileExtension == ".DAT" || FileExtension == ".csv")
        Dts.Variables["FileExist"].Value = 1;
}

Edit:
Based on what I think you are saying it sounds like you want FileExist to equal 1 only when it contains only DAT and CSV types and no other types, in that case you want to reverse the logic a bit.
filenames = Directory.GetFiles(@"C:\Input_Data\");
Dts.Variables["FileExist"].Value = 1;
foreach(string filename in filenames)
{
    string FileExtension = Path.GetExtension(filename);
    if (FileExtension != ".DAT" && FileExtension != ".csv")
        Dts.Variables["FileExist"].Value = 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How To Start Programming I have taken a programming course 2 years ago but I haven't worked in  programming since then. I recently found a programmer job, but there is no programming team so for me to gain valuable experience from.
I am Programming by myself and making changes on a program already made by my Ex-colleague. I need to know what should I do to be on the right track for becoming a professional programmer without a team to take experience from. What are the good practices to improve and what are the bad ones?
I'm using VB.Net, ASP.Net and SQL.

A: I experienced the exact same thing around 6 or 7 months ago. You will certainly remember the things you learnt 2 years ago very quickly as you do more and more work.
My best advice for you, based on my own experience is to get your hands on a copy of the following books:

*

*The Pragmatic Programmer: From Journeyman to Master
by Andrew Hunt and David Thomas

*Pragmatic Thinking and Learning: Refactor Your Wetware
by Andy Hunt
Primarily the first one.
You would learn all that can be learned from those books as time goes by and you make a lot of the mistakes it points out, I just wish in hindsight that I had brushed over each of these books to avoid a lot of unnecessary pain that comes with encountering the issues yourself.
Other than that be active in your learning and ensure you are asking why something works, don't just accept that it works.

A: I was a naive programmer 1.5 year ago. TO be able to learn programming (in situations when you are not already a programming background) you first need to build some confidence in programming.

*

*Concentrate on one programming language initially

*Try to grasp the generic concepts form it like (not in order)

*

*Compilation process

*runtime

*Memory management

*Message passing

*methods invocations

*nature of variables, etc
that are applicable almost all programming language

*Then focus the building of your logic in context of the programming language.

*Its not always that what you plan you can (or should) program.

*go for the best approach no matter what (no compromise while learning)

*Read some good code.

*listen to music

I am posting some URLs that you can use to get an idea

*

*Udacity

*http://codeacademy.com/

*Khan Academy

*projecteuler

*Learn Street(Specially for Python, Ruby and JS)

A: You need to first do code, and then code on different logic with different application, like web application and windows application.
You have to be clear with your logic.  Alternatively, you can get sample code from the internet or other Stack Exchange sites, for example Stack Overflow.
Just practice your coding. Experience can make you perfect.


text:
Q: Why is cookie expiry disappearing? I create a cookie and it has the proper expiry set, but when I go to update the cookie and check it with the debugger the expiry is gone. What is going on?
' Cookie Helper: Updates cookie with the selected source ids
Protected Sub UpdateCookieFor(ByVal cookieName As String, ByVal sourceIds As String)

    ' Update cookie if it exists
    If Request.Cookies(cookieName) IsNot Nothing Then
        Response.Cookies(cookieName).Value = sourceIds
    End If

End Sub

' Cookie Helper: Create cookie
Protected Sub CreateCookie(ByVal cookieName As String, ByVal sourceIds As String)

    ' Create cookie if it does not exist
    If Request.Cookies(cookieName) Is Nothing Then
        Response.Cookies(cookieName).Value = sourceIds
        Response.Cookies(cookieName).Expires = DateTime.Now.AddYears(10)
    End If

End Sub

A: I just ran into this issue today (using C#).  Apparently, the expiry is never sent to the server from the browser, so you always have to set the value.  I read about this on MSDN at:
http://msdn.microsoft.com/en-us/library/aa289495(v=vs.71).aspx#vbtchaspnetcookies101anchor8
See the section: "What's the Expiration?"
I was able to work around this by setting a value in the cookie with the original expiry date, so it would be sent to the server.
HttpCookie myCookie = new HttpCookie(Constants.CookieName);
myCookie.Expires = DateTime.Now.AddDays(numberOfdaysToExpireCookie);
myCookie["MyKey"] = myValue;
myCookie["MyExpiry"] = myCookie.Expires.Ticks.ToString();
HttpContext.Current.Response.Cookies.Add(myCookie);

Then, when updating the cookie, I read in the original expiry and write it out again.
//Get the expiry date that was stored
string cookieExpiryDateValue = myCookie.Values["MyExpiry"];
long ticks;
DateTime expiryDate = DateTime.Now.AddDays(numberOfdaysToExpireCookie);
if(long.TryParse(cookieExpiryDateValue, out ticks)){
    expiryDate = new DateTime(ticks);
}

//Update the value in the cookie.  Persist the expiry and domain
HttpCookie responseCookie = HttpContext.Current.Response.Cookies[Constants.CookieName];
responseCookie.Values["MyKey"] = cookieValues;
responseCookie.Values["MyExpiry"] = cookieExpiryDateValue;
responseCookie.Expires = expiryDate;


text:
Q: How can I shorten this expression? $\frac {-x \cdot a_1 -x\cdot a_2 -x\cdot a_3 -u}{a_4}\cdot l$ I have this fraction:
$$\frac {-x \cdot a_1 -x\cdot a_2 -x\cdot a_3 -u}{a_4} \cdot l$$
You see, there are many $-x$ terms. How can I make this shorter? Can I write:
$$x\,\frac { -a_1 -a_2 -a_3}{a_4} \cdot l  -u\,\frac { l}{a_4}$$
Is this right?
Regards.

A: You can do $$\frac{-a_1x-a_2x-a_3x -u}{a_4}l = \left(\frac{-a_1x-a_2x-a_3x}{a_4}-\frac{u}{a_4}\right)l = -x l \frac{a_1 + a_2 + a_3}{a_4} - l \frac{u}{a_4}$$ but there is nothing shorter.


text:
Q: What is then correct link to my app in the Apple AppStore? I tried to figure out the correct link to my app in the Apple AppStore but I found many different answers...
I just want to provide a link on my website which directly leads to the app in the AppStore of the region the user is in. So users from Germany should see the app in the German store and users from the US should see the app in the American store.
Some links, for example on Apples "Market with the App Store" website use the "us" or "de" country region shortcut. Do I have to change this for every country or is there a link which just leads to the correct AppStore which is selected in the settings of the iPhone?
Thanks!


text:
Q: Como Selecionar Elemento Anterior CSS ? A href id Existe alguma maneira de selecionar o elemento anterior de outro elemento com CSS?
Eu preciso ocultar só o primeiro elemento

 cujo tem dentro um <a href = "#TAB-1" .
Fiz dessa maneira abaixo e não funcionou:

TAB1

TAB2

A: pode usar o seletor :nth-child(3). No caso ficaria
ul:nth-child(1){
...
}

Mas não funciona para o elemento anterior no html, apenas para os elementos selecionados.
pode dar uma olhada na documentação da monzilla
https://developer.mozilla.org/pt-BR/docs/Web/CSS/:nth-child


text:
Q: Running Command as Administrator from a SYSTEM Process So I need to clear a user's run dialog history which I can do perfectly fine with "reg delete HKEY_CURRENT_USER\Software\Windows etc..." from an elevated powershell window on the logged in user's machine, but what I'm looking to do is that same command but from a SYSTEM powershell process. I have already used psexec to create a powershell window which runs as SYSTEM, but because you can't just use HKEY_CURRENT_USER as SYSTEM with the same results, I am finding it quite difficult. If I could just run that command but as username\Administrator then I wouldn't have this problem.
Also to note, if I can somehow grab the username of the logged on user (from SYSTEM still) in one line in plain text (with no other output in sight), then I can store the username in a variable and convert that to an SID and use HKEY_USERS instead.
P.S. Don't ask why I'm running powershell as SYSTEM, I know what I'm doing :D

A: you can use get-process under the system context powershell and filter where explorer.exe process is running, get the account it is running under then use to convert to SID and go through the registry.

A: something like this assuming only 1 explorer.exe process is running which is the norm on windows client OS.
$proc = Get-CimInstance Win32_Process -Filter "name = 'explorer.exe'"
$owner = Invoke-CimMethod -InputObject $proc -MethodName GetOwner
$username = $owner.user

$username will contain the user, $owner will also contain domain and a few other things.
to convert to sid
$objUser = New-Object System.Security.Principal.NTAccount($owner.Domain, $owner.User)
$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$strSID.Value


text:
Q: Identity morphism In a category these equations holds:
b = b * a
c = c * a
for some morphisms a,b,c;
a IS NOT an identity morphism.
Is this possible?
If the answer is yes can you show me some examples of such categories?

A: I'm not sure which direction you're composing functions in, but if you take the category of sets, let b and c be constant functions, and let a be some permutation that fixes the values of b and c then you get an example working in either direction.

A: Use your equations to directly build a category. I see two examples:
Two objects
Your category has two objects, $X$ and $Y$. The morphisms of the category are presented by

*

*Generator $a : X \to X$

*Generators $b,c : X \to Y$

*Relation $b = ba$

*Relation $c=ca$

It's clear that this presents a category where $b \neq c$ and with

*

*$\hom(X,X) = \{ 1, a, a^2, a^3, \ldots \} $

*$\hom(X,Y) = \{ b, c \} $

*$\hom(Y,Y) = \{ 1 \}$

and the only nontrivial products are $ba^n = b$ and $c a^n = c$.
If we were lazy, we might add a relation $a^2 = a$ too, to simplify things.
One object
Your category has one object $X$. $\hom(X,X)$ is the monoid presented by generators $a,b,c$ and relations $b=ba$ and $c=ca$. It's not too hard to see that $b \neq c$ and $a \neq 1$.
Again, we could simplify; e.g. by adding the relation $xy=x$ whenever $x \neq 1$. Then the monoid is finite, with four distinct elements $\{1, a, b, c\}$.
(equivalently, this is monoid you get by adding a unit to the semigroup with three elements satisfying the identity $xy=x$)


text:
Q: What is this IC? AY7397 I'm trying to identify this IC. It's on the motherboard of an Epson 5040UB 4K HD projector. The projector tries to boot and then shuts off after 4 mins. A flir thermal image of the MB during this boot sequence shows IC 4706 at 204°F hot. I'm looking to replace this IC, but I cannot identify it. The printed marking on the IC is "AY 7397"
UPDATE: according to user Diah on badcaps.net forum:

AY are DC to DC PWM (Pulse-width modulation) step down. with easy
language of my...the boot didn't receive signal LAMP ON, it will not
step down. it keep on high pulse ( FAN High SPEED ) ( ERROR BLINKING )
this why they become warm.

So, perhaps the problem is with the ballast and this chip is operating as expected within tolerance and just heating up because its holding the load until the shutdown occurs? If so, would its twin IC4707 not exhibit similar thermal reaction?

A: Looks like an Rohm BD2242G-GTR  Adjustable Current Limit High Side Switch


text:
Q: Eclipse CVS compare: difference not disappearing after copying In Eclipse, CVS text comparing works poorly against large numbers of difference between the local and the remote version. It's very desirable to update the the status of comparison every once in a while by a simple command. Basically it's reloading the local file, do the comparison again, to see where we have reached, and try not to make mistakes.
Unfortunately, "Team" - "Synchronize" again after editing every several lines is not convenient, neither does it solve our problem. As I have observed, when there are many differences, Eclipse can mark the already identical lines as different to the remote ones, if we use this approach to compare again.
How can we solve it in Eclipse?

A: At last I found a simple enough solution, but can be ignored easily: use the "Java structure compare" panel.

*

*When doing the CVS comparison, above the two horizontal text area, we can see the "Java structure compare" panel.

*The icon "+", "-" and arrows can show structurally how the two files are different.

*Double-click on a method to edit. After several lines of work, double-click the method again to update the status of comparison. If the local version is identical to the remote one, all the color squares will dissappear from the vertical scroll bar on the right, clearly marking where we have reached. Also, after doing this, you jump to the next difference in this method, to start working again.

Re-"Synchronize" will mess the whole file up, so don't do it in the middle, unless you are at the final stage and have fewer enough differences.
Just a little piece of humble opinion about how to use Eclipse more efficiently. After all it's our daily tool. Better to learn these tricks as soon as possible.


text:
Q: JavaFX: Disable multiple rows in TableView based on other TableView I'm creating an application in JavaFx. Right now I have two tableviews next to each other:
------------------------------------------------------------------------------
| TableView 1                        |  TableView 2                          |
|                                    |                                       |
|                                    |  Entry 1                              |
|                                    |  Entry 2                              |
|                                    |  Entry 3                              |
|                                    |  Entry ...                            |
|                                    |  Entry N                              |
------------------------------------------------------------------------------

I would like to copy items from TableView 2 to TableView 1, but at the same time, the entries that have been copied from TableView 2 need to be disabled (disable the row with setDisable or something similar). I do know how to copy the items from one tableview to another. The problem is that I do not know how to disable multiple rows when one or multiple entries have been copied to TableView 1.
I tried this with a RowFactory, like this:
productsInTransaction.setRowFactory(tv -> {
      TableRow<Product> row = new TableRow<>();
      row.disableProperty().bind(???);
      return row;
});

Any help is much appreciated!

A: I'm not quite sure of the logic you're wanting, but if your row factory is attached to table 1, and you are disabling the row when the item is present in table 2, do:
row.disableProperty().bind(Bindings.createBooleanBinding(() ->
    table2.getItems().contains(row.getItem()), table2.getItems(), row.itemProperty()));


text:
Q: Embedded Youtube video stopped working on iPhone I built a site which includes embedded youtube videos. Up until recently they worked on all devices, but recently they have stopped working on iPhones (and iTouch).
The videos play only for few seconds and then just show a black screen. Console show the usual youtube errors, and are the same for chrome on desktop, and safaris on iphone:
Unable to post message to .... Recipient has origin ....
Blocked a frame with origin .... from accessing a frame with origin .... Protocols, domains, and ports must match.
The js to load the video players is addapted from youtube API examples
// the width of player
var plwidth = 274;
var plheight = 171;

// This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');

// This is a protocol-relative URL as described here:
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// Create an  (and YouTube player) when the buttons are pressed.
function onYouTubeIframeAPIReady(){
    //alert('youtube downloaded');

    var player;

    var buttons = document.getElementsByClassName('playbutton');

    for(var i = 0; i < buttons.length; i++){
        buttons[i].style.display = "block";
    }

    // display play buttons
    var button = document.getElementById('playbutton');

    button.onclick = function(){
        player = new YT.Player('player', {
            height: plheight,
            width: plwidth,
            videoId: 'wr7-K42RXh8',
            events: {
                'onReady': onPlayerReady,
            }
        });
        return false;
    }

}

// The API will call this function when the video player is ready.
function onPlayerReady(event) {
    var videoplaceholder = document.getElementById('videoplaceholder');
    videoplaceholder.style.display = "none";
    event.target.playVideo();
    var button = document.getElementById('playbutton');
    button.style.display = "none";
}

Any ideas why it suddenly stopped working on iPhone (it works on iPad)? Any help is really appreciated.
cheers

A: Try using this method for playing your Youtube videos in UIWebView.
-(NSString*)htmlStringForEmbeddingYTVideoWithVideoID:(NSString*)videoId andPlayerWindowSide:(CGSize)playerWindowSize
{
    NSString *htmlString = [NSString stringWithFormat:@"<!DOCTYPE html>

    ",playerWindowSize.height,playerWindowSize.width,playerWindowSize.height,playerWindowSize.width,videoId];
    return htmlString;
}


text:
Q: Testing an http request error using sinon I'm currently using stubs to write tests for an http request function as such
// api.js
var https = require('https');

function httpsGet(domain, options, parameters)
  var deferred = Q.defer();

  var request = https.request(options, function(res) {
    var resBody = '';
    res.on('data', function(data) {
      resBody += data;
    });
    res.on('end', function() {
      if (resBody.length > 0) {
        try {
          var response = JSON.parse(resBody);
          if(response.Error) {
            var errorString = domain;
            for(var key in parameters){
              errorString += '\n\t' + key + ' - ' + parameters[key];                 }
            deferred.reject(new Error(errorString + '\n' + response.Error.Code + ' - ' + response.Error.Message + ' - ' + response.Error.Reference));
          }
          deferred.resolve(response);
        }
        catch(err) {
          deferred.reject(new Error('Error: Response not JSON from ' + domain));
          }
        }
        else {
          deferred.reject(new Error('Response body of ' + domain + ' HTTPs call is empty.'));
        }
      });
    });
    request.on('error', function(error) {
      deferred.reject(new Error('Error: ' + error));
    });
    request.end();
  }
  return deferred.promise;
}

module.exports = {
    httpsGet: httpsGet
};

How would I able to test the request.on('error', function() {}) statement? I'm trying using mocha, stubs and streams and I don't feel like I'm understanding this at all. I can't seem to create an erroneous request that leads to that statement.

A: Try this:
var assert = require('assert');

describe('httpsGet functional tests', function () {
    it('should catch an error', function (done) {
        httpsGet('', {})
            // We don't want it to resolve.
            .then(function () {
                done('Expected invocation to reject');
            })
            // We do expect a rejection.
            .catch(function (err) {
                // console.log(err);
                assert(/ECONNREFUSED/.test(err.message), 'should be an error');
                done();
            })
            // Just in case we still have an error.
            .catch(done);
    });
});

All you need to do is trigger any old error in http request.
To be honest though, I'd probably swap to using request because it handles some of the low level stuff for you. Then you can use nock to provide fake responses to test.


text:
Q: Double multiplication vs addition speed Background
I'm an aerospace engineering and EECS student. I'm at the point where I work with a lot of math and physics, but haven't gotten into algorithms or assembly language yet.
I design and code a comically wide variety of programs, from business proposal software to satellite hardware controllers.
Most of this work involves doing math in some other medium, then writing code to implement it.
I algebraically simplify these equations before putting them into code. But before I expend the time to do so, I would like to know whether I should favor more addition operations, or more multiplication operations. (I already know division is much more costly.)

Example

This is an equation I've derived from some other work, and this is pretty typical of what I see.
We can plainly see that there are at least a handful of ways to simplify this equation. Since the simplification is at my discretion, I'd like to pick the option that favors performance as much as practical. I'm not going for bleeding-edge performance at the cost of algorithm design time.

The Question
In general, which double operation is faster: addition or multiplication?
I know the only definitive way to know which is faster is to write and run benchmarks, but that isn't the point here. This is not a high enough priority in what I do to justify writing test code every time I need to simplify an equation. What I need is a rule of thumb to apply to my algebra.
If the difference is so marginal as to border on negligible or inconclusive, that's an acceptable answer, so long as I know it makes nearly no difference.

Backing Research
I know that, in C and C++, the optimizer takes care of the algebra, so it's a null-issue. However, as I understand it, the Java compiler does not do algebraic simplification/optimization. Specifically, this answer indicates this to be the case, and that the programmer should do this sort of optimization.
There are scattered answers for this across the internet, but I can't come up with a conclusive answer. A former University of Maryland physics student ran these tests on Java, but the double performance data is absent in the tables, and the graph scales make the results indiscernible. This University of Quebec CS professor's tests only reveal results for integer operations. This SO answer explains that, on a hardware level, multiplication is a more complicated operation, but I'm also aware that engineers design processors with these sorts of things in mind.
Other marginally helpful links:

*

*SO: Decimal vs Double Speed

*IBM article on Java bytecode

*SO: Theory - Addition operation versus multiplication operation

*SO: (n - Multiplication) vs (n/2 - multiplication + 2 additions) which is better?

A: In general, you should write the code which is clearest.  The JIT (not the javac) takes simple, common patterns and optimises them.  This means using simple, common patterns is often the best way to optimise code.
If you profile your application and find that code is not running optimially you can try optimising the code yourself however;

*

*meaningful micro benchmarks are difficult to write.

*the results can be highly sensitive to the environment. Change the update of Java or the CPU model and you can get conflicting result.

*when you performance test the whole code you are likely to find the delays are not when you expect them to be. e.g, they are often in IO.

Unless you are confident an optimisation really helps, you should stick with code which is simplest and easiest to maintain and you are likely to find it run fast enough.


text:
Q: I want to convert excel data into multiple Json in Javascript/Typescript My Excel has many data table which i want to convert it into a Json in javascript/typescript. Following are the sample of my excel data in one sheet separated by one or more empty rows.

Name
Age

John
40

Olivia
30

EmpId
Salary
LanguagesKnown

43567
15000
English,French

98543
20000
Arab,Chinese

I want to convert these into Json.
Expected output:
**Json for first table:**

{
"Name" : "John",
"Age" : 40
}

{
"Name" : "Olivia",
"Age" : 30
}

**Json for Second Table:**

{
"EmpId" : 43567,
"Salary" : 15000,
"LanguagesKnown" : ["English","French"]
}

{
"EmpId" : 98543,
"Salary" : 20000,
"LanguagesKnown" : ["Arab","Chinese"]
}

A: js-xlsx library can convert Excel/CSV files into JSON objects.
<!doctype html>
<html>

<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.15.6/xlsx.full.min.js"></script>
</head>

<body>

    <script>
        var url = "https://file-examples-com.github.io/uploads/2017/02/file_example_XLS_10.xls"; //Excel File
        var oReq = new XMLHttpRequest();
        oReq.open("GET", url, true);
        oReq.responseType = "arraybuffer";

        oReq.onload = function(e) {
            var arraybuffer = oReq.response;

            /* convert to binary */
            var data = new Uint8Array(arraybuffer);
            var arr = new Array();
            for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
            var bstr = arr.join("");

            var workbook = XLSX.read(bstr, {
                type: "binary"
            });

            var first_sheet_name = workbook.SheetNames[0]; //Excel sheet No
            var worksheet = workbook.Sheets[first_sheet_name];
            const convertToJson = XLSX.utils.sheet_to_json(worksheet, {
                raw: true
            })
            console.log(convertToJson);
        }

        oReq.send();
    </script>
</body>
</html>

Output:
[
    {
        "0": 1,
        "First Name": "Dulce",
        "Last Name": "Abril",
        "Gender": "Female",
        "Country": "United States",
        "Age": 32,
        "Date": "15/10/2017",
        "Id": 1562
    },
    {
        "0": 2,
        "First Name": "Mara",
        "Last Name": "Hashimoto",
        "Gender": "Female",
        "Country": "Great Britain",
        "Age": 25,
        "Date": "16/08/2016",
        "Id": 1582
    },
    {
        "0": 3,
        "First Name": "Philip",
        "Last Name": "Gent",
        "Gender": "Male",
        "Country": "France",
        "Age": 36,
        "Date": "21/05/2015",
        "Id": 2587
    },
    {
        "0": 4,
        "First Name": "Kathleen",
        "Last Name": "Hanner",
        "Gender": "Female",
        "Country": "United States",
        "Age": 25,
        "Date": "15/10/2017",
        "Id": 3549
    },
    {
        "0": 5,
        "First Name": "Nereida",
        "Last Name": "Magwood",
        "Gender": "Female",
        "Country": "United States",
        "Age": 58,
        "Date": "16/08/2016",
        "Id": 2468
    },
    {
        "0": 6,
        "First Name": "Gaston",
        "Last Name": "Brumm",
        "Gender": "Male",
        "Country": "United States",
        "Age": 24,
        "Date": "21/05/2015",
        "Id": 2554
    },
    {
        "0": 7,
        "First Name": "Etta",
        "Last Name": "Hurn",
        "Gender": "Female",
        "Country": "Great Britain",
        "Age": 56,
        "Date": "15/10/2017",
        "Id": 3598
    },
    {
        "0": 8,
        "First Name": "Earlean",
        "Last Name": "Melgar",
        "Gender": "Female",
        "Country": "United States",
        "Age": 27,
        "Date": "16/08/2016",
        "Id": 2456
    },
    {
        "0": 9,
        "First Name": "Vincenza",
        "Last Name": "Weiland",
        "Gender": "Female",
        "Country": "United States",
        "Age": 40,
        "Date": "21/05/2015",
        "Id": 6548
    }
]

A: I make use of async-csv package
import * as fs from "fs";
import csv from 'async-csv';

const fsInstance = fs.promises;

const csvString = await fsInstance.readFile(mailListFound.mailListPath, 'utf-8');
const rows = await csv.parse(csvString);
rows.shift();
const data = JSON.parse(JSON.stringify(rows));

The data inside the data variable is now a JSON that you can use.
Notes: I used the rows.shift() to remove the header row from my data before parsing it with JSON.parse.
My sample file looks like this


text:
Q: rss-parser: Uncaught TypeError: get is not a function at Parser.js:79:1 I'm making an RSS parser with the Node package rss-parser but I think it's only currently compatible with Webpack 4 because webpack 4 auto-shims Node built-ins, but I'm a newb.js so I need help. You can read about Shimming in Webpack here and Upgrading Webpack from 4 to 5 here. Here is the line that is blowing up (parser:79)
let req = get(requestOpts, (res) => {

Here is the entire function.
  parseURL(feedUrl, callback, redirectCount=0) {
    let xml = '';
    let get = feedUrl.indexOf('https') === 0 ? https.get : http.get;
    let urlParts = url.parse(feedUrl);
    let headers = Object.assign({}, DEFAULT_HEADERS, this.options.headers);
    let timeout = null;
    let prom = new Promise((resolve, reject) => {
      const requestOpts = Object.assign({headers}, urlParts, this.options.requestOptions);
      let req = get(requestOpts, (res) => {
        if (this.options.maxRedirects && res.statusCode >= 300 && res.statusCode < 400 && res.headers['location']) {
          if (redirectCount === this.options.maxRedirects) {
            return reject(new Error("Too many redirects"));
          } else {
            const newLocation = url.resolve(feedUrl, res.headers['location']);
            return this.parseURL(newLocation, null, redirectCount + 1).then(resolve, reject);
          }
        } else if (res.statusCode >= 300) {
          return reject(new Error("Status code " + res.statusCode))
        }
        let encoding = utils.getEncodingFromContentType(res.headers['content-type']);
        res.setEncoding(encoding);
        res.on('data', (chunk) => {
          xml += chunk;
        });
        res.on('end', () => {
          return this.parseString(xml).then(resolve, reject);
        });
      })
      req.on('error', reject);
      timeout = setTimeout(() => {
        return reject(new Error("Request timed out after " + this.options.timeout + "ms"));
      }, this.options.timeout);
    }).then(data => {
      clearTimeout(timeout);
      return Promise.resolve(data);
    }, e => {
      clearTimeout(timeout);
      return Promise.reject(e);
    });
    prom = utils.maybePromisify(callback, prom);
    return prom;
  }

Here is the stack trace from Chrome:
Uncaught TypeError: get is not a function
    at Parser.js:79:1
    at new Promise (<anonymous>)
    at Parser.parseURL (Parser.js:76:1)
    at FeedRSSPrint (Popup.tsx:18:1)
    at App (Popup.tsx:30:1)
    at renderWithHooks (react-dom.development.js:16305:1)
    at mountIndeterminateComponent (react-dom.development.js:20074:1)
    at beginWork (react-dom.development.js:21587:1)
    at beginWork$1 (react-dom.development.js:27426:1)
    at performUnitOfWork (react-dom.development.js:26560:1)

And in //../node_modules/@types/node/https.d.ts in that https Node package, it was get as defined as
    /**
     * Like `http.get()` but for HTTPS.
     *
     * `options` can be an object, a string, or a `URL` object. If `options` is a
     * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
     *
     * ```js
     * const https = require('https');
     *
     * https.get('https://encrypted.google.com/', (res) => {
     *   console.log('statusCode:', res.statusCode);
     *   console.log('headers:', res.headers);
     *
     *   res.on('data', (d) => {
     *     process.stdout.write(d);
     *   });
     *
     * }).on('error', (e) => {
     *   console.error(e);
     * });
     * ```
     * @since v0.3.6
     * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`.
     */
    function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest;
    function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest;
    let globalAgent: Agent;
}

In node_modules/@types/node/http.d.ts it's defined:
/**
     * Since most requests are GET requests without bodies, Node.js provides this
     * convenience method. The only difference between this method and {@link request} is that it sets the method to GET and calls `req.end()`automatically. The callback must take care to consume the
     * response
     * data for reasons stated in {@link ClientRequest} section.
     *
     * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}.
     *
     * JSON fetching example:
     *
     * ```js
     * http.get('http://localhost:8000/', (res) => {
     *   const { statusCode } = res;
     *   const contentType = res.headers['content-type'];
     *
     *   let error;
     *   // Any 2xx status code signals a successful response but
     *   // here we're only checking for 200.
     *   if (statusCode !== 200) {
     *     error = new Error('Request Failed.\n' +
     *                       `Status Code: ${statusCode}`);
     *   } else if (!/^application\/json/.test(contentType)) {
     *     error = new Error('Invalid content-type.\n' +
     *                       `Expected application/json but received ${contentType}`);
     *   }
     *   if (error) {
     *     console.error(error.message);
     *     // Consume response data to free up memory
     *     res.resume();
     *     return;
     *   }
     *
     *   res.setEncoding('utf8');
     *   let rawData = '';
     *   res.on('data', (chunk) => { rawData += chunk; });
     *   res.on('end', () => {
     *     try {
     *       const parsedData = JSON.parse(rawData);
     *       console.log(parsedData);
     *     } catch (e) {
     *       console.error(e.message);
     *     }
     *   });
     * }).on('error', (e) => {
     *   console.error(`Got error: ${e.message}`);
     * });
     *
     * // Create a local server to receive data from
     * const server = http.createServer((req, res) => {
     *   res.writeHead(200, { 'Content-Type': 'application/json' });
     *   res.end(JSON.stringify({
     *     data: 'Hello World!'
     *   }));
     * });
     *
     * server.listen(8000);
     * ```
     * @since v0.3.6
     * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored.
     */
    function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest;
    function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest;

When I do a console.log(get), it is undefined for both HTTP and HTTPS feeds. I'm importing them like this:
import Parser from '../RSS/Parser'
const http = require('http');
const https = require('https');

The error before this show stopper was "Uncaught TypeError: Stream is undefined/Cannot read property 'prototype' of undefined" and I was able to get rid of that error by installing the Node pacakge 'npm i --save-dev stream' using info from this GitHub thread, but I'm not using that library so I have no clue why it made the error go away.
I copied the rss-parser files into my project into the //RSS folder, renaming //index.d.ts to //RSS/Parser.d.ts, added "export default Parser" at the end, and added //RSS/index.ts that contained:
import Parser from './Parser'

export default Parser

Seems like that was a good module configuration but again I'm a newb.js so let me know if this is not right.
Here are my dependencies:
  "devDependencies": {
    "@material-ui/core": "^4.12.4",
    "@material-ui/icons": "^4.11.3",
    "@types/chrome": "^0.0.195",
    "@types/react": "^18.0.18",
    "@types/react-dom": "^18.0.6",
    "clean-webpack-plugin": "^4.0.0",
    "copy-webpack-plugin": "^11.0.0",
    "css-loader": "^6.7.1",
    "entities": "^4.4.0",
    "html-webpack-plugin": "^5.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "stream": "^0.0.2",
    "stream-http": "^3.2.0",
    "style-loader": "^3.3.1",
    "terser-webpack-plugin": "^5.3.5",
    "ts-loader": "^9.3.1",
    "typescript": "^4.7.4",
    "url": "^0.11.0",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0",
    "webpack-merge": "^5.8.0",
    "xml2js": "^0.4.23"
  }

I also had to add this to the webpack configuration:
module.resolve: {
    extensions: ['.tsx', '.ts', '.js'],
    fallback: { "http": false, "browser": false, "https": false,
      "stream": false, "url": false, "buffer": false, "timers": false
    }

I tried to do npm i --save-dev http and npm i --save-dev https but those aren't legit npm libraries so I'm not sure if they're included in Node at this point or what.

A: The problem was that I was not loading rss-parser from the pre-built 'rss-parser.min.js' file. When I tried to compile the rss-parser, I needed to do some stuff for Node.JS with fallback, but you don't need to do that when you use the rss-parser.min.js file. I'm using TypeScript so I just added this to my parser file and it works just fine.
interface Enclosure {
  url: string
  length: number
  type: string
}

interface Item {
  link: string
  guid: string
  title: string
  pubDate: string
  creator: string
  summary: string
  content: string
  isoDate: string
  categories?: string[]
  contentSnippet: string
  enclosure: Enclosure
}


text:
Q: captcha code on popup window I want to add captcha code on popup window.
I have some category**(On Demand Services)** in list. If any one click on any service then a popup window open according the service ID. Its working properly.
But I also have captcha code in javascript. But its not working. If any one click on any service then a popup window should open according the service ID and captcha code should be present. I tried, but nothing happend.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

On Demand Services:

 Car Washing

 Carpenter

 Painters

   <button type="button" class="close" data-dismiss="modal">×Close</button>

Enquiry Form: (All Fields are required.)

       <form method="post" action="" id="dummy" onsubmit="return ValidCaptcha(this);">

Service Name:

       <input type="text" class="form-control" required readonly name="bookId" value="Car Washing" style="color:#000;">

Full Name:

      <input type="text" class="form-control" required name="name" value="" style="color:#000;">

Email Address:

       <input type="email" class="form-control" required name="email" value="" style="color:#000;">

Mobile Number:

    <input type="tel" class="form-control" required name="mno" value="" style="color:#000;">

Message:

    <textarea name="msg" class="form-control" required style="color:#000;">I am interested in your service. Please contact me back on email/phone.</textarea>

Address:

   <textarea name="address" class="form-control" required style="color:#000;"></textarea>

Captcha:

   <input type="text" class="txtCaptcha" readonly id="txtCaptcha" style="background-color:yellow; text-align:center; border:none;font-weight:bold; font-family:Modern">
    <input type="button" value="Refresh" onclick="DrawCaptcha('my_modal');">
    <input type="text" id="txtInput">

     <button type="submit" name="submit" class="btn btn-default col-md-3">Submit</button>
     <button type="button" class="btn btn-default col-md-3" data-dismiss="modal">Close</button>

   </form>

   <button type="button" class="close" data-dismiss="modal">×Close</button>

Enquiry Form: (All Fields are required.)

    <form method="post" action="" id="dummy" onsubmit="return ValidCaptcha(this);">

Service Name:

    <input type="text" class="form-control" required readonly name="bookId" value="Carpenter" style="color:#000;">

Full Name:

    <input type="text" class="form-control" required name="name" value="" style="color:#000;">

Email Address:

    <input type="email" class="form-control" required name="email" value="" style="color:#000;">

Mobile Number:

    <input type="tel" class="form-control" required name="mno" value="" style="color:#000;">

Message:

     <textarea name="msg" class="form-control" required style="color:#000;">I am interested in your service. Please contact me back on email/phone.</textarea>

Address:

    <textarea name="address" class="form-control" required  style="color:#000;"></textarea>

Captcha:

   <input type="text" class="txtCaptcha" id="txtCaptcha1" readonly style="background-color:yellow; text-align:center; border:none;font-weight:bold; font-family:Modern">
    <input type="button" value="Refresh" onclick="DrawCaptcha('my_modal1');">
  <input type="text" id="txtInput">

     <button type="submit" name="submit1"  class="btn btn-default col-md-3">Submit</button>
     <button type="button" class="btn btn-default col-md-3" data-dismiss="modal">Close</button>

     </form>

    <button type="button" class="close" data-dismiss="modal">×Close</button>

Enquiry Form: (All Fields are required.)

     <form method="post" action="" onsubmit="ValidCaptcha();">

Service Name:

    <input class="form-control" required="true" readonly="" name="bookId" value="Painters" style="color:#000;" type="text">

Full Name:

    <input class="form-control" required="true" name="name" value="" style="color:#000;" type="text">

Email Address:

    <input class="form-control" required="true" name="email" value="" style="color:#000;" type="email">

Mobile Number:

    <input class="form-control" required="true" name="mno" value="" style="color:#000;" type="tel">

Message:

    <textarea name="msg" class="form-control" required="true" style="color:#000;">I am interested in your service. Please contact me back on email/phone.</textarea>

Address:

    <textarea name="address" class="form-control" required="true" style="color:#000;"></textarea>

Captcha:

   <input type="text" class="txtCaptcha" id="txtCaptcha2" readonly style="background-color:yellow; text-align:center; border:none;font-weight:bold; font-family:Modern">
    <input type="button" value="Refresh" onclick="DrawCaptcha('my_modal2');">
   <input type="text" id="txtInput">

    <button type="submit" name="submit2" class="btn btn-default col-md-3">Submit</button>
    <button type="button" class="btn btn-default col-md-3" data-dismiss="modal">Close</button>

   </form>

A:

  //Created / Generates the captcha function
 function DrawCaptcha(modal_id)
 {
    var a = Math.ceil(Math.random() * 10)+ '';
    var b = Math.ceil(Math.random() * 10)+ '';
    var c = Math.ceil(Math.random() * 10)+ '';
    var d = Math.ceil(Math.random() * 10)+ '';
    var e = Math.ceil(Math.random() * 10)+ '';
    var f = Math.ceil(Math.random() * 10)+ '';
    var g = Math.ceil(Math.random() * 10)+ '';
    var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
    //document.getElementById("txtCaptcha").value = code
    txt_captcha="#"+modal_id+" .txtCaptcha";
    $(txt_captcha).val(code);

}

// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
    var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
    var str2 = removeSpaces(document.getElementById('txtInput').value);
    if (str1 == str2)
    alert("good");
    else
    alert("bad");

}

// Remove the spaces from the entered and generated code
function removeSpaces(string)
{
    return string.split(' ').join('');
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

On Demand Services:

 Car Washing

 Carpenter

 Painters

    <button type="button" class="close" data-dismiss="modal">×Close</button>

Enquiry Form:

  <form method="post" action="" id="dummy" onsubmit="return checkform(this);">

Service Name:

    <input type="text" class="form-control" required readonly name="bookId" value="" style="color:#000;">

Full Name:

    <input type="text" class="form-control" required name="name" value="" style="color:#000;">

Email Address:

    <input type="email" class="form-control" required name="email" value="" style="color:#000;">

Mobile Number:

    <input type="tel" class="form-control" required name="mno" value="" style="color:#000;">

Message:

    <textarea name="msg" class="form-control" required style="color:#000;">I am interested in your service. Please contact me back on email/phone.</textarea>

Address:

    <textarea name="address" class="form-control" required style="color:#000;"></textarea>

Captcha:

  <input type="text" class="txtCaptcha" id="txtCaptcha" style="background-image:url(1.jpg); text-align:center; border:none;font-weight:bold; font-family:Modern">
  <input type="button" value="Refresh" onclick="DrawCaptcha();">
 <input type="text" id="txtInput">

    <button type="submit" name="submit" onclick="javascript:submitmydata();" class="btn btn-default col-md-3">Submit</button>
    <button type="button" class="btn btn-default col-md-3" data-dismiss="modal">Close</button>

  </form>

    <button type="button" class="close" data-dismiss="modal">×Close</button>

Enquiry Form:

  <form method="post" action="" onsubmit="return checkform(this);">

Service Name:

    <input type="text" class="form-control" required readonly name="bookId" value="" style="color:#000;">

Full Name:

    <input type="text" class="form-control" required name="name" value="" style="color:#000;">

Email Address:

    <input type="email" class="form-control" required name="email" value="" style="color:#000;">

Mobile Number:

    <input type="tel" class="form-control" required name="mno" value="" style="color:#000;">

Message:

    <textarea name="msg" class="form-control" required style="color:#000;">I am interested in your service. Please contact me back on email/phone.</textarea>

Address:

    <textarea name="address" class="form-control" required         style="color:#000;"></textarea>

Captcha:

  <input type="text" class="txtCaptcha" id="txtCaptcha1" style="background-image:url(1.jpg); text-align:center; border:none;font-weight:bold; font-family:Modern">
  <input type="button" value="Refresh" onclick="DrawCaptcha();">
   <input type="text" id="txtInput">

    <button type="submit" name="submit1" class="btn btn-default col-md-3">Submit</button>
    <button type="button" class="btn btn-default col-md-3" data-dismiss="modal">Close</button>

  </form>

You can not use same id on form for multiple times. Id must be unique. Instead of it use class. You can change y code as below. Also you dont have my_modal2 in your code so define it first

On Demand Services:

 Car Washing

 Carpenter

 Painters

    <button type="button" class="close" data-dismiss="modal">×Close</button>

Enquiry Form:

  <form method="post" action="" id="dummy" onsubmit="return checkform(this);">

Service Name:

    <input type="text" class="form-control" required readonly name="bookId" value="" style="color:#000;">

Full Name:

    <input type="text" class="form-control" required name="name" value="" style="color:#000;">

Email Address:

    <input type="email" class="form-control" required name="email" value="" style="color:#000;">

Mobile Number:

    <input type="tel" class="form-control" required name="mno" value="" style="color:#000;">

Message:

    <textarea name="msg" class="form-control" required style="color:#000;">I am interested in your service. Please contact me back on email/phone.</textarea>

Address:

    <textarea name="address" class="form-control" required style="color:#000;"></textarea>

Captcha:

  <input type="text" class="txtCaptcha" id="txtCaptcha" style="background-image:url(1.jpg); text-align:center; border:none;font-weight:bold; font-family:Modern">
  <input type="button" value="Refresh" onclick="DrawCaptcha();">
 <input type="text" id="txtInput">

    <button type="submit" name="submit" onclick="javascript:submitmydata();" class="btn btn-default col-md-3">Submit</button>
    <button type="button" class="btn btn-default col-md-3" data-dismiss="modal">Close</button>

  </form>

    <button type="button" class="close" data-dismiss="modal">×Close</button>

Enquiry Form:

  <form method="post" action="" onsubmit="return checkform(this);">

Service Name:

    <input type="text" class="form-control" required readonly name="bookId" value="" style="color:#000;">

Full Name:

    <input type="text" class="form-control" required name="name" value="" style="color:#000;">

Email Address:

    <input type="email" class="form-control" required name="email" value="" style="color:#000;">

Mobile Number:

    <input type="tel" class="form-control" required name="mno" value="" style="color:#000;">

Message:

    <textarea name="msg" class="form-control" required style="color:#000;">I am interested in your service. Please contact me back on email/phone.</textarea>

Address:

    <textarea name="address" class="form-control" required         style="color:#000;"></textarea>

Captcha:

  <input type="text" class="txtCaptcha" id="txtCaptcha1" style="background-image:url(1.jpg); text-align:center; border:none;font-weight:bold; font-family:Modern">
  <input type="button" value="Refresh" onclick="DrawCaptcha();">
   <input type="text" id="txtInput">

    <button type="submit" name="submit1" class="btn btn-default col-md-3">Submit</button>
    <button type="button" class="btn btn-default col-md-3" data-dismiss="modal">Close</button>

  </form>


text:
Q: Sudoku candidate probability Supose a Sudoku puzzle row has four empty cells. The candidates for each cells is as follows:

*

*$3, 6, 9$

*$7, 9$

*$3, 6, 7$

*$3, 7$

Looking at the possible cells for $3$ (cells $1$, $3$ and $4$), the probability for $3$ in each cell could be:
a) $\frac13$, $\frac13$, $\frac13$: if we only look at the possible choices for $3$
b) $\frac13$, $\frac13$, $\frac12$: if we figure the total candidates for each cell.
Both the assumptions above are wrong.
What is the probability of each cell being a $3$ in cells $1, 3$ and $4$?

A: Whenever you talk about the probability of an event, you have to talk about the sample space (or equivalently, the measure) with respect to which you're taking the probability; otherwise, you run into potential paradoxes such as the Bertrand Paradox.  Since you're talking about a Sudoku puzzle, the (IMHO) most natural sample space for determining your probability is the space of correctly filled grids; by this measure, the probability of 3 being in e.g. the first place is just the number of correctly filled grids with 3 in that space divided by the total number of correctly-filled grids.
Unfortunately, because of the constraints involved, I don't believe there's any cleaner way of doing this than 'the hard way': enumerate all of the possibilities and then tally.  For convenience, I'll write the assignments in the form abcd, where a is the value in the first cell, b is the value in the second, etc.

*

*if the first cell is a 9, then by elimination (remove 9 from the possibilities for the second cell, then 7 from the third and fourth cells, then 3 from the third) the only arrangement is 9763.

*If the first cell is not a 9, then the second cell must be a 9; this leaves us with (36)9(367)(37).  Now, if the first cell is a 3 then the arrangement collapses (similarly to the above) into 3967; if the first cell is a 6 then we have one final ambiguity in the last two cells, giving us the configurations 6937 and 6973.

Thus, there are a total of four possible configurations for the puzzle: 9763, 3967, 6937 and 6973.  This gives probabilities of $\frac14$, $0$, $\frac14$, and $\frac12$ for 3 being in each of the four cells, respectively.

A: I'm going to map your cells as $1 = A, 2 = B, 3 = C$ and $4 = D$ so they won't get confused with the numbers to come.
Cell $B$ can be ignored as $3$ is not a possibility there.
Cell $A$ has $3$ possibilities, one of which is $3$.
Cell $C$ has $3$ possibilities, one of which is $3$.
Cell $D$ has $2$ possibilities, one of which is $3$.
It turns out that the the second approach is on the right track. It just needs to be scaled down to $100%$, or 1 total. $\frac13 + \frac13 + \frac12 = \frac76$. To turn that into a 1 you need to multiply by $\frac67$. This is done to the probability for each cell.

Cell $A = \frac13 \cdot \frac67 = \frac{6}{21} = \frac27 \approx 28.57%$
Cell $C = \frac13 \cdot \frac67 = \frac{6}{21} = \frac27 \approx 28.57%$
Cell $D = \frac12 \cdot \frac67 = \frac{6}{14} = \frac37 \approx 42.86%$

Note that this approach works for cases where several elements can be a particular possibility, but only one of them is permitted to be. Add up the individual probabilities, then multiply each by the reciprocal of the sum.


text:
Q: c# Get name of variable(s) during object deconstruction Given this code:
var (c, d) = new Test();

This it possible to get the variables names from the Deconstruct method?
public class Test
{
    public void Deconstruct(out string value1, out string value2)
    {
        // is there a way to know the parameters are
        // being mapped to "c" and "d" respectively
        // inside this method?
    }
}

The idea to refactor the follow code to reduce the amount of repetition:
var parsed = Regex
    .Match("123: qwe: qweasd", @"(?<id>\d+?): (?<level>\d+?): (?<message>\d+?):")
    .Apply(m => !m.Success ? null : new
    {
        // notice the names are repeated on both side
        ID = m.Group["id"].Value,
        Level = m.Group["level"].Value,
        Message = m.Group["message"].Value,
    });

What I'm trying to solve with Test class:
var (id, level, message) = Regex
    .Match("123: qwe: qweasd", @"(?<id>\d+?): (?<level>\w+?): (?<message>\w+?):")
    .Groups
    .AsDeconstructable(); //

A: I really don't think this is a good idea, and Reflection can be terribly slow, but here we go.
First, we need some extensions to make dealing with properties and fields a little cleaner:
public static class HelperExtensions {
    // ***
    // *** Type Extensions
    // ***
    public static List<MemberInfo> GetPropertiesOrFields(this Type t, BindingFlags bf = BindingFlags.Public | BindingFlags.Instance) =>
        t.GetMembers(bf).Where(mi => mi.MemberType == MemberTypes.Field | mi.MemberType == MemberTypes.Property).ToList();

    // ***
    // *** MemberInfo Extensions
    // ***
    public static void SetValue<T>(this MemberInfo member, object destObject, T value) {
        switch (member) {
            case FieldInfo mfi:
                mfi.SetValue(destObject, value);
                break;
            case PropertyInfo mpi:
                mpi.SetValue(destObject, value);
                break;
            default:
                throw new ArgumentException("MemberInfo must be of type FieldInfo or PropertyInfo", nameof(member));
        }
    }

    public static TOut Apply<TIn, TOut>(this TIn m, Func<TIn, TOut> applyFn) => applyFn(m);
}

Then, we need to create a class to represent the desired result:
public class ParsedMessage {
    public string ID;
    public string Level;
    public string Message;
}

Now, we write an extension to map Group named values to properties or fields in an object:
public static class MatchExt {
    public static T MakeObjectFromGroups<T>(this Match m) where T : new() {
        var members = typeof(T).GetPropertiesOrFields().ToDictionary(pf => pf.Name.ToLower());
        var ans = new T();
        foreach (Group g in m.Groups) {
            if (members.TryGetValue(g.Name.ToLower(), out var mi))
                mi.SetValue(ans, g.Value);
        }

        return ans;
    }

    public static string[] MakeArrayFromGroupValues(this Match m) {
        var ans = new string[m.Groups.Count-1];
        for (int j1 = 1; j1 < m.Groups.Count; ++j1)
            ans[j1-1] = m.Groups[j1].Value;

        return ans;
    }
}

Finally, we can use our new extension:
var parsed = Regex
    .Match("123: qwe: qweasd", @"(?<id>\d+?): (?<level>\w+?): (?<message>\w+?)")
    .Apply(m => m.Success ? m.MakeObjectFromGroups<ParsedMessage>() : null);

Note: it is possible to create anonymous types on the fly at runtime, but they are rarely useful. Since you don't know anywhere else in your code what the properties are, you must do everything through Reflection, and unless you are using the objects in a Reflection heavy environment like ASP.Net, you might as well use a Dictionary, or if you must, a DynamicObject (though, again, without knowing the field names that isn't too practical).
I added an additional extension to map Groups to a string[]. Since names for ValueTuple fields are only usable at compile time, creating an array and using indexes is just as good as creating a ValueTuple and using Item1, etc.
Finally, an attempt to work with an anonymous object. By passing in a template for the anonymous object, you can create a new anonymous object from the capture group values that have matching names.
Using a method extension for type inference:
public static class ToAnonymousExt {
    public static T ToAnonymous<T>(this T patternV, Match m) {
        var it = typeof(T).GetPropertiesOrFields();
        var cd = m.Groups.Cast<Group>().ToDictionary(g => g.Name, g => g.Value);
        return (T)Activator.CreateInstance(typeof(T), Enumerable.Range(0, it.Count).Select(n => cd[it[n].Name]).ToArray());
    }
}

Now you can pass in an anonymous type as a template and get a filled in anonymous object back. Note that only the fields in the anonymous type that match capture group names will be filled in, and no runtime error handling is done.
var parsed3 = Regex.Match("123: qwe: qweasd", @"(?<id>\d+?): (?<level>\w+?): (?<message>\w+?)")
                   .Apply(m => m.Success ? new { message = "", id = "", level = "" }.ToAnonymous(m) : null);

A: In C# 10, you can use the new attribute CallerArgumentExpression combined with out variable declaration in the call to get close to what you want:
First, a string extension method:
public static class StringExt {
    public static string Past(this string s, string separator) {
        var starterPos = s.IndexOf(separator);
        return starterPos == -1 ? s : s.Substring(starterPos + separator.Length);
    }
}

Now a sample ToVariables extension method for GroupCollection for arity 3 (obviously it is easy to create other arities):
public static class GroupCollectionExt {
    public static void ToVariables(this GroupCollection gc, out string v1, out string v2, out string v3,
                                   [CallerArgumentExpression("v1")] string name1 = "", [CallerArgumentExpression("v2")] string name2 = "", [CallerArgumentExpression("v3")] string name3 = "") {
        v1 = gc.TryGetValue(name1.Past(" "), out var g1) ? g1.Value : default;
        v2 = gc.TryGetValue(name2.Past(" "), out var g2) ? g2.Value : default;
        v3 = gc.TryGetValue(name3.Past(" "), out var g3) ? g3.Value : default;
    }
}

And now you can declare variables and assign them to group values from a Regex match with the only repetition in the pattern:
Regex
    .Match("123: qwe: qweasd:", @"(?<id>\d+?): (?<level>\w+?): (?<message>\w+?):")
    .Groups
    .ToVariables(out var id, out var level, out var message);

Note: An obvious extension would be to create ToVariables for Dictionary<string,T>. Another extension might be to fall back to positional groups when there are no named groups.


text:
Q: Fragment doesn't work using fragment tag, works in framelayout Fragment doesn't work when using fragment tag in XML layout. But, after replace fragment tag to Framelayout it works fine without making any change in my code.
When i use the code below fragment doesn't change/work.
<fragment
    android:id="@+id/fragment_container"
    android:name="com.example.user.example.MyFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/btnPressMe"
    />

But, when i replace the above code with the code below it changes/works.
<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/btnPressMe">
</FrameLayout>

Java code:
   FragmentManager fragmentManager = getFragmentManager();
   FragmentTransaction fragmentTransaction =  fragmentManager.beginTransaction();

    Fragment2 fragment2 = new Fragment2();
    fragmentTransaction.replace(R.id.fragment_container, fragment2);
    fragmentTransaction.commit();

A: if you want to infalte to another fragment you must use
 getChildFragmentManager() instead of  getFragmentManager()
FragmentManager fobject = getChildFragmentManager();
FragmentTransaction transaction = fobject .beginTransaction();
fragment_container= fobject .findFragmentById(R.id.fragment_container);

if (fragment_container!= null) {
transaction.replace(R.id.fragment_container, yournewfragment);
transaction.commit();
}
transaction.commit();


text:
Q: My read more/ read less is not showing header tags I am trying to add read more/ less in a div, which will have header tags too, but it's not reflecting
codes are:

$(function() {
var showTotalChar = 200, showChar = "Show (+)", hideChar = "Hide (-)";
$('.show').each(function() {
var content = $(this).text();
if (content.length > showTotalChar) {
var con = content.substr(0, showTotalChar);
var hcon = content.substr(showTotalChar, content.length - showTotalChar);
var txt= con + '...' + hcon + '  ' + showChar + '';
$(this).html(txt);
}
});
$(".showmoretxt").click(function() {
if ($(this).hasClass("sample")) {
$(this).removeClass("sample");
$(this).text(showChar);
} else {
$(this).addClass("sample");
$(this).text(hideChar);
}
$(this).parent().prev().toggle();
$(this).prev().toggle();
return false;
});
});
.morectnt span {
display: none;
}
<!DOCTYPE html>

  <title>Bootstrap 4 Website Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

lorem ipsum doler sit amet

subtitle

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec magna tellus, vulputate in feugiat vel, auctor at ipsum. Curabitur imperdiet orci eget congue malesuada. Vestibulum gravida mi sed facilisis elementum. Phasellus sed eros nulla. Proin porta aliquam tristique.

Suspendisse tincidunt augue eget nulla luctus porta. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec magna tellus, vulputate in feugiat vel, auctor at ipsum. Curabitur imperdiet orci eget congue malesuada. Vestibulum gravida mi sed facilisis elementum. Phasellus sed eros nulla. Proin porta aliquam tristique. Suspendisse tincidunt augue eget nulla luctus porta.

It's not taking h1, h2 tags, all content are coming in one single line as a paragraph.

A: when you get the text of the div it ignores what tag it is in. so i replaced .text() with .html() and it's fixed

$(function() {
  var showTotalChar = 200,
    showChar = "Show (+)",
    hideChar = "Hide (-)";
  $('.show').each(function() {
    var content = $(this).html();
    if (content.length > showTotalChar) {
      var con = content.substr(0, showTotalChar);
      var hcon = content.substr(showTotalChar, content.length - showTotalChar);
      var txt = con + '...' + hcon + '  ' + showChar + '';
      $(this).html(txt);
    }
  });
  $(".showmoretxt").click(function() {
    if ($(this).hasClass("sample")) {
      $(this).removeClass("sample");
      $(this).text(showChar);
    } else {
      $(this).addClass("sample");
      $(this).text(hideChar);
    }
    $(this).parent().prev().toggle();
    $(this).prev().toggle();
    return false;
  });
});
.morectnt span {
  display: none;
}
<!DOCTYPE html>

  <title>Bootstrap 4 Website Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

lorem ipsum doler sit amet

subtitle

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec magna tellus, vulputate in feugiat vel, auctor at ipsum. Curabitur imperdiet orci eget congue malesuada. Vestibulum gravida mi sed facilisis elementum. Phasellus sed eros nulla. Proin porta
      aliquam tristique. Suspendisse tincidunt augue eget nulla luctus porta. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec magna tellus, vulputate in feugiat vel, auctor at ipsum. Curabitur imperdiet orci eget congue malesuada. Vestibulum
      gravida mi sed facilisis elementum. Phasellus sed eros nulla. Proin porta aliquam tristique. Suspendisse tincidunt augue eget nulla luctus porta.


text:
Q: Is there jQuery plugin for editing text similar to Google plus posting box - using contenteditable? I am currently searching up and down for jQuery plugin that would be similar to the box for posting text on Google Plus. It uses contenteditable="plaintext-only" and is very simple to use, especially when some external content (link, image, video, ...) is mentioned in the text.
Is there something at least close to appearance and function to Google+'s contenteditable textbox ?

A: No, Google's editor is custom.  It also requires an additional server component that goes out and fetches the external content and formats it to display nicely in the editor.
The closest you'll get is a rich text editor like TinyMCE.  However, this is only intended for WYSIWYG editing, and doesn't have any facilities for fetching and formatting external content when links are posted.


text:
Q: What is 'oip' in the zimbra mail server logs? This is the first time I am trying to understand Zimbra logs. I noticed that every action (like deletion of a mail, addition of an incoming mail etc.) is logged in the mailServer.log file. Since emails can also be deleted (from java code remotely), I wanted to know which IP the command came from. For example, for the below log line (taken from https://wiki.zimbra.com/wiki/Log_Files), what exactly is 'oip' (originating IP).
Is it the IP address of the server from where the command originated ? If yes, then we can find who remotely sent the command (delete/add/expunge etc.). Is that correct ?
2013-08-30 11:19:41,043 INFO  [qtp2050551931-94:http://127.0.0.1:8080/service/soap/AuthRequest] [name=user1@example.com;oip=5.6.7.8;ua=zclient/8.0.4_GA_5737;] mbxmgr - Mailbox 3 account abcdef8f-1234-5678-9012-8abcdefe2658 LOADED

Thanks in advance.

A: Correct, it's the address of the client or, if you have one, the proxy that originated the request
You can log public IP following the steps in this wiki
https://wiki.zimbra.com/wiki/Log_Files#Logging_the_Originating_IP


text:
Q: Como fazer update de um select com sub consultas que contem Group by e order by Tabela Fisica
Registro IDBanco DataMovimento Credito Debito SaldoAtual Ordenado
    1      26     2020-07-05   500,00   0,00    0,00        5
    2      26     2020-07-03    0,00    10,00   0,00        3
    3      26     2020-07-06    0,00    20,00   0,00        6
    4      26     2020-07-01    0,00    30,00   0,00        1
    5      26     2020-07-06    0,00    40,00   0,00        7
    6      26     2020-07-01    0,00    50,00   0,00        2
    7      26     2020-07-08    0,00    60,00   0,00        8
    8      26     2020-07-04    0,00    70,00   0,00        4
    9      26     2020-07-11    0,00    80,00   0,00        9
   10      26     2020-07-15    0,00    80,00   0,00       11
   11      26     2020-07-11    0,00   100,00   0,00       10

Quando executo este select obtenho o resultado da consulta na tabela abaixo na coluna "Soma".
SELECT t1.Ordenado, SUM(t2.SaldoInicial + T2.Credito - T2.Debito) as Soma
FROM tbl_SaldoAtual AS t1
INNER JOIN tbl_SaldoAtual AS t2 on t1.Ordenado >= t2.Ordenado
GROUP BY  t1.Ordenado
ORDER BY t1.Ordenado  ASC

Ordenado  Soma
    1   -30.00
    2   -80.00
    3   -90.00
    4  -160.00
    5   340.00
    6   320.00
    7   280.00
    8   220.00
    9   140.00
   10    40.00
   11   -40.00

Não estou conseguindo encontrar um caminho para fazer update da coluna "Soma" da consulta para a tabela física na coluna "SaldoAtual", onde a coluna "Ordenado" será a coluna do Group by e Order by conforme o select acima.
Já tentei com CTE, Tabela temporária, Update com sub consultas, mas sem exito.
Se alguém puder dar uma luz agradeço.

A: Solução encontrada para o problema acima.
UPDATE tbl_SaldoAtual
SET SaldoAtual = Soma
FROM
(SELECT TOP(15) WITH TIES t1.Ordenado, SUM(t2.SaldoInicial + T2.Credito - T2.Debito) as Soma
FROM tbl_SaldoAtual AS t1
INNER JOIN tbl_SaldoAtual AS t2 on t1.Ordenado >= t2.Ordenado
GROUP BY  t1.Ordenado
ORDER BY t1.Ordenado  ASC) TS
WHERE tbl_SaldoAtual.Ordenado = TS.Ordenado


text:
Q: Unable to logically adress x,y-values of rasterToPoints extraction I am unsure how to describe this problem. I have a feeling it is trivial but I cannot get a hold of it.
I have a stack of raster objects (object NDVI). From these I extracted x and y coordinates using rasterToPoints
xycoord1 <- rasterToPoints(NDVI)
xycoord <- xycoord1[,c(1:2)]

Along the pre-processing I kicked out several unusable pixels and ended up with:
> str(xycoord.short)
 num [1:20054, 1:2] 3802292 3802523 3802755 3802987 3803218 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:2] "x" "y"

No I simply want to find a certain x and y coordinate.
e.g.
> which(xycoord.short[,1]==3802292)
integer(0)

But I seem unable to "get hold" of the values inside for example one column.
> xycoord.short[,1][1]
[1] 3802292
> xycoord.short[,1][1]==xycoord.short[,1][1]
[1] TRUE
> xycoord.short[,1][1]==3802292
[1] FALSE

Can anyone help me along this problem? I just don't find the problem. Does it have to do with initial extraction through rasterToPoints? Thanks!
EDIT:
dput output for the first 10 rows of my xy-coordinates
xy <- structure(c(3802291.63636448, 3802523.29272274, 3802754.94908101,
                 3802986.60543927, 3803218.26179754, 3803449.9181558, 3803681.57451406,
                 3803913.23087233, 3804144.88723059, 3804376.54358886, -49690.2888476191,
                 -49690.2888476191, -49690.2888476191, -49690.2888476191, -49690.2888476191,
                 -49690.2888476191, -49690.2888476191, -49690.2888476191, -49690.2888476191,
                 -49690.2888476191), .Dim = c(10L, 2L), .Dimnames = list(NULL,
                                                                         c("x", "y")))

EDIT2:
After posting the dput output it makes sense, as the values are obviously rounded.
Using the exact numbers works...
> any(xycoord.short[,1]==3802291.63636448)
[1] TRUE

A: What you have here is a rounding "problem". Your coordinates are in what we call "double" (10.3 is a double) but you're trying to subset based on an integer (say 10). What you can do here is round to n places and subset based on that.
For instance, let's check eight digits.
format(xy, digits = 8)

      x             y
 [1,] "3802291.636" " -49690.289"
 [2,] "3802523.293" " -49690.289"
 [3,] "3802754.949" " -49690.289"
 [4,] "3802986.605" " -49690.289"
 [5,] "3803218.262" " -49690.289"
 [6,] "3803449.918" " -49690.289"
 [7,] "3803681.575" " -49690.289"
 [8,] "3803913.231" " -49690.289"
 [9,] "3804144.887" " -49690.289"
[10,] "3804376.544" " -49690.289"

So in essence, when you're looking for 3802292 it doesn't find it because it's actually 3802291.636....
You can either specify exact coordinate up to x places correct, or perhaps round your number and work on that. Or you could specify a range of values that would encompass your desired value(s).


text:
Q: Pass no value to function with default parameters I have this Kotlin function:
fun doSomething(user: User = defaultUser) {
  //do something
}

and I call it from another place:
val user: User? = getUser()
if (user == null) {
  doSomething()
} else {
  doSomething(user)
}

Is it possible to improve this code? I think this "if/else" is a little bit messy. Is possible to do something like this?
doSomething(user ?: NoValue)

A: You can cut it down to user?.run(::doSomething) ?: doSomething() (if doSomething doesn't return null) but I don't know why you'd want to!
Honestly the if/else reads nice to me, stick it on one line without the braces and it's nice and compact. Unfortunately I don't think you can conditionally add parameters into a function call (and handling default parameters can get unnwieldy when you have a few).
I agree with @benjiii, it might be better to have a nullable parameter and handle the default internally, if you don't need to use null as a legit value

A: You could do something like this:
getUser()?.let { // user is not null
  doSomething(it)
} ?: run { // user is null here
  doSomething()
}

(cf: Swift 'if let' statement equivalent in Kotlin)
I don't think you could do something shorter without making the code hard to understand Edit 2: Actually you can, see the comment
Edit: I would personally handle the nullable variable inside the function like this:
fun doSomething(user: User?) {
  val correctUser = user ?: defaultUser
  //do something
}

so you can use the function like this:
doSomething(getUser())

A: I agree with cactustictacs, just putting it on one line is clear and simple. However, if you use it often and it's bothering you, it's easy enough to wrap it in a function without the default parameter:
fun doSomethingSensibly(user: User?) =
    if (user == null)
        doSomething()
    else
        doSomething(user)

Which can be used as:
doSomethingSensibly(getUser())


text:
Q: Push this into an array onClick I'm trying to push data into an array when I do an onClick event.
function clickCard() {
    $(document).on('click', '.card', function() {
        $(this).addClass('visible');

        var cardValue = $(this).attr('src');
        matchOrNot.push(cardValue);

    })
}

I'm trying to get the src of an image into the array and it needs to be that specific image (this) that I clicked on. Hope it makes sense.
When I try this I get 'undefined' of the variable matchOrNot.
This function works if I target a selector with a notation [0] but I want to get this.
Any idéas?

A: Something like this?

var A = []

  $('.card').on('click', e => {
      let $this = $(e.currentTarget)
      $this.addClass('visible')
      let cardValue = $this.attr('src');
      A.push(cardValue);

      console.log(A)
  })

Update:
After seeing your code I got the problem. Not matchOrNot is undefined, but the src attribute, as your current target is not the image but an outer div. You need to find the image within first:
$this.find('img').attr('src')

A: You are trying to access the object src with the class .card when using $(this), the fastest solution would be to use a $('#id') to get the image src.

A: The given click event i.e. click event on element with class 'card' should get registered when DOM is ready for interaction, and the place for that is $(document).ready() method.
Please wrap $(document).on inside ready event.
This should fix the issue.


text:
Q: sqlalchemy one to many relationship and adding to data base hi there hope yu will be able to help me.
im trying to add a post to a blog, now im trying to fetch the name of the user so it
will be diplayed on the site.
def add_new_post():
form = CreatePostForm()
if request.method == 'POST':
    user_data = User.query.filter_by(id=current_user.id).first()
    user_name_to_post = str(user_data.name)
    print(current_user.name)
    new_post = BlogPost(
        title=form.title.data,
        subtitle=form.subtitle.data,
        body=form.body.data,
        img_url=form.img_url.data,
        author=current_user, <-------------------
        date=date.today().strftime("%B %d, %Y")
    )
    db.session.add(new_post)
    db.session.commit()
    return redirect(url_for("get_all_posts"))
return render_template("make-post.html", form=form, is_active=current_user.is_active)

now as long the author=current_user, it works but it displays "user1"
as the author name on the site.
if im trying to put the name it raise an exaption
new_post = BlogPost(
        title=form.title.data,
        subtitle=form.subtitle.data,
        body=form.body.data,
        img_url=form.img_url.data,
        author=current_user.name, <------------------
        date=date.today().strftime("%B %d, %Y")

AttributeError: 'str' object has no attribute '_sa_instance_state'
i have tried to go more direct into the user and did this idea that i read somewhere.
new_post = BlogPost(
        title=form.title.data,
        subtitle=form.subtitle.data,
        body=form.body.data,
        img_url=form.img_url.data,
        author=User(name=current_user.name), <--------------
        date=date.today().strftime("%B %d, %Y")
    )

it gives me this error:
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed:
users.email
[SQL: INSERT INTO users (name, email, password) VALUES (?, ?, ?)]
[parameters: ('jay ber', None, None)]
(Background on this error at: http://sqlalche.me/e/13/gkpj)

Traceback (most recent call last)

my databse looks like that:
class BlogPost(db.Model):
__tablename__ = "blog_posts"
id = db.Column(db.Integer, primary_key=True)
author = db.Column(db.String(250), nullable=False)
title = db.Column(db.String(250), unique=True, nullable=False)
subtitle = db.Column(db.String(250), nullable=False)
date = db.Column(db.String(250), nullable=False)
body = db.Column(db.Text, nullable=False)
img_url = db.Column(db.String(250), nullable=False)
author_id = db.Column(db.Integer, db.ForeignKey("users.id"))
author = relationship("User", back_populates="posts")

class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(100), nullable=False)
password = db.Column(db.String(250), nullable=False)
posts = relationship("BlogPost", back_populates="author")

i hope some one can help me with it.
all i want is to display the name of the author as part of the blog post


text:
Q: Conditional CTE in PostgreSQL I'm trying to write a dynamic query. I've tried to simplify this as best as I can. @Condition and @Filter are the dynamic inputs of the query.
There are two cases:

*

*If @Condition is TRUE, then do not filter the data on the presence of any metadata

*Otherwise, find the rows of metadata that match a certain filer, and filter the data on those.

Pseudo code a little bit like this:
WITH selected_metadata AS (
    IF (@Condition = TRUE) {
        -- Do not filter on metadata
        SELECT NULL;
    }
    ELSE {
        -- Find the matching metadata rows
        SELECT id FROM metadata WHERE field = @Filter
    }
)
SELECT
    *
FROM data
WHERE
    (
        -- Ignore the metadata filter
        selected_metadata IS NULL
        OR
        -- Filter on metadata
        data.metadataid IN (selected_metadata)
    )
    ...more filters

I think there might be easier ways to do this without a CTE, but because of how the query looks in real life, I think I need to split it up to minimize complexity.

A: I think you can try to set those condition in where instead of CTE directly.
SELECT
    *
FROM data
WHERE
    (
        -- Ignore the metadata filter
        @Condition = TRUE
        OR
        -- Filter on metadata
        @Condition = FALSE AND data.metadataid IN (SELECT ID FROM selected_metadata AND field = @Filter)
    )
    ...more filters

A: Try something like this:
WITH selected_metadata AS (
  -- Find the matching metadata rows
  SELECT id FROM metadata WHERE field = @Filter OR @Condition <> TRUE
)
SELECT ...


text:
Q: Сохранение элементов ListView после перезагрузки приложения Есть приложение, в котором при нажатии на кнопку создаются и добавляются элементы списка ListView. При перезагрузке приложения, они пропадают. Догадываюсь, что нужно использовать БД, и при создании элемента добавлять его в БД, а в методе OnCreate поставить создание списка ListView из элементов в БД(исправьте, если я не прав). Вопрос такой: можно ли сохранять список после перезагрузки приложения НЕ ИСПОЛЬЗУЯ БД, т.к. в списке будет максимум 10-15 элеметов(это потолок). Б

A: У Activity есть onSaveInstanceState, который срабатывает при закрытии. Переопределите его, чтоб сохранить данные из ListView:
public void onSaveInstanceState(Bundle savedState) {

    super.onSaveInstanceState(savedState);

    // здесь берём данные из адаптера
    // если у вас ArrayAdapter, то будет так
    String[] values = mAdapter.getValues();
    savedState.putStringArray("myKey", values);

}

А потом в onCreate получайте:
public void onCreate (Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        String[] values = savedInstanceState.getStringArray("myKey");
        if (values != null) {
           mAdaptor = new MyAdaptor(values);
        }
    }

    [...]

}

A: Можно. Вы можете хранить данные разными способами:

*

*В SharedPreferences

*Записывая данные в свой файл любого формата.

*Использовать БД

Также, если вы под "перезагрузкой приложения" имеете в виду пересоздание экрана при его повороте, то вам также поможет инфа по ссылке из п.1 (сохранение данных активити в Bundle при поворотах экрана)


text:
Q: JDBC sink connector insert/upsert based on max timestamp? I'm very new to Kafka connect
I am inserting records from multiple sources into one table.
In some cases, it may be possible for some records to reach before others.
Since I cannot control which source will pull which record first, I want to add a check on the timestamp key of the record.
I have a key called "LastModified_timestamp" in my schema where I store the timestamp of the latest state of my record.
I want to add a check to my JDBC sink connector where I can upsert a record based on comparing the value of LastModified_timestamp
I want to ignore the records which have a older timestamp and only want to upsert/insert the latest one. I couldn't find any configuration to achieve this
Is there any way by which I can achieve this?
Will writing a custom query help in this case?

A: The JDBC Sink connector does not support this kind of feature. You have two options to consider:

*

*Single Message Transform (SMT) - these apply logic to records as they pass through Kafka Connect. SMT are great for things like dropping columns, changing datatypes, etc. BUT not appropriate for more complex processing and logic, including logic which needs to span multiple records as yours does here

*Process the data in the source Kafka topic first, to apply the necessary logic. You can do this with Kafka Streams, KSQL, and several other stream processing frameworks (e.g. Spark, Flink, etc). You'd need some kind of stateful logic that could work out if a record was older than already processed.
Can you describe more about your upstream source for the data? It might be there's a better way to orchestrate the data coming through to enforce the ordering.
A final idea would be to land all records to your target DB and then use logic in your database query consuming it to select the most recent (based on LastModified_timestamp) record for a given key.
Disclaimer: I work for Confluent, the company behind the open-source KSQL project.


text:
Q: c# transfer string to another project with no reference To clarify, there is a reference in my solution. I currently have 2 projects => UI and Engine. UI references Engine.
I'm looking to transfer a string that is based on user input from the UI project to the Engine project. Specifically the 'GameSession' class. Though I cannot just put it in a string and reference it (Though I'm not sure even that would work) since UI references Engine, not the other way around.
So I've looked to solve this problem this way:
        private void Button_Click(object sender, RoutedEventArgs e)
    {
        testvar = boxUser.Text;
        _gameSession.TestMethod(testvar);
        MainWindow main = new MainWindow();
        main.Show();
    }

Here I convert the textbox input to a string, then call the TestMethod in the gameSession class which has a string parametar, putting the input in that method, and open the window where the textbox input should be seen.
    private string _test;
    public void TestMethod(string test)
    {
        _test = test;
    }

I then define a string _test and in the Method I called earlier then just equal it out.
       public GameSession()
    {

        CurrentPlayer = new Player(_test, "Hardcoded", 0, 10, 10, 1000000);

Then in the GameSession constructor I create a new instance of a Player with the name as the _test variable (the user input), but when I run it, it just comes out as null when the MainWindow opens. It does take the form of the _test variable after the fact, but I need it to take the form of the variable literally as soon as it can. How would I go about achieveing this? What could I do to improve/rewrite the code for it to work?

A: You set a value to _test after you have created a player. Re-create a player in TestMethod or update name of the player if it's possible.
public void TestMethod(string test)
{
    CurrentPlayer = new Player(test, "Hardcoded", 0, 10, 10, 1000000);
}

Or
public void TestMethod(string test)
{
    CurrentPlayer.Name = test;
}

Remember that string is reference type but it is immutable.
_test = "some name";
CurrentPlayer = new Player(_test, "Hardcoded", 0, 10, 10, 1000000);
// CurrentPlayer.Name = "some name"

_test = "another name";
// CurrentPlayer.Name will remain "some name"


text:
Q: Stuck at getting all the links exhausting view more button using requests I've created a script to fetch the link of different containers from the two identical links. The script is doing fine as long as the first page is concerned. However, there is a button at the bottom View More which does not have any link associated with it so, I'm stuck at getting the rest using requests. To bring out the clarity, the following image represents the first container of the first link.

I've tried with:
import requests
from bs4 import BeautifulSoup

base = 'https://hipages.com.au{}'

links = (
    'https://hipages.com.au/find/antenna_services/sa/adelaide',
    'https://hipages.com.au/find/antenna_services/vic/melbourne'
)

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'
    for link in links:
        r = s.get(link)
        soup = BeautifulSoup(r.text,"html5lib")
        for item in soup.select("[class*='BusinessListingHeaderColumn'] a:has(> h3)[href]"):
            print(base.format(item.get("href")))

How can I get the links from all the containers making use of view more button using requests?

This is the type of output I'm after:
https://hipages.com.au/connect/cinemaathome
https://hipages.com.au/connect/mrcommunications
https://hipages.com.au/connect/adelaidevideoscreens

A: requests might not be the best tool for this type of the job, because you have to keep adding more content to the page dynamically.
One workaround would be to use an API, as there's one. But I found several problems with this request for example:
https://hipages.com.au/api/directory/sites?suburb=adelaide&state=sa&category=145&page=2&perpage=10&code=c237ab1d599590b23f25c822a43c74528d7d55182331509852906e86cf0710b1c1d72087cbbbaa1f4ff8dcb50c9f234e

*

*You'd have to somehow map the category=145 value to its name.

*I wasn't able to figure out where the code part is coming from.

Another workaround would be to, well, keep clicking on the View more button until there's no such button. Then, scrape the "final" version of the page for all the urls matching the css selector.
Repeat for the next url and so on...
How? Enters selenium.
PS. To get this running, apart from the selenium module, you need the Chrome driver. See this for installation instructions.
The code:
import time

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException

base = 'https://hipages.com.au{}'
links = (
    'https://hipages.com.au/find/antenna_services/sa/adelaide',
    'https://hipages.com.au/find/antenna_services/vic/melbourne'
)

options = Options()
options.headless = True
driver = webdriver.Chrome(options=options)

for link in links:
    print(f"Fetching connect links for {link}...")
    driver.get(link)

    while True:
        try:
            element = driver.find_element_by_css_selector('.jRFKbg').click()
            time.sleep(2)  # wait for more content to load
        except NoSuchElementException:
            break
    follow_links = BeautifulSoup(
        driver.page_source,
        "html5lib",
    ).select("[class*='BusinessListingHeaderColumn'] a:has(> h3)[href]")

    for follow_link in follow_links:
        print(base.format(follow_link.get("href")))

This outputs (for Adeladie):
https://hipages.com.au/connect/cinemaathome
https://hipages.com.au/connect/mrcommunications
https://hipages.com.au/connect/adelaidevideoscreens
https://hipages.com.au/connect/justantennas
https://hipages.com.au/connect/celciustechnicalservices
https://hipages.com.au/connect/ljhelectricalsolutions
https://hipages.com.au/connect/voltechservices
https://hipages.com.au/connect/comtelecom
https://hipages.com.au/connect/homedigitalsystems
https://hipages.com.au/connect/samedaytvantennaservice
https://hipages.com.au/connect/pheds
https://hipages.com.au/connect/parksidedigitaltvservice
https://hipages.com.au/connect/antennatoday
https://hipages.com.au/connect/getfusedelectricalptyltd
https://hipages.com.au/connect/switchedonwiring
https://hipages.com.au/connect/lightningelectricalsolutionssa
https://hipages.com.au/connect/evanselectricalandair
https://hipages.com.au/connect/lynchelec
https://hipages.com.au/connect/asapantennas
https://hipages.com.au/connect/spacetelecommunications
https://hipages.com.au/connect/outpulseelectrical
https://hipages.com.au/connect/markgentle
https://hipages.com.au/connect/matchmastertvreceptionsystems
https://hipages.com.au/connect/empireelectricalsa
https://hipages.com.au/connect/sasecureservices
https://hipages.com.au/connect/powerlux
https://hipages.com.au/connect/ecolightselectrical
https://hipages.com.au/connect/kdiselectricalandairconditioningservices
https://hipages.com.au/connect/jptelecomptyltd
https://hipages.com.au/connect/bhullarelectricalsandsolar
https://hipages.com.au/connect/tkhelectrical
https://hipages.com.au/connect/njstechnologies
https://hipages.com.au/connect/apexelectricalsolarservices
https://hipages.com.au/connect/handymanservice6
https://hipages.com.au/connect/pricelesselectricalptyltd
https://hipages.com.au/connect/zaccelectrical
https://hipages.com.au/connect/adelaidehometheatre
https://hipages.com.au/connect/wescombeelectrical
https://hipages.com.au/connect/batterselectrical
https://hipages.com.au/connect/avanditconnections
https://hipages.com.au/connect/andersonelectric
https://hipages.com.au/connect/tappelectrical
https://hipages.com.au/connect/smartgridelectrical
https://hipages.com.au/connect/scothernselectricaldataservicesptyltd
https://hipages.com.au/connect/nexuselectricalairconditioning
https://hipages.com.au/connect/apcelectrical
https://hipages.com.au/connect/paultompkinselectricalcontracting
https://hipages.com.au/connect/aaronlampreelectricalservices
https://hipages.com.au/connect/sparrowelectricalandconstructionservices
https://hipages.com.au/connect/djairelectrical
https://hipages.com.au/connect/localchoiceelectrical
https://hipages.com.au/connect/knicelectricalservicesptyltd

EDIT:
This is based on your own answer you've shared with me. Basically, you couldn't break out of the loop because the API kept serving you the last page over and over again even if it was the same page.
So, we need to know when we've seen the page or the follow link. Here's my attempt, which boils down to checking if any lead link from the API is in the list of all follow links. If so, we've seen this API page. Time to move on to the next URL.
import re
import requests

lead_link = "https://hipages.com.au/connect/"
links = (
    "https://hipages.com.au/find/antenna_services/sa/adelaide",
    "https://hipages.com.au/find/antenna_services/vic/melbourne",
)

all_follow_links = []
for link in links:
    r = requests.get(link)
    print(f"Getting links for {link}...")
    payload = {
        "suburb": link.split("/")[-1],
        "state": link.split("/")[-2],
        "category": re.search(r'category_id":(.*?),', r.text).group(1),
        "page": 1,
        "perpage": 10,
        "code": re.search(r'"code":"(.*?)",', r.text).group(1),
    }
    while True:
        response = requests.get(
            'https://hipages.com.au/api/directory/sites?',
            params=payload,
        ).json()
        leads = [f"{lead_link}{item['siteKey']}" for item in response]
        if any(lead in all_follow_links for lead in leads):
            break
        all_follow_links.extend(leads)
        payload["page"] += 1

print(all_follow_links)


text:
Q: What is the role of run script in Build Phases in Xcode 4 Can any one explain actual usage of run script in xcode 4.

*

*what is the usage of run script.

*which type of scripts we can add in run script.

*when will execute the run script.

*explain some of the example to write the run script.
can you give over all idea of run script in Build Phases in xcode 4.

A: 1) You can execute scripts during build.
2) Mainly sh scrips.
3) You can drag the phase where ever you like it.
4) Have a look at this link.


text:
Q: How to spawn an offline process from a TFS vNext build step that would last beyond the build? It seems that if my build step spawns a child process, that process cannot survive the end of the build - it is killed.
But I have a scenario where a child process is triggered in order to complete offline certain operations that the build should not wait for their completion (reporting metrics to Azure AppInsights).
This procedure worked fine in XAML builds, but now that we migrated to vNext it is broken, because the child process is killed when the build ends.
What can be done about it?

A: The easiest way is to schedule a task using the task scheduler.
Example using Microsoft.Win32.TaskScheduler NuGet package:
using (var ts = new TaskService())
{
    // Create a new task definition and assign properties
    var td = ts.NewTask();
    td.Triggers.Add(new TimeTrigger(DateTime.Now.AddDays(-1)));
    td.Actions.Add(new ExecAction(MyExe, MyArgs));
    ts.RootFolder.RegisterTaskDefinition(MyTaskName, td).Run();
    ts.RootFolder.DeleteTask(MyTaskName);
}