text:
Q: JButtons re-enable themselves after being disabled I have an array of JButtons which form a keypad interface. After six numbers are entered I want to disable the keypad so that no further numbers can be entered by the user.
I have written the code and the buttons do disable until the mouse hovers above any of them, then the buttons seem to re-enable themselves and run actionEvents added to them.
The full code is available here.
Possible things that I think are wrong.

*

*There is some sort of MouseListener which is ignoring when I set  button.setEnabled(false);

*I haven't separated attributes from the buildGUI(); correctly, I only did this anyway so that the inner class could access them.

*Possibly something to do with the gridLayout as disabling the buttons seems to work for my services JPanel buttons.

A: The problem lies in how you instantiated your Frame (CashMachine), not (directly) with its implementation.
You are calling buildGUI twice, one in the object's constructor, and then in the Driver class that instantiates the object. As a result, you are creating (and laying out) two sets of buttons.
When the buttons of the first set were eventually disabled, your mousing activity was revealing the second set of buttons. And a flaw in your ActionListener implementation can cause inputCount to take on values greater than 6, so buttons in the second set were not eventually disabled like those from the first set.
buildGUI should be private; it should be called in the CashMachine constructor, and not by your Driver class.
Conversely, in my opinion, CashMachine.setVisible should be called by the Driver class, and not by the CashMachine constructor.

A: The code works just fine I guess.

A: One possible source of confusion in your program is mixing number keys with control keys, Clear and Enter. Consider handling number keys separately with a single listener, as suggested in the NumberButton class shown below. Then you can handle the Clear and Enter buttons as desired. Also, using a List<NumberButton> makes the enable and disable loops easier.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class KeyPadPanel extends JPanel implements ActionListener {

    private static final int MAX = 6;
    private final List<NumberButton> numbers = new ArrayList<NumberButton>();
    private final JTextArea text = new JTextArea(1, MAX);
    private final JButton clear = new JButton("Clear");
    private final JButton enter = new JButton("Enter");

    public KeyPadPanel() {
        super(new BorderLayout());

        JPanel display = new JPanel();
        text.setEditable(false);
        display.add(text);
        this.add(display, BorderLayout.NORTH);

        JPanel pad = new JPanel(new GridLayout(4, 4));
        for (int i = 0; i < 10; i++) {
            NumberButton n = new NumberButton(i);
            numbers.add(n);
            if (i > 0) {
                pad.add(n);
            }
        }
        pad.add(clear);
        pad.add(numbers.get(0));
        pad.add(enter);
        clear.addActionListener(this);
        enter.addActionListener(this);
        this.add(pad, BorderLayout.CENTER);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        text.setText("");
        enableButtons();
    }

    private void enableButtons() {
        for (NumberButton n : numbers) {
            n.setEnabled(true);
        }
    }

    private void disableButtons() {
        for (NumberButton n : numbers) {
            n.setEnabled(false);
        }
    }

    private class NumberButton extends JButton implements ActionListener {

        public NumberButton(int number) {
            super(String.valueOf(number));
            this.addActionListener(this);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            NumberButton b = (NumberButton) e.getSource();
            if (text.getText().length() < MAX) {
                text.append(b.getText());
            }
            if (text.getText().length() == MAX) {
                disableButtons();
            }
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.add(new KeyPadPanel());
                f.pack();
                f.setVisible(true);
            }
        });
    }
}

A: Examining the class files was helpful! The problem is in the Driver class:
the buildGUI() method is being called 2 times: once in the constructor of CashMachine and second in the main method after calling the constructor.
public static void main(String args[])
{
    CashMachine cashmachine = new CashMachine();
    cashmachine.buildGUI();
}

This way you end up with the double number of buttons, that is, a pair of buttons at each position. But only one of each is being disabled.
Just remove the call to buildGUI from main (or from the constructor).
(I would change buildGUI to private as it should not be called from outside the class...)


text:
Q: My Macbook Air fan is really loud My fan is running really loud. I have tried resetting the SMC and it didn't work. I have no applications running and my mac is not hot. If you have any idea what is wrong please help me!

A: If the SMC reset did not work it seems likely it could be a hardware problem. I would guess it's going into a fail safe mode causing the fans to always run full speed. This could happen if a temperature sensor malfunctioned , I would recommend taking the system into an Apple Authorized Service provider.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I extract X,Y screen coordinates from listener thread pynput? I'm unable to access values for screen X,Y coordinates when using mouse.Listener (Pynput)
I am trying to build a screen capture tool using pynput, Pillow (ImageGrab) and OpenCV (cv2) and need to store X,Y screen coordinates in separate variables.
I've tired returning x,y variables from within the on_click() function and tried assigning the mouse.Listener (threading function) to a variable with no luck (just returns )
The function works correctly and accurately displays the X,Y coordinates on pressing and releasing the mouse.
Is there a way to store the X,Y coordinates obtained on mouse pressing and release ?
Mac OSX 10.13.6, Python 3.7.3.
from pynput import mouse

def on_click(x, y, button, pressed):

    if pressed:
        print(f"start_pos = ({x},{y})")
    elif not pressed:
        print(f"end_pos = ({x},{y})")
        return False

listener = mouse.Listener(on_click=on_click)
listener.start()

I cannot store the values from the output thread object.

A: If you import Controller from pynput and use it as such;
mouse = Controller()
mouse.position

Hope it helps!


text:
Q: LCD write update issue I am using arduino Uno and 16X2 lCD for programming. I have almost written code which seems working. I am facing small problem while updating LCD values.I cant paste my full code, just pasting part of it.It just menu selection and Editing option. i am pasting part by part.
This How called in Loop
void loop()
{
    LCD_Display();
    CHK_Key();
    wdt_reset();
    Track_loop();
    //Serial.println("..........................");
}

LCD Display program called below
void LCD_Display()
{
    Display_counter1=Display_counter1+1;

    if(Update_Screen==1)
    {
        lcdClear();
        switch(cur_disp_screen_type1)
        {
            case DATE_TIME:digitalClockDisplay();break;
            case COORDINATE:Display_coordinate();break;
            case WIND_SPEED: Display_Wind();break;
            case SOLAR_ANGLE:Display_angle();break;
            case SET_PARAMETER:Set_Parameter();break;
            case GET_PASSWORD:GetEditPassword(Edit_password,4);Blink_Password(current_Password);break;
            case EDIT_MODE:Edit_parameter();break;
            case EDIT_DATE_TIME:ClockEditDisplay(edit_date_time,6); Blink_LCD(cur_edit_item);break;
            case EDIT_TRACK_TIME:Track_Edit_Display(edit_track_time,2);Blink_Track(cur_edit_time_item);break;
            case EDIT_COORDINATE:Edit_Coordinate_Display(edit_cordinate,4);Blink_Coordinate(cur_coordinate_item);break;
            case EDIT_LIMIT:Edit_Limit_Display(edit_limits,4); Blink_Limit(cur_edit_limit);break;
        }
        Update_Screen=0;
        if( cur_disp_screen_type1>DISPLAY_COUNT_MAX)
        {
            cur_disp_screen_type1= DATE_TIME;
        }
    }
    if(Display_counter1>=6)
    {
        Display_counter1=0;Update_Screen=1;
    }
}

I can read the values properly . So problem while Editing. So Here is part of editing option.
void GetEditPassword(int password_data[],int size)
{
    lcd.setCursor(0,0);
    lcd.write("ENTER PASSWORD  ");
    lcd.setCursor(0,1);
    lcd.print(password_data[0]);
    lcd.print(password_data[1]);
    lcd.print(password_data[2]);
    lcd.print(password_data[3]);
    lcd.print("              ");
}

Here i have doubt i am setting cursor 0,0 and 0,1 . so every time function called i am assuming these function being updated so because of which i can see letters behind while editing. My question is How to ovecome this problem.
void Blink_Password(int Password_pos)
{
    int term1;
    int term2;
    lcd.blink();
    delay(40);
    switch(Password_pos)
    {
    case PASSWORD_ITEM1:  lcd.print(password1);Update_Screen=1;
                          goto PASSWORD;
                          break;

    case PASSWORD_ITEM2:lcd.print(password2);Update_Screen=1;
                             goto PASSWORD;
                          break;

    case PASSWORD_ITEM3:lcd.print(password3);Update_Screen=1;
                          goto PASSWORD;
                          break;

    case PASSWORD_ITEM4:lcd.print(password4);Update_Screen=1;
                           goto PASSWORD;
                          break;
    }
PASSWORD:   lcd.setCursor(Blink_password_pos[Password_pos][0],Blink_password_pos[Password_pos][1]);
    lcd.noCursor();//timedBeep(shortBeep,1);
    delay(40);
}


text:
Q: JSON.parse syntax error validating user info I've been trying to work out what my problem is for the last 5 hours and all I have to show for it is a pounding headache... please help me...
I'm trying to create a login and registration form; the login part is working fine however the registration one is throwing me a "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data". I don't know where this is coming from and how to fix it.
I believe the issue is in the register part of the handler, but other than that I'm clueless:
//*************************************************************
  // Register

  else if($requestType == 'Register')
  {
    function complexEnough($pass)
    {
      if (preg_match('/[A-Za-z]/', $pass) && preg_match('/[0-9]/', $pass))
        if (strlen($pass) > 6)
          return true;

      return false;
    }

    try {
      $email = $jsonContent['Email'];
      $username = $jsonContent['Username'];
      $password1 = $jsonContent['Password1'];
      $password2 = $jsonContent['Password2'];

      if ($username == "")
        echo "Registration failed: Username was blank";

      else if ($email == "")
        echo "Registration failed: email address field was blank";

      else if ($password1 != $password2)
        echo "Registration failed: passwords did not match";

      else if ($password1 == "")
        echo "Registration failed: passwords were blank";

      else if (!complexEnough($password1))
      {
        echo "Registration failed: Password must contain an uppercase, lowercase, number and be at least 6 characters long";
      }

      else
      {
        $db = new PDO('mysql:host=localhost; dbname=SpaceInvaders', $DbConfig['Uid'], $DbConfig['Password']);

        $query = $db->prepare("insert into users(username, email, password) values (:username, :emailAddress, :password)");
        $query->bindParam(':username', $username);
        $query->bindParam(':emailAddress', $email);
        $hashedPassword = password_hash($password1, PASSWORD_DEFAULT);
        $query->bindParam(':password', $hashedPassword);
        $result = $query->execute();

        if ($result)
          $jsonResponse = array( 'ErrorCode' => '0', 'Message' => "");
        else
          $jsonResponse = array( 'ErrorCode' => '3', 'Message' => "Email Address already allocated");

        $query = null;
        $db = null;
      }
    }
    catch (Exception $e)
    {
      $jsonResponse = array( 'ErrorCode' => '1', 'Message' => "Unexpected Error:" . $e->getMessage());
    }
    echo json_encode($jsonResponse);
  }

