text:
Q: "Google Drive can corrupt repositories" in Github Desktop I primarily work out of a Google Drive folder and it is mentioned in Github Desktop when creating a new repository that "Google Drive can corrupt repositories".

What are the issues specifically and what can be done to avoid repositories being corrupted?

A: We've put that warning in place because we've seen quite a few users get their repositories corrupted by various cloud-backed storage solutions such as Google Drive and Dropbox.
The problem boils down to a race condition where Git creates and modifies files rapidly and the storage solution trying to keep up. In some scenarios this can lead to file IO not behaving as Git expects. A storage solution might also erroneously restore a file that was meant to be removed. While these sort of issues are most likely to occur when you're sharing the repository with other people we've seen issues with people who only use the storage for backup purposes.
The best way to backup Git repositories is to commit early and often and push your changes to GitHub frequently, even if you push them to work-in-progress branches rather than master or other long-running branches.
If you're not using GitHub or any other remote and your repository is local I'd recommend creating a bare repository inside your Google Drive and then clone your repository to a location outside of Google Drive and work from there. Whenever you've made changes you can push those to the bare repository. That way you'll have two copies of all your data in case the Google Drive version gets corrupted.

A: Google Drive already messed up my life two times (yes I needed to see the second to believe).
My solution to avoid forgetting push to a safe place I've created some automated tasks.
You can create a scheduled task to commit and push your changes every each X hours/days...etc. to one work-in-progress branche for example.
Using Unix based systems (Mac / Linux) you can use crontab.
First create one bash script, i.e: /home/myScripts/autoGit.sh
# add and commit changes
cd /home/myProject && /home/myGit commit -a -m "automated commit/push `date`"

# push git server
cd /home/myProject && /home/myGit push origin wip

Then you create your crontab job as needed:
crontab -e

then add the commands to the file
mailto: your@email.com
59 * * * 1,2,3,4,5 /home/myScripts/autoGit.sh

This will commit and push your repo every each 59 minutes on mon,tue,wed,thu,fri.
Hope it helps

A: (Google Drive File Stream user)
I am currently having this problem, and the solution I found was having my git repositories in a non-synced hard disk, and then create a mirror folder for each one inside the GoogleFileStream Drive, which gets copied every time I execute a .bat script, with the robocopy command (Windows).
robocopy "\\Git\to\repo1\nonsynced" "\\Mirror\target\git\repo1\to\sync" /E /MIR
robocopy "\\Git\to\repo2\nonsynced" "\\Mirror\target\git\repo2\to\sync" /E /MIR
I perform the commits and pushes as usual, and run the script to sync with drive. This can be automated with a FolderMonitor script, or task scheduler command.


text:
Q: Stopping a postgresql instance For the sake of educational purposes I  have two identical instances of postgresql running on my machine.
I can easily stop the service of the instance that is running on port 5432 like this :
sudo service postgresql stop

What I like to know is that how I can stop the other instance (it is running on port 5433)

A: Use systemctl
sudo systemctl stop postgresql