P.S. - I know there'll be stuff that isn't 'best practice', It's only an introductory course to web scripting.

A: You need to check JSON what you get from the request and validate it with any online JSON validator services. I'm sure you're getting invalid JSON and you need to check how you form it.


text:
Q: Receiving async data on an ObservedObject I am trying to build a Singleton ApiManager class that can build and send all of my API requests for me and send the response data to awaiting request object. In SwiftUI when I see, say a user successfully login, I would like to switch the views to maybe a dashboard. The problem is that I am using an ObservableObject to publish the "isLoggedIn" Bool and I make all of my backend requests on a background thread. I am getting this error

[SwiftUI] Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like
receive(on:)) on model updates.

Here is how I perform API requests
func performRequest(with request: some AbstractRequest) {
    var link = host + request.endpoint
    appendParameters(to: &link, with: request.params)

    guard let url = URL(string: link) else {
        print("Failed to generate url from \(link)")
        return
    }

    let task = URLSession.shared.dataTask(with: url){ data, response, error in
        guard let data = data, error == nil else{
            print("\(error?.localizedDescription ?? "")")
            return
        }
        request.completion(data: data)
    }
    task.resume()
}

Here is an example completion handler (Bonus point if you can tell me why I get this warning

Conditional cast from '[LoginResponse]' to '[LoginResponse]' always succeeds

on the cast line but if I remove the cast it complains.)
func completion(data: Data)
{
    do{
        guard let response = try JSONDecoder().decode([LoginResponse].self, from: data) as? [LoginResponse] else { return }
        delegate.responseReceived(response: response)
    }catch let error{
        print("\(error.localizedDescription)")
    }
}

Here is what my LoginManager looks like
class LoginManager: ObservableObject, ApiRequestDelegate{
    static var shared = LoginManager()

    var token = ""
    @Published var isLoggedIn: Bool = false

    func responseReceived(response: Any) {
        guard let response = response as? LoginResponse, response.token != -1 else { return }
        token = String(response.token)
        isLoggedIn = true
    }
}

And finally my ContentView
struct ContentView: View {
    @ObservedObject var loginManager = LoginManager.shared
    var body: some View {
        if !loginManager.isLoggedIn {
            LoginView()
        }else {
            OpenLinkButton().ignoresSafeArea()
        }
    }
}

A: Your completion handler inside URLSession.shared.dataTask is called on a background thread. So everything that follows is on a background thread.
The most simple solution would be to dispatch UI changes to the main Thread. e.g.:
DispatchQueue.main.async{
    isLoggedIn = true
}

another solution would be to decorate the function interacting with the UI with @MainActor atribute. e.g.:
@MainActor
func responseReceived(response: Any) {


text:
Q: EF6 many-to-many, WillCascadeOnDelete and multiple cascade paths In EF6 CodeFirst, I want to model a many-to-many relationship with navigation properties.
The classes:
public class Event
{
    [DataMember]
    [Required]
    public int Id { get; set; }

    // Other properties

    [DataMember]
    public virtual ICollection<Notification> Notifications { get; set; }
}

public class Notification
{
    [DataMember]
    [Required]
    public int Id { get; set; }

    // Other properties

    [DataMember]
    public virtual ICollection<Event> Events { get; set; }
}

class EventConfiguration : EntityTypeConfiguration<Event>
{
    public EventConfiguration()
    {
        HasMany(e => e.Notifications)
            .WithMany(e => e.Events)
            .Map(m => m.ToTable("NotificationEvents"));
    }
}

There are cascade deletes on Event and Notification from other tables.
If I try to create the database, I get:

Introducing FOREIGN KEY constraint
  'FK_dbo.NotificationEvents_dbo.Events_Event_Id' on table
  'NotificationEvents' may cause cycles or multiple cascade paths.
  Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other
  FOREIGN KEY constraints.

Which is fair enough, given other cascades. Now my question is: how to (or can I) specify no cascades on one or both sides of this relationship only?
If I add (as suggested in another post):
class NotificationConfiguration : EntityTypeConfiguration<Notification>
{
    public NotificationConfiguration()
    {
        HasOptional(e => e.Events).WithMany().WillCascadeOnDelete(false);
    }
}

I get:

The navigation property 'Events' declared on type
  'Notification' has been configured with
  conflicting multiplicities.


text:
Q: How to keep OpenLayers.StyleMap and OpenLayers.SelectFeature from conflicting? I have an OpenLayers.Layer.Vector layer, something like this:
layer = new OpenLayers.Layer.Vector("zzzzz", {
  strategies: [
    new OpenLayers.Strategy.Fixed(),
  ],
  // styleMap: new OpenLayers.StyleMap({
  //   'default': { .. layer styles here ..}
  //   'select': { .. selected styles here ..}
  // }),
  protocol: new OpenLayers.Protocol.HTTP({
    url: "/kml/zzzzzz.kml",
    renderers: ['Canvas','SVG'],
    format: new OpenLayers.Format.KML({
      extractStyles: false,
      extractAttributes: true,
      maxDepth: 0
    })
  })
});

Then I have an OpenLayers.Controls.SelectFeature control, something like this:
selectFeature = new OpenLayers.Control.SelectFeature(
    [layer],
    {
      renderIntent: "select",
      clickout: true,
      toggle: true
    }
);

Then, I add it to the map, like so:
map = new OpenLayers.Map('map');
map.addLayer(layer);
map.addControl(selectFeature);
selectFeature.activate();

Now, the instant that I uncomment those styleMap lines, all of my features become unclickable and unresponsive. Not only do the styles not reflect the state, but the states don't seem to be changing at all.
What do I need to do to maintain custom styles AND have the layers be hoverable and/or clickable?

A: How are you styling the intents? What is the value of your symbolizer hash 'default': { .. layer styles here ..} ???
I think you are creating an "empty" object and setting only some properties for your default and select style, for example:
default: {
    strokeColor: "red"
}

which produces a style with only one attribute and without lineWidth, strokeOpacity, etc.
Next code works fine for me. Also note the renderers must be specified in the layers instead in the protocol.
    var map = new OpenLayers.Map("map");

    // Create an OpenStreeMap raster layer and add to the map
    var osm = new OpenLayers.Layer.OSM();
    map.addLayer(osm);

    // Set view to zoom maximum map extent
    map.zoomToMaxExtent();

    // Create symbolizers inherited from the predefined styles and change only some properties.
    var defaultStyleSymbolizer = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    defaultStyleSymbolizer.strokeColor = "green";
    var selectStyleSymbolizer = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['select']);
    selectStyleSymbolizer.strokeColor = "red";

    // Create a vector layer
    var layer = new OpenLayers.Layer.Vector("zzzzz", {
      strategies: [
        new OpenLayers.Strategy.Fixed(),
      ],
      // Set the renderers
      renderers: ['Canvas','SVG'],
      // Apply the style map
      styleMap: new OpenLayers.StyleMap({
        'default': defaultStyleSymbolizer,
        'select': selectStyleSymbolizer
      }),
      protocol: new OpenLayers.Protocol.HTTP({
        url: "./global_undersea.kml",
        format: new OpenLayers.Format.KML({
          extractStyles: false,
          extractAttributes: true,
          maxDepth: 0
        })
      })
    });

    // The select control
    var selectFeature = new OpenLayers.Control.SelectFeature([layer], {
      renderIntent: "select",
      clickout: true,
      toggle: true
    });

    // Add layer and control
    map.addLayer(layer);
    map.addControl(selectFeature);
    selectFeature.activate();


text:
Q: Trouble tracing reverse function for doubly inked list I have a complete working  method to reverse a doubly linked list. To be honest I've been going back and fourth for months trying to trace this code to see exactly how it works but I get confused at the end of the while look when I update my current node with current.prev
Ive tried to print out the values of the nodes for each time it changes the next and previous pointers however I get a nullpointerexception, so no luck there.
public void reverse(){
    Node temp  = null;
    Node current = head;

    while(current != null){
        temp = current.prev;
        current.prev = current.next;
        current.next = temp;
        current = current.prev;
    }

    if(temp != null){
        head = temp.prev;
    }
}

There are no errors here, I passed it thru my own test cases for the worst and best scenario. I just can't seem to understand what is going on. I know this is essentially swapping the next and prev pointers but I need to know how.