A: pg_ctl is the postreSQL way to stop postgreSQL (in Ubuntu and Debian we should use pg_ctlcluster which is a wrapper for pg_ctl). The example in that link uses option `-p 5433".
As suggested by naoko in the comments below, use pg_lsclusters to list clusters.
Another way is to give a kill signal to the process running postgresqld. To stop both at once, killall postgresqld might work.
Finally as suggested in the comment by psyCHOder, pgAdmin can also stop the server, but of course that means installing that package.

A: In Ubuntu use systemctl:
:~/github/kafka/postgres-kafka-demo$ pg_lsclusters
Ver Cluster Port Status Owner    Data directory              Log file
12  main    5432 online postgres /var/lib/postgresql/12/main /var/log/postgresql/postgresql-12-main.log

:~/github/kafka/postgres-kafka-demo$ sudo -u postgres pg_ctlcluster 12 main stop
[sudo] password for :

Warning: stopping the cluster using pg_ctlcluster will mark the systemd unit as failed. Consider using systemctl:
sudo systemctl stop postgresql@12-main
:~/github/kafka/postgres-kafka-demo$ sudo systemctl stop postgresql@12-main

:~/github/kafka/postgres-kafka-demo$ pg_lsclusters
Ver Cluster Port Status Owner    Data directory              Log file
12  main    5432 down   postgres /var/lib/postgresql/12/main /var/log/postgresql/postgresql-12-main.log

A: You can run
sudo systemctl stop postgresql[@version-main]

For example, if you are trying to stop version 10 run
sudo systemctl stop postgresql@10-main

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change border color in TextBox C# I have the following code:
public class OurTextBox : TextBox
{
    public OurTextBox()
        : base()
    {
        this.SetStyle(ControlStyles.UserPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
         base.OnPaint(e);
         Pen penBorder = new Pen(Color.Gray, 1);
         Rectangle rectBorder = new Rectangle(e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.Width - 1, e.ClipRectangle.Height - 1);
         e.Graphics.DrawRectangle(penBorder, rectBorder);
   }
}

This is working perfectly, but it doesn't show the text until it gets focus.
Can anybody help me? What is wrong?

A: You have to draw text manually as well.
protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    Pen penBorder = new Pen(Color.Gray, 1);
    Rectangle rectBorder = new Rectangle(e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.Width - 1, e.ClipRectangle.Height - 1);
    e.Graphics.DrawRectangle(penBorder, rectBorder);

    Rectangle textRec = new Rectangle(e.ClipRectangle.X + 1, e.ClipRectangle.Y + 1, e.ClipRectangle.Width - 1, e.ClipRectangle.Height - 1);
    TextRenderer.DrawText(e.Graphics, Text, this.Font, textRec, this.ForeColor, this.BackColor, TextFormatFlags.Default);
}

Alternatively you can try to use e.Graphics.DrawString() method if TextRenderer is not giving you desired results (I always have better results with this approach thou).

A: To change border color of TextBox you can override WndProc method and handle WM_NCPAINT message. Then get the window device context of the control using GetWindowDC because we want to draw to non-client area of control. Then to draw, it's enough  to create a Graphics object from that context, then draw border for control.
To redraw the control when the BorderColor property changes, you can use RedrawWindow method.
Code
Here is a TextBox which has a BorderColor property. The control uses BorderColor if the property values is different than Color.Transparent and BorderStyle is its default value Fixed3d.
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public class MyTextBox : TextBox {
    const int WM_NCPAINT = 0x85;
    const uint RDW_INVALIDATE = 0x1;
    const uint RDW_IUPDATENOW = 0x100;
    const uint RDW_FRAME = 0x400;
    [DllImport("user32.dll")]
    static extern IntPtr GetWindowDC(IntPtr hWnd);
    [DllImport("user32.dll")]
    static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
    [DllImport("user32.dll")]
    static extern bool RedrawWindow(IntPtr hWnd, IntPtr lprc, IntPtr hrgn, uint flags);
    Color borderColor = Color.Blue;
    public Color BorderColor {
        get { return borderColor; }
        set { borderColor = value;
            RedrawWindow(Handle, IntPtr.Zero, IntPtr.Zero,
                RDW_FRAME | RDW_IUPDATENOW | RDW_INVALIDATE);
        }
    }
    protected override void WndProc(ref Message m) {
        base.WndProc(ref m);
        if (m.Msg == WM_NCPAINT && BorderColor != Color.Transparent &&
            BorderStyle == System.Windows.Forms.BorderStyle.Fixed3D) {
            var hdc = GetWindowDC(this.Handle);
            using (var g = Graphics.FromHdcInternal(hdc))
            using (var p = new Pen(BorderColor))
                g.DrawRectangle(p, new Rectangle(0, 0, Width - 1, Height - 1));
            ReleaseDC(this.Handle, hdc);
        }
    }
    protected override void OnSizeChanged(EventArgs e) {
        base.OnSizeChanged(e);
        RedrawWindow(Handle, IntPtr.Zero, IntPtr.Zero,
               RDW_FRAME | RDW_IUPDATENOW | RDW_INVALIDATE);
    }
}

Result
Here is the result using different colors and different states. All states of border-style is supported as you can see in below image and you can use any color for border:

Download
You can clone or download the working example:

*

*Download Zip

*Github repository

A: There are several ways to do this and none are ideal. This is just the nature of WinForms. However, you have some options. I will summarise:
One way you can achieve what you want is by embedding a TextBox in a Panel as follows.
public class BorderedTextBox : Panel
{
    private TextBox textBox;
    private bool focusedAlways = false;
    private Color normalBorderColor = Color.Gray;
    private Color focusedBorderColor = Color.Red;

    public BorderTextBox()
    {
        this.DoubleBuffered = true;
        this.Padding = new Padding(2);

        this.TextBox = new TextBox();
        this.TextBox.AutoSize = false;
        this.TextBox.BorderStyle = BorderStyle.None;
        this.TextBox.Dock = DockStyle.Fill;
        this.TextBox.Enter += new EventHandler(this.TextBox_Refresh);
        this.TextBox.Leave += new EventHandler(this.TextBox_Refresh);
        this.TextBox.Resize += new EventHandler(this.TextBox_Refresh);
        this.Controls.Add(this.TextBox);
    }

    private void TextBox_Refresh(object sender, EventArgs e)
    {
        this.Invalidate();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        e.Graphics.Clear(SystemColors.Window);
        using (Pen borderPen = new Pen(this.TextBox.Focused || FocusedAlways ?
            focusedBorderColor : normalBorderColor))
        {
            e.Graphics.DrawRectangle(borderPen,
                new Rectangle(0, 0, this.ClientSize.Width - 1, this.ClientSize.Height - 1));
        }
        base.OnPaint(e);
    }

    public TextBox TextBox
    {
        get { return textbox; }
        set { textbox = value; }
    }

    public bool FocusedAlaways
    {
        get { return focusedAlways; }
        set { focusedAlways = value; }
    }
}

You can also do this without overriding any controls, but the above method is better. The above will draw a border when the control gets focus. if you want the border on permanently, set the FocusedAlways property to True.
I hope this helps.

A: set Text box Border style to None
then write this code to container form "paint" event
    private void Form1_Paint(object sender, PaintEventArgs e)
        {
System.Drawing.Rectangle rect = new Rectangle(TextBox1.Location.X, TextBox1.Location.Y, TextBox1.ClientSize.Width, TextBox1.ClientSize.Height);

                rect.Inflate(1, 1); // border thickness
                System.Windows.Forms.ControlPaint.DrawBorder(e.Graphics, rect, Color.DeepSkyBlue, ButtonBorderStyle.Solid);

}


text:
Q: NSLocationAlwaysUsageDescription does not appear in the list I want to add a NSLocationAlwaysUsageDescription to Info.plist , but does not come out in the list

A: Just try to manually enter the string in your info.plist, like editing a plan text.
In the end your list will look like this

A: I am assuming you mean that Xcode is not providing auto completion for that particular key when editing the project info. Which if that is the case, the yes, you will not see auto completion for either in use or always keys. You must manually enter them.
For some reason the Xcode team has not added those into whatever settings file is necessary to provide auto completion in the info lane of the project settings.


text:
Q: CSS Not Changing Svelte + Chota I have been learning Svelte for the past couple days and now I am trying to use it in combination with Chota. I am following the Chota docs instructions for dark mode but it won't change. In addition, if I add my own CSS it wont update. Here is my App.svelte:
<svelte:head>
    <link rel="stylesheet" href="https://unpkg.com/chota@latest">
</svelte:head>

    {name}

      Link 1
      Link 2

    Button

I have made sure that the code that adds the class is executing, and it is. I have added !important to the CSS yet it doesn't change anything.
EDIT:
I have been doing some more CSS testing and it seems that the :root selector works fine with variables (haven't tested with non-variables), but the body.dark selector doesn't even compile into the bundle.css file.

A: You should get an Unused CSS selector "body.dark" warning.
That's because by default all css inside the


text:
Q: How does Adam Smasher avoid becoming a cyberpsycho? In the Cyberpunk universe, over usage of implants eventually leads to one losing their humanity and becoming mindlessly violent cyberpsychos. However, there is one exception -- Adam Smasher has been almost full Borg for years and yet he retains his self-control and mental faculties. How did he achieve this feat?

A: According to the creator of the Cyberpunk game, he is a cyberpsycho, but not a normal one. As he explains:

Didn't say he wasn't. Theres a concept in psychology called "high
functioning." Adam is a high functioning cyberpsycho who happens to
have a job where they want him to kill people.

Of note, Adam's EMP (empathy) statistic, which when it goes too low leads to cyberpsychosis, is officially listed as "Yeah, right...".
Pondsmith further elaborated on the mechanism of cyberpsychosis in a way that sheds some light on Adam Smasher:

First of all, Cyberpsychosis is a disorder that in part depends on the
subject's overall internal susceptibility. Just like every person who
drinks a lot at parties doesn't end up an alcoholic in the gutter, not
everyone who gets loaded up on cyberware is going to automatically go
cyberpsycho. You have to have an inherent susceptibility, which (in
the TRPG) is represented by the player's Humanity Stat. Humanity is
not just a measure of one aspect of personality, but an overall
measure of several elements including the subject's ability to
emphasize and relate with others, their ability to absorb and rebound
from mental and physical stressors, their ability to show compassion
and flexibility to others, and whether they are able to balance their
worldview through other methods.
So, in some ways, I tend to treat cyberware as an addiction--heavy
anabolic steroid use being my favorite model. Not everyone who juices
ends up crazy mad with roid rage. But those who are more susceptible
to the need to take more steroids are more likely to hit a point where
they do flip into roid rage...
[...]
David's starting Humanity was probably already pretty high. And before
things went to crap, he had a loving mother, a career path, and no
more hassle than the average poor guy in a wealthy Ivy League school.
So he had lots of buffer. But even so, he still, even after losing all
that, was able to make friends, build a replacement family, and (after
some prompting) even get a girlfriend. And a mentor (Maine) to create
a supportive father figure. So he could definitely handle the stress
of added cyberware up to a point.
Most people in Night City don't have the level of Humanity to pull
this kind of stunt off without going cyberpsychotic. So David is one
in a million. And that's why Arasaka wants him.

In essence, everyone reacts differently to cybernetic implants. Adam Smasher is a cyberpsycho with an uncommon degree of self-control: all of the vicious impulses without the compulsion to act on them in any and every situation. Since he almost certainly did not start with a high level of Humanity (in game terms), his advantage was different—perhaps because he was already so cruel and vicious beforehand, he was better able to channel the cyberpsychosis.


text:
Q: Wrap items in a windows applications List View control Is there a way to make long items wrap in a .net windows forms application,  I have already got LabelWrap set to true, but it doesn't work, I am using Details View Type,
Thanks

A: ListView doesn't allow text-wrapping.
What I usually do is set "ShowItemToolTips" property true in such cases. Then user can see the whole text a ToolTip. This is the only simple option I can see with ListView to help in this case.
If you really want to support for text-wrapping you will have to either use a third party ListView or use a DataGridView.
EDIT
If you are using VS2010, Tile View is an option for you.

With the tile view feature of the ListView control, you can provide a
  visual balance between graphical and textual information. The textual
  information displayed for an item in tile view is the same as the
  column information defined for details view. Tile view works in
  combination with either the grouping or insertion mark features in the
  ListView control.

A: The LabelWrap property only works for icons (View types of LargeIcon or SmallIcon), not Details.  As others have already answered, you have to use DataGridView or a 3rd party listview such as ObjectListView.


text:
Q: Jquery validate: How to validate that all or none of a group of textboxes have values? I have a form consisting of a couple of dozen labels and textboxes. But for simplicity's sake, let's say I have only six such items:

    A-text
    <input type="text" id="input-A" name="A" required>

    B-text
    <input type="text" id="input-B" name="B" required>

    C-text
    <input type="text" id="input-C" name="C" required>

    D-text
    <input type="text" id="input-D" name="D" required>

    E-text
    <input type="text" id="input-E" name="E" required>

    F-text
    <input type="text" id="input-F" name="F" required>

And the rules are as follows:
If A has a value, then B must also have a value. And vice versa.
If C, D, E or F has a value, then every input has got to have a value.
A value here means "has text of length > 0". But in reality, I also check some validity (is it a number, is it a valid e-mail address, etc.)
I have tried to validate the first set of rules, the ones pertaining to A and B, but this does not work:
$("#myform").validate({
                rules: {
                    A: {
                        depends: function(element) {
                            ($("#input-A").val().length > 0) == ($("#input-B").val().length > 0);
                        }
                    }
                }
            });

My thinking is that the above "depends" statement should make sure that the page only validates if the function called returns True. But I can submit the form even if one of the text areas has text and the other doesn't.
Why is this, and what should I do instead?

A: Your code...
rules: {
    A: {
        depends: function(element) {
            ....
        }
    }
}

There is no such thing as a depends rule.
depends is a property that goes under an existing rule in order to "apply the rule only in certain conditions".
rules: {
    A: {
        required: {
            depends: function(element) {
                // return true or false here
            }
        }
    }
}

Whenever the depends function returns true, the associated required rule is activated.
That being said, the function/logic is flawed...
depends: function(element) {
    ($("#input-A").val().length > 0) == ($("#input-B").val().length > 0);
}

*

*You need a return statement.

*You can't use ($("#input-A").val().length > 0) as part of the depends function under required for input A because it will always evaluate to false.  It always starts off empty, right?  (Besides, it doesn't make sense to change the field's rule based upon the same field's own content... you'd probably never be able to satisfy this rule.)

Try something more like this...
rules: {
    A: {
        required: {
            depends: function(element) {
                return $("#input-B").is(':filled');
            }
        }
    },
    B: {
        required: {
            depends: function(element) {
                return $("#input-A").is(':filled');
            }
        }
    }
}

depends will return true if B is filled out and activate the required rule on A.  The same logic is applied to field B.
Working DEMO:  http://jsfiddle.net/t9y2x3jf/
NOTE:  You must remove any inline HTML5 required attributes from your input elements, otherwise, these will over-ride your depends logic.
<input type="text" id="input-A" name="A" />


text:
Q: Is there a way to "deallocate" id's that were allocated? Let's say I have allocated a block of IDs using the allocateIdRange method. Is there a way to undo this? I'm nervous about allocating large chunks of IDs without having a way to undo it and potentially/accidentally allocating a large range of IDs that will never be able to be allocated again.

A: Short Answer: No, it is not possible to deallocate Ids after using allocateIdRange method.
Long Answer: After a lot of testing with this method, I think it is not possible to "deallocate" those IDs. Even looking at the docs for Datastore or the docs for the App Engine API for any possible methods.
Since you're concerned about allocating a lot and then not able to allocate again them because those are already reserved, I'll just say that being careful is the best option since there is no built-in method in the libs to deallocate.

A: I haven't tried this personally, but I would just think you could do a delete on the keys to wanted to 'deallocate'. Just as if you were deleting an entity in general.


text:
Q: How to know who is the BigQuery view creator? There is a view in a BigQuery project, and nobody knows who has created it. Is there a way to get known who did it?
Thanks.

A: This is something you should be able to find in your project's audit logs.  You should look for the tables.insert call that created the view.
The view's creator is not stored as part of its metadata, so the BigQuery API doesn't return this value as a part of tables.get or any other API call.


text:
Q: Appwrite return 500 error when trying to add custom domain I get a 500 internal error when i try to add a custom domain to appwrite 1.2.0 server.
I have changed .env variable _APP_ENV and _APP_DOMAIN_TARGET to "api.example.com"
I have also followed manual ssl generation method here
When i navigate to my domain "api.example.com" i can access the console with no other issues and certificate in toolbar show connection secure certificate is valid.
However when i try to login to my app i get an error in console: Access to XMLHttpRequest at ... from origin 'https://www.mydomain.0r' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://localhost' that is not equal to the supplied origin.
I assume this is because i am unable to set the custom domain in appwrite console but cant figure out what is causing the 500 error


text:
Q: Block video requests on puppeteer I want to block(abort) all requests to video resources, how can I achieve it with puppeteer?
I see there is an example in the documentation:

An example of a naïve request interceptor that aborts all image requests:

page.on('request', interceptedRequest => {
    if (interceptedRequest.url().endsWith('.png') || interceptedRequest.url().endsWith('.jpg'))
      interceptedRequest.abort();
    else
      interceptedRequest.continue();
});

But I can't seem to find an example on how to block videos.
Only the response headers says the content-type and I don't want to waste the bandwidth for vain.

A: Great question, had the same issue myself.
The main problem is videos URLs don't have to end with a specific suffix and indeed they don't on many websites (YouTube for example).
But there this function:

request.resourceType()
Contains the request's resource type as it was perceived by the rendering engine. ResourceType will be one of the following: document, stylesheet, image, media, font, script, texttrack, xhr, fetch, eventsource, websocket, manifest, other.

A bit of Googling and found this MDN:

media
Resources loaded by a  <video> or  <audio> element.

And as I don't mind on blocking audio requests as well (thanks God, they are not in use in normal web pages...)
Eventually this is what I ended up doing:
page.on('request', request => {
  const url = request.url().toLowerCase()
  const resourceType = request.resourceType()

  if (resourceType == 'media' ||
    url.endsWith('.mp4') ||
    url.endsWith('.avi') ||
    url.endsWith('.flv') ||
    url.endsWith('.mov') ||
    url.endsWith('.wmv')) {

    console.log(`ABORTING: video`)
    request.abort();
  }
  else
    request.continue();
})


text:
Q: Como melhorar a formatação das informações dentro da minha Div? Senhores, preciso formatar minha Div de acordo com a imagem anexada abaixo, com informações de Meta sobre a Div, etc.
Atualmente meu código está quebrando essas informações em linhas, conforme imagem anexada.
Segue um trecho do meu código, espero que consigam me ajudar.

                APPLE

                META: <c:out value="${AP.rows[0].META}"/>

                REALIZADO: <c:out value="${AP.rows[0].REALIZADO}" />
/br>
                ACUMULADO: <c:out value="${AP.rows[0].ACUMULADO}" />

Como podem ver acima, tenho uma div principal e outra dentro da mesma.
Meu código acima quando executado retorna as informações da imagem abaixo.

Porém eu preciso que as informações fiquem de acordo com imagem abaixo, como consigo realizar essa alteração dentro

A: Gabriel existem vária formas de fazer isso.
Poderia ser da forma mais antiga e não recomendada com floats e clearfix ou até <tabel>. Ou com Flexbox e Grid que é o mais adequado hj em dia.
Eu fiz esse modelo usando o display:grid para montar o grid no pai, e o display:flex nos filhos para alinhar tudo no centro (essa parte do flex não é obrigatória, vc pode alinha com text-aling e line-height, fica a seu critério)
Segue o exemplo:

html,
body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
body {
    background-image: url(http://unsplash.it/g/380/160);
    background-size: cover;
}
.container {
    width: 380px;
    height: 160px;
    display: grid;
    grid-template-columns: 1fr 1fr;
}
.container div {
    border: 1px solid black;
    display: flex;
    justify-content: center;
    align-items: center;
}
.rel, .acu {
    grid-column: span 2;
    background-color: red;
}

Marca

Meta

Realizado

Acumulado


text:
Q: How to check if a file or directory exists without using fs.exists? The reason I ask, is because Node.js on ubuntu doesn't seem to have the fs.exists() function. Although I can call this when I run Node.js on my Mac, when I deploy to the server, it fails with an error saying the function does not exist.
Now, I am aware that some people consider it an "anti-pattern" to check if a file exists and then try and edit / open it etc, but in my case, I never delete these files, but I still need to check if they exist before writing to them.
So how can I check if the directory (or file) exists ?
EDIT:
This is the code I run in a file called 'temp.'s' :
var fs=require('fs');
fs.exists('./temp.js',function(exists){
    if(exists){
        console.log('yes');
    }else{
        console.log("no");
    }
});

On my Mac, it works fine. On ubuntu I get the error:
node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^ TypeError: Object #<Object> has no method 'exists'
    at Object.<anonymous> (/home/banana/temp.js:2:4)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:32)
    at Function._load (module.js:308:12)
    at Array.0 (module.js:479:10)
    at EventEmitter._tickCallback (node.js:192:41)

On my Mac - version : v0.13.0-pre
On Ubuntu - version : v0.6.12

A:
It's probably due to the fact that in NodeJs 0.6 the exists() method was located in the path module: http://web.archive.org/web/20111230180637/http://nodejs.org/api/path.html –  try-catch-finally

^^ That comment answers why it isn't there. I'll answer what you can do about it (besides not using ancient versions).
From the fs.exists() documentation:

In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it's not there.

You could do something like this:
fs.open('mypath','r',function(err,fd){
    if (err && err.code=='ENOENT') { /* file doesn't exist */ }
});

A: The accepted answer does not take into account that the node fs module documentation recommends using fs.stat to replace fs.exists (see the documentation).
I ended up going with this:
function filePathExists(filePath) {
  return new Promise((resolve, reject) => {
    fs.stat(filePath, (err, stats) => {
      if (err && err.code === 'ENOENT') {
        return resolve(false);
      } else if (err) {
        return reject(err);
      }
      if (stats.isFile() || stats.isDirectory()) {
        return resolve(true);
      }
    });
  });
}

Note ES6 syntax + Promises - the sync version of this would be a bit simpler. Also my code also checks to see if there is a directory present in the path string and returns true if stat is happy with it - this may not be what everyone wants.

A: The Sync methods don't have any way of notifying about an error. Except for exceptions! As it turns out, the fs.statSync method throws an exception when the file or directory doesn't exist. Creating the sync version is as easy as that:
  function checkDirectorySync(directory) {
  try {
    fs.statSync(directory);
  } catch(e) {
    try {
        fs.mkdirSync(directory);
    } catch(e) {
        return e;
    }
  }
}

And that's it.
Using is as simple as before:
checkDirectorySync("./logs");
//directory created / exists, all good.

[]´z


text:
Q: Reading a text file from implementation I am trying to create an implementation that reads a file that the user has typed and submitted. The code for that is located in the SetTester class (shown below). In my implementation I already have an array declared called String[] myArray = new String [] {}; to hold the data from the file. How would I be able to take the file that is being called in the tester class and put it into that array?
    public class SetTester
{
    public static void main(String [] args) {
        StringSet words = new MyStringSet();
        Scanner file = null;
        FileInputStream fs = null;
        String input;
        Scanner kb = new Scanner(System.in);
        int wordCt = 0;

        boolean ok = false;

        while (!ok)
        {
            System.out.print("Enter name of input file: ");
            input = kb.nextLine();
            try
            {
                fs = new FileInputStream(input);
                ok = true;
            }
            catch (FileNotFoundException e)
            {
                System.out.println(input + " is not a valid file.  Try again.");
            }
        }

        file = new Scanner(fs);
        while (file.hasNext())
        {
            input = file.next();
            words.insert(input);
            System.out.println("Current capacity: " + words.getCapacity());
            wordCt++;
        }

        System.out.println("There were " + wordCt + " words in the file");
        System.out.println("There are " + words.inventory() + " elements in the set");
        System.out.println("Enter a value to remove from the set: ");
        input = kb.nextLine();
        while (!words.contains(input))
        {
            System.out.println(input + " is not in the set");
            System.out.println("Enter a value to remove from the set: ");
            input = kb.nextLine();
        }

        words.remove(input);
        System.out.println("There are now " + words.inventory() + " elements in the set");
        System.out.println("The first 10 words in the set are: ");
        for (int x=0; x<10; x++)
            System.out.println(words.getFirstItem());
        System.out.println("There are now " + words.inventory() + " elements in the set");
        System.out.println("5 random words from the set are: ");
        for (int x=0; x<5; x++)
            System.out.println(words.getRandomItem());
        System.out.println("There are now " + words.inventory() + " elements in the set");
    }
}

A: For reading from a file I use this class:
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;

public class ReadFile {
    private static String path;

    public ReadFile(String file_path){
        path = file_path;
    }
    public String[] OpenFile() throws IOException {
        FileReader fr = new FileReader(path);
        BufferedReader textReader = new BufferedReader(fr);

        int numberOfLines = readLines();
        String[] textData = new String[numberOfLines];

        for (int j = 0; j < numberOfLines; j++) {
            textData[j] = textReader.readLine();
        }

        textReader.close();
        return textData;
    }
    static int readLines() throws IOException {
        FileReader file_to_read = new FileReader(path);
        BufferedReader bf = new BufferedReader(file_to_read);

        String aLine;
        int numberOfLines = 0;

        while((aLine = bf.readLine()) != null){
            numberOfLines++;
        }
        bf.close();
        return numberOfLines;
    }
}

then in the class main you can add this code and you edit the path so you can read a file an get an array out of it
public static void main(String args[]) throws IOException {
    ReadFile r = new ReadFile("here you put the path that the user provide");
    String[] text = r.OpenFile();
    ArrayList<String> array = new ArrayList<>();
    array.addAll(Arrays.asList(text));
}

If you have any questions let me know!


text:
Q: Pairwise value counts based on category column in Pandas I have datasets which look like

Each dataset corresponds to output of a clustering algorithm. Now I want to calculate, Number of times any pair of Names are occurring together
Example:
Pair John & Katie are occurring together in all datasets so their score would 3
Pair Paul & Ruth are occurring together in 2 datasets so their score would 2
Expected output:

I have tried taking outer joins but the code doesn't seem to work.

A: For ease of reference and to avoid errors due to differing names, I would first concatenate the three dataframes into one, so that it looks like this:
import pandas as pd

df = pd.DataFrame({'Name': ['John', 'Katie', 'Paul', 'Ruth', 'Emily', 'Monica'],
                   'Category1': ['A', 'A', 'B', 'B', 'C', 'C'],
                   'Category2': ['A', 'A', 'B', 'C', 'B', 'C'],
                   'Category3': ['A', 'A', 'A', 'A', 'B', 'B']})
df

    Name    Category1   Category2   Category3
0   John    A           A           A
1   Katie   A           A           A
2   Paul    B           B           A
3   Ruth    B           C           A
4   Emily   C           B           B
5   Monica  C           C           B

You can use the combinations function from the itertools module to get all possible pairs of names, as well as the corresponding pairs of categories. This is most conveniently done within a dictionary comprehension, so that you can directly create a new dataframe from it.
Then you just have to count the number of category pairs in each row for which both categories are the same.
from itertools import combinations

df_pairs = pd.DataFrame({col: combinations(df[col], 2) for col in df.columns})
df_pairs['Score'] = df_pairs.apply(lambda row: sum([int(pair[0] == pair[1])
                                                    for pair in row[1:]]), axis=1)
df_pairs

    Name            Category1   Category2   Category3   Score
0   (John, Katie)   (A, A)      (A, A)      (A, A)      3
1   (John, Paul)    (A, B)      (A, B)      (A, A)      1
2   (John, Ruth)    (A, B)      (A, C)      (A, A)      1
3   (John, Emily)   (A, C)      (A, B)      (A, B)      0
4   (John, Monica)  (A, C)      (A, C)      (A, B)      0
5   (Katie, Paul)   (A, B)      (A, B)      (A, A)      1
6   (Katie, Ruth)   (A, B)      (A, C)      (A, A)      1
7   (Katie, Emily)  (A, C)      (A, B)      (A, B)      0
8   (Katie, Monica) (A, C)      (A, C)      (A, B)      0
9   (Paul, Ruth)    (B, B)      (B, C)      (A, A)      2
10  (Paul, Emily)   (B, C)      (B, B)      (A, B)      1
11  (Paul, Monica)  (B, C)      (B, C)      (A, B)      0
12  (Ruth, Emily)   (B, C)      (C, B)      (A, B)      0
13  (Ruth, Monica)  (B, C)      (C, C)      (A, B)      1
14  (Emily, Monica) (C, C)      (B, C)      (B, B)      2


text:
Q: Where to place a nested union in a struct in C? I have an anonymous union nested within a struct, as well as other common fields. Is there any reason to place the union in a specific place within the struct (e.g. first or last)?
For example, is this:
typedef struct _Message
{
    MessageType type;
    union
    {
        SystemMessageArgs systemArgs;
        OtherMessageArgs usbArgs;
    };
} Message;

better than this:
typedef struct _Message
{
    union
    {
        SystemMessageArgs systemArgs;
        OtherMessageArgs usbArgs;
    };
    MessageType type;
} Message;

in any way?
The context is embedded-C, specifically TI's MSP430

A: There may be a possible difference in padding, you can find that out by using sizeof() on both of them and comparing the results. This may be relevant if you are dealing with heavily constrained memory amounts.
Other than that, they are equivalent.


text:
Q: Why does the binaryw. format behave differently above width 58? Consider the following program and output:
data _null_;
input a;
length b $64;
do i = 1 to 64;
  fmtname = cats('binary',i);
  b = cats(putn(a,fmtname));
  put i= b=;
end;
cards;
1
;
run;

Output (SAS 9.1.3, Windows 7 x64):
i=1 b=1
i=2 b=01
i=3 b=001
i=4 b=0001
i=5 b=00001
/*Skipped a few very similar lines*/
i=58 b=0000000000000000000000000000000000000000000000000000000001
i=59 b=11111110000000000000000000000000000000000000000000000000000
i=60 b=111111110000000000000000000000000000000000000000000000000000
i=61 b=1111111110000000000000000000000000000000000000000000000000000
i=62 b=11111111110000000000000000000000000000000000000000000000000000
i=63 b=011111111110000000000000000000000000000000000000000000000000000
i=64 b=0011111111110000000000000000000000000000000000000000000000000000

Last few lines of output from SAS 9.4 on Linux x64:
 i=60 b=000000000000000000000000000000000000000000000000000000000001
 i=61 b=1111111110000000000000000000000000000000000000000000000000000
 i=62 b=11111111110000000000000000000000000000000000000000000000000000
 i=63 b=011111111110000000000000000000000000000000000000000000000000000
 i=64 b=0011111111110000000000000000000000000000000000000000000000000000

This behaviour is rather unexpected, to me at least, and doesn't seem to be documented on the help page. It agrees with the document I found here for width 64 - standard double precision - but I don't understand why it flips over at width 59.

A: I don't quite get the same result - mine switches at 61 - but I believe the answer is the same.
Up to some point - 58, 60, somewhere around there - SAS is showing you the fixed-point integer representation of the number.  Test this with a decimal, like so:
data _null_;
a=3.14159265358979323846264338327950288419716939937510582;
length b $64;
put a= hex4.;
put a= hex8.;
put a= hex16.;
do i = 1 to 64;
  fmtname = cats('binary',i);
  b = cats(putn(a,fmtname));
  put i= b=;
end;
run;

And you will get a sort-of-surprising result - you see 000...0011 for most of your rows, up through 60.  The documentation doesn't explicitly mention this, but it does show it in the example (123.45 and 123 are identical in binary8.).
Then starting at 61, or 59 for you I'm guessing, you see the actual representation of the number as SAS internally stores it (or, arguably, how Intel internally stores it).
The binary documentation doesn't explain this well, but the HEX. documentation does explain it pretty clearly in a tip:

If w< 16, the HEXw. format converts real binary numbers to fixed-point integers before writing them as hexadecimal characters. It also writes negative numbers in two's complement notation, and right aligns digits. If w is 16, HEXw. displays floating-point values in their hexadecimal form.

Binary is doing the same, and on my machine it happens right at the point HEX would also make the change - at 15x4=60.  And HEX. shows the same - notice below; hex4. and hex8. show a different result than hex16..
To be clear, the value shown at binary64. is correct, and not any sort of truncation (though 61-63, and in your example 59-60, are left-truncated).

I did find a SAS usage note regarding this, though it's clearly out of date based on our tests:

Beginning with SAS® Version 7, the BINARYw. format was changed to be more consistent with the HEXw. format. When the HEXw. format uses a width of 16, (corresponding to 8 bytes of data), it produces a hexadecimal representation of the floating point value. The BINARYw. format changed so that widths of 57-64 produce a binary representation of the floating point value, since widths of 57-64 correspond to 8 bytes of data.

It also contains a suggestion for how to get consistent results for integers, which may be of use.

BIN_64=PUT(PUT(VALUE,S370FIB8.),$BINARY64.);

S370FIB8. is a format that converts numbers to their fixed integer binary representation, in IBM Mainframe format.  (I.e., it writes the integer in Big-Endian format, which is not what you'd get on an Intel machine.)


text:
Q: A way to include paths dynamically in php? I have structured a server with this file and folders:
index.php
|lib -> lib.php
|framework -> fw.php
|folderA -> index2.php

In lib.php there is functionA() with a require_once inside that calls "fw.php" correctly from index2.php:
functionA(){
    require_once "../framework/fw.php";
    //other stuff...
}

if it's called from index.php, the path must be changed.
I really need a method to include paths dynamically without setting up a specific code inside every page.
Does exist a method to fix the path?
I tried to use __FILE__, dirname()...but without a satisfied solution.

A: You might have to tweak this to get it to work depending on how your path is set up ... but for most standard setups this will work.
$basepath = substr($_SERVER['DOCUMENT_ROOT'], 0, strrpos($_SERVER['DOCUMENT_ROOT'], '/')).
'/framework/';

require_once($basepath.'fw.php');

A: If using php 5.3+ you can use the magic constant __DIR__
functionA(){
    require_once __DIR__."/../framework/fw.php";
    //other stuff...
}

This will take the path of the functionA of lib/lib.php and go from there even if lib.php is included in index.php or anywhere.
And for previous PHP versions:
dirname(__FILE__)


text:
Q: Error at "java.lang.reflect.InvocationTargetException" I have encountered a problem at Android Studio when I just imported a project,
the sources is no problem I think,because it can be run at other computer.
But I just can't find a way to solve this error.
Error:Android Dex: [appPortal] Exception in thread "main" java.lang.reflect.InvocationTargetException
Error:Android Dex: [appPortal] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Error:Android Dex: [appPortal] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
Error:Android Dex: [appPortal] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Error:Android Dex: [appPortal] at java.lang.reflect.Method.invoke(Method.java:606)
Error:Android Dex: [appPortal] at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:130)
Error:Android Dex: [appPortal] Caused by: java.lang.UnsupportedClassVersionError: com/android/dx/command/dexer/Main : Unsupported major.minor version 52.0
Error:Android Dex: [appPortal] at java.lang.ClassLoader.defineClass1(Native Method)
Error:Android Dex: [appPortal] at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
Error:Android Dex: [appPortal] at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
Error:Android Dex: [appPortal] at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
Error:Android Dex: [appPortal] at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
Error:Android Dex: [appPortal] at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
Error:Android Dex: [appPortal] at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
Error:Android Dex: [appPortal] at java.security.AccessController.doPrivileged(Native Method)
Error:Android Dex: [appPortal] at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
Error:Android Dex: [appPortal] at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
Error:Android Dex: [appPortal] at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
Error:Android Dex: [appPortal] at org.jetbrains.android.compiler.tools.AndroidDxRunner.loadDex(AndroidDxRunner.java:75)
Error:Android Dex: [appPortal] at org.jetbrains.android.compiler.tools.AndroidDxRunner.runDex(AndroidDxRunner.java:128)
Error:Android Dex: [appPortal] at org.jetbrains.android.compiler.tools.AndroidDxRunner.main(AndroidDxRunner.java:294)
Error:Android Dex: [appPortal] ... 5 more


text:
Q: Can't select data of Kendo Multiselect using Tab key press I am able to select Data listed into Kendo Multiselect by pressing 'Enter' button or by selecting it using 'Mouse click'. But can't select it by pressing 'TAB' key

A: You can select Value in multiselect on pressing 'TAB' key using HTML helper provided by kendo as .HighlightFirst(true)
that you can implement with your Kendo Autocomplete as:
                    @(Html.Kendo().AutoComplete()
                          .Name("User")
                          .DataTextField("UserName")
                          .Filter("contains")
                          .HighlightFirst(true)
                          .MinLength(2)
                          .DataSource(source =>
                          {
                              source.Read(read =>
                              {
                                  read.Action("GetUsers", "GetData");
                              }).ServerFiltering(true);
                          })
                    )

This will select First Value in Autocomplete and you can choose & press TAB key for selection of result.


text:
Q: Which version of CDH using Cloudera Manager automatically Installs JDK1.7? I am using Cloudera Manager with CDH4.2.2 for my 3+1 cluster. On starting the installation with cloudera manager, it automatically downloads and installs JDK1.6. I want to use JDK1.7 with CDH for my convinience. Is it possible or is there any version of CDH which while installating Hadoop in the cluster automatically downloads and installs and successfully runs Hadoop with JDK1.7?
If yes, may I know which version of CDH is it and where do i get to download it from?
I want to work with JDK1.7 instead of 1.6 because i want to install Apache Giraph on CDH but it seems Giraph does not fit fine with JDK1.6 and needs the JDK1.7.
With Regards,

A: JDK 1.7 is supported for all CDH applications as of CDH 4.4 and Cloudera Manager 4.7.
That being said, no version of Cloudera Manager 4.x installs JDK 1.7 during the installation (latest version is 4.8.2).  The only version of Cloudera Manager that installs JDK 1.7 automatically is 5.0.0.
To summarize:  If you want an automated installation of JDK 1.7 via Cloudera Manager, you need to upgrade to CDH 5, and CM 5.0.0.  Alternatively, you could upgrade to CDH4.4, and then perform a manual installation of JDK 1.7.


text:
Q: Tailwind style not applied with Angular 13 Hi everyone I was trying to implement Tailwind in angular, I installed tailwindcss post css and autoprefixer

{
  "name": "ip-tracker",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~13.0.0",
    "@angular/common": "~13.0.0",
    "@angular/compiler": "~13.0.0",
    "@angular/core": "~13.0.0",
    "@angular/forms": "~13.0.0",
    "@angular/platform-browser": "~13.0.0",
    "@angular/platform-browser-dynamic": "~13.0.0",
    "@angular/router": "~13.0.0",
    "leaflet": "^1.7.1",
    "rxjs": "~7.4.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~13.0.1",
    "@angular/cli": "~13.0.1",
    "@angular/compiler-cli": "~13.0.0",
    "@types/jasmine": "~3.10.0",
    "@types/node": "^12.11.1",
    "autoprefixer": "^10.4.2",
    "jasmine-core": "~3.10.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "postcss": "^8.4.6",
    "tailwindcss": "^2.1.2",
    "typescript": "~4.4.3"
  }
}

and I imported the styles in the style.scss file:
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

and here is my tailwind.config.js file:
module.exports = {
  mode: "jit",
  purge: {
    enabled: true,
    content: ["./src/**/*.{html,ts}"],
  },
  darkMode: false,
  theme: {
    extend: {},
    screens: {
      sm: "375px",
      lg: "1440px",
    },
    colors: {
      "very-dark-grey": "hsl(0, 0%, 17%)",
      "dark-grey": "hsl(0, 0%, 59%)",
    },
    fontFamily: {
      sans: ["Rubik", "sans-serif"],
    },
  },
  plugins: [
    require("postcss-import"),
    require("tailwindcss"),
    require("autoprefixer"),
  ],
};

but when I use one of the tailwind classes I don't see the style applied to the elements:

Test

Can anyone tell me where am I wrong and why?
Thanks so much...

A: I can't able to figure out the issue. But I tried with the same configuration that you posted above in my tailwind.config.js file. It works fine for me.
My tailwind.config.js file
module.exports =[ {
  mode: "jit",
  purge: {
    enabled: true,
    content: ["./src/**/*.{html,ts}"],
  },
  darkMode: false,
  theme: {
    extend: {},
    screens: {
      sm: "375px",
      lg: "1440px",
    },
    colors: {
      "very-dark-grey": "hsl(0, 0%, 17%)",
      "dark-grey": "hsl(0, 0%, 59%)",
    },
    fontFamily: {
      sans: ["Rubik", "sans-serif"],
    },
  },
  plugins: [
    require("postcss-import"),
    require("tailwindcss"),
    require("autoprefixer"),
  ]
}]

My Package.json file
{
  "name": "tailwind-app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~13.0.0",
    "@angular/common": "~13.0.0",
    "@angular/compiler": "~13.0.0",
    "@angular/core": "~13.0.0",
    "@angular/forms": "~13.0.0",
    "@angular/platform-browser": "~13.0.0",
    "@angular/platform-browser-dynamic": "~13.0.0",
    "@angular/router": "~13.0.0",
    "rxjs": "~7.4.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~13.0.0",
    "@angular/cli": "~13.0.0",
    "@angular/compiler-cli": "~13.0.0",
    "@types/jasmine": "~3.10.0",
    "@types/node": "^12.11.1",
    "autoprefixer": "^10.4.2",
    "jasmine-core": "~3.10.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "postcss": "^8.4.6",
    "tailwindcss": "^2.1.2",
    "typescript": "~4.4.3"
  }
}

styles.css

My app.component.html

Output

A: To create custom styles, in tailwind.config.js extend object must be added to theme. Inside extend a colors object is added, where its key-value is the name of the custom color and its corresponding value
...
theme: {
    extend: {
        colors: {
            "very-dark-grey": "hsl(0, 0%, 17%)",
            "dark-grey": "hsl(0, 0%, 59%)",
        },
    },
...


text:
Q: Python: single instance of program on Windows using mutexes I create an executable using py2exe in python.
I was looking at this post but unfortunately the answers were superficial.
The first solution using Tendo but this works to limit 1 instance of application per user, and my app is being used in a Windows Server Environment where there are 20+ users loged in at a time.
And the second solution offered Listening to a defined port doesn't have examples of how it could be accomplished.
So I decided to go for mutexes to prevent my app from running multiple times.
So I currently use this code for using mutexes, but it doesn't have mutex detection between applications and Services.
This post shows how to accomplish mutexes, but doesn't show how its done in python.
How could I use Mutexes to have single instance of program on Windows where the mutexes don't limit single instance of program on Windows, and has detection between applications and Services.

A: I'm not sure why you'd have to use mutexes to this purpose on Windows? There's much simpler option: a bad old lockfile.
If all you want to achieve is making sure that only a single instance of the app runs, you could do something like this:
Windows supports you here since you can't delete a file if it's opened by another process. So (code untested):
tempdir = tempfile.gettempdir()
lockfile = os.sep.join([tempdir, 'myapp.lock'])
try:
    if os.path.isfile(lockfile):
        os.unlink(lockfile)
except WindowsError as e: # Should give you smth like 'WindowsError: [Error 32] The process cannot access the file because it is being used by another process..'
    # there's instance already running
    sys.exit(0)

with open(lockfile, 'wb') as lockfileobj:
    # run your app's main here
    main()
os.unlink(lockfile)

with section ensures the file is opened when your main runs and it is closed when your main finishes running. Then os.unlink removes the lockfile.
If another instance tries to start up, it exits on WindowsError exception (it would be good to check its numeric code though to be sure it's precisely the case of the file already opened).
Above is a rough solution, a niftier one would be to use entry/exit functionality to delete lockfile if main exits for any reason. Explanation here: http://effbot.org/zone/python-with-statement.htm


text:
Q: Within- and between-group variance does not add up to the total variance The variance is additively decomposable (Shorrocks 1982). That is, when decomposing it into within- and between-group components, the within and between-group component should add up to the total variance.
Empirically, however, it does not always seem to be the case, especially in smaller samples. Here an example (written in R):
# Income data from East and West (sample size of the two groups is the same)
East <- c(60,60,90)
West <- c(30,30,130)

# Within- and between-group variance
VarW <- 1/2 * (var(East) + var(West))
VarB <- 1/2 * (((mean(East)-mean(c(East, West)))^2) + ((mean(West)-mean(c(East, West)))^2))

# Total variance
VarT <- var(c(East, West))

# The sum of within and between-group variance and the total variance are not the same
VarW+VarB # 1828
VarT # 1467

I wonder in which circumstances do they / don't they add up.


text:
Q: Can I construct a logic AND on a "power" line I have two 12W LED bulbs which are wired in parallel. I control them both with a MOSFET (M1.) Now I want to be able to dim one of the bulbs, but it should still only light up when the "original" MOSFET M1 is on.

simulate this circuit – Schematic created using CircuitLab
Would it be possible to construct such an AND gate on a power line? I mean I'm not sure if this can be considered a power line but 1A is definitely not logic current.

A: This should work fine.

*

*M1 on, M2 source is GND, M2 switches on with PWM

*M1 off, M2 source is pulled to 12V via LAMP1, so M1 can never turn on

Just be mindful of the max Vgs your FETs can allow. M2 can have as much as -12V Vgs when M1 is off. The IRLZ44N FET shown has a max Vgs of +/-16V so it's ok; another FET might not be (many are +/-10V.) This limit will be found in "Absolute Maximum Ratings" in the datasheet.


text:
Q: WPF Событие Drop вызывается для родительского и дочернего itemscontrol при перетаскивании в дочерний Я делаю проект в WPF, где пользователь может создавать форму заявления перетаскивая элементы внутрь itemscontrol'а, так же у меня есть контрол "группа", который состоит из itemscontrol и label, который может хранить различные элементы. Когда я перетаскиваю элемент в группу, событие Drop вызывается в у группы, и у главного itemscontrol'а и элемент добавляется сразу в два itemscontrol'а. Кажется, что дочерний элемент передает событие Drop в родительский. Как сделать чтобы событие Drop вызывалось именно в элементе, в который происходит перетаскивание?
Пример:

A: Попробуй
e.Handled = true

поставить в OnDrop.
Таким образом эвент не будет всплывать т.к. он является bubbling event.
Если не получится - попробуй добавить эвент DragOver и там e.Handled выставить в true.


text:
Q: What's the easiest way to replace categorical columns of data with codes in Pandas? I have a table of data in .dta format which I have read into python using Pandas. The data is mostly in the categorical data type and I want to replace the columns with numerical data that can be used with machine learning, such as boolean (1/0) or codes. The trouble is that I can't directly replace the data because it won't let me change the categories, unless I add them.
I have tried using pd.get_dummies(), but it keeps returning an error:
TypeError: 'columns' is an invalid keyword argument for this function
print(pd.get_dummies(feature).head(), columns=['smkevr', 'cignow', 'dnnow',
                                               'dnever', 'complst'])

Is there a simple way to replace this data with numerical codes based on the value (for example 'Not applicable' = 0)?

A: I do it the following way:
df_dumm = pd.get_dummies(feature).head()
df_dumm.columns = ['smkevr', 'cignow', 'dnnow',
                   'dnever', 'complst']
print (df_dumm.head())


text:
Q: how can I open the project folder after cloning it with https using github I am using deepin 15,5 but how can I know the repository folder after cloning it with https and the command was
git clone

A: Assuming this is a follow-up to your previous question,
cd dde-dock

will change to the cloned repository. It's the last part of the cloned URL.


text:
Q: Firebase onFinalize doesn't trigger for functions emulator I'm setting up the env for local development and just testing to see if the emulators are working but my simple test is failing without any errors.
// functions/index.js
exports.pdftoimg = functions.storage.object().onFinalize(async (object) => {
  console.log({ object });
});

Emulators start without issues:
firebase emulators:start
i  emulators: Starting emulators: auth, functions, firestore, hosting, pubsub, storage
✔  functions: Using node@16 from host.
i  hosting: Serving hosting files from: dist
✔  hosting: Local server: http://localhost:5002
i  functions: Watching "/Users/xxx/Code/myApp/functions" for Cloud Functions...
✔  functions[us-central1-pdftoimg]: storage function initialized.

┌─────────────────────────────────────────────────────────────┐
│ ✔  All emulators ready! It is now safe to connect your app. │
│ i  View Emulator UI at http://localhost:4000                │
└─────────────────────────────────────────────────────────────┘

But when I upload a test pdf file to storage emulator using the UI (http://localhost:4000/storage/default-bucket) nothing is displayed in the logs.
I tested the cloud triggers for Firestore Db but that seems to work though.
What am I missing?
Thanks

A: I can see you are Triggering a Cloud Function on Cloud Storage Changes that returns the uploaded object metadata.
However, this function does not upload the file:

onFinalize Sent when a new object (or a new generation of an existing object) is successfully created in the bucket. This includes copying or rewriting an existing object. A failed upload does not trigger this event.

In that case please follow the documentation provided to Upload Files.
Finally, adding Error Handling to your code will help you the next time as in this case you have no logs or anything to debug the error.
Update:
This issue onFinalize trigger not working in emulator, that uses the same Cloud Functions with the same results. We have to wait for support on that.
After some research a colleague found this github issue that uses the same documentation and the same methods you are using.
The first one describes how 'onFinalize' is triggered even on failed upload: and also redirects to the documentation that was mentioned above. In this case the function is triggered when it's not supposed to, you can try executing it like this.


text:
Q: Is it possible to insert a small matrix in to a big matrix in to a desired location? I have to insert a small matrix into a big matrix (zeros matrix), I was trying through a loop, but every time I am getting the value error: could not broadcast the input array from the shape (6,6) into shape (4,4)
there are two issues:-

*

*how to insert it into the zeros matrix. (specifying the location into the big zeros matrix).

*how to put that matrix, from the 23rd row of the 40*40 zeroes matrix.

import numpy as np

ndofs = 39

k = np.array(  [  [   1,         0,        1,       0,          0,          0 ],
                  [   0,         12,       6,       0,        -12,          6 ],
                  [   0,         6 ,       4,       0,         -6,          2 ],
                  [   1,          0,       0,       1,          0,          0 ],
                  [   0,        -12,      -6,       0,         12,          6 ],
                  [   0,          6,       2,       0,         -6,          4 ] ] )

K = np.zeros((ndofs+1,ndofs+1))
print(K.shape)

# for each element, changes to global coordinates

for i in range(ndofs):
    K_temp = np.zeros((ndofs+1,ndofs+1))
    K_temp[3*i:3*i+6, 3*i:3*i+6] = k
    K  += K_temp

print(K)

A: you just overwrite the indexes in the bigger array...
a = numpy.zeros((50,50))
b = numpy.ones((10,10))
a[2:12,2:12] = b # insert b at 2,2


text:
Q: achemso package in suppinfo mode does not show Contents I am writing a JACS communication Supporting Information in Latex using achemso package where the manuscript type set to suppinfo.
\documentclass[journal=jacsat,manuscript=suppinfo]{achemso}

I am then calling for the contents (sections and subsections) with:
\tableofcontents

As here in the simplified form
\documentclass[journal=jacsat,manuscript=suppinfo]{achemso}
\title{Title goes here}

\begin{document}

\tableofcontents

\section{Header 1}
\subsection{Header 1.1}
\subsection{Header 1.2}
\subsection{Header 1.3}
\subsection{Header 1.4}
\section{Header 3}
\section{Header 4}
\section{Header 5}
\section{Header 6}

\end{document}

But I get an empty contents section
How can I fix that?

A: The standard settings used unnumbered sections for supinfo: these are not written to the .toc file. You need to add
\SectionNumbersOn

before \begin{document} to reactivate them.


text:
Q: How do I show that if $A$ is compact and $U \supseteq A$ is open, then there is an open $V$ with $A \subseteq V \subseteq \overline{V} \subseteq U$? This question is from Wayne Patty's Topology Section 5.2.

Consider $A$ be a compact subset of a regular space and let $U$ be an open set such that $A\subseteq U$. Prove that there is an open set $V$ such that $A \subseteq  V \subseteq \overline{V} \subseteq U$.

Let $p \in A$ which implies $p \in U$. Then a result is given in   the book (Theorem 5.11): A $T_1$-space $(X, \mathcal T)$ is regular if and only if for each member $p$ of $X$ and each neighbourhood $U$ of $p$, there is a neighbourhood $V$ of $p$ such that $\overline{V}\subseteq U$. So, I got $ V \subseteq \overline{V} \subseteq U$.
But I am unable to prove that $A\subseteq V \subseteq \overline{V}$. I thought that I should let $V\subseteq \overline{V} \subseteq A$ but I am not able to find a contradiction.
Can you please help with that?


text:
Q: How do i build react-native application avoiding the many breaking changes that lead to failure? i just created a new react-native app using npx create-react-native-app myapp which was successfully created. but when i try to build it using gradlew assembleRelease, i get this error
FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:compileReleaseJavaWithJavac'.
> Failed to find Platform SDK with path: platforms;android-30

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.8/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 43s

it appears like theres a gradle problem. how do i fix it?

A: the perfect way to build react native apps ive found is using the command `assembleRelease'. this builds your code and gives you an apk