A: public void reverse(){
// Create initial values
Node temp  = null;
// Note that you are using current to traverse through the linked list
Node current = head;

// While current is not at the end of the original (non-reversed) list
while(current != null){
    // Swapping prev and next
    temp = current.prev; // temp 'temporarily' holds copy of current.prev
    current.prev = current.next; // current.prev is overwritten with current.next
    current.next = temp; // current.next is overwritten with temp (containing original current.prev)
    // You are setting current to the newly redefined prev
    // This was equal to current->next in the original (non-reversed) list
    // So you are traversing through the original list
    // Anything 'before' this has already been reversed
    // Anything 'after' still needs to be reversed
    current = current.prev;
}

// Condition checks for edge case of a one node linked list
if(temp != null){
    // Set the head of the reversed list
    head = temp.prev;
}

Commented code above. I'm not a Java programmer, but in C I would print out the addresses of each node before and after the reversal to check I am doing things properly. Perhaps, you can use hashcodes to do something similar?

A: This is similar to a swap in Java:
  while(current != null){
        temp = current.prev;  //gets the 'end' of the doubly linked list
        current.prev = current.next; //sets the 'end' of the doubly linked list to the 'first' of the list
        current.next = temp;  //sets the 'first' of the list to temp, which is the 'end' of the list
        current = current.prev;  //iterate through the list in reverse order (similar to i++ in for loops)
    }

 if(temp != null){
        head = temp.prev;  //edge case when there is only 1 node.
    }


text:
Q: GitLab CI with r testthat package Can anyone run testthat tests for a minimal R package using GitLab.com continuous integration tools?
My attempt:
https://gitlab.com/djchapman/CI_example
This is the .gitlab-CI.yml text I am using,
image: rocker/rstudio
test:
   script:
    - R -e 'install.packages(c("devtools", "testthat"))'
    - R CMD build . --no-build-vignettes --no-manual
    - PKG_FILE_NAME=$(ls -1t *.tar.gz | head -n 1)
    - R CMD check "${PKG_FILE_NAME}" --no-build-vignettes --no-manual
    - R -e 'devtools::test()'

It is adapted from this website. I realize that devtools has dependencies which may need to be included as packages are installed, and I tried that, but the libraries for git2r didn't seem to install correctly, and now I wonder if I'm going about it wrong. Thanks.

A: You do not need to run the tests via devtools since R CMD check does that already. The following should work:
image: rocker/rstudio
test:
   script:
    - R -e 'install.packages(c("testthat"))'
    - R CMD build . --no-build-vignettes --no-manual
    - PKG_FILE_NAME=$(ls -1t *.tar.gz | head -n 1)
    - R CMD check "${PKG_FILE_NAME}" --no-build-vignettes --no-manual

Alternatively you could use an image that allows for binary installs:
image: rocker/r-base
test:
   script:
    - apt-get update
    - apt-get install --yes --no-install-recommends r-cran-testthat r-cran-devtools
    - R -e "devtools::install_deps()"
    - R CMD build . --no-build-vignettes --no-manual
    - PKG_FILE_NAME=$(ls -1t *.tar.gz | head -n 1)
    - R CMD check "${PKG_FILE_NAME}" --no-build-vignettes --no-manual

This is useful if you have dependencies that have not been packaged for Debian, or if you don't want to update your CI script when you add a new dependency.

A: For me this didn't work as expected. I found out that the problem was I had vignettes. Using the following content of my .gitlab-ci.yml, I worked around that problem:
image: rocker/r-base
gitlab:
   script:
    - apt-get update
    # install dependencies for package
    - apt-get install --yes --no-install-recommends r-cran-xml2 r-cran-testthat r-cran-devtools
    - R -e 'devtools::install_deps(dependencies = c("Depends", "Imports", "Suggests"))'
    # remove vignettes folder and get VignetteBuilder field out of DESCRIPTION file
    - rm -rf vignettes
    - R -e 'd <- read.dcf("DESCRIPTION"); d[, colnames(d) == "VignetteBuilder"] <- NA; write.dcf(d, "DESCRIPTION")'
    - R CMD build . --no-build-vignettes --no-manual
    - PKG_FILE_NAME=$(ls -1t *.tar.gz | head -n 1)
    - R CMD check "${PKG_FILE_NAME}" --no-build-vignettes --no-manual --as-cran
    # update code coverage
    - apt-get install --yes git
    - R -e "covr::codecov(token = 'mytoken')"

It removes the vignettes folder and removes the VignetteBuilder field from the DESCRIPTION file before it starts building. Quite convenient, although I now cannot test the contents of it.
After a while I found out that covr::codecov() works really well if you give the token as input (from https://codecov.io/gl/yourname/yourproject/settings) and install git on beforehand.


text:
Q: error Status: 'SyntaxError'. Error code: 0 is coming on jqgrid delete in Internet Explorer (please tell me any iconsistncies with jquery in IE like $("#tbl").delGridRow(selr,
{
   msg: "Delete selected rows",
   caption: "Delete Record",
   bSubmit: "Ok",
   bCancel: "Cancel",
   url: '#tbl'

});

i used this to delete data from jqgrid it giving error in IE only on delete ..

A: Remove , in end of the script i.e url: '#tbl'
$("#tbl").delGridRow(selr,
{
   msg: "Delete selected rows",
   caption: "Delete Record",
   bSubmit: "Ok",
   bCancel: "Cancel",
   url: '#tbl'

});


text:
Q: PyInstaller to create executable program that will pull a existing .xlsx file and read it I've been trying to find a solution to this problem for a long time now. So from what I understand when you pyinstaller --add-data 'file.xlsx:.' it will create the file.xlsx in the temporary folder and when the program runs it will pull the xlsx file from that temp folder. So if I edit the xlsx file when I run the executable it will not pull the new data from the xlsx file. It will use the old one that was created when I compiled the program.
I could be wrong so correct me if I am. I'm very sorry if this question is in a confusing format this is the first question I have asked. Please ask me if you want any more details on what I'm trying to do. This would be extremely helpful if someone could help me figure this out. Thank you!


text:
Q: Javascript "Tooltip" with continuously changing content I have a canvas element and I want to show a tooltip following the mouse pointer with the text in the tooltip continuously changing depending on what is currently under the pointer.
I have found qtip but it looks like it is geared more towards a declarative approach where you don't have the text in your tooltip continuously changing. Also it looks a bit of an overkill for a simple text tooltip. I may be wrong though.
So how do I show a tooltip (with the ability to continuously change its contents and coordinates) with javascript (any libraries permitted)?

A: theres a plugin http://koteako.com/hoverbox/
folowes your mouse youst change its content on mousemove

A: I ended up modifying the hoverbox plugin slightly to allow for the text to be updated while mouseover'ing the element so that I can set the title attribute in my other mouseover handler to update the hoverbox:
/*
 * jQuery Hoverbox 1.0
 * http://koteako.com/hoverbox/
 *
 * Copyright (c) 2009 Eugeniy Kalinin
 * Dual licensed under the MIT and GPL licenses.
 * http://koteako.com/hoverbox/license/
 */
/*
*  Slightly modfied to allow for updating the text
*  of the hoverbox while mouseover the element
*/
jQuery.fn.hoverbox = function(options) {
    var settings = jQuery.extend({
        id: 'tooltip',
        top: 0,
        left: 15
    }, options);

    var handle;
    var that;

    function tooltip(event) {
        if ( ! handle) {
            // Create an empty div to hold the tooltip
            handle = $('

').appendTo(document.body).hide();
        }

        if (event) {
            //update the text
            that.t = that.title;
            that.title = '';
            handle.html(that.t);

            // Make the tooltip follow a cursor
            handle.css({
                top: (event.pageY - settings.top) + "px",
                left: (event.pageX + settings.left) + "px"
            });
        }
        return handle;
    }

    this.each(function() {
        $(this).hover(
            function(e) {
                that = this;
                tooltip(e).fadeIn('fast');
            },
            function() {
                if (this.t) {
                    this.title = this.t;
                    tooltip().hide();
                }
            }
        );
        $(this).mousemove(tooltip);
    });
};


text:
Q: Relation between ostream insertion operator and its non-member overload int i=0;
std::cout << i;

1, The non-member overload(two arguments, one being ostream& the other being type of operand, say int) is defined in std namespace. So if using namespace std; is not present, there's no way I see that the non-member overload can be called.
2, If instead, the member operator(member of ostream; one argument, being the type of operand, say int) function << of ostream is called, I'd expect something like: std::cout.operator<< i; --- isn't this rediculous?
So, what on earth is the relation between the two?
Question extended: if I want to overload the insertion operator so that std::cout << my_obj; works(assume my_obj is the instance of a user-defined type, MyType), should I do
a) ostream& operator<< (ostream& os, MyType obj); in the namespace of MyType
or
b) in MyType:
class MyType
{
 ...
   ostream& operator<< (MyType);
};

does option b) ever work? Does it even make sense(I remember seeing it somewhere ...)? What's the relation between option a) & b)?

EDIT MAR 27
Upon the request from ecatmur, here're two overloads that have the same signature but in different namespaces. Using gcc 4.9.2: http://melpon.org/wandbox/
#include <iostream>

namespace MyNameSpace
{
    class MyType
    {};

    // signature can be found here: http://www.cplusplus.com/reference/ostream/ostream/operator-free/
    std::ostream& operator<<(std::ostream& out, char ch)
    {
        out << "std is doomed\n";
        return out;
    }

    std::ostream& operator<<(std::ostream& out, MyType t)
    {
        out << "std is super doomed\n";
        return out;
    }
}

int main()
{
    MyNameSpace::MyType t;
    std::cout << t; // ... super doomed; ADL is working as intended.
    std::cout << 't'; // t; this proves that when there're two operator overloads with the same signature but in different namespaces, there're no compilation errors. gcc defaults to the std one.
    return 0;
}

A: The non-member overloads you're thinking of are those for character data and those for std::string etc.; they're available via argument-dependent lookup.  You can indeed write std::cout.operator<<(i) for types where ostream has a member operator<<.
For your own types you're thinking of a (non-member) friend operator<<, which can be particularly useful for template classes (the Barton-Nackman trick) or for those where the operator<< accesses data not available via accessors:
class MyType
{
 ...
   friend std::ostream& operator<< (std::ostream&, MyType obj) { ... }
};

Your proposed signature would allow you to write my_obj << my_obj, which is unlikely to make much sense.


text:
Q: Way to achieve backwards compatibility from PHP 5.3 to 5.2 (Pre processor directive?) I have written a cool little PHP library but it makes use of closures which cause a PARSE ERROR (not a runtime error!) when I run the app on my webhost (1and1). What I would love is something like a c++ preprocessor directive or an CSS version-specific comment that basically ignores a segment of code for PHP < 5.3
$this->register_validator(
    function($val) use ($length_expr)
    {
        $x = strlen($val);
        return eval("return $x $length_expr;");
    }
);

A: I think there is a syntax error, which causes the parse error in the eval()'d code.
I tried it in PHP 5.2.17 and 5.3.6 too:
You can not return two values inmediately, like this:
return $x $legth_expr;

This is throwing a parse error in the mentioned two versions.
What do you want to achieve exactly?


text:
Q: Rotating image caption with the images I have a photogallery in which i have rotating images with pagination. I want to display a caption below the image and caption should also change as the image changes.
I wrote the following html code

        #IMG#

        #CAPTION#

The problem with this is that the caption for all images is displayed together below the images not rotating.. :(

A: Without seeing the rest of your code, I would think you have ONE slider and have this

#CAPTION#

and
var captions["Caption for image1", "Caption for image2"]

and change the onChange part of your script
onChange: function(previndex, curindex){
//event handler fired whenever script changes slide
//previndex holds index of last slide viewed b4 current (1=1st slide, 2nd=2nd etc)
//curindex holds index of currently shown slide (1=1st slide, 2nd=2nd etc)
 document.getElementById("caption").innerHTML=captions[curindex];
}


text:
Q: I am getting some extra message when i call my php file from android app I have just started connecting android app with php
My file works very fine when i run on local wamp server
After uploading on remote server , I am getting what i want but i am getting some extra code on my emulator. I want to get rid of it
Please help.
When i call the same file in my chrome using an html file then also it works fine.
Here is code of my android app
public class LoginActivity extends Activity {

HttpClient hc;
HttpPost hp;
List<NameValuePair> nvp;
HttpResponse hr;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final EditText username=(EditText) findViewById(R.id.username);
    final  EditText password=(EditText) findViewById(R.id.password);
    Button b=(Button) findViewById(R.id.register);
    final  TextView res=(TextView) findViewById(R.id.textView3);

    b.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // String result="Username: "+username.getText().toString()+"\n"+"Password: "+password.getText().toString();
            //res.setText(result);
            try
            {
                hc=new DefaultHttpClient();
                hp=new HttpPost("http://pratik30.host56.com/insertquery.php");
                nvp=new ArrayList<NameValuePair>(2);
                nvp.add(newBasicNameValuePair("username", username.getText().toString()));
                nvp.add(new BasicNameValuePair("password", password.getText().toString()));
                hp.setEntity(new UrlEncodedFormEntity(nvp));
                //hr=hc.execute(hp);
                ResponseHandler<String> rs= new BasicResponseHandler();
                String r=hc.execute(hp,rs);
                res.setText(r);
            }
            catch(Exception e)
            {
                res.setText(e.getLocalizedMessage());
            }
        }
    });
}

}
Here is the php file
<?php
    $dbc=mysqli_connect('localhost','root','mypassword','pratik') or die('Error connecting to mysql server');
    $user=$_POST['username'];
    $pass=$_POST['password'];
    echo $user;
    echo $pass;
    $query = "Insert into users values ('$user','$pass');";
    $result=mysqli_query($dbc,$query) or die('Error querying database');
    mysqli_close($dbc);