text:
Q: Magento2 : Add Category Attribute Dropdown I want to Create Category Attribute With Drop down
Drop down options are all list of Product Attributes
like http://prntscr.com/juglsn :
I tried but it didn't works
1.In setup file
$eavSetup -> addAttribute(\Magento\Catalog\Model\Category :: ENTITY, 'cat_attr1', [
    'type' => 'int',
    'label' => 'Attribute 1',
    'input' => 'select',
    'source' => 'Xx\Yy\Model\Config\Source\ProductAttributes',
    'required' => false,
    'sort_order' => 130,
    'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
    'group' => 'Product Attribute Info',
    "default" => "",
    "class"    => "",
    "note"       => ""
]);

2. Incategory_form.xmlfile
<field name="cat_attr1">
    <argument name="data" xsi:type="array">
        <item name="options" xsi:type="object">Xx\Yy\Model\Config\Source\ProductAttributes</item>
        <item name="config" xsi:type="array">
            <item name="sortOrder" xsi:type="number">130</item>
            <item name="dataType" xsi:type="string">string</item>
            <item name="formElement" xsi:type="string">select</item>
            <item name="label" xsi:type="string" translate="true">Attribute 1</item>

            <item name="notice" xsi:type="string" translate="true"></item>
             <item name="additionalClasses" xsi:type="string"></item>
        </item>
    </argument>