?>

Here is a picture of the output I am getting.

A: Your php  returns the following you have to remove it  from there:

you're setting the whole result text into your
TextView res.setText(r);

hope it helps.


text:
Q: does affine transformation change neighbourhood
I have a set of 100 points.
I am considering 4 closest neighbour of each point.
Using three (non-collinear) points as basis among these four, I get affine coordinate of the fourth point.
This way I create database for 100 points.
There are 100 x 4C3 x 3 records. Each having an affine coordinate.
Now, I did affine transformation on all 100 points.
Specifically ,
If a point is (x,y)
It becomes new_x = x+2y+5
It becomes new_y = 3x+4y+6
I have observed that closest neighbours of all points got changed.
Actually some points had 1 or 2 neighbours as before, but rest changed.As a result affine coordinate matching did not work.
Note that I am calculating closest neighbour using euclidean distance i.e sqrt((x2-x1)2+(y2-y1)2).
When I think about affine transformation - I feel rotation,scaling and translation won't change neighbours but shearing maybe can.
Is my transformation not affine ?
Can you suggest a better way to get neighbours ?
Thanks.


text:
Q: I am unable to import a file no matter what I do And although this was asked a MILLION times, this case is special, because either I am very dumb, or my laptop is.
So to make sure that everybody is on the same page, here is what I want to do: use import menu inside of fish life imulator.py, and here is the file tree that I did:

*

*fish_life_simulator

*

*fish_life_simulator.py

*extra_programs

*

*__init__.py

*menu.py
And I tried EVERYTHING that I found, os.chdir redirect to the extra programs folder, sys.path.append or sys.path.insert, import file or from file import def, __init__.py as you can see, but I always seem to get the same error: ModuleNotFoundError: No module named 'menu'
Edit: here is a sample of my code:
fish_life_simulator
import pygame, random, time, sys, os
from pygame.locals import *

os.chdir(os.path.dirname(__file__))

pygame.init()

size_of_monitor = pygame.display.Info()

flags = RESIZABLE

width = size_of_monitor.current_w - 25
height = size_of_monitor.current_h - 50

from extra_programs import menu

screen, screen_size, menu_background_image, menu_background_stretched_image, menu_background_rect = initiation(width, height, flags)

menu.py
def initiation(width, height, flags):

    screen = pygame.display.set_mode((width, height), flags)

    screen_size = screen.get_size()

    menu_background_image = pygame.image.load(r'sprites\menu_background.jpg')
    menu_background_stretched_image = pygame.transform.scale(menu_background_image, (screen_size))
    menu_background_rect = menu_background_stretched_image.get_rect()

    return screen, screen_size, menu_background_image, menu_background_stretched_image, menu_background_rectscreen, screen_size, menu_background_image, menu_background_stretched_image, menu_background_rect

A: Inside a folder fish_life_simulator execute
PYTHONPATH=. python fish_life_simulator.py

Where in fish_life_simulator.py your import are
from extra_programs import menu
...

Or one level outside folder fish_life_simulator execute
PYTHONPATH=fish_life_simulator/  python fish_life_simulator/fish_life_simulator.py

Where in fish_life_simulator.py your import are
from fish_life_simulator.extra_programs import menu
...

A: I got it to work with the following folder structure and the following code:
fish_life_simulator
|-- extra_programs
|   |-- __init__.py
|   `-- menu.py
`-- fish_life_simulator.py

menu.py
def menu():
    print("hello from menu")

fish_life_simulator.py
from extra_programs import menu

menu.menu()

There is no need at all to edit the path or something like that.
Just navigate into the folder fish_life_simulator and run the code with python fish_life_simulator.py.
If you don't want to type the menu. prefix, you can adapt fish_life_simulator.py like below:
from extra_programs.menu import menu

menu()

In your code, you are lacking the prefix, when calling initiation(...), it should be menu.initiation(...). You need to decide for one of the above ways to import.


text:
Q: Post parameters during asmx web service call I am trying to make a web service call to following address: http://www.webservicex.net/CurrencyConvertor.asmx?op=ConversionRate
However, I get WebException : Protocol Error. So, I need some help to find where I went wrong. Thanks.
protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        string FromCurrency = "GBP";
        string ToCurrency = "ALL";

        string postString = string.Format("FromCurrency={0}&ToCurrency={1}", FromCurrency, ToCurrency);
        const string contentType = "application/x-www-form-urlencoded";
        System.Net.ServicePointManager.Expect100Continue = false;

        // Creates an HttpWebRequest for the specified URL.
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.webservicex.net/CurrencyConvertor.asmx?op=ConversionRate");
        req.ContentType = "text/xml;charset=\"utf-8\"";
        req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        req.Method = "POST";
        req.ContentLength = postString.Length;
        req.Referer = "http://webservicex.net";

            StreamWriter requestWriter = new StreamWriter(req.GetRequestStream());
            requestWriter.Write(postString);
            requestWriter.Close();

            StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream());
            string responseData = responseReader.ReadToEnd();

            responseReader.Close();
            req.GetResponse().Close();
    }

    catch (WebException ex)
    {
        Response.Write("\r\nWebException Raised. The following error occured : {0}" + ex.Status);
    }
    catch (Exception exc)
    {
        Response.Write("\nThe following Exception was raised : {0}" + exc.Message);
    }
}

A: I guess you are getting protocol exception because service is SOAP based. It would be easier to add service reference to that service from http://www.webservicex.net/CurrencyConvertor.asmx?WSDL. And then you could use that service as following:
static void Main(string[] args)
    {
        ServiceReference1.CurrencyConvertorSoapClient client = new ServiceReference1.CurrencyConvertorSoapClient("CurrencyConvertorSoap");
        client.Open();
        double conversionResult = client.ConversionRate(ServiceReference1.Currency.AED, ServiceReference1.Currency.ANG);
        Console.WriteLine("{0} to {1} conversion rate is {2}", ServiceReference1.Currency.AED, ServiceReference1.Currency.ANG, conversionResult);
        client.Close();
        Console.Read();
    }

[Edit]
Sorry for misunderstanding. Here is how to call SOAP services without adding service reference:
static void Main(string[] args)
    {
        HttpWebRequest request = CreateWebRequest();
        //Create xml document for soap envelope
        XmlDocument soapEnvelopeXml = new XmlDocument();
       //string variable for storing body of xml document
       //with parameters for  FromCurrency and ToCurrency
        string soapEnvelope =
            @"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
                <s:Body xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
                    <ConversionRate xmlns=""http://www.webserviceX.NET/"">
                        <FromCurrency>{0}</FromCurrency>
                        <ToCurrency>{1}</ToCurrency>
                    </ConversionRate>
                </s:Body>
              </s:Envelope>";
        //add your desired currency types
        soapEnvelopeXml.LoadXml(string.Format(soapEnvelope, "USD", "EUR"));
        //add your xml to request
        using (Stream stream = request.GetRequestStream())
        {
            soapEnvelopeXml.Save(stream);
        }
        //call soap service
        using (WebResponse response = request.GetResponse())
        {
            using (StreamReader rd = new StreamReader(response.GetResponseStream()))
            {
                string soapResult = rd.ReadToEnd(); //read the xml result
                //you can handle xml and get the conversion result, but here
                //I'm outputting raw xml.
                Console.WriteLine(soapResult);
            }
        }

        Console.Read();
    }

    public static HttpWebRequest CreateWebRequest()
    {
        //create web request for calling soap service
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@"http://www.webservicex.net/CurrencyConvertor.asmx");
        //add soap header
        webRequest.Headers.Add(@"SOAP:Action");
        //content type should be text/xml
        webRequest.ContentType = "text/xml; charset=\"utf-8\"";
        //response also will be in xml, so request should accept it
        webRequest.Accept = "text/xml";
        webRequest.Method = "POST";
        return webRequest;
    }

As you see, you should use xml for sending request. I added comments where they are necessary.


text:
Q: How do i use firebase realtime database and firestore together in one app in angular I am setting up a new project on angular using firebase. After certain period of time I realise I need the firestore also included into my project. Now the problem is that how do I configure that in one application in angular so that I can use firebase realtime database and firestore together.
This is my firebase realtime database configuration in angular -
export const environment = {
  production: false,
  firebaseConfig: {
    apiKey: "apikey",
    authDomain: "friendlyeats-3f66a.firebaseapp.com",
    databaseURL: "https://friendlyeats-3f66a.firebaseio.com",
    projectId: "friendlyeats-3f66a",
    storageBucket: "friendlyeats-3f66a.appspot.com",
    messagingSenderId: "xxxxxxxxxxxx",
    appId: "1:xxxxxxxxxxxx:web:546e663bfcf9179d"
  }
};

A: There's nothing stopping you from using Cloud Firestore and Realtime Database in the same application, in the same project.  Nothing special needs to be configured for that.  Just use each SDK as you would normally.

A: You just once init AngularFireModule.initializeApp(envi) then u just import modules like for real time database: AngularFireDatabaseModule Cloud store: AngularFirestoreModule Auth: AngularFireAuthModule or functions: AngularFireFunctionsModule
imports: [
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFirestoreModule,
    AngularFireDatabaseModule,
    AngularFireFunctionsModule,
    AngularFireAuthModule,
  ],


text:
Q: Why these functions delete all my data on json-server? First of all sorry for my English. I have a problem. Why is this thing delete all my data in json-server?
taskSlice.js file
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
  tasks: [],
  taskDetail: [],
};

export const tasksSlices = createSlice({
  name: "task",
  initialState,
  reducers: {
    setTasks: (state, action) => {
      state.tasks = action.payload;
      console.log(action.payload);
    },
  },
});

export const { setTasks } = tasksSlices.actions;
export default tasksSlices.reducer;

api.js file
import { setTasks } from "../../slices/tasksSlice";
import axios from "axios";

export const deleteTask = (id) => async (dispatch) => {
  const response = await axios.delete("http://localhost:5000/tasks/" + id);
  dispatch(setTasks(response.data));
};

export const fetchTasks = () => async (dispatch) => {
  const response = await axios.get("http://localhost:5000/tasks");
  dispatch(setTasks(response.data));
};

Tasks.jsx file
const Tasks = () => {
  const tasks = useSelector((state) => state.task.tasks);
  const dispatch = useDispatch();

  const handleTaskDelete = (id) => {
    dispatch(deleteTask(id));
    console.log(id);
  };
  useEffect(() => {
    dispatch(fetchTasks());
  }, [dispatch]);
  return (
    <div
      className="vh-100"
      style={{
        background: `url(${bgTask})`,
        backgroundSize: "600px",
        backgroundRepeat: "no-repeat",
        backgroundPosition: "right bottom",
      }}
    >

Tasks List

      {tasks?.length > 0 ? (
        <TasksContent tasks={tasks} handleTaskDelete={handleTaskDelete} />
      ) : (

...

      )}

  );
};
export default Tasks;

TasksContent.jsx file
import TasksUserContent from "./TasksUserContent";

const TasksContent = ({ tasks, handleTaskDelete }) => {
  return tasks?.map((task) => (

 handleTaskDelete(task.id)}>

{task.title}

{task.info}

          <TasksUserContent taskId={task.employeeId} />

  ));
};

export default TasksContent;

First of all sorry for my English. I have a problem. Why is this thing delete all my data in json-server? I try everything that what I know. But I don't know what should I do?


text:
Q: Button not changing its position when clicked What am I doing wrong here? How can I make this work? http://jsfiddle.net/qUjDa/
The button only moves if I click on the right side of the button or below it, but If I click on the button nothing happens and I want it to move like it moves when I click on the right side of it. I'm newbie with javascript so I don't how to do this right.
Here's the code:
html

css
.button.move{margin-left:50px;}

Js
var d = document.getElementById("button");
d.addEventListener('click',function(){
    d.className = d.className + " move";
});

A: Click events inside an iFrame don't bubble out of the iFrame. Regardless, you can't actually do what you're doing, putting an iframe inside a button. That's invalid. An iframe cannot exist inside a button.
You cannot use vanilla jQuery to detect when somebody interacts with a Facebook Like button. You need to use Facebooks API for that:
https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/v2.0


text:
Q: Problema com Bundle no servidor Bom dia,
fui implementar o uso de bundle no meu projeto ASP.NET MVC, no ambiente de desenvolvimento funcionou perfeitamente. Porém quando subo no servidor o mesmo não funciona. Fui debugar no navegador e ele da o seguinte retorno:
"Resource interpreted as Stylesheet but transferred with MIME type text/html"
Alguém poderia me dar alguma dica de como solucionar este problema?
BundleConfig.cs:
        bundles.Add(new StyleBundle("~/auth/css").Include(
            "~/Content/assets/bootstrap/css/bootstrap.css",
            "~/Content/assets/css/user.css",
            "~/Content/font/css/font-awesome.min.css"));

View onde faço a chamada:

    <title>Recuperar Senha</title>
    @Styles.Render("~/auth/css")

                     voltar

Esqueceu sua Senha - PráticoERP

                    @Html.Partial("_AlertMessage")

                    @using (Html.BeginForm())
                    {

                            @Html.TextBox("login", null, new { @class = "form-control", placeholder = "Login" })

                            @Html.TextBox("email", null, new { @class = "form-control", placeholder = "Email" })

                                <button type="submit" class="btn btn-lg btn-block btn-success" disabled>Recuperar senha</button>

                                    Não tem conta?
                                    Entre em contato

                    }

Agradeço dês de já.

A: É preciso instalar o recurso de Static Content do IIS para que arquivos CSS sejam distribuídos com o tipo MIME correto. Esta configuração pode ser feita através do menu Ativar ou Desativar Recursos do Windows (Add or Remove Windows Features):


text:
Q: The same component render two times I want render the same component instance of <Child /> two times in <Parent /> component.
index.js
import React from 'react';
import { render } from 'react-dom';

import Parent from './Parent';

render(
  <Parent />,
  document.getElementById('root')
);

Parent.js
import React from 'react';
import Child from './Child';

const child = <Child />

export default () => {
  return (
    <>
      {child}
      {child}
    </>
  )
}

Child.js
import React, { useState } from 'react';

function generateRandomString() {
  return Math.random().toString();
}

export default () => {
  const [text, setText] = useState(generateRandomString());

  function onClickHandler() {
    setText(generateRandomString());
  }

  return (

text: {text}

  )
}

Is it possible to do?

A: You are treating component as value. Just change your parent.js as follow.
import React from 'react';
import Child from './Child';
export default () => {
  return (

     <Child/>
     <Child/>

 )
}


text:
Q: independently change the background image of each page of QStackedWidget I would like to independently change the background image of each page of the stacked widget . However, when I add background-image: to the styleSheet tab on Qt creator, the result is that all the pages of the stacked widget get that background image.
Is there a way to set a different background image to each page with out using QT's styleSheet Method

A: Try this:
QWidget *widget = stackWidget->currentWidget();
QPixmap background("/home/user/Pictures/background.png");
bkgnd = background.scaled(widget->size(), Qt::IgnoreAspectRatio);
QPalette palette;
palette.setBrush(QPalette::Background, background);
widget->setPalette(palette);


text:
Q: Referencing a listing and getting two question marks I'm using TexShop 4.69 and I'm using lstlistings. But now after inserting my 3rd lstlisting, I can't get an adequate reference number. I'm receiving now two "??" in my text. Can somebody please give me a tip?
See Listing \ref{lst:codejson}.

 \begin{lstlisting}
[caption={JSON Format},captionpos=b,label=lst:codejson,language=bash]

[{
"id":0,
"category":"Category",
"chapter":"Chapter",
"requester":"Requester",
"version":"Version",
},
...
]
 \end{lstlisting}

A: The bracket introducing the options to lstlistings must be in the same line as \begin{lstlisting}.
With your code I get

and you see that the options are treated as part of the listing.
\documentclass{article}
\usepackage{listings}

\begin{document}

See Listing \ref{lst:codejson}.

\begin{lstlisting}[
  caption={JSON Format},
  captionpos=b,
  label=lst:codejson,
language=bash
]
[{
"id":0,
"category":"Category",
"chapter":"Chapter",
"requester":"Requester",
"version":"Version",
},
...
]
\end{lstlisting}

\end{document}


text:
Q: Is it valid to use const char*[] as the type of second parameter of main I am learning C++ and learnt that the following given declarations are equivalent:
int main (int argc, char *argv[]); //first declaration
int main (int argc, char **argv);  //RE-DECLARATION. Equivalent to the above declaration

My question is that if i change the declaration to say:
//note the added const
int main (int argc,const char *argv[]); //IS THIS VALID?

Is the above declaration where i have added a const valid? That is, does the C++ standard allow this modified declaration with the added const.

A: Adding const changes the type of the function. It is not declaration of the same function.
Whether that is valid for main in particular, depends on language implementation:

[basic.start.main]
An implementation shall not predefine the main function.
Its type shall have C++ language linkage and it shall have a declared return type of type int, but otherwise its type is implementation-defined.
An implementation shall allow both

*

*a function of () returning int and

*a function of (int, pointer to pointer to char) returning int

as the type of main ([dcl.fct]).

It may in theory be valid in some implementation, but it will not be portable to all systems.

A: According to cppreference.com (main_function), main should have one of the following forms:
int main () { body }    (1)
int main (int argc, char *argv[]) { body }  (2)
/* another implementation-defined form, with int as return type */  (3)

Using int main (int argc,const char *argv[]) (your suggested variation) works for example in MSVC. This case falls under form (3) above.
But since it is implementation-defined it is better to avoid (even if works in your current environment).


text:
Q: formtools.org preg_replace /e I need to install formtools.org on multiple domains, but because of its use of preg_replace(),  my hosting company won't allow this. I've searched their forums with not luck (I can't get access to ask a question)
I believe if the following can be rewritten using preg_replace_callback() this would solve all my problems.
    $source_content = preg_replace($search.'e', "'"
. $this->_quote_replace($this->left_delimiter) . 'php'
. "' . str_repeat(\"\n\", substr_count('\\0', \"\n\")) .'"
. $this->_quote_replace($this->right_delimiter)
. "'"
, $source_content);

Any help would be greatly appreciated!

A: If the service doesn't support preg_replace(), I would be surprised if it supports preg_replace_callback() (since they are essentially the same).  However, if the problem is due to the deprecated e modifier, preg_replace_callback() will help.
Using preg_replace_callback() is very simple, the second parameter is a callable function to create your replacement text.  This function takes one parameter which is an array of that match's groups.  So reset($matches) in my answer is similar to the \\0 in your example.  Try this:
$source_content = preg_replace_callback(
  $search,
  function($matches) {
    $match = reset($matches);
    $count = substr_count($match, "\n");

    $string = "'" . $this->_quote_replace($this->left_delimiter) . "php'";
    $string .= str_repeat("\n", $count);
    $string .= "'" . $this->_quote_replace($this->right_delimiter) . "'";

    return $string;
  },
  $source_content
);

Note: since I don't have the easiest way to test this without making up your functions, expression, and $source_content, this is just translated from scratch.  If you have any errors, please comment (instead of downvoting) and I can work to fix them :)


text:
Q: average 3d matrix matlab using reshape I have a 27x38x8760 matrix where the 27x38 represents a grid and the 8760 hours of the year. I would like to make daily avarages for the grid so that my resulting matrix is 27x38x365.
I was using reshape for 2 dimensional matrix but is there a posibily to use it also for 3d?
kind regards Matthias

A: Assuming A to be the input matrix, see if this works for you -
[m,n,r] = size(A)
daily_avg = squeeze(mean(reshape(A,m,n,24,[]),3))

Or avoid squeeze with permute -
daily_avg = mean(permute(reshape(A,m,n,24,[]),[1 2 4 3]),4)

A: You can also use a loop,
A = rand([27 38 8760]);
for i = 1 : 24 :8760
    A_avg(:,:,ceil(i / 24)) = mean(A(:,:,i : i + 23),3);
end


text:
Q: How to add background image in CocosSharp? I have used this code to add background image in CCLayer but it's not working:
public class GameLayer : CCLayerColor
{
    private CCSprite background;
    public GameLayer() : base(CCColor4B.Transparent)
    {
        background = new CCSprite("cbg")
        {
            AnchorPoint = new CCPoint(0, 0),
            IsAntialiased = true,
            Position = new CCPoint(0, 0),

        };
        this.AddChild(background);
    }
}

My problem is image is displaying but not of screen size as background image, its just displaying at the bottom-left corner of the screen.
EDIT:
Solved:
To solve this problem I have added Contnetsize to my image same as screen size.

A: Here is the code I use to display a background :
var sprite = new CCSprite("bg.jpg");
sprite.AnchorPoint = new CCPoint(0, 0);
sprite.IsAntialiased = false;
layer.AddChild(sprite);

almost the same code, but CocosSharp has strange behaviours sometimes.


text:
Q: What is the best optimization method for WordPress i have a website about the social media which is http://www.vuub.net but my site is very slow and i thought it's about the Theme. How can i reduce to server load time an easy way. I am using WP Super Cache plug-in but still have a problem about the server load time. Thanks for advice!

A: Here are few articles, hope it will helps you,

*

*http://wp.tutsplus.com/tutorials/10-quick-tips-optimizing-speeding-up-your-wordpress-site/

*http://graphpaperpress.com/blog/10-seo-tips-for-wordpress-websites/

*http://www.inkthemes.com/12-ways-to-optimize-speed-of-large-wordpress-websites/01/

A: First of all like the your website look but as you can say, site performance are is not good right now. Here is the some steps before the move for more advancing steps;
1) De-activate all of your plug-ins.
2) Try the use W3 Total Cache instead of WP Super Cache.
After to using this methods come and we can speak again. Also while you are from Turkiye, you can check my web site about more advancing steps about the WordPress and WordPress Optimization; http://www.fatihtoprak.com
Cheers,