</field>

3. inProductAttributes.phpfile

namespace Xx\Yy\Model\Config\Source;

class ProductAttributes extends
\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{

    protected $productModel;

    public function __construct(
        \Magento\Catalog\Model\Product $productModel
    )
    {
        $this->_productModel = $productModel;
    }

    public function getAllOptions(){

     $productAttributes = $this->_productModel->getAttributes();

     $productAttribute = [];
     foreach ($productAttributes as $attribute) {
        $productAttribute[$attribute->getAttributeCode()]= $attribute->getFrontendLabel();
     }
      return $productAttribute;
    }

}

When I check In backend I show Loader only when  I Open category Tab

A: We have to customize convert the below functionality toOptionArray and add in Catalog Configuration.
Vendor\Config\Model\Config\Source\ProductAttributes
public function __construct(
    \Magento\Catalog\Model\Product $productModel
)
{
    $this->_productModel = $productModel;
}

public function toOptionArray()
{

    $productAttributes = $this->_productModel->getAttributes();
    $productAttribute = [];
    foreach ($productAttributes as $attribute) {
        $productAttribute[] = [ 'value' => $attribute->getAttributeCode(), 'label' => $attribute->getFrontendLabel() ];
    }
    return $productAttribute;
}

Vendor/Module/view/adminhtml/ui_component/catalog_form.xml
<fieldset name="general">
    <field name="cat_prod_attr" sortOrder="40" formElement="select">
            <settings>
                <dataType>string</dataType>
                <label translate="true">Product Attribute Name</label>
            </settings>
            <formElements>
                <select>
                    <settings>
                        <options class="Vendor\Module\Model\Config\Source\ProductAttributes"/>
                    </settings>
                </select>
            </formElements>
    </field>