text:
Q: MSMQ service does not recover when restarted with Recoverable message on queue I have a private, non-transactional message queue running on Win2008 R2. The queue breaks when I do the following:

*

*Place a recoverable message on a queue like so:
Message msg = new Message
{
  Body = "hello",
  Formatter = new XmlMessageFormatter(),
  Label = "Notification",
  Recoverable = true,
  AppSpecific = 123
};

mq.Send(msg);

Do not retrieve the message!

*Restart the Message Queue service

*The service does not successfully restart. The following message is logged in the Event Viewer:
The Message Queuing service cannot start because a queue is in an
inconsistent state. For more information, see Microsoft Knowledge
Base article 827493 at support.microsoft.com.

Points to note:

*

*A message added to the queue this way can be successfully retrieved from the queue before restart.

*The only way I can get the queue running again is to follow these instructions: MSMQ Inconsistent State After Restart but this obviously prevents message recovery.

*If I leave Message.Recoverable = false then the service restarts successfully. But I want my messages to survive a service restart.

*I get exactly the same behaviour when I set the queue as Transactional.

Any ideas?

A: Give your machine name less than 15 characters then it will works. This is due to Netbios names can only be 15 characters or less. This was causing problems with the MSMQ Service as a result it was ending up in the inconsistent state as specified in the error. To fix this issue, uninstalled MSMQ, renamed the machine to something smaller than 15 characters and then reinstalled MSMQ. This resolved the issue.

A: Sounds like something is interfering with the storage files.
Recoverable (which includes transactional) messages are written to files in the MSMQ\Storage directory as well as being mapped into memory.
On startup, the files are reloaded to recreate the messages mapped into memory.
For some reason these storage files don't work anymore.
Things I would look for:

*

*Any other software that has access to the system32\msmq directory tree, such as Anti Virus products. Block these products from the directory tree.

*Is storage on a locally attached disk or a network drive (e.g. SAN); if not local try reconfiguring MSMQ to use the local disk.

*Is the disk error-free? Run chkdsk or similar.

*If you create a new provate queue, does the problem affect that too?

Cheers
John Breakwell

A: Try moving the msmq dirctory to a different location. Maybe there is a permission problem on the disk.


text:
Q: SSL error when trying to open Jupyter server on aws I am using windows 10, and configure my aws configuration followed tutorial here
https://docs.aws.amazon.com/dlami/latest/devguide/setup-jupyter.html
The TCP/IP port has been open for 8888, so is my putty connection add the tunnel for 8888. Yet still when I access the Jupyter from browser, I have error says:
This page isn't working 127.0.0.1 didn't send any data.
When I looked at server side, there's an SSL error, how do I proceed to open the jupyter notebook from browser ?


text:
Q: Is it possible to manually set Work Item ID in Team Foundation Server 2010? Is it possible to manually set Work Item IDs in Team Foundation Server 2010?
When I put the id field on the work item layout it's automatically set as readonly.

A: No it is the identifier of the workitems and cannot be changed.
If you want to have a reference number (for e.g. another ticketing system), then add a new field.
If you want to start with a certain value, then create first n dummy work items to reach that number: http://blog.hinshelwood.com/archive/2010/10/20/tfs-2010-work-item-seed-tfs-work-item-system.id-at.aspx