</fieldset>

Hope this will help you

A: Your question is seems to unclear to me.  But if you want to display Product attributes as drop-down.
Here i am assuming that you trying to display drop-down at admin.
You need to create a class that will return value like, toOptionArray.
Than you can use in your category's ui_component select field and than define options for that field like below.
        <formElements>
            <select>
                <settings>
                    <options class="Vendor\Module\Block\Product\Attributes"/>
                </settings>
            </select>
        </formElements>

Block must have toOptionArray Method and it will return array same as class Magento\Config\Model\Config\Source\Locale\Country.

Hope it will resolve you problem.

A: You can try below code for customer dropdown

app/code/VendorName/ModuleName/etc/extension_attributes.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="Magento\Customer\Api\Data\CustomerInterface">
        <attribute code="seller_register_plan" type="string"/>
    </extension_attributes>
</config>

app/code/VendorName/ModuleName/Setup/InstallData.php

<?php

namespace [VendorName]\[ModuleName]\Setup;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{

    private $customerSetupFactory;

    /**
     * Constructor
     *
     * @param \Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory
     */
    public function __construct(
        CustomerSetupFactory $customerSetupFactory
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function install(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        $customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'seller_register_plan', [
            'type' => 'varchar',
            'label' => 'Seller Register Plan',
            'input' => 'select',
            'source' => '[VendorName]\[ModuleName]\Model\Customer\Attribute\Source\SellerRegisterPlan',
            'required' => false,
            'visible' => true,
            'position' => 333,
            'system' => false,
            'backend' => ''
        ]);

        $attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'seller_register_plan')
            ->addData(['used_in_forms' => [
                'adminhtml_customer'
            ]]);
        $attribute->save();

    }
}