text:
Q: Regex Conversion issues from PHP to Javascript Basically, I don't have knowledge on how to build a regex, currently I am having
PHP regex as
/^[\w\s'-\/\.\,\(\)\\\]{0,100}$/

But now I want to convert this regex into Javascript compatible regex.
How to make the above regex compatible in Javascript?

A: You have too many escape characters in your regex, other thatn that, it should Work.
So here's a modified version that should Work, although it's a strange regex that will always match zero to 100 characters:
/^[\w\s'-\/\.,\(\)\\]{0,100}$/

A: The backslash character is used to escape metacharacters. In sets (between square brackets) you don't need to escape most metacharacters.
This will do as well:
^[\w\s'-/.,()\\]{0,100}$
In PHP, you can escape a backslash with three or four backslashes:
\\\ - Escapes a backslash (PHP)
\\\\ - Also escapes a backslash (PHP)
But please don't mix and match as it's confusing and prone to mishaps.
With JavaScript, you have to represent a literal backslash with exactly two backslashes.
\\ - Escapes a backslash (JS)
Here is a further resource: https://javascript.info/regexp-character-sets-and-ranges#no-escaping-in-
If you have a couple hours to spend, I learnt most of what I know about regexes with Sam's Teach Yourself. The material is focused on PCRE, but is 98% useful for JS as well. You'll be happier; regexes are tough.


text:
Q: If $x=\frac{1}{z}$ and $y=f(x)$ then $\frac{d^2f}{dx^2}=2z^3.\frac{dy}{dz}+z^4.\frac{d^2y}{dz^2}$ If $x=\frac{1}{z}$ and $y=f(x)$ then prove that:

$$\frac{d^2f}{dx^2}=2z^3.\frac{dy}{dz}+z^4.\frac{d^2y}{dz^2}$$

How should I approach this? I don't know how to eliminate $f'$  term.

A: Write down
$$
y(z)=f\Bigl(\frac1z\Bigr)\text{ resp. }f(x)=y\Bigl(\frac1x\Bigr)
$$
and apply the differentiation theorems, Alexandre Chain's rule etc.
$$
y'(z)=f'\Bigl(\frac1z\Bigr)·\Bigl(-\frac1{z^2}\Bigr),\quad y''(z)=f''\Bigl(\frac1z\Bigr)·\Bigl(-\frac1{z^2}\Bigr)^2+f'\Bigl(\frac1z\Bigr)·\Bigl(\frac2{z^3}\Bigr)
$$
resp.
$$
f'(x)=y'\Bigl(\frac1x\Bigr)·\Bigl(-\frac1{x^2}\Bigr),\quad f''(x)=y''\Bigl(\frac1x\Bigr)·\Bigl(-\frac1{x^2}\Bigr)^2+y'\Bigl(\frac1x\Bigr)·\Bigl(\frac2{x^3}\Bigr).
$$
Partially replacing $\frac1x$ by $z$ gives then
$$
f''(x)=z^4·y''(z)+2z^3·y'(z)
$$

A: You should use the chain rule. Suppose that $y=f(x)$ and $x=g(z)$. Then we have
$$y=f \circ g$$
and hence chain rule for the first derivative will be
$$\frac{dy}{dz} = \left( \frac{df}{dx}\circ g \right) \frac{dg}{dz}$$
and then using the product rule and chain rule again we will get
$$\frac{d^2y}{dz^2} = \left( \frac{d^2f}{dx^2}\circ g \right) \left( \frac{dg}{dz} \right)^2 + \left( \frac{df}{dx}\circ g \right) \frac{d^2g}{dz^2}$$


text:
Q: Doctrine2 - select from multiple tables with no direct relations This question is about selecting data from multiple tables, joins, Doctrine2, ResultSetMapping, DQL and such stuff.
I have 4 tables:

*

*user

*contact

*contact_phone

*call

With relations as shown on the image: http://i.stack.imgur.com/762Jw.png
Every user can have many contacts, each contact can have many phones and each user can have many calls to/from his contacts. Just like in the real world... I've limited the number of fields in each table just for clarity.
So my problem is that I don't know how exactly to map call numbers to contact names when showing a list of calls for a specific user.
If I want to list all calls of user 1 I do:
    $callRepository = $this->getDoctrine()->getRepository('MyBundle:Call');
    $calls = $callRepository->findAll(array('user' => 1));

But this will give me just the list of all calls for this user and will not associate number (call.number) with names (contact.name).
I can achieve what I want with plain SQL with this query:
SELECT
    c.number,
    contact.name
FROM
     `call` c
JOIN contact_phone cp ON
    cp.number = c.number
JOIN contact ON
    contact.id = cp.contact_id
WHERE
    c.user_id = contact.user_id
    AND c.user_id = 1

Please note that I don't want to select all calls (with SQL) and then map numbers to names with another query from the PHP layer because this way I won't be able to search the calls by name for example.
I was thinking that ResultSetMapping could help me in this case but I have no luck putting the SQL query and the ResultSetMapping together.
Please help,
Thanks!

A: As per my knowledge, you can acheive by using the below methods. Please go to bottom of the page. you can find Joins... try once..
http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/dql-doctrine-query-language.html


text:
Q: Fetching data from entity in one to many relationship in Core data I have 2 entities. 1 called WishListElement and other WishListContainer.

 -(BOOL)addElementToWishList:(WishListElement*)element
{
  ASAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
_managedObjectContext = [appDelegate managedObjectContext];

WishListElement *wishList = [NSEntityDescription insertNewObjectForEntityForName:@"WishListElement" inManagedObjectContext:_managedObjectContext];

[wishList setAppName: element.appName];
[wishList setAppPrice: element.appPrice];
[wishList setAppCategory: element.appCategory];
[wishList setAppSummary: element.appSummary];
[wishList setAppCopyright:element.appCopyright];
[wishList setAppAuthor: element.appAuthor];
[wishList setAppImage:element.appImage];

NSError *error = nil;
[_managedObjectContext save:&error];

WishListContainer *wishListContainer = [NSEntityDescription insertNewObjectForEntityForName:@"WishListContainer" inManagedObjectContext:_managedObjectContext];
[wishListContainer addContainsObject:wishList];

if (![_managedObjectContext save:&error])
{
    return NO;
}
else
{
    return YES;
}
}

 -(NSMutableArray*)getWishListElement
{
ASAppDelegate *appDelegate = (ASAppDelegate*) [[UIApplication sharedApplication]delegate];
_managedObjectContext = [appDelegate managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"WishListContainer" inManagedObjectContext:_managedObjectContext];
[request setEntity:entity];

NSError *error = nil;
NSMutableArray *fetchRequest = [[_managedObjectContext executeFetchRequest:request error:&error]mutableCopy];

[self setWishListArray:fetchRequest];

WishListContainer *container = [fetchRequest objectAtIndex:0];
NSLog(@"%d",container.contains.count);
return [container.contains.allObjects mutableCopy];
}

But the problem is that when I try to display the wishlist contents using the above code, it shows an empty table view.
WishListContainer *container = [fetchRequest objectAtIndex:0];
NSLog(@"%d",container.contains.count);
return [container.contains.allObjects mutableCopy];

The above lines are showing 0. Please help me.

A: First of all, create an inverse relationship. As explained here https://stackoverflow.com/a/764572/3429577 it is necessary for data integrity.


text:
Q: Windows XP Service Pack 3 installation on a PC with no Internet connection I need to install Windows XP Service Pack 3 on a machine that currently has Windows Xp Service Pack 2.
What is the right way to do it?
Someone suggested downloading the executable from here and installing it.
Will this be sufficient to get that machine from Service Pack 2 to Service Pack 3? Or, is there more to be done?
I need Service Pack 3 to install a new Antivirus Software on that machine.

A: Yes thats all you need.  You can put it on a USB stick or burn in to a CD.  There are some patches and hotfixes that came after SP3, if I remember correctly.  However, that wouldnt stop you from installing your AV software.


text:
Q: It does not output all variables in success message Below I have a mysqli query which does successfully work;
$courseid = (isset($_POST['courses'])) ? $_POST['courses'] : '';
$moduleid = (isset($_POST['moduleid'])) ? $_POST['moduleid'] : '';
$moduleno = (isset($_POST['moduleno'])) ? $_POST['moduleno'] : '';
$modulename = (isset($_POST['modulename'])) ? $_POST['modulename'] : '';

$query = "SELECT cm.CourseId, CourseNo, CourseName, cm.ModuleId
FROM  Course c
INNER JOIN Course_Module cm
ON
c.CourseId = cm.CourseId
JOIN Module m
ON
cm.ModuleId = m.ModuleId
WHERE cm.CourseId = ? AND cm.ModuleId = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("ii", $courseid, $moduleid);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbCourseId, $dbCourseNo, $dbCourseName, $dbModuleId);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();

The problem I am getting though is in my success message. It is able to output the $moduleno and $modulename variables but it does not output the $dbCourseNo and $dbCourseName variables in the success message. Why is this?
if ($numrows == 1){

echo "The following Module has been added into Course:" . $dbCourseNo . " - " . $dbCourseName . ":
" . $moduleno . " - " . $modulename . "";

}

A: You never actually fetched the result, and I suspect the variables that do show are stale from a previous operation.
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbCourseId, $dbCourseNo, $dbCourseName, $dbModuleId);

// Can't remember, but you may need to call store_result() before bind_result() ??
// maybe not...
$stmt->store_result();
$numrows = $stmt->num_rows();
// Fetch the row...
$stmt->fetch();
// Now your variables are populated.


text:
Q: Spacy Matcher date pattern will match hyphens, but not forward slashes? I cannot find any reason why pattern_2 works in the code below, but pattern_1 does not. Why would the matcher be able to find the date pattern with hyphens, and not the date pattern with forward slashes?
import spacy
from spacy.tokens.doc import Doc
from spacy.matcher import Matcher
nlp = spacy.load('en_core_web_sm')

matcher = Matcher(nlp.vocab)
doc: Doc = nlp('4/15/2021 4-15-2021')

pattern_1 = [{'IS_DIGIT': True}, {'ORTH': '/'}, {'IS_DIGIT': True}, {'ORTH': '/'}, {'IS_DIGIT': True}]
pattern_2 = [{'IS_DIGIT': True}, {'ORTH': '-'}, {'IS_DIGIT': True}, {'ORTH': '-'}, {'IS_DIGIT': True}]

matcher.add('DATE_PATTERN_1', None, pattern_1)
matcher.add('DATE_PATTERN_2', None, pattern_2)
matches = matcher(doc)
print(f"matches = {matches}")

for match_id, start, end in matches:
    matched_span = doc[start:end]
    print(matched_span.text)

OUTPUT:

matches = [(93485516188963487, 1, 6)]

4-15-2021

A: The first one, 4/15/2021, is parsed as a single token:
print([t for t in doc])
# => [4/15/2021, 4, -, 15, -, 2021]

You may use a regex based pattern to detect this kind of token:
pattern_1 = [{'TEXT':{'REGEX':r'^\d{1,2}/\d{1,2}/\d{2}(?:\d{2})?$'}}]

Then, the outcome will look like
print(f"matches = {matches}")
# => matches = [(2279607876847626059, 0, 1), (93485516188963487, 1, 6)]
for match_id, start, end in matches:
    matched_span = doc[start:end]
    print(matched_span.text)

# => 4/15/2021
#    4-15-2021

The regex matches

*

*^ - start of string

*\d{1,2} - one or two digits

*/ - a / char

*\d{1,2}/\d{2} - one or two digits, /, two digits

*(?:\d{2})? - an optional sequence of two digits

*$ - end of the string (here, token).


text:
Q: using the Atmega328P if I take the micro controller (ATmega328P) from the Arduino board and simply place it on to a breadboard, do I still need to upload the boot loader ?

A: No, you don't need to upload the Bootloader, it's already in the chip.
BUT, when you unplug the ATMega328 you no longer have the serial connection support over USB.
If you upload a sketch while the ATMega328 is on the Arduino board and then put it in a breadboard, it will work providing you don't need serial/USB and you have the correct oscillator (16Mhz) on your breadboard.
There are a couple of approaches to create your own breadboard projects:

*

*Keep your Arduino intact and buy some ATMega328 chips. You can use the Arduino as an ISP to program the chips without needing a serial/USB connection.

*Use an Arduino Nano. This plugs directly into your breadboard and has everything you need onboard.
Start reading here, this has all been done before.

A: No, the bootloader is already installed.  You will need a 16 MHz crystal, two 22pF caps, a 10K resistor (reset pullup), and four 0.1uF caps - one for Vcc, one for Avcc, one for Aref, and one for DTR if you plan to add a 6-pin header to plug an FTDI Basic (or equivalent clone) for downloading code via the Arduino IDE, or use the serial port for debugging your code with the serial monitor - basically the same as a Promini less the 5V regulator.
Do not connect Aref to 5V - just the cap to Gnd.

A: If you want to program it using the Arduino tools you need the boot-loader. (which boot-loader will be present if you removed the ATMega328 from an Arduino board)
If it is already progammed you don't need the boot loader
If you intend to use a SPI programmer (eg: AVRASP) then you do not need the boot loader.


text:
Q: .htaccess issue with ExpressionEngine and YOURLS I have a primary site running ExpressionEngine and I am trying to get YOURLS running in a subfolder called "work", ie:  http://foo.com/work/ for short urls and EE is running at the root, ie: http://foo.com/.  Please note there is no 'www'.
The problem I am having is that when I use a short URL and a user adds "www" to the URI, such as http://www.foo.com/work/123 I get a redirect chain that looks like this:

*

*http://www.foo.com/work/123 302 redirects to

*http://www.foo.com/work 301 redirects to

*http://www.foo.com/work/ which returns 200

Everything works fine if you omit the 'www' from the URI.  YOURLS is set up to use the non-www but the worry is that some users might habitually type the 'www' as these URIs are being placed on printed ads.
The root .htaccess file looks like this:
SetOutputFilter DEFLATE
DirectoryIndex index.php index.html

# BEGIN ExpressionEngine Rewrite
<IfModule mod_rewrite.c>
RewriteEngine On

RewriteBase /
RewriteCond %{HTTP_HOST} ^www.foo.com [NC]
RewriteRule ^(.*)$ http://foo.com/$1 [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
RewriteRule ^(.*)$ /index.php?$1 [NC,L]
</IfModule>
# END ExpressionEngine Rewrite

The /work/ (YOURLS) .htaccess looks like this:
# BEGIN YOURLS
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /work/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /work/yourls-loader.php [L]
</IfModule>
# END YOURLS

How can I get the 'www' URIs to work like the non-www URIs do without completely hosing EE?  :)

A: I faced a similar issue. Some end users or people publishing the short urls tend to append them with www while the short url was bought with the intention of using it without www.
I also installed the YOURLS redirect index plugin to forward homepage visitors to our regular homepage.
So  I had a few different types of urls:

*

*short domain homepage, should lead to the regular https homepage

*short domain YOURLS admin panel, should lead to the https admin panel

*short domain shortened urls, should lead to the long url

I wanted all urls to work with or without www and make sure http was forwarded to https.
My solution was to start .htaccess with these lines:
# Force HTTPS (because of passwords via /admin) and use clean domain (non www)
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www.examp.le [NC]
RewriteRule ^(.*)$ https://examp.le/$1 [L,R=301]


text:
Q: Import csv file into existing gridview I have a tabcontainer with two tabs:

*

*The first tab contains a button.

*The second tab contains a gridview that has three textboxes.

I would like to do the following: when one clicks on the button in tab1, the gridview in tab2 is populated with data in a prespecified csv file (note that the file has the same column names as the gridview).
This is what I have so far, but for some reason, the gridview doesn't get populated with the data in the csv.
aspx.cs
<asp:UpdatePanel ID="WholeUpdatePanel" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
       <asp:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0" HeaderText=""
            Width="900px" TabStripPlacement="Top" ScrollBars="None" UseVerticalStripPlacement="false"
            VerticalStripWidth="120px" BackColor="White" BorderColor="White"
            Style="margin-right: 84px">
            <asp:TabPanel ID="OptionPanel" runat="server" Height="600px">
                <HeaderTemplate>
                    Simulation Option
                </HeaderTemplate>
                <ContentTemplate>
                      <asp:Button ID="PreviousSimButton" runat="server" Text="Run Previous Simulation" Width="250px" OnClick="PreviousSimButton_OnClick" />
                <ContentTemplate>
   </asp:TabPanel>
 <asp:TabPanel ID="TabPanel1" runat="server" Height="600px" >
         <HeaderTemplate>
                    General
                </HeaderTemplate>
                <ContentTemplate>
                    <asp:UpdatePanel ID="TestUpdatePanel" runat="server" UpdateMode="Conditional">
                        <ContentTemplate>
                            <asp:Panel ID="GeneralPanel" runat="server" Height="274px">
                                 <div style="overflow: auto; height: 222px; width: 100%">
                                     <asp:GridView ID="InflationGridView" runat="server" AutoGenerateColumns="False" Width="52%"
                                                    ShowHeaderWhenEmpty="True" CellPadding="4" ForeColor="#333333" GridLines="None"
                                                    AllowSorting="True" ShowFooter="True">
                                                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" Height="2px" />
                                                    <Columns>
                                                        <asp:TemplateField HeaderText="Start Year">
                                                            <ItemStyle Font-Size="13px" Width="20%" HorizontalAlign="Center" />
                                                            <ItemTemplate>
                                                                <asp:TextBox ID="StartInflationTextBox" runat="server" Width="60px" Text="" Style="text-align: center;"></asp:TextBox>
                                                                <asp:NumericUpDownExtender ID="StartInflationNumericUpDownExtender" runat="server"
                                                                    TargetControlID="StartInflationTextBox" Minimum="1" Width="60">
                                                                </asp:NumericUpDownExtender>
                                                            </ItemTemplate>
                                                        </asp:TemplateField>
                                                        <asp:TemplateField HeaderText="End Year">
                                                            <ItemStyle Font-Size="13px" Width="20%" HorizontalAlign="Center" />
                                                            <ItemTemplate>
                                                                <asp:TextBox ID="EndInflationTextBox" runat="server" Width="60px" Text="" Style="text-align: center;"></asp:TextBox>
                                                                <asp:NumericUpDownExtender ID="EndInflationNumericUpDownExtender" runat="server"
                                                                    TargetControlID="EndInflationTextBox" Minimum="1" Width="60">
                                                                </asp:NumericUpDownExtender>
                                                            </ItemTemplate>
                                                        </asp:TemplateField>
                                                        <asp:TemplateField HeaderText="Inflation Rate">
                                                            <ItemStyle Font-Size="13px" Width="25%" HorizontalAlign="Center" Height="2px" />
                                                            <ItemTemplate>
                                                                <asp:TextBox ID="InflationTextBox" runat="server" Text="" Width="60px" Style="text-align: center;"></asp:TextBox>
                                                                %
                                                            </ItemTemplate>
                                                            <FooterStyle HorizontalAlign="Right" />
                                                            <FooterTemplate>
                                                                <asp:Button ID="AddNewInflationRowButton" runat="server" Text="Add New Row" OnClick="AddNewInflationRowButton_Click"
                                                                    Height="25px" />
                                                            </FooterTemplate>
                                                        </asp:TemplateField>
                                                    </Columns>
                                                    <FooterStyle Font-Bold="True" ForeColor="White" Height="20px" />
                                                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                                                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                                                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                                                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" Height="10px" />
                                                    <SortedAscendingCellStyle BackColor="#E9E7E2" />
                                                    <SortedAscendingHeaderStyle BackColor="#506C8C" />
                                                    <SortedDescendingCellStyle BackColor="#FFFDF8" />
                                                    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                                                </asp:GridView>
                                            </div>
                                 </asp:Panel>
                   </ContentTemplate>
             </asp:UpdatePanel>
         </contenttemplate>
    </asp:TabPanel>
   </asp:TabContainer>
  </ContentTemplate>
 </asp:UpdatePanel>

aspx.cs
    protected void PreviousSimButton_OnClick(object sender, EventArgs e)
    {
            TabContainer1.ActiveTabIndex = 1;

            string file = "C:\\inst_research\\MonteCarlo\\Data\\inflation.csv";
            InflationGridView.DataSource = (DataTable)ReadToEnd(file);
            InflationGridView.DataBind();

            WholeUpdatePanel.Update();
            TestUpdatePanel.Update();

    }

    private object ReadToEnd(string filePath)
    {
        DataTable dtDataSource = new DataTable();
        string[] fileContent = File.ReadAllLines(filePath);
        if (fileContent.Count() > 0)
        {
            string[] columns = fileContent[0].Split(',');
            for (int i = 0; i < columns.Count(); i++)
            {
                dtDataSource.Columns.Add(columns[i]);
            }

            for (int i = 1; i < fileContent.Count(); i++)
            {
                string[] rowData = fileContent[i].Split(',');
                dtDataSource.Rows.Add(rowData);
            }
        }
        return dtDataSource;
    }

A: Your code should not give any issues if you use :
fileContent.Length instead of fileContent.Count()


text:
Q: Python Function return True/False I am writing a Python code that determines whether a year is a leap year. I think my algorithm is fine, but the result of my code is not as desired.
def isLeapYear(n):
if n % 400 == 0:
    print ("The year", n, "is a leap year:")
    return True
if n % 100 == 0:
    print ("The year", n, "is a leap year:")
    return False
if n % 4 == 0:
    print ("The year", n, "is a leap year:")
    return True
else:
    print ("The year", n, "is a leap year:")
    return False
isLeapYear(2000)

If the code is run, the results are as follows:
runfile('C:/Users/username/Desktop/isLeapYear.py',
wdir='C:/Users/username/Desktop')
The year 2000 is a leap year

The first issue is that I do not understand why the runfile filepath is  showing. Second, I would like my code to output whether or not the statement is True or False. So ideally, I'm looking for:
The year 2000 is a leap year: True

A: I feel like it is worth noting as a potential answer that there is a function for this exact purpose without all the code you used to determine if the year is a leap year:
import calendar
print calendar.isleap(1900)

And as an alternative to utilizing the calendar module, you can write this in a simpler fashion which will return a Bool (True/False):
def is_leap_year(year):
    """Determine whether a year is a leap year."""

    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

A: The reason you are not getting the output you want is that when you say

"I would like my code to output whether or not the statement is True or `False."

you don't specify how you want that output. Right now, your code is mixing print statements with return statements. If you change all of your return statements to print statements, the function will print
The year 2000 is a leap year:
True

in your terminal.


text:
Q: Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Schema validation failed with the following errors:
  Data path ".builders['app-shell']" should have required property 'class'.

Schema validation failed with the following errors:
  Data path ".builders['app-shell']" should have required property 'class'.
Error: Schema validation failed with the following errors:
  Data path ".builders['app-shell']" should have required property 'class'.
    at MergeMapSubscriber._registry.compile.pipe.operators_1.concatMap.validatorResult [as project] (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\@angular-devkit\core\src\workspace\workspace.js:210:42)
    at MergeMapSubscriber._tryNext (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\operators\mergeMap.js:65:27)
    at MergeMapSubscriber._next (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\operators\mergeMap.js:55:18)
    at MergeMapSubscriber.Subscriber.next (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\Subscriber.js:64:18)
    at MergeMapSubscriber.notifyNext (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\operators\mergeMap.js:84:26)
    at InnerSubscriber._next (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\InnerSubscriber.js:25:21)
    at InnerSubscriber.Subscriber.next (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\Subscriber.js:64:18)
    at MapSubscriber._next (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\operators\map.js:52:26)
    at MapSubscriber.Subscriber.next (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\Subscriber.js:64:18)
    at SwitchMapSubscriber.notifyNext (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\operators\switchMap.js:77:26)

A: Update @angular-devkit/build-angular to "^0.13.9" . Then run npm install
and after that, run npm serve.
Specs:
Angular: 7.2.15
Angular CLI: 7.3.9
Node: 11.2.0
OS: darwin x64

A: Below worked for me.
> 1. npm uninstall @angular-devkit/build-angular

> 2. npm install @angular-devkit/build-angular@0.13.0

if we use
AVOID:    npm audit fix -f
it may create problem, so dont use it.

A: This worked for me.
npm uninstall @angular-devkit/build-angular

npm install @angular-devkit/build-angular@0.13.0

A: What i did was to uninstall and install the "^0.13.0".
I confirm/ support this last  answer. It worked for me as well.
I had uninstall version "^0.800.0" and installed the "^0.13.0".
rebuild your project it will work fine.

A: I got the same error when upgraded angular from 6 to 8.
Simple update angular cli to latest version & node version to 10+.
1) Visit this link to get the latest node version. Angular 8 requires 10+.
2) Execute npm i  @angular/cli@latest to update cli.

This is what I have currently

A: This is worked for me

*

*npm uninstall @angular-devkit/build-angular

*npm install @angular-devkit/build-angular@0.13.0

A: Most of the answers are correct in stating that this occurs either because of a mismatch between:

*

*Nodejs version and Angular version

OR

*

*@angular-devkit/build-angular version and angular version

Also, this issue is most likely to occur if you either:

*

*upgraded/downgraded Nodejs version (which is no longer compatible with the angular version)

*Upgraded Angular version

*Run npm audit fix
For 1, check the Nodejs version support needed here: https://angular.io/guide/setup-local and check the installed version. If you are using the latest version of angular, you should be able to make it work with the latest version of Nodejs.
For 2, did you follow instructions here: https://update.angular.io/ ? If yes, and still have issues, look for any issues already created or create an issue here: https://github.com/angular/angular/issues
For 3, npm audit fix updates the @angular-devkit/build-angular version to a higher version because @angular-devkit/build-angular does not follow proper versioning (major releases still update only the minor version). Check the link below to check the compatible version for your Angular version: https://www.npmjs.com/package/@angular-devkit/build-angular?activeTab=versions Use the correct version and the issue will be fixed.
P.S: This is a good read about angular versioning: https://angular.io/guide/releases

A: I have to say, if you don't want to change anything in package.json file, try to update your Node.js version to latest. (currently 12.13.1 LTS)

A: I got this issue when installing Bootstrap.
The following commands are what worked for me:
npm uninstall @angular-devkit/build-angular

npm install @angular-devkit/build-angular@0.13.0

A: Try to update the package.json file so that "@angular-devkit/build-angular": "^0.800.1" reads "@angular-devkit/build-angular": "^0.12.4"
Then run npm install in the command line.
Reference: https://stackoverflow.com/a/56537342

A: Try to update @angular/core using ng update @angular/cli @angular/core

A: Angular Cli 8 support Node Js 10.9+. After update Node.js to 10.16 works fine.

A: Just found this answer from another link,
npm uninstall @angular-devkit/build-angular
npm install @angular-devkit/build-angular@0.13.0

A: This will do the trick for you:

*

*Update your angular cli by running the command ng update @angular/cli @angular/core

*Run or build your project by running the commands ng s or ng build respectively.

A: *

*Opened package.json

*Changed "@angular-devkit/build-angular": "^0.800.0" to "@angular-devkit/build-angular": "^0.10.0" or changed Changing from
"@angular-devkit/build-angular": "^0.802.1"     to
"@angular-devkit/build-angular": "^0.13.9"

*Run npm install

*Run ng serve

The original version can be diferent, but is necessary change it at 0.10.0 or 0.13.9 version that fix the problem

A: *

*open cmd from current project

*npm uninstall @angular-devkit/build-angular

*npm install --save-dev @angular-devkit/build-angular

A: This worked for me:
In package.json
Changed "@angular-devkit/build-angular": "^0.800.0" -->
"@angular-devkit/build-angular": "^0.10.0"
Then:
 npm install
 ng serve

Specs:
Angular CLI: 6.1.5
Node: 10.15.3
OS: win32 x64
Angular: 6.1.9