This is the source Model

[VendorName][ModuleName]\Model\Customer\Attribute\Source\SellerRegisterPlan.php

<?php

namespace [VendorName]\[ModuleName]\Model\Customer\Attribute\Source;

class SellerRegisterPlan extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{

    /**
     * getAllOptions
     *
     * @return array
     */
    public function getAllOptions()
    {
        if ($this->_options === null) {
            $this->_options = [
                ['value' => '0', 'label' => __('Select an option')],
                ['value' => 'standard', 'label' => __('Standard')],
                ['value' => 'advanced', 'label' => __('Advanced')],
                ['value' => 'premium', 'label' => __('Premium')]
            ];
        }
        return $this->_options;
    }
}

Let me know if face any issue....

A: Use the code to get all the product attribute as dropdown
class AttSource implements \Magento\Framework\Option\ArrayInterface
{
protected $collectionFactory;
public function __construct(
    \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory $collectionFactory
) {
    $this->collectionFactory = $collectionFactory;
}

public function toOptionArray(){

    $collection = $this->collectionFactory->create();
    $collection->addFieldToSelect('*');
    $attributesArray = array();
    $attributesArray = array(
        array(
        'label' => __('None'),
        'value' => ''
        )
    );

    foreach ($collection->getItems() as $attribute) {
        $attributesArray[] = array('value'=> $attribute->getAttributeCode(),'label'=> $attribute->getFrontendLabel());
    }
    return $attributesArray;
}

}


text:
Q: Azure Cognitive Services Computer Vision fails in QA but works perfectly in dev I have this code to run Azure Cognitive Service's Computer Vision API in a C# API. I've ran this in Dev for a couple weeks and everything is good at this point. However I moved this to our QA environment and all of a sudden I get:
InnerException  {"Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."}   System.Exception {System.IO.IOException}
This tells me the service is alive but unavailable. imageURL is a fully formed public URL (an image).
            string imageURL = _storageAccount.BlobStorageUri.PrimaryUri.AbsoluteUri + container + "/" + fullFileName;

            // Create a client
            ComputerVisionClient client = Authenticate(cvEndpoint, cvSubscriptionKey);

            // Creating a list that defines the features to be extracted from the image.
            List<VisualFeatureTypes?> features = new List<VisualFeatureTypes?>()
            {
                VisualFeatureTypes.Categories, VisualFeatureTypes.Description,
                VisualFeatureTypes.Faces, VisualFeatureTypes.ImageType,
                VisualFeatureTypes.Tags, VisualFeatureTypes.Adult,
                VisualFeatureTypes.Color, VisualFeatureTypes.Brands,
                VisualFeatureTypes.Objects
            };

            // Analyze an image to get features and other properties.
            ImageAnalysis results = await client.AnalyzeImageAsync(imageURL, features); //fails here

This is pretty vanilla code directly from Microsoft's documentation. Anyone knows what could be happening here?

A: I fixed this issue by adding TLS 1.1 and 1.2 in my API. Not sure why 1.0 is by default but it is and the cognitive service API needs 1.2 minimum.
The fix is to add this line:
System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Found the solution here: C# HttpClient An existing connection was forcibly closed by the remote host


text:
Q: Viewing images in birt reports Problem with viewing images.
So ..if I deploy the report and images in a folder called project I can view the report
http://localhost:8080/birt/frameset?__report=project/example.rptdesign

That works ok.
But if I want to structure things, in the folder project: I made folders, one for reports called report and one for images called resources
I call the report like this
http://localhost:8080/birt/frameset?__report=project/report/example.rptdesign

the report looks ok, but the images do not show up.
Thank you.

A: When you changed the image's location, did you delete the image from the report and re-add it from the new Resources" folder?  You should be able to store and access an image from any relative path quite easily, but it needs to be stored in that location relative to the report when you add the resource.


text:
Q: Android Studio - How to Find and Change System Variables I am currently trying to find out the values of $HOME and $ANDROID_AVD_HOME as I am having difficulties running an emulator.
I have searched through various posts to try and find an answer, people simply suggest "changing this variable", however I have no inkling how to find the value or location of these variables.
I would, ideally, like to know how to display their values then, if I need to, change them.


text:
Q: Iterating over a VBA.Collections in C# I'm working on some code in my COOP and I have a parameter for a method which is of type VBA.Collection. I'm trying to see what's inside of it but I can't find a way to iterate over it. The only methods that it has are

*

*Add

*Count

*Equals

*GetEnumerator

*GetHashCode

*GetType

*Item

*Remove

*ToString

I tried using the Item method but it has ref Object index as a parameter, and it also can't be used as a an array.
Any help on this would be awesome. Thanks!

A: The entire purpose of GetEnumerator is to allow iteration of the type.  If you want to iterate it, use that.
You could, for example, do:
foreach(object item in collection)
{
    //use item here
}


text:
Q: Component with setinterval not updating on context state change PROBLEM
When I update the object stored in my ContextProvider I can see all the data update accordingly except for my date countdown.
DETAILS
I have a sidepanel component that displays data from a list. When a list item is clicked I update the state pf which object is selected in a separate react context. This works fine. An example of what object is stored is below.
Context Object
{
   "title": "I am the title",
   "startDate" "2021-11-01T02:00:00.000Z"
}

I then use this object to render out a sidepanel component with the title and seconds counting down.
Sidepanel.tsx
export function SidePanel() {
    const { active } = useSidePanel()

    const countdown = useCountdown(new Date(active.startDate))

    return (

{active.title}

{countdown} seconds to go

    )
}

useCountdown.tsx
export function useCountdown(date: Date) {
    const [countdown, setCountdown] = useState<number>(0)

    const formatCountdown = () => {
        const diffInSeconds = dateFns.differenceInSeconds(date, new Date())

        if (diffInSeconds <= 1) return 0
        setCountdown(diffInSeconds)
    }

    useEffect(() => {
        const interval = setInterval(() => {
            formatCountdown()
        }, 1000)

        return () => clearInterval(interval)
    }, [])

    return countdown
}

A: So by adding 'date' inside the useEffect array inside useCountdown.tsx I was able to solve this problem
export function useCountdown(date: Date) {
    ...

    useEffect(() => {
        const interval = setInterval(() => {
            formatCountdown()
        }, 1000)

        return () => clearInterval(interval)
    }, [date])

    ...

}


text:
Q: Is my logic for this EER diagram correct? I'm practicing creating EER schemas for an exam and was wondering if my logic for this EER diagram for the circled part is correct. Something tells me I'm wrong:

I'm trying to say that for the dealership branch, it has many vehicles, hence, 1:N.
Though, I feel like it would make more sense to have a relationship like:
(0,1):(0,N) would make more sense because it's possible for the dealership in question may not have the vehicle, hence 0, and if it does, hence 1. The dealership branch may have 0 vehicles, or many (N) vehicles.
So, this is where I'm stumped at. If someone can explain the logic to me and help me understand my mistake or if I'm correct, that would be great.


text:
Q: Using a nullable string resource id from view model in Android data binding I am trying to map API errors (exceptions) to String resources in my view model. My view model looks like the following.
@HiltViewModel
class AccountViewModel @Inject constructor(accountRepository: AccountRepository) : ViewModel() {

  val isLoadingProfile = MutableLiveData(false)
  val profile = MutableLiveData<Profile>()
  val profileLoadError = MutableLiveData<Int>()

  fun loadProfile() {
    isLoadingProfile.postValue(true)
    viewModelScope.launch(Dispatchers.IO) {
      try {
        profile.postValue(accountRepository.getProfile())
      } catch (e: Throwable) {

        // assign String resource id to profileLoadError
        profileLoadError.postValue(
          when (e) {
            is NetworkError -> R.string.network_error
            else -> R.string.unknown_error
          }
        )

      } finally {
        isLoadingProfile.postValue(false)
      }
    }
  }
}

And my error text view XML looks like the following.
<TextView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text="@{viewModel.profileLoadError ?? ``}"
  android:visibility="@{viewModel.profileLoadError != null ? View.VISIBLE : View.GONE}" />

But I am getting a class cast exception when I try to run it.
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.CharSequence

If I remove the null coalescing operator from the data binding expression like the following, I get a resource not found exception.
android:text="@{viewModel.profileLoadError}"

Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0

I know that it is kind of an idiotic question, but how do I fix this?

A: is NetworkError -> R.string.network_error  ->in this line you are returning String to post value for profileLoadError of type Int.That's why you got ClassCastException.
So change the type of LiveData  to String
val profileLoadError = MutableLiveData()

A: After the suggestion from @androidLearner, I created a binding adapter for the android:text attribute.
@BindingAdapter("android:text")
fun TextView.setText(@StringRes resId: Int?) {
  resId ?: return
  if (resId == ResourcesCompat.ID_NULL) {
    text = ""
  } else {
    setText(resId)
  }
}

Now, I can pass the string id without worrying about its nullability.
android:text="@{viewModel.profileLoadError}"


text:
Q: Function not implemented I tried to authenticate the server with user name and password with the below url, there was error prompted in the server console.
http://servername/names.nsf?login&Username=Shibu%20Mathew&Password=welcome2lotus

HTTP Web Server: Function Not Implemented Exception
Please help me to fix this issue

A: You probably get this error because the server has been set up to use basic authentication (and not session-based authentication).
Try using http://<username>:<password>@servername/ instead.
See more here: http://www-01.ibm.com/support/docview.wss?uid=swg21176893


text:
Q: Need to convert %amp; to just & in otder for script to work I'm converting a website in modx which makes use of a java wrapper to dynamically pull in content and display it without any page reloading. the basics of the site are there but I'm having a slight issue with generated links and I'm not sure what the best way to get around it is.
I didn't write the original javascript that the site uses, I'm just trying to refactor it slightly so modx leverages the right pieces.
Here is an example of the template I'm using to page next/previous

Basically modx's generated links take the following format in the page:
 setNext('nb/index.php?id=17&page=2');

For them to work, they need to be:
 setNext('nb/index.php?id=17&page=2');

The sites using jquery, I was thinking there might be a way I can get that to convert text strings before it renders the page?
Hope someone can point me in the right direction cos I'm a bit stumped atm.

A: setNext(htmlDecode('nb/index.php?id=17&page=2'));

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

See unescape html entities in javascript

A: This would do the trick
var str = 'nb/index.php?id=17&page=2'
str = str.replace(/&/g, '&');
setNext(str);

A: IMO it would be better to correct it at the source rather than 'patching it up' in the browser.
Worst case, you can do it in PHP like this:
$href = 'nb/index.php?id=17&page=2';
$modx->setPlaceholder('href', str_replace('&', '&', $href));

However if the link was generated using MODX's makeUrl() method then it should already be formatted correctly.


text:
Q: How to use Netplan to remove IPv6 address on a single interface Running Ubuntu Server 19.04. Using SoftEther's Local Bridge feature. Their docs recommend disabling IP on the interface used for bridging.
Here's my Netplan configuration:
network:
  version: 2
  renderer: networkd
  ethernets:
    lan:
      match:
        macaddress: c8:2a:14:00:00:00
      addresses:
      - 192.168.1.253/24
      dhcp4: false
      gateway4: 192.168.1.254
      nameservers:
        addresses:
        - 192.168.1.254
      set-name: lan
    softether:
      match:
        macaddress: a8:60:b6:00:00:00
      dhcp4: false
      optional: true
      set-name: softether
    wifi:
      match:
        macaddress: 40:6c:8f:00:00:00
      dhcp4: true
      optional: true
      set-name: wifi

Still getting an IPv6 on the softether interface:
$ ip a
2: softether: <BROADCAST,MULTICAST,PROMISC,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether a8:60:b6:00:00:00 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::aa60:b6ff:fe09:937c/64 scope link
       valid_lft forever preferred_lft forever

Is there a way to remove IPv6 using Netplan alone?

A: This question is a bit old, however there is a way to do it with netplan, using this answer to a similar question:

Just add link-local: [] within the interface you want to disable the ipv6 link local address option. Save and test the new config with: sudo netplan try and if everything was okay enforce it with: sudo netplan apply.

This did exactly what I wanted - disabling ipv6 on just one of the two NICs in the server.
NOTE: As Raptor points out, this will also disable link-local adresses for IPv4 as well, so if you need that then you will need to use a different solution.

A: FYI:
link-local: [ ipv4 ]

helps keeping ipv4 up while disabling ipv6.
Cheers

A: Have you tried
sysctl -w net.ipv6.conf.softether.disable_ipv6 = 1


text:
Q: How to change timeout on a form submit in ExtJs 4 Where should I change the timeout configuration for a form submit?
Should it be in the definition of the class(form) and if so why isn't it listed a config in form xtype?
http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.form.Panel
Should it be in the submit action and if so where can I see the documentation about it?
I'm using ExtJs 4.2.1
Thanks.

A: In the form creation or in the definition of a class that extends form.
"Although not listed as configuration options of FormPanel, the FormPanel class accepts all of the config options supported by the Ext.form.Basic class, and will pass them along to the internal BasicForm when it is created."
http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.form.Panel


text:
Q: Validation error: EntityType has no key defined when i  try to create controller i get error call " EntityType has no key defined" . why is that?
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace HotelManagementSystem.Models
{
    public class Room
    {
        public int RoomNo { get; set; }
        public string PackageiD { get; set; }
        public string ResiD { get; set; }
        public bool Tv { get; set; }
        public bool Wifi { get; set; }
        public bool Internet { get; set; }
        public bool Telephone { get; set; }
        public bool Ac { get; set; }
        public bool Bathroom { get; set; }
        public bool Fridge { get; set; }
        public bool Homethearter { get; set; }
    }
    public class RoomContext : DbContext
{
    public DbSet<Room/*table name*/> HotelManagementSystem /*Data Base name */ { get; set; }
}
}

erroe message is :

A: Add a property of Id which will be primary key like this:
[Key]
public int Id  {get;set;}

actually you have not defined primary key in the model.
If RoomNo will always be unique in each row, then you can make it primary key.


text:
Q: globals and includes in PHP I have a bootstrap script.
bootstrap.php
<?php
  $bootstrapFoo = 'foo';

and a main script.
main.php
<?php
  require_once 'bootstrap.php';
  print $bootstrapFoo; // this is working

  // I include a subscript
  include_once 'subscript.php';

subscript.php
<?php
  print $bootstrapFoo; // this is NOT working.

my solution :
<?php
  global $bootstrapFoo;
  print $bootstrapFoo; // now that's working

Is this the right way ?

ps: no duplicates found.


text:
Q: Controlling the direction of JavaScript .show() / .toggle()? I'm using JavaScript's .toggle() to have this  appear/ disappear:
{
    display: none;
    position: fixed;
    top: 100px;
    right: 0;
    left: 0;
    background: rgba(0,0,0,0.75);
    padding: 15px;
}

However, over the duration of the animation it starts from the top-left corner and expands out to the bottom-right corner of the div.
Ideally, I'd like to start it from the both top corners and expand downwards to both bottom corners evenly.
I thought the CSS transition-origin property might have an effect, but it doesn't seem to be the case.
Any ideas? Thanks in advance. :)

A: I would start a height of 0 and the animate the height property.

function toggle() {
    var el = document.getElementsByTagName('div')[0];
    if (el.className) {
      el.className = '';
    } else {
      el.className = 'grow';
    }
}
div {
  background-color: black;
  width:200px;
  height: 0;
}

.grow {
  height: 200px;
  transition: height 2s;
}
<button onclick="toggle()">Toggle</button>

A: I don't know much about jQuery's toggle method, so I looked in the docs, and sure enough it gives some helpful info. (This is a gentle hint that before coming to StackOverflow you should try solving the problem on your own, including looking at any relevant documentation online).

The .toggle() method animates the width, height, and opacity of the
  matched elements simultaneously.

The documentation doesn't give any info about customizing how toggle does its animation, so it looks like you're stuck. If I'm understanding you correctly, it seems like you want the element to animate only the height and not the width, so it stays the same width as it toggles and just animates the height. I don't see any way of doing that with jQuery's toggle.
BUT WAIT! It looks like jQuery has another method called slideToggle which does exactly what you want. It's just like toggle except it only animates the height and keeps the width the same. Hooray!
http://api.jquery.com/slidetoggle/
Moral of the story: if you're using a third party Javascript library like jQuery, you really need to get comfortable finding the information you need in the online documentation my friend. :)


text:
Q: Sub Category listing according to category in drop down I'm stuck here.
I want to display particular sub categories when a particular category is selected from the category drop down.
For instance, suppose we have categories :-
Cate1
Cate2
Then under Cate1, we have :-
Sub1
Sub2
and under Cate2, we have
Sub3
Sub4
Then how would the sub category change values according to the categories?I guess some js or php ?
Please help.

A: Depends what do you want, if you have simple and short list, use HTML ,  and
http://htmldog.com/reference/htmltags/optgroup/
If not, then yes, you must use JavaSript to build new select depending on main category value


text:
Q: How to deal with the .next() function with hidden elements I am making a custom drop down menu with arrow key functions as well as being filtered by :contains.
I can't seem to get past the following code. What is happening is that I need to start the selection at the current hovered li, then proceed to the next or previous li that has the class match.
My following code starts correctly but even though it has .next('.match') it wont pass the
's that either don't have the class (match) or are (hidden)
Does the next() function break on hidden elements?
Jquery Code
 $('.dropdown_shell.opened li.match.hovered')
     .next('.match')
     .addClass('hovered')
     .siblings()
     .removeClass('hovered');

Html

None

For Sale

For Rent

For Lease

Sale or Lease

New Listing

Open House

A: Your next() function is not doing what you think it is. It looks at the next element, and only matches it if it makes the given selector. Otherwise it returns  an empty jQuery object.
Instead, you want nextAll(), which looks at all future siblings, then use the first() method (or :first) selector to match the first one.
You can see this working here; http://jsfiddle.net/DH3hG/
To answer your question about whether next() considers hidden elements; yes it does. Anything that is inserted into the DOM is considered.


text:
Q: Split string, unicode, unicode, string in python I was trying to split combination of string, unicode in python. The split has to be made on the ResultSet object retrieved from web-site. Using the code below, I am able to get the details, actually it is user details:
from bs4 import BeautifulSoup
import urllib2
import re

url = "http://www.mouthshut.com/vinay_beriwal"
profile_user = urllib2.urlopen(url)
profile_soup = BeautifulSoup(profile_user.read())

usr_dtls = profile_soup.find("div",id=re.compile("_divAboutMe")).find_all('p')
for dt in usr_dtls:
    usr_dtls = " ".join(dt.text.split())
    print(usr_dtls)

The output is as below:
i love yellow..

Name: Vinay Beriwal
Age: 39 years
Hometown: New Delhi, India
Country: India
Member since: Feb 11, 2016

What I need is to create distinct 5 variables as Name, Age, Hometown, Country, Member since and store the corresponding value after ':' for same.
Thanks

A: You can use a dictionary to store name-value pairs.For example -
my_dict = {"Name":"Vinay","Age":21}

In my_dict, Name and Age are the keys of the dictionary, you can access values like this -
print (my_dict["Name"])   #This will print Vinay

Also, it's nice and better to use complete words for variable names.
results = profile_soup.find("div",id=re.compile("_divAboutMe")).find_all('p')

user_data={}  #dictionary initialization
for result in results:
    result = " ".join(result.text.split())
    try:
        var,value = result.strip().split(':')
        user_data[var.strip()]=value.strip()
    except:
        pass

#If you print the user_data now
print (user_data)

'''
This is what it'll print
{'Age': ' 39 years', 'Country': ' India', 'Hometown': 'New Delhi, India', 'Name': 'Vinay Beriwal', 'Member since': 'Feb 11, 2016'}
'''

A: You can use a dictionary to store your data:
my_dict = {}

for dt in usr_dtls:
    item = " ".join(dt.text.split())
    try:
        if ':' in item:
            k, v = item.split(':')
            my_dict[k.strip()] = v.strip()
    except:
        pass

Note: You should not use usr_dtls inside your for loop, because that's would override your original usr_dtls


text:
Q: Running Selenium Chrome on a server There's a page I need to scrape which contains javascript and html. When I run a Selenium Chrome browser and save the page to a file, I get a result I need. However, it doesn't work with PhanthomJS -- I get a pretty different html code, even if I add this string to it as a user agent:
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"

The reason I need PhanthomJS is because I'll need to run it on a server where, of course, will be no display.
1) Why are the results different in for Chrome and PhanthomJS?
2) Since Chrome selenim creates a visible window, is it ok and possible at to run it as it is on server? Or should I somehow to hide the window? How?
3) Or should I instead run only PhanthomJS on a server because it creates no window?


text:
Q: In JQuery, .html(var) vs .html(var.html()) This code is provided for context, please see below for my question:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Document</title>

item 1

item 2

item 3

item 4

This is paragraph 1

This is paragraph 2

This is paragraph 3

This is paragraph 4

`

The is the part I am interested in:
var newItem = $("
This is a new paragraph
");
    $("#para2").html(newItem.html());

It appears to be functionally equivalent to this:
var newItem = $("
This is a new paragraph
");
    $("#para2").html(newItem);

The former method, I noticed in a video demonstration that teaches jQuery. As far as I know all that the added .html() part does is to get the matching element. To me, it doesn't seem like getting it in this case would help, since in  var newItem = $("
This is a new paragraph
"); the $() already made it a Jquery object.

Question:
Is there a meaningful and impactful difference between the two above methods, or is it just a matter of coding preference?

A: html() serialises the HTML inside the element to a string.
In this case, the difference is that $("#para2").html(newItem.html()); will give you some text and $("#para2").html(newItem); will give you a paragraph containing that text.
Since #para2 is a paragraph, and HTML does not allow paragraphs to be nested, the latter would also generate invalid HTML.

If you weren't creating the paragraph from scratch at at the same time (e.g. if var newItem = $("#existingParagraph");), then you would also be moving the element rather than copying its content.

Since you are just changing the text in the element, there is no need to create a jQuery object in the first place.
This:
    var newItem = $("
This is a new paragraph
");
    $("#para2").html(newItem.html());

is equivalent to:
    $("#para2").html("This is a new paragraph");