text:
Q: Regular expressions for grok pattern I was facing issues while trying to print second string (only) from below line.
Input:
Severity: error

And the output i am expecting is, error. Can someone please help? I am new to regex and tried many options and somehow i arrived at this after trimming all other stuff from the line and stuck here.

A: Severity:\s(?<log_severity>[^\s|\r|\n|\r\n]*)

Above regex works for my requirement. Actually, I was looking to implement it in logstash.conf file to input logs to Kibana. The full patter is as follow,
input {
    file {
        path => ["your input log file path"]
        start_position => beginning
        ignore_older => 0
        sincedb_path => "NUL"
    }
}

filter{

grok {

match => ["message","Severity:\s(?<log_severity>[^\s|\r|\n|\r\n]*)"]
#You can add more as per your requirement. It display in Kibana as
#Severity: Error
}
}

output {
   elasticsearch {
    hosts => "localhost:9200"
    }
}

A: Hope this helps
Regex=> ^Severity: \K\w+

A: You have over complicated your filter. Since you need to match a single word, you can use WORD pattern as follows,
filter {
  grok {
    match => { "message" => "Severity: %{WORD:Severity}" }
  }
}

It will output,
{
  "Severity": [
    [
      "error"
    ]
  ]
}

You can test it here,
https://grokdebug.herokuapp.com/


text:
Q: How to disable a specific profile in pulseaudio My USB microphone is recognized also as a speaker (both analog and digital). Is there a way to blacklist/disable this output "feature", leaving the input feature active?
This is the relevant entry of the mic in pacmd list-cards:
        name: <alsa_card.usb-Samson_Technologies_Samson_Meteor_Mic-00>
        driver: <module-alsa-card.c>
        owner module: 22
        properties:
                alsa.card = "2"
                alsa.card_name = "Samson Meteor Mic"
                alsa.long_card_name = "Samson Technologies Samson Meteor Mic at usb-0000:02:00.0-4.4.1, full speed"
                alsa.driver_name = "snd_usb_audio"
                device.bus_path = "pci-0000:02:00.0-usb-0:4.4.1:1.0"
                sysfs.path = "/devices/pci0000:00/0000:00:01.3/0000:02:00.0/usb1/1-4/1-4.4/1-4.4.1/1-4.4.1:1.0/sound/card2"
                udev.id = "usb-Samson_Technologies_Samson_Meteor_Mic-00"
                device.bus = "usb"
                device.vendor.id = "17a0"
                device.vendor.name = "Samson Technologies Corp."
                device.product.id = "0310"
                device.product.name = "Meteor condenser microphone"
                device.serial = "Samson_Technologies_Samson_Meteor_Mic"
                device.form_factor = "microphone"
                device.string = "2"
                device.description = "Meteor condenser microphone"
                module-udev-detect.discovered = "1"
                device.icon_name = "audio-input-microphone-usb"
        profiles:
                input:analog-stereo: Ingresso «Stereo analogico» (priority 65, available: unknown)
                input:iec958-stereo: Ingresso «Stereo digitale (IEC958)» (priority 55, available: unknown)
                output:analog-stereo: Uscita «Stereo analogico» (priority 6500, available: unknown)
                output:analog-stereo+input:analog-stereo: Duplex stereo analogico (priority 6565, available: unknown)
                output:analog-stereo+input:iec958-stereo: Uscita «Stereo analogico» + Ingresso «Stereo digitale (IEC958)» (priority 6555, available: unknown)
                output:iec958-stereo: Uscita «Stereo digitale (IEC958)» (priority 5500, available: unknown)
                output:iec958-stereo+input:analog-stereo: Uscita «Stereo digitale (IEC958)» + Ingresso «Stereo analogico» (priority 5565, available: unknown)
                output:iec958-stereo+input:iec958-stereo: Duplex stereo digitale (IEC958) (priority 5555, available: unknown)
                off: Spento (priority 0, available: unknown)
        active profile: <output:iec958-stereo+input:analog-stereo>
        sinks:
                alsa_output.usb-Samson_Technologies_Samson_Meteor_Mic-00.iec958-stereo/#1: Meteor condenser microphone Stereo digitale (IEC958)
        sources:
                alsa_output.usb-Samson_Technologies_Samson_Meteor_Mic-00.iec958-stereo.monitor/#1: Monitor of Meteor condenser microphone Stereo digitale (IEC958)
                alsa_input.usb-Samson_Technologies_Samson_Meteor_Mic-00.analog-stereo/#2: Meteor condenser microphone Stereo analogico
        ports:
                analog-input-mic: Microfono (priority 8700, latency offset 0 usec, available: unknown)
                        properties:
                                device.icon_name = "audio-input-microphone"
                iec958-stereo-input: Ingresso digitale (S/PDIF) (priority 0, latency offset 0 usec, available: unknown)
                        properties:

                analog-output-speaker: Altoparlanti (priority 10000, latency offset 0 usec, available: unknown)
                        properties:
                                device.icon_name = "audio-speakers"
                iec958-stereo-output: Uscita digitale (S/PDIF) (priority 0, latency offset 0 usec, available: unknown)
                        properties:

In short, I would like to keep all the input profiles:
input:analog-stereo: Ingresso «Stereo analogico» (priority 65, available: unknown)
input:iec958-stereo: Ingresso «Stereo digitale (IEC958)» (priority 55, available: unknown)

and remove the output profiles:
output:analog-stereo: Uscita «Stereo analogico» (priority 6500, available: unknown)
output:analog-stereo+input:analog-stereo: Duplex stereo analogico (priority 6565, available: unknown)
output:analog-stereo+input:iec958-stereo: Uscita «Stereo analogico» + Ingresso «Stereo digitale (IEC958)» (priority 6555, available: unknown)
output:iec958-stereo: Uscita «Stereo digitale (IEC958)» (priority 5500, available: unknown)
output:iec958-stereo+input:analog-stereo: Uscita «Stereo digitale (IEC958)» + Ingresso «Stereo analogico» (priority 5565, available: unknown)
output:iec958-stereo+input:iec958-stereo: Duplex stereo digitale (IEC958) (priority 5555, available: unknown)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Second method scanner doesn't work When I execute the code below, it takes the input correctly for inputCar1 method, but in inputCar2 method it executes all except the first scanner command. If I use this command twice then it works like what I expected, but it shouldn't be. For understanding well my problem, I attached my code and the output.
PrintClass:
package TestPackage;

/**
 * Created by km.muzahid on 03-May-15.
 */
public class PrintClass {
    public static void print(Object value){
        System.out.print(value);
    }
    public static void println(Object value)
    {
        System.out.println(value);
    }
}

CarClass:
 package TestPackage;

    /**
 * Created by km.muzahid on 03-May-15.
 */
public class CarClass {
    public String manufacturerName;
    public int CarCC;
    public float CarWeight;
    public float FuealAmount;
    public CarClass()//constructor
    {
        CarCC=0;
        CarWeight=0;
        FuealAmount=0;
    }
    public CarClass(String CarNumber,String Name,int cc,float fuel,float weight)//constructor
    {
        PrintClass ShowMassage=new PrintClass();
        ShowMassage.println(CarNumber +"Car Manufacturer Name : "+Name+"\nCC of Car : "
                +cc+"\nAmount of fuel of car : "+fuel+"\nWeight of car : "+weight);
    }
}

Problem code :
package TestPackage;
import java.util.Scanner;
/**
 * Created by km.muzahid on 03-May-15.
 */
public class testclass {
    static private PrintClass ShowMassage;
    public static Scanner MyScanner=new Scanner(System.in);
    public static CarClass car=new CarClass();
    public static CarClass car2nd=new CarClass();//create new object from carclass for 2nd car

    public static void main(String[] args)
    {
      //1st car
       inputCar1("Enter for first car: ");
        CarClass SeeCar1=new CarClass("1st car details: \n",car.manufacturerName,car.CarCC,car.FuealAmount,car.CarWeight);
//        //2nd car
      CarClass See=new CarClass("2nd car details: \n",car2nd.manufacturerName,car2nd.CarCC,car2nd.FuealAmount,car2nd.CarWeight);

    }
    protected static void inputCar1(String Massege)
    {
        ShowMassage.println(Massege);
        ShowMassage.println("Enter Name of car manufactueing : ");
        car.manufacturerName=MyScanner.nextLine();
        ShowMassage.println("Enter weight of car :");
        car.CarWeight=MyScanner.nextFloat();
        ShowMassage.println("Enter the amount of Fuel : ");
        car.FuealAmount= MyScanner.nextFloat();
        ShowMassage.println("Enter the car CC : ");
        car.CarCC= MyScanner.nextInt();
        inputCar2("Enter For 2nd Car : ");
    }
    protected static void inputCar2(String Massege)
    {
        ShowMassage.println(Massege);
        ShowMassage.println("Enter Name of car manufactueing : ");
       //car2nd.manufacturerName=MyScanner.nextLine();
        car2nd.manufacturerName=MyScanner.nextLine();//problem indicated
        ShowMassage.println("Enter weight of car 2nd  :");
        car2nd.CarWeight=MyScanner.nextFloat();
        ShowMassage.println("Enter the amount of Fuel 2nd : ");
        car2nd.FuealAmount= MyScanner.nextFloat();
        ShowMassage.println("Enter the car 2nd  CC : ");
        car2nd.CarCC= MyScanner.nextInt();
        CarClass SeeCar1=new CarClass("1st car details: \n",car.manufacturerName,car.CarCC,car.FuealAmount,car.CarWeight);
        //2nd car
        CarClass See=new CarClass("2nd car details: \n",car2nd.manufacturerName,car2nd.CarCC,car2nd.FuealAmount,car2nd.CarWeight);
    }
}

Output :
Enter for first car:
Enter Name of car manufactueing :
lamborghini
Enter weight of car :
2222
Enter the amount of Fuel :
2.369
Enter the car CC :
236
Enter For 2nd Car :
Enter Name of car manufactueing :
Enter weight of car 2nd  :
263
Enter the amount of Fuel 2nd :
3
Enter the car 2nd  CC :
56
1st car details:
Car Manufacturer Name : lamborghini
CC of Car : 236
Amount of fuel of car : 2.369
Weight of car : 2222.0
2nd car details:
Car Manufacturer Name :
CC of Car : 56
Amount of fuel of car : 3.0
Weight of car : 263.0
1st car details:
Car Manufacturer Name : lamborghini
CC of Car : 236
Amount of fuel of car : 2.369
Weight of car : 2222.0
2nd car details:
Car Manufacturer Name :
CC of Car : 56
Amount of fuel of car : 3.0
Weight of car : 263.0

A: The problem is that when you press ENTER, you send a new line ('\n') to the input buffer, and when you do car.CarCC= MyScanner.nextInt();, it will consume the digits but not the new line. So later, when you do car2nd.manufacturerName=MyScanner.nextLine(); the '\n' is still in the input buffer and the nextLine() will consume that '\n' and immediately return an empty string.
The solution is to put a MyScanner.nextLine(); somewhere between these two lines to consume that lost new line.


text:
Q: Difference Between Class.contextType and Context.Consumer with working example I am trying to understand the React context API and was going through the official docs. I will appreciate if someone can throw some more light on the following points as the official doc does not address it clearly.

*

*What is the difference in contextType and Consumer methods to
consume the values provided by Provider? In what situation we should
use which method?

*Can the value exposed by Provider in a class based component, be
used by a react hook component using useContext? I had the same
setup and i ended up converting the useContext to Context.Consumer.

*I have a very straightforward setup in which i have a Provider Class
based component which is exposing some state values. The Provider
has only one children component which is also a consumer. When i use
Context.Consumer in the children to fetch the values, everything
works as expected. But when i use contextType in the children
component, i see an empty object.

ContextProvider.js
import React from "react";
import {ContextConsumer} from "./ContextConsumer";
export const TestContext = React.createContext({
    count: 1,
    incrCount: (count)=>{
     console.log(`count value :- ${count}`)
     }
});

export class ContextProvider extends React.Component {
  incrCount = () => {
    this.setState({
      count: this.state.count + 1,
    });
  };

  state = {
    count: 5,
    incrCount: this.incrCount,
  };

  render() {
    return (
      <TestContext.Provider value={this.state}>
        <ContextConsumer />
      </TestContext.Provider>
    );
  }
}

ContextConsumer.js
import React from "react";
import { TestContext } from "./ContextProvider";

export class ContextConsumer extends React.Component {
    static contextType=TestContext

  componentDidMount() {
        const {count,incrCount}= this.context;
        console.log(`count:- ${(count)}`)
        console.log(`incrCount:- ${incrCount}`)
    }
  render() {

    return (
      <div>

        **// BELOW CODE IS WORKING AS EXPECTED**
        <TestContext.Consumer>
          {({ count, incrCount }) => (
            <button onClick={incrCount}>Count is {count}</button>
          )}
        </TestContext.Consumer>
      </div>
    );
  }
}

App.js
import {ContextProvider}  from "../../playground/ContextProvider";

const output = (
  <Provider store={reduxStore}>
    <ContextProvider />
  </Provider>
);

ReactDOM.render(output, document.getElementById("root"));

A: What is the difference in contextType and Consumer methods to consume the values provided by Provider? In what situation we should use which method?
The static contextType assignment was introduced in v16.6.0 as a way to use context outside of render method. The only difference between Consumer and static context is the fact that using contextType allows you use context outside of render method too
Can the value exposed by Provider in a class based component, be used by a react hook component using useContext?
Yes the context value from Provider can be used by useContext too. However you can only make use of useContext inside a functional component and not a class component and also after v16.8.0 or react which supports hooks
P.S. You must ensure one thing that you are not causing a circular dependency by importing provider in consumer component and also the other way around

A: *

*Static contextType and class.contextType

*useContext

*context.Consumer

are almost same the difference between them is that (1) is used in class component and
useContext is a hook and the best thing is we can use this hook multiple times in one functional component.(3) can only be used in jsx or in render(return).(1)and(2) can be used outside return.

A: to put it more simply:
if (functional components) { useContext }
else {
   if (multiple contexts) { Context.Consumer }
   else { Class.contextType }
}

// "static contextType" is experimental lets avoid


text:
Q: pip doesn't fetch any url I've just installed python 3.4 (from source) and I want to use pip to download packages. But every time I run it using e.g.:
pip install -v django

I get following error (Same output as in /root/.pip/pip.log:
/var/www/sova_move/newvenv/venv/bin/pip run on Thu Apr  3 18:16:44 2014
Downloading/unpacking django
  Getting page https://pypi.python.org/simple/django/
  Could not fetch URL https://pypi.python.org/simple/django/: connection error: [Errno 2] No such file or directory
  Will skip URL https://pypi.python.org/simple/django/ when looking for download links for django
  Getting page https://pypi.python.org/simple/
  Could not fetch URL https://pypi.python.org/simple/: connection error: [Errno 2] No such file or directory
  Will skip URL https://pypi.python.org/simple/ when looking for download links for django
  Cannot fetch index base URL https://pypi.python.org/simple/
  URLs to search for versions for django:
  * https://pypi.python.org/simple/django/
  Getting page https://pypi.python.org/simple/django/
  Could not fetch URL https://pypi.python.org/simple/django/: connection error: [Errno 2] No such file or directory
  Will skip URL https://pypi.python.org/simple/django/ when looking for download links for django
  Could not find any downloads that satisfy the requirement django
Cleaning up...
  Removing temporary dir /var/www/sova_move/newvenv/venv/build...
No distributions at all found for django
Exception information:
Traceback (most recent call last):
  File "/var/www/sova_move/newvenv/venv/lib/python3.4/site-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/var/www/sova_move/newvenv/venv/lib/python3.4/site-packages/pip/commands/install.py", line 278, in run
    requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
  File "/var/www/sova_move/newvenv/venv/lib/python3.4/site-packages/pip/req.py", line 1177, in prepare_files
    url = finder.find_requirement(req_to_install, upgrade=self.upgrade)
  File "/var/www/sova_move/newvenv/venv/lib/python3.4/site-packages/pip/index.py", line 277, in find_requirement
    raise DistributionNotFound('No distributions at all found for %s' % req)
pip.exceptions.DistributionNotFound: No distributions at all found for django

my connection is fine (I can normally upgrade my system, ping google...) and https://pypi.python.org/simple/Django/ definetly exist (I can see it right now). Furthermore - I can use pip list, pip search and when I manually download package using wget and then use
python setup.py install

it works OK and it even can download dependencies. I'm not using proxy. This is being done on raspbery pi with archlinux. My connection is static. Python is working OK and pip is also installed (by default in 3.4).
Thanks

A: I made a fresh reinstall of my virtualenv using local version of python without using symbolic links and it works now. Thank you


text:
Q: How to validate data in a List<> property in a class? I am just now studying about OOP and i have a problem with an exercise. I have a SchoolClass that has Students. The Students in a SchoolClass are not allowed to have the same number. I have the following:
class SchoolClass
{
    private List<Student> students;

    public List<Student> Students
    {
        get { return this.students; }
        set
        {
            if (value == null) throw new ArgumentNullException("Students list can not be null!");
            if (value.Select(n => n.Number).Distinct().Count() != value.Count())
                throw new ArgumentException("There are students in the list with the same class number!");
            this.students = value;
        }
    }
public SchoolClass( List<Student> students)
    {
        this.Students = students;
    }
}
class Student
{
    private uint number;

    public uint Number
    {
        get { return this.number; }
        set
        {
            if (value == 0) throw new ArgumentException("Student's number can not be null!");
            else this.number = value;
        }
    }

    public Student(string name, uint number)
    {
        this.Number = number;
    }
}

When I initialize two students in the Main() class with the same number, I have an ArgumentException("There are students in the list with the same class number!"); as expected. But when I have an instance of a SchoolClass (sc) and call its students list and use Add() (sc.students.Add(new Student(..)) I can insert a Student with a duplicate number. The same is with the List.InsertAt() method. I read that The getter can be done readonly using ReadOnlyCollection<...>(...) or AsReadOnly() but how will I add new students to the list in this case?
What is the best practice to avoid/solve this?

A: You should not be exposing a List<> property on your class - it's almost never a good idea, as it gives the user of the class way too much control over your data, and it's certainly not a good option in this case. Instead, you should expose just the properties you need, and perform your own validation:
// store the students as a List<>...
private List<Student> students;

// ...but expose them as IEnumerable<>.
public IEnumerable<Student> Students
{
    get { return this.students; }
}

// IEnumerable<> does not allow adding, removing, clearing, etc -
// you know you're the only one altering the data

// and you can choose to give them restricted access with your own
// validation logic
public void AddStudent(Student student)
{
    if (this.students.Any(s => s.Number == student.Number))
        throw new ArgumentException("Duplicate student number!");
    this.students.Add(student);
}

A: I would recommend using a Dictionary, as it is ideal for warding off duplicates according to a Key.  It would also be much faster than using just a List while checking for duplicates.
class SchoolClass
{
    protected Dictionary<uint, Student> _Students = new Dictionary<uint, Student>();
    public IEnumerable<Student> Students
    {
        get { return _Students.Values; }
    }

    public SchoolClass(List<Student> students)
    {
        if (students == null) throw new ArgumentNullException("Students list can not be null!");

        foreach (var student in students)
            AddStudent(student);
    }

    public void AddStudent(Student student)
    {
        if (_Students.ContainsKey(student.Number))
            throw new ArgumentException("There are students in the list with the same class number!");

        _Students.Add(student.Number, student);
    }
}

In the example, I expose Students as an IEnumerable so it is obvious it cannot be modified directly because it does not have Add or Remove.  _Students, a Dictionary is used as the backer/source of this property.
I also exposed an AddStudent method which will handle adding the students, and checking for duplicates Numbers.

Further clarification:
_Students is protected so that any class that is derived from SchoolClass can access it.  It seems very likely in this case.
I did not define a set { } for Students because it is acting as a collection that should not be directly modified.  Not creating providing a set makes it so the only means of modifying it is through modifying _Students (its backer).

A: You can mark the getter as readonly and write following method to add a new student,
public void AddStudent(Student s)
{
    if(!this.studentList.Contains(s))
    this.studentList.Add(s);
    else
     throw new Exception("Duplicate entry");
}

Contains() only helps if you have Equals Implemented in student class. Instead you can use this.studentList.Any(s => s.Number == s.Number)
@pauls's comment, HashSet also a good option to go...

A: You could use a System.Collections.ObjectModel.KeyedCollection:
public class SchoolClass : KeyedCollection<uint, Student>
    {
        protected override uint GetKeyForItem(Student newStudent)
        {
            return newStudent.Number;
        }
    }

this will throw an ArgumentException when a student with the given number already exists

A: Since you are using the list from the getter as instance.Property.Operation, you are directly manipulating the list without going through the setter. A read-only property would probably not give you the behavior you want, since a read-only property is simply a property without a setter.
You could in fact use the .AsReadOnly() method, combined with new methods on your SchoolClass class, something like AddStudent(Student student) and AddStudents(List<Students> students). The AddStudents method could use the AddStudent method in a loop, which could in turn use a private setter on your property. Validations would probably be done in the private setter.
See http://msdn.microsoft.com/en-us/library/75e8y5dd.aspx and http://msdn.microsoft.com/en-us/library/e78dcd75.aspx

A: I think  you need to use List.Contains Method with custom IEqualityComparer. So you can have your comparison with other property along with number. So you will have provision without altering much code if any change required.
Please refer this link


text:
Q: How to LineWrap a text in JTextPane that is layouted with GridBagLayout I use a Jpane with a GridBagLayout. In the GridBags I put a JTextPane component.
But I can't linewrap my text in the JTextPane when I resize the JFrame.
Here is my code...
package problems;

import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.*;

public class ScrollbarTest {

private JFrame frame;
private JPanel panel;
private JScrollPane [] scrollpane = new JScrollPane[4];
private JTextPane [] textPane = new JTextPane[4];
private JScrollPane scrollbar;

ScrollbarTest() {
    //initialize jtextarea
    for(int i=0;i<textPane.length;i++) {

        textPane[i]=new JTextPane();
        textPane[i].setText("xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx | ");
        scrollpane[i] = new JScrollPane(textPane[i]);
    }

    panel     = new JPanel();
    frame     = new JFrame();

    createList(panel);
    scrollbar = new JScrollPane(panel);

    frame.add(scrollbar);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setSize(new Dimension(400,400));
} //constructor

//method to easily add components to GridBags
static void addComponent(JPanel panel,
                         GridBagLayout gbl,
                         Component c,
                         int x, int y,
                         int width, int height,
                         double weightx, double weighty) {

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.gridx = x; gbc.gridy = y;
    gbc.gridwidth = width; gbc.gridheight = height;
    gbc.weightx = weightx; gbc.weighty = weighty;
    gbl.setConstraints( c, gbc );
    panel.add( c );
}//addComponent

public void createList(JPanel panel) {
    //setting layout: "GridBagLayout"
    GridBagLayout gbl = new GridBagLayout();
    panel.setLayout(gbl);

    //put created components to the gridbags of gridbaglayout
    //                                            x  y  w  h  wx wy
    addComponent( panel, gbl, scrollpane[0]     , 0, 1, 1, 1, 1 ,0  );
    addComponent( panel, gbl, scrollpane[1]     , 0, 2, 1, 1, 1 ,0  );
    addComponent( panel, gbl, scrollpane[2]     , 1, 1, 1, 1, 1 ,0  );
    addComponent( panel, gbl, scrollpane[3]     , 1, 2, 1, 1, 1 ,0  );
} //createList

public static void main (String[] args) {
    new ScrollbarTest();
} //main

} //end of class

Where is the problem?
Many thanks in advance

A: You are missing setLineWrap on your JTextArea.
for(int i=0;i<textArea.length;i++) {
        textArea[i]=new JTextArea();
        textArea[i].setLineWrap(true);
        textArea[i].setText("xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx | ");
    }

EDIT

in the case of JTextPane you shall create a scrollpane with no
  horizontal scroll policy and set your JtextPane as its viewPort


text:
Q: What's the "correct" way to pass an empty vector to an object? I am working on a fairly large C++ project which unfortunately doesn't really use C++ to its full potential. Large portions of the code are still plain C wrapped in ridiculous C++ classes.
So I tried to make the code more readable and more safe by introducing some C++ and STL.
However, when I assign a vector to an object member I get a strange crash (debug error to be exact). Imagine this:
class A
{

public:

    // Default constructor
    A()
    {
        initialize(std::vector<unsigned long>());
    };

    A(const std::vector<unsigned long> &data)
    {
        initialize(data)
    };

    ~A() {};

    void initialize(const std::vector<unsigned long> &data)
    {
        m_data = data;
    };

private:

    std::vector<unsigned long> m_data;

};

Then somewhere else in the code, I call:
a.initialize(std::vector<unsigned long>());

However, the program terminates du to a debug error: vector iterators incompatible.
It happens on this assignment:
m_data = data;

... which should make a copy, which is what I intend to do.
However, if I change this line to:
m_data = std::vector<unsigned long>(data);

... everything works as expected.
My questions are: Why's that? And is this the correct way to initialize an object with an empty vector?
Keep in mind that the class in reality is much bigger and has much more members which are passed, which is why I use an initialize function. And there is also the possibility of passing an already existing array, so I do need to be able to initialize it either empty or with existing data.
EDIT: I have found the cause of the crash. I have found out that the code I'm looking at actually works a bit different:
A *pA = malloc(...); // Not really malloc but a wrapper for a WINAPI-Alloc
// Some stuff happens in between
pA->initialize(std::vector<unsigned long>());

So in fact the constructor of A has never been called and therefore the constructor of the vector member (m_data) also never executeded. That's why assigning a constructor worked while implicitly calling the copy-function crashed, since the destination vector hasn't been constructed yet. Well a lesson learned and more horrible code to improve :)
Thanks!

A: I don't know why your code crashes with that error, as it looks ok, superficially.  Perhaps you should edit your question to include a minimal test case.
However, there are better ways to do initialisation:
class A
{
public:

    // Default constructor.
    // Relies on the fact that the default constructor for std::vector is
    // an empty vector.
    A()
    {}

    // Use the initialisation list.
    A(const std::vector<unsigned long> &data)
    : m_data(data)
    {}

private:
    std::vector<unsigned long> m_data;
};

A: std::vector constructor already initializes an empty vector.
And if you want to assign data from another std::vector, you can use a copy constructor.
class A
{

public:

    // Default constructor
    A()
    {
        // Not required:
        // initialize(std::vector<unsigned long>());
    }

    // Make it explicit
    explicit A(const std::vector<unsigned long> &data)
      : m_data(data) // vector copy ctor
    {
    }

    ~A() {}

private:

    std::vector<unsigned long> m_data;

};

A: Is the call:
a.initialize(std::vector<unsigned long>());
in a different library than where A is defined? In that case I would guess one of the libraries is built with debug iterators enabled and the other one is not.


text:
Q: Call function to specific class I need a specific input field on the page to have its text changed to uppercase. I am aware that CSS can be used to display uppercase on the page but I need this javascript as the underlying input data has to be uppercase.
I am using javascript below to change the text to uppercase on input fields on my website
function handleInput(e) {
document.getElementsByClassName("bottomtext");
   var ss = e.target.selectionStart;
   var se = e.target.selectionEnd;
   e.target.value = e.target.value.toUpperCase();
   e.target.selectionStart = ss;
   e.target.selectionEnd = se;
}

this is being called via php using:
'oninput'      => 'handleInput(event)',
my only problem is that it is being applied to all input fields on the page, but I only want it applied to a specic field with the class "bottomtext". Can someone please help with having this only apply to the specific class. Thank you.

A: You can attach an event handler to that element like so:
<input type="text" id="bottomtext">

Next, call the addEventListener function on that element and pass the event function to it like so:
document.getElementById('bottomtext').addEventListener('input', handleInput);
// The handleInput function here

I hope this helps.

A: maybe you could try:
function handleInput(e) {
     const value = document.getElementByClassName("bottomtext").value.toUpperCase()
     return value
}

But remember that you have to call the function


text:
Q: Javascript autocloses HTML tags? Why do these two functions give different results?

var table1 = document.getElementById("table1");
var table2 = document.getElementById("table2");

var register = [
  {att1: 1, att2: 2, att3: 3},
  {att1: 4, att2: 5, att3: 6},
  {att1: 7, att2: 8, att3: 9}
];

//table1.innerHTML = "";
//table2.innerHTML = "";

function drawTable1() {
  for (var i = 0; i < register.length; i++) {
    table1.innerHTML += "
" + register[i].att1 + "	" + register[i].att2 + "	" + register[i].att3 + "
";
  }
}

function drawTable2() {
 for (var i = 0; i < register.length; i++) {
   table2.innerHTML += "
";
    table2.innerHTML += "" + register[i].att1 + "	";
    table2.innerHTML += "" + register[i].att2 + "	";
    table2.innerHTML += "" + register[i].att3 + "	";
    table2.innerHTML += "
";
  }
}

drawTable1();
drawTable2();
table {
  display: inline;
}

        Att1
        Att2
        Att3

        Att1
        Att2
        Att3

I'm just beginning with js, and I've noticed this thing. From a logical point of view i see no differences between the two functions, the second has just been broken up to make the code easier to read. It should simply be adding strings to a string, but it seems like at every operation the opened tags get closed by the program, resulting in a multitude of rows.
Why is this? How is this useful?

A: innerHTML isn't actually a string. It's an interface to the DOM (the elements on the page); reading from it generates a string version of what's currently there, and assigning a value to it modifies the tree.
It's impossible to have an unclosed
 element in the DOM -- when you perform an operation like table1.innerHTML += "
", the browser sees the unclosed
 tag as invalid HTML and has to repair it by inserting a closing
. When you later access innerHTML to perform another modification, you see the "repaired" version, not the value you initially assigned.
The easiest fix will be to build the entire table as a string, then assign to innerHTML all at once, e.g.
var html = "";
for (...) {
   html += "
";
   html += "example	";
   html += "
";
}
table1.innerHTML = html;

You may also want to investigate Javascript DOM methods to create HTML elements (like document.createElement()) as an alternative -- innerHTML is a clumsy interface.

A: Well the innerHTML content is — as the name implies — HTML and HTML is not just a string. I assume you know that browsers build a DOM out of it. Basically a tree out of nodes that know their tag, attributes, children etc.
Now you need this DOM to render anything. Sure, it is nearly impossible to get invalid html as non-html can just be interpreted as a mere string (which is valid html). However, the browser tries to fullfill the html standard as much as possible. Therefore it also generates missing end tags in order to produce well-formed html. (even when it is not in the html, he will implicitely generate them for the DOM and in some browsers you can see that in the HTML provided in the dev console).
So now you add a random
 attribute to your html like this table2.innerHTML += "
". This would produce not-well-formed html. Therefore it should generate the missing end tag. Whether that is done while running the js-code or afterwards when refreshing the DOM, I don't know, but generally it helps generate well-formed HTML.

I'm sure you know how to circumvent that problem, but anyways: Instead of using an temporary string, you might want to look at document.createElement(). This is generally used to generate well-formed html in a non-confusing and safe (as in "something unexpected like above doesn't happen safe") way.


text:
Q: I want to form a group of order one, is it possible? Can a set with one element be a group, or does a group need to have at least two elements?

A: It is possible to have an element with just one element. Take $G=\{e\}$ with the group law defined as $e\circ e=e$. Then it is easy to verify that:

*

*The group law is associative: $(e\circ e)\circ e=e\circ(e\circ e)=e$

*There is an identity $e$ such that $e\circ g=g = g \circ e$ for all $g\in G$.

*Every element of $G$ has an inverse, since $e$ is its own inverse.


text:
Q: background and toolbar apear sometimes xamarin forms I have this page in xamarin.forms
the problem is: mainly when it's the first time that the device is opened, My first page is bad loaded and I don't know why
this is the xaml
<?xml version="1.0" encoding="utf-8" ?>
 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="neoFly_Montana.Views.Splash2"
         BackgroundImage="Abertura.jpg"
         NavigationPage.HasNavigationBar="False">
<ContentPage.Content>
</ContentPage.Content>

The background is not loaded and I have a blank screen, and the HasNavigationBar="False" doesn't work...and a toolbar appears...but, always in the first time that the app is oppened...I don't understand that...


text:
Q: Installing pandas, python34? I am trying to install pandas and I keep getting an error
Microsoft visual c++ 10.0 is required?

Is it really necessary to have it ? and how can I have it?
when I try to upgrade pip from 9 to 18, it says I should do it through python, how is that?
Thanks in advance

A: You should first try to upgrade your pip from version 9 to version 18.
If you have virtual environment. Then first activate your virtualenv or else if you have global python installed. They simply type the following command

pip install --upgrade pip

This will show the following output
(p_env) ➜  python_playground git:(master) ✗ pip install --upgrade pip
Collecting pip
  Downloading https://files.pythonhosted.org/packages/5f/25/e52d3f31441505a5f3af41213346e5b6c221c9e086a166f3703d2ddaf940/pip-18.0-py2.py3-none-any.whl (1.3MB)
    100% |████████████████████████████████| 1.3MB 1.4MB/s
Installing collected packages: pip
  Found existing installation: pip 10.0.1
    Uninstalling pip-10.0.1:
      Successfully uninstalled pip-10.0.1
Successfully installed pip-18.0

Once your pip is upgraded. Then type the following command to install pandas

pip install pandas


text:
Q: SOAP-ERROR: Encoding: object has no 'sortAscending' property" Here is the code that makes the SOAP call
require_once("zulutradeClient.php");
date_default_timezone_set('America/New_York');

$params->providerId = 128391;
$params->validTrades = true;
$params->lotSize = "Standard";
$params->start = 0;
$params->length = 20;
//$params->sortAscending = false;
$params->fromDateStr = "1986-08-27T09:00:00";
$params->toDateStr = "2014-01-12T09:00:00";
$params->sortBy = "dc";

$ztclient = new zulutradeClient();
$response = "";

try {
    $response = $ztclient->GetProviderTrades( $params );
    var_dump($response);
}
catch (SoapFault $e) {
   var_dump($e);
}

The wsdl is here
http://www.zulutrade.com/WebServices/Performance.asmx?WSDL

When the 'sortAscending' is commented out, i get the no property error:
SOAP-ERROR: Encoding: object has no 'sortAscending' property"

When it is uncommented I get the following error:
message: Could not connect to host
faultcode: http

It seems really hopeless, I've tried everything, and it just doesn't want to take that parameter.

A: When the 'sortAscending' is commented out, i get the no property error:

SOAP-ERROR: Encoding: object has no 'sortAscending' property"

<s:element minOccurs="1" maxOccurs="1" name="sortAscending" type="s:boolean" />

sortAscending is a mandatory field in wsdl, that's why you are getting above error.
When it is uncommented I get the following error:

 message: Could not connect to host
 faultcode: http

There is no fault in your request soap message here. The issue here is, this end point url.
http://www.zulutrade.com:81/WebServices/Performance.asmx

It is not accessible. Connect with your wsdl provider regarding this. you can not do anything about that.
Most probably, this srvice would be hosted on some other port rather than 81.


text:
Q: Developing Apache module - error: dereferencing pointer to incomplete type 'apr_socket_t {aka struct apr_socket_t}' I'm trying to access the socket descriptor in apache module. Changed mod_example.c:
conn_rec *conn = r->connection;
struct apr_socket_t *csd = (struct apr_socket_t *)((core_net_rec *)conn->input_filters->ctx)->client_socket;
int sock_fd = csd->socketdes;

And there is an error:
error: dereferencing pointer to incomplete type 'struct apr_socket_t'
         int sock_fd = csd->socketdes;
apr_network_io.h is in the include path.
Please advice.

A: Here is the typesafe recipe for getting the native socket in a module:
apr_socket_t s = ap_get_conn_socket(r->connection);
int fd = 0;
apr_os_sock_get(&fd, s);


text:
Q: curl extract answers in a stream I'm sending a cURL request and get responses through a stream on which I can see all the answers as they arrived.
However, I'd like to extract each line to used them within a script.
Have you got any idea on how I can achieve that with bash, python or whatever ?
Thx


text:
Q: SQL Server Replication I need to perform replication on MS SQL Server 2005 Standard Edition. The goal is, that I have several databases (for example 4 instances of SQL Server) and each must act as publisher to other sites. I know, that merge replication model of subscriber - publisher - subscriber is possible, but it doesn't suit me. I need to maintain replication process between other machines when no matter which server is down, so all other servers will have actual data.
Is it even possible? And if yes, can You point me to something?
Thanks in advance.

A: It sounds like you're describing peer-to-peer replication. Read up on it here.


text:
Q: How to create a file with contents based on files in a directory I have an existing xls file which creates a CONTENTS file based on the files in a directory. For example, if a directory contains file.pdf and file.txt, it will create a file with contents
file.pdf
file.txt

with each file separated by a line break.
What I would like to do is that I want the contents to contain
file.pdf    bundle:ORIGINAL
file.txt    bundle:TEXT

file.pdf and bundle:ORIGINAL is separated by a tab character. The directory will contain these 2 filetypes, 1 pdf and 1 text file. So basically, what I want is that for every pdf file, it should be followed by bundle:ORIGINAL text while if its a text file, it should be followed by bundle:TEXT.
The original code is below:
For i = 2 To lRows
If Trim(Cells(i, 1).Value) = "" Then Exit For

' create the CONTENTS file

FileList = GetFileList(oDirectory & "\" & Trim(Cells(i, lCols).Value) & "\")
cFileNum = FreeFile
ContentsPath = oDirectory & "\" & Trim(Cells(i, lCols).Value) & "\" & "contents"
Open ContentsPath For Output As #cFileNum
For k = 1 To UBound(FileList)
If (FileList(k) <> "contents" And FileList(k) <> "dublin_core.xml") Then
    Print #cFileNum, FileList(k)
    End If
    Next k
Close #cFileNum

EDIT
This is the Function GetFileList
Function GetFileList(FileSpec As String) As Variant
'   Returns an array of filenames that match FileSpec
'   If no matching files are found, it returns False

Dim FileArray() As Variant
Dim FileCount As Integer
Dim FileName As String

On Error GoTo NoFilesFound

FileCount = 0
FileName = Dir(FileSpec)
If FileName = "" Then GoTo NoFilesFound

'   Loop until no more matching files are found
Do While FileName <> ""
    FileCount = FileCount + 1
    ReDim Preserve FileArray(1 To FileCount)
    FileArray(FileCount) = FileName
    FileName = Dir()
Loop
GetFileList = FileArray
Exit Function

'   Error handler
NoFilesFound:
GetFileList = False
End Function

Please note that I am obviously not the author of this code, I just downloaded this excel file (the site no longer exists) a long time ago and I just need to tweak this for my own use.
Thanks in advance.

A: Something like this should do it:
'...
If (FileList(k) <> "contents" And FileList(k) <> "dublin_core.xml") Then
    Print #cFileNum, FileList(k) & vbTab & GetType(Cstr(FileList(k)))
End If
'...

Function:
Function GetType(fName as string)
    Dim rv As String
    Select Case Right(Ucase(fName),3)
        Case "TXT": rv = "bundle:TEXT"
        Case "PDF": rv = "bundle:ORIGINAL"
    End Select
    GetType = rv
End Function


text:
Q: Implementing Revit to Excel Exporter in Autodesk Forge I am attempting to implement the Revit to Excel exporter discussed here.  The button is working and passing urn and token to
ForgeXLS.downloadXLSX(urn, token, callback /*Optional*/);

I receive an error" "GET " 403 (forbidden)"

I am extending the Extensions Skeleton tutorial found here.
Is it possible that there is an issue with the scopes... if so can you guide me as to how to adjust the scope of the access token I am pulling?
Code for ForgeXLSX.downloadXLSX is:
downloadXLSX: function (urn, token, status) {
    var fileName = decodeURIComponent(atob(urn).replace(/^.*[\\\/]/, '')) + '.xlsx';
    if (fileName.indexOf('.rvt') == -1) {
      if (status) status(true, 'Not a Revit file, aborting.');
      return;
    }

    if (status) {
      status(false, 'Preparing ' + fileName);
      status(false, 'Reading project information....');
    }

    this.prepareTables(urn, token, function (tables) {
      if (status) status(false, 'Building XLSX file...');

      var wb = new Workbook();
      jQuery.each(tables, function (name, table) {
        if (name.indexOf('<')==-1) { // skip tables starting with <
          var ws = ForgeXLS.sheetFromTable(table);
          wb.SheetNames.push(name);
          wb.Sheets[name] = ws;
        }
      });

      var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'binary'});
      saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), fileName);

      if (status) status(true, 'Downloading...');
    })
  },

A: Scope wise, you will need both data:read bucket:read to have sufficient access to model metadata:

Token with insufficient scope ends up with a 403:

Make sure your server sets scope up properly in the request body to fetch access tokens.
And your best bet to observe the URN and Token variables in the process of calling the Forge endpoints is here at ForgeXLS.forgeGetRequest:

A: After digging around a bit (and some help from a friend) figured out that it was the scopes after all.  Adding 'data:read' scope to the public scope in the config.js file provided the needed access and the exporter now works.
 scopes: {
        // Required scopes for the server-side application
        internal: ['bucket:create', 'bucket:read', 'data:read', 'data:create', 'data:write'],
        // Required scope for the client-side viewer
        public: ['viewables:read', 'data:read']
    }


text:
Q: How to get url from website elements and open it in another window I'm trying to open web url what is hidden in elements, but if i click on button what in on web page, it shows up in the elements.
So want to use javascript, when i click on button, then javascript find that url and open it in another window.
I want to use tampermonkey, the userscript manager to run that script.
Iam new to coding, except wrong code.
I already tried some commands like this: document.getElementById("vjs_tech")
it shows up like <video *there are some random* and src="https://and some random words"></video>
and i tried use method window.open("src").
document.getElementById("vjs_tech");
window.open("src");

I excepted that will open the link from src but it only opened same window again.

A: You have to take the value of src attribute from the element.
var videoURL = document.getElementById('vjs_tech').src;
window.open(videoURL);


text:
Q: Is it possible to keep the text below or above the ttk Checkbutton? I am coding an alarm GUI in python using tkinter/ttk. For this section, my code looks like
    self.checkFrame = ttk.Frame(self.alarm1)
    self.checkFrame.grid(row = 1)
    self.mon = ttk.Checkbutton(self.checkFrame, text = 'MON')
    self.mon.grid(column = 0, row = 0)
    self.tue = ttk.Checkbutton(self.checkFrame, text = 'TUE')
    self.tue.grid(column = 1, row = 0)
    self.wed = ttk.Checkbutton(self.checkFrame, text = 'WED')
    self.wed.grid(column = 2, row = 0)
    self.thur = ttk.Checkbutton(self.checkFrame, text = 'THUR')
    self.thur.grid(column = 3, row = 0)
    self.fri = ttk.Checkbutton(self.checkFrame, text = 'FRI')
    self.fri.grid(column = 4, row = 0)
    self.sat = ttk.Checkbutton(self.checkFrame, text = 'SAT')
    self.sat.grid(column = 5, row = 0)
    self.sun = ttk.Checkbutton(self.checkFrame, text = 'SUN')
    self.sun.grid(column = 6, row = 0)

Everything looks good except the text appears on the right of the button. I was wondering if there is anyway that I can move those texts below the button.


text:
Q: Автоматически уменьшить padding между элементами при уменьшении родительского контейнера? Не срабатывает box-sizing: border-box Помогите пожалуйста. Хотелось бы чтобы между link1, link2, ... уменьшалось расстояние при уменьшении ширины окна (а именно чтобы уменьшался padding вплоть до 0), но чтобы при максимальной ширине окна между ними оставался заданный padding (в моем случае padding: 0 25px). box-sizing: border-box не работает. Пробовал много разных вариантов, но ничего не выходит: link-и выходят за рамки родительского окна сразу же при уменьшении родительского окна, а хотелось бы держать их внутри до последнего.

* {
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}

nav {
    width: 100%;
    height: 60px;
}

.wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 100%;
    padding: 0 25px;

    border: 1px solid red;
}
.wrapper ul {
    display: flex;
    justify-content: space-between;
    flex-grow: 1;
    max-width: 100%;
    list-style: none;

    border: 1px solid green;
}

.wrapper ul li {
    padding: 0 25px;
}
<!DOCTYPE html>

link1

link2

link3

link4

link5

link6

A: Уберите просто ваш инлайновый style="margin-left: auto"

* {
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}

nav {
    width: 100%;
    height: 60px;
}

.wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 100%;
    padding: 0 25px;

    border: 1px solid red;
}
.wrapper ul {
    display: flex;
    justify-content: space-between;
    flex-grow: 1;
    max-width: 100%;
    list-style: none;

    border: 1px solid green;
}

.wrapper ul li {
    padding: 0 25px;

    border: 1px solid blue;
}

link1

link2

link3

link4

link5

link6


text:
Q: How to install the Windows 7 look on Zorin OS, Ubuntu Based Distro The default interface of Zorin OS is a Windows 7 like interface, which is what I am looking for:

In the gallery page of the Zorin OS website, it shows, the option to change to a Windows 7, XP, 2000 interface.
I downloaded the free Zorin OS Lite, installed it next to Windows 7(dual boot). After I installed it, the interface was a Windows 2000 like interface. I found out in the Zorin OS look changer, that I only have the option of changing the looks to Windows 2000 Or Mac OS X. Don't like either of them.
This is for a former Windows user, he has an old PC, with Win7, thats just too slow. and I want to make his transition to Linux* as enjoyable as possible. Hence the Windows 7 look is needed.

A: When you're main objective is to get a Linux-based Windows-lookalike and you're not stuck with Zorin (of which I've never heard before1), I'd recommend Linux Mint + KDE + Windows 7 themes. Themes I've found there are much closer to the Windows (7 or 8) look than what I could see from your Zorin reference AND extremely easy to install, IMHO.
There is a risk, though, since using KDE requires a certain level of graphics hardware performance. On the other hand, I'm using a 7 years old 2x2.26GHz@3GB RAM laptop with Intel Integrated Graphics 4500MHD and it runs great (Linux Mint 17.1).
Example of the themes provided by the Linux Mint community:

However, I agree with the statement that sometimes change can be for the better. It gives you the chance to start fresh and get to know the advantages of the new that you might miss when trying to stick with the old forever. Having said that, the default Linux Mint Cinnamon2 desktop is worth a try. ;)

1 You might also want to take into consideration that while ZorinOS is certainly an interesting project that is worth being tested (for yourself), it's probably not the best idea to choose for a distribution with such a small community (support). The bigger the community the likelier it is that you will be able to help your friend when problems occure.
2 which is also highly customizable


text:
Q: Suggestions for printing content with Django I'm developing a django project (multiuser/multicustomer), and I'm looking for a "print solution".
My first idea was to generate a PDF and let the user print by himself.
Reading the django documentation I've found the note:

ReportLab is not thread-safe. Some of our users have reported odd issues with building PDF-generating Django views that are accessed by many people at the same time.

After searching a bit on google, I've also found some users complaining about weird issues with reportlab on multiuser systems.
Any ideas/suggestions for printing?
As a sidenote, the requirement for this application is a modern browser (updated Firefox or Chrome, so old browsers are not an issue).
Thank you.

A: You don't need a PDF. All browsers support a print-specific CSS stylesheet, so you can format your output as you like.
<link href="/static/print.css" media="print" rel="stylesheet" type="text/css">


text:
Q: How datas pass through in a android wifi direct connection I would like to know how datas transit in a group of wifi direct devices. Assuming that we have a group of 3 wifi direct devices A, B and C. A is the owner of the group. Now, if B wants to send datas through wifi direct to C, will datas of B be sent directly to C or they are obliged to pass by A (the group owner) and then be redirect to C?
Thank you

A: They will pass through A but A will not be able to see them. This is useful as B and C need not be even in each others range.


text:
Q: How can I convert a csv file to lowercase or uppercase maintaining it's structure using powershell? I have a CSV file that with contents that needs to be converted to all lowercase
I have tried the code below but it doesn't maintain the CSV structure.
(Get-Content C:\_Scratch\export.csv).ToLower() | Out-File C:\_scratch\export.csv

$Init = Import-Csv C:\_Scratch\export.csv

Is there another option I can try?

A: Get-Content is going to give you string array.  Add the -Raw switch to read it in as a single string, and the .toupper() and .tolower() string methods should work on that.
(Get-Content C:\_Scratch\export.csv -Raw).ToLower() | Out-File C:\_scratch\export.csv

A: $TempContentArray = $NULL
$TempContent = $NULL
$TempContent = Get-Content C:\_Scratch\import.csv
Foreach ($Line in $TempContent)
{
    $TempContentArray += $Line.ToUpper()
}
$TempContentArray | C:\_scratch\export.csv
$Init = Import-Csv C:\_Scratch\export.csv


text:
Q: Rails nested resources available in another context I plan on having galleries with nested images, so images belong in a gallery. I would then like images to have a Boolean option to determine whether or not a particular image shows up on the front page. Setting up a nested resource with a Boolean property is simple, but I haven't yet figured out how to access all images that have that property set to true.
Is iterating through each gallery and image the only way to do that? It seems to me there must be a better way...

A: Create a scope on the Image class and then you can chain that scope onto any other activerecord list of images:
class Image
  scope :homepage, where(:appear_on_homepage => true)
end

@gallery.images.homepage # Just the relevant images


text:
Q: .NET/Oracle Document Management System We have a custom built system that uses a ASP.Net front end with an Oracle backend (as per client requirements). Within this system is a custom module that functions as the system's document management/content management system. The module allows us to (1) Upload and manage documents available on the website and (2) Edit HTML pages which provide the links to said documents.
We would very much like to do away with our custom module and replace it with 3rd party software – either open source or commercial. Keeping in the spirit of our ASP.Net/Oracle environment, does anyone know of existing software that would satisfy our needs AND uses a ASP.Net front end and Oracle database?

A: Some co-workers and I just started looking into an open source tool called "My Webpage Starter Kit." It has an ASP.Net front end (using the file based setup) and uses XML to store its data. It allows you to accomplish both of the requirements you mentioned above.
Here is the link: http://mywebpagesstarterkit.codeplex.com/
Hope this helps.

A: The FileNet P8 Content Manager can store files in an Oracle database and it has a very rich API that you can use with .Net. It's not open source, and it's not cheap, but it can certainly do everything that you want to do and then some.
Also, please note that Oracle has a document management tool that is part of the "middleware fusion" suite of tools. It is also not free, but I know of a team that built a significant front-end on top of it using .Net.
HTH!
Tom Purl


text:
Q: Create a pivot table from 2 fact tables I have three tables fetched from an SQL DB:
[T1] changes: CR Number is the primary key.
CR Number | Planned Start | Planned End | Category

[T2] changes_impacted_clients: No primary key
CR Number | Impacted Client

[T3] clients: Client ID is the primary key.
Client ID | Status

I created a 1-to-many relationship between:

*

*changes[CR Number] and changes_impacted_clients[CR Number]

*clients[Client ID] and changes_impacted_clients[Impacted Client]

Desired Results:
I would like to create a Pivot Table to list the following columns:
CR Number | Planned Start | Planned End | Impacted Client

I want each row to the list of clients related to each CR Number. The pivot keeps repeating the records in the Impacted Clients at each row not matter they are related to the CR Number or not.


text:
Q: Polymer: Access dynamically created node of dynamically created custom element While updating my polymer project from 1.x to 2.0 I encountered this problem
I am wrapping one of my custom elements in dom-repeat like this
Host
<dom-repeat items="{{customer.hubs}}" as="item">
      <template>
        <paper-card elevation="2" class="hubCard">

HUB [[printIndex(customer.hubs,index)]]

          <hub-info hub="{{item}}" isloading="{{isloading}}" refresh-customer="[[refreshCustomer]]"/>
        </paper-card>
      </template>
    </dom-repeat>

part of the code of custom element is like below
Custom element

  <dom-if if="{{displayDebugger}}">
  <template>

     Debugger

    <iron-icon id="downArrow4" icon="icons:arrow-drop-down"></iron-icon>

</template>
  </dom-if>
<iron-collapse id="collapseDebugger" >
<hub-debugger hub-id="{{hub.hubId}}" isloading="{{isloading}}"></hub-debugger>
</iron-collapse>

Problem
First i tried to access iron-collapse as
this.$.collapseDebugger but i couldn't ,as i thought the custom elemrnt hub-info is inside dom-repeat i used this.shadowRoot.querySelector('#collapseDebugger') and accessed it.
Again i tried to access iron-icon (which is again dynamically created inside dom-if) as this.shadowRoot.querySelector('#downArrow4') but i am unable to access it.
How to access a dynamic node inside dynamic element?
 What if there is nesting of dynamic creations?

A: The this.shadowRoot.querySelector(selector) syntax should work.
Is the conditional template actually rendered? Do you  import polymer/lib/elements/dom-if.html in your custom element? This is needed, if you otherwise only import polymer/polymer-element.html.


text:
Q: SSH Tunnel/Forwarding not working for OpenSearch in VPC from EC2 I have created a OpenSearch cluster in AWS VPC with fine grained access. To login to OpenSearch Dashboard URL I created a bastion host(EC2) in public subnet of the same VPC. I have added security group to EC2 which has outbound rule to access security group of OpenSearch Cluster. I have also added another security group in EC2 to have inbound HTTPS rule for port 443.
Using Putty I configured SSH tunneling from EC2 to OpenSearch Tunneling from source port 9200 to 443. However when I logged in to https://localhost:9200/_dashboards, the page timeout. I tried curl OpenSearch-domain-URL and I get "Authentication finally failed" error. Please suggest if I'm missing anything here.
Thanks!


text:
Q: what is glushkov NFA. What is the difference between Glushkov NFA and Thompson NFA? I saw this term "Glushkov NFA" at http://lambda-the-ultimate.org/node/2064 . Search engines are returning references to articles that use glushkov nfa, but nothing specific about the glushkov nfa itself.
What is Glushkov NFA? How different is it from the NFA created from Thompson Construction?

A: I found this article "A Unified Construction of the Glushkov, Follow, and Antimirov Automata" containing a definition of the Glushkov construction of an NFA.

A: Flexible Pattern Matching in Strings contains a very good definition of Glushkov automata. It is the NFA constructed from a regex parse tree using the last,first, follow,nullable functions. This NFA does not contain empty transitions which is the main difference from the NFA created in Thompson Construction.


text:
Q: play youtube video in uiwebview without iphone video player I want to play youtube video in UIWebView only.
And don't want that iPhone video player plays video.
I want to implement this in swift

var url = "https://www.youtube.com/embed/yUEFauIpR40"

var htmlUrl = "<html><head><body style=\"(margin:0)\"><embed id=\"yt\" src=\"\(url)\" type=\"application/x-shockwave-flash\"width=\"\(560)\" height=\"\(315)\"></embed> </body></html>"

webView.loadHTMLString(url, baseURL: nil)

It plays the video in video player instead UIWebView.

A: webView.loadHTMLString(htmlUrl, baseURL: nil)

The above code solves your problem. Rory has the correct answer, you need to pass the htmlUrl.


text:
Q: ChangeStreamDocument.ClusterTime always throws FormatException I am on Windows 7 using MongoDB.Driver 2.7.0 in a net461/netstandard2.0 dll against a local install of community server 4.0.2 with a single replica set configured.
I am listening to a change stream on a collection, but when I simply try to access the ClusterTime property of the resulting ChangeStreamDocument it throws an exception:
    private static DateTime? GetTimeStamp(ChangeStreamDocument<T> csd)
    {
        try
        {
            var clusterTime = csd.ClusterTime; // BOOM
            return clusterTime.ToNullableUniversalTime();
        }
        catch
        {
            return null;
        }
    }

  System.FormatException
  HResult=0x80131537
  Message=Cannot deserialize a 'BsonDocument' from BsonType 'Timestamp'.
  Source=MongoDB.Bson
  StackTrace:
   at MongoDB.Bson.Serialization.Serializers.SerializerBase`1.EnsureBsonTypeEquals(IBsonReader reader, BsonType bsonType)
   at MongoDB.Bson.Serialization.Serializers.BsonValueSerializerBase`1.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
   at MongoDB.Bson.Serialization.Serializers.SerializerBase`1.MongoDB.Bson.Serialization.IBsonSerializer.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
   at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize(IBsonSerializer serializer, BsonDeserializationContext context)
   at MongoDB.Bson.Serialization.BsonSerializationInfo.DeserializeValue(BsonValue value)
   at MongoDB.Bson.Serialization.BsonDocumentBackedClass.GetValue[T](String memberName, T defaultValue)
   at Foo.GetTimeStamp(ChangeStreamDocument`1 csd) in Foo.cs:line 28

Looking at the backing document, clusterTime is indeed a Timestamp:
{
  "_id": {
    "_data": "825B9102E30000000129295A1004BFB7B7E0A5F648929251FC06F06640A2463C5F6964003C62366332623361352D313965352D343162392D386336322D396565313130393337666634000004"
  },
  "operationType": "insert",
  "clusterTime": Timestamp(1536230115, 1),
  // ... omitted
}

Is this a bug/known issue or a problem with my setup?

A: This has been confirmed as a bug by MongoDB.


text:
Q: How to add a phrase-less key to ssh agent? On running the command ssh-add mykey.ppk it asks for passphrase:

Enter passphrase for mykey.ppk:

But I can see that the key does not have any passphrase and is not encrypted
$ head mykey.ppk
PuTTY-User-Key-File-2: ssh-rsa
Encryption: none
Comment: imported-openssh-key
Public-Lines: 6
AAAAB3NzaC1yc2EAAAADAQABAAABAQC8V+PLuklXrfFDZ9GNluXB/L8foOzaEp5s
jwaOL1iAxCKDWWsfsmyj9MbhV5r4Z6VGo/0T

Simply pressing enter at the prompt does not work. How can I add this key to the agent?
PS: I've already heard the sermon on security practices, so you can save your breath :-)

A: ssh-agent does not support private keys in PPK format (PuTTY). You need to convert the key to OpenSSH key using PuTTY gen to be able to add it to your ssh-agent.
Related question on RaspberryPi.
These steps are needed:

*

*Load your private key into PuTTYgen

*Go to Conversions → Export OpenSSH and export your key as mykey.key

*Add your key to your agent using ssh-add mykey.key.

On Linux, the equivalent puttygen command is:
puttygen mykey.ppk -o mykey.key -O private-openssh


text:
Q: Population JavaFX listView with ProcessBuilder results i am try to populate javaFX listView with process builder results. i could fill listView but
i want to do; smooth display of the columns like terminal, can any one help  me?
My execute command codes:
public List<String> executeCommand(String[] command, boolean joption) {
    List<String> output = new ArrayList<>();
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.command(command);
    try {
        Process process = processBuilder.start();
        Scanner reader = new Scanner(new InputStreamReader(process.getInputStream()));
        while ((reader.hasNextLine())) {
            output.add(reader.nextLine());
        }
        int exitCode = process.waitFor();
        System.out.println("\nExited with error code : " + exitCode);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return output;
}

and
@FXML
private void searchImage(ActionEvent event) {
    ObservableList<String> images = FXCollections.observableArrayList();
    final String imageName = searchImage.getText();
    String[] command = {"docker", "search", imageName};
    CalistirShellCommand calistir = new CalistirShellCommand();
    images = FXCollections.observableArrayList(calistir.executeCommand(command, true));
    listView.setItems(images);
    System.out.println("bitti");
}

Terminals Picture
when codes run, listView's picture:


text:
Q: preg_replace (or other) to remove duplicate tags I'm merging two HTML files together, and as such, they have duplicate <head> </head>, <html> </html> and <body> </body> tags. Is there a way to get preg_replace remove only the second batch of duplicate tags, so the content of the second document blend together without any problems?
If not with preg_replace, is there another way of doing this?
Conceptual Information:
In this instance, there are two files. There will be more eventually.
Each file starts off like this:
<html>
<head>
<style type='text/css'>
(Template Data)
</style>
</head>
<body>

My script is taking those files (which live in some directory), and creating a NEW file that combines both outputs. However, the result of this is something along the lines of:
<html>
<head>
<style type='text/css'>
(Template Data)
</style>
</head>
<body>
blah blah blah
<html>
<head>
<style type='text/css'>
(Template Data)
</style>
</head>
<body>
blah blah blah 2

This creates duplicate tags.  The desired output would be:
<html>
<head>
<style type='text/css'>
(Template Data)
</style>
</head>
<body>
Blah blah blah
Blah blah blah 2

Essentially cutting out the head data for all of the HTML files outside of the first one processed through a while loop
Thanks so much!

A: You can just apply the tag removal on the second HTML before you merge it, then merge the first HTML with the stripped second HTML.
Here's a pseudocode example if you have more HTMLs to merge:
$strip_tags = false;
foreach ($htmls_to_merge as $html) {
    if ($strip_tags) { // this will be false in the first iteration, then true
        $html = what you do to strip the tags;
    }
    merge;
    $strip_tags = true;
}

A: You can try SoftSnow Merger. Not a very hacker-y way of doing things but as long as it works...


text:
Q: Generic Array Index Does C# have an array type indexable by a generic type (obviously one constrained to IComparable or some such)? For example:
public class GenericallyIndexedArray<I,T> where I : struct, IComparable { // ...

Order is important.

A: Yes, it's SortedList<TKey, TValue>
You can supply the IComparer<T> to use for the keys, or use the default one if the key type implements it.


text:
Q: Toggle decorations for a window from the shell? Is there a way to toggle X11 window decorations for a single window, given the window's ID, from a script?  If the answer to this question is window manager specific, I'm using openbox.
I thought xdotool could do this with:
xdotool ID alt+space d

or
xdotool ID alt+space; sleep 1; xdotool ID d

The popup does appear but something is typed into my shell rather than into the popup.

A: you could set a keystroke for that in the openbox config ~/.config/openbox/${config}.xml in the <keyboard> section like this:
 <keybind key="C-S-d">
   <action name="ToggleDecorations"/>
 </keybind>

..to have decorations toggled by pressing CTRL-SHIFT-d in almost any application.
I've made 'em toggled by the maximize/shade function automatically when double-clicking the titlebar by adding <action name="ToggleDecorations"/> to the <mousebind button="Left" action="DoubleClick"> part of the <context name="Titlebar"> section like this:
<mousebind button="Left" action="DoubleClick">
  <action name="ToggleDecorations"></action>
  <action name="ToggleMaximize"/>
</mousebind>

so windows are decorized only as I need 'em to be. hope it helps even if the question is years old...
regards

A: Finally got something close to what I want.  Example:
xdotool key -windowid 0x1200016 alt+space; sleep 1; xdotool key -windowid 0x1200016 End Up Return

The End moves the cursor to the last item in the popup menu.
The Up moves the cursor up one entry in the popup menu where the "Un/Decorate" item lives.
The Return simulates the press of the Enter key.
However, I still get something typed into the window being un/decorated.
If I try this:
xdotool key -windowid 0x1200016 alt+space End Up Return

garbage is continuously "typed" into the window being un/decorated and hides my mouse cursor until I press Control+c a few times.
Further, openbox fails to acknowledge keyboard presses and mouse clicks for a few seconds afterward.
Follow Up:
Sometimes xdotool and wmctrl cease to do anything.  This solution does not meet my needs.


text:
Q: ngPattern rejecting all inputs, inside ngForm I have a ngRepeat populating a form but form.input.$error.pattern is true (the input does not match the RegExp) with anything in the text input for the first input. For all inputs after that form.input.$error.required stays true, even with something present in the input text. The classes .ng-pristine, .ng-touched, .ng-dirty, etc. still behave as expected.
A service defines the regular expressions:
.service('Apform', function () {
  'use strict';
var patt = {
            alpha: /^[a-zA-Z]+$/,
            alpha_numeric: /^[a-zA-Z0-9]+$/,
            phone: /^\d{3}[\-]\d{3}[\-]\d{4}$/,
            postal: /^[A-Za-z][0-9][A-Za-z] [0-9][A-Za-z][0-9]$/,
        };
return patt;

Which is injected into the controller:
controller: function ($scope, Apform)
        {
        $scope.patt = Apform;
        $scope.application = [
            {
                label: 'Name',
                model: 'clientName',
                required: true,
                pattern: $scope.patt.alpha,
                error: 'Valid with letters only',
                type: 'text',
            },
            {
                label: 'Address',
                model: 'clientAddress',
                required: true,
                pattern: $scope.patt.alpha_numeric,
                error: 'Valid with letters and numbers only',
                type: 'text',
            },
    ....
    ];}};});

The object is used in an ngRepeat inside ngForm:
<ng-form name="applicationForm">

                        {{form.label}}

                        <input type="{{form.type}}"
                               id="{{form.label}}"
                               name="{{form.label}}"
                               placeholder="{{form.label}}"
                               ng-required="{{form.required}}"
                               ng-pattern="'{{form.pattern}}'"
                               ng-model="$parent.$parent.output[form.model]">

                        applicationForm[{{form.label}}].$valid: {{applicationForm[form.label].$valid}}

                        applicationForm[{{form.label}}].$error: {{applicationForm[form.label].$error}}

                        applicationForm[{{form.label}}].required: {{applicationForm[form.label].required}}

                        applicationForm.$valid: {{applicationForm.$valid}}

</ng-form>

What's going wrong?


text:
Q: extracting the data of a specified function in a python file | adding comments to highlight what is removed I want to extract the code written under a specified function. I am trying to do it like this:
With an example file TestFile.py containing the following function sub():
def sub(self,num1,num2):
    # Subtract two numbers
    answer = num1 - num2
    # Print the answer
    print('Difference = ',answer)

If I run get_func_data.py:
def giveFunctionData(data, function):
    dataRequired = []
    for i in range(0, len(data)):
        if data[i].__contains__(str(function)):
            startIndex = i
            for p in range(startIndex + 1, len(data)):
                dataRequired.append(data[p])
                if data[p].startswith('\n' + 'def'):
                    dataRequired.remove(dataRequired[len(dataRequired) - 1])
                    break
    print(dataRequired)
    return dataRequired

data = []
f = open("TestFile.py", "r")
for everyLine in f:
    if not(everyLine.startswith('#') or everyLine.startswith('\n' + '#')):
        data.append(everyLine)

giveFunctionData(data,'sub') # Extract content in sub() function

I expect to obtain the following result:
answer = num1 - num2
print('Difference = ',answer)

But here I get the comments written inside the function as well. Instead of the list, Is there a way to get it as it is written in the file?

A: Returning a string from your function giveFunctionData()
In your function giveFunctionData you're instantiating the variable dataRequired as a list and returning it after assigning it a value so of course you're getting a list back.
You'd have to unpack the list back into a string. One way could be this:
# Unpack the list into a string
function_content = ''
for line in dataRequired:
    function_content += line + '\n'
# function_content now contains your desired string

The reason you're still getting comment lines
Iterating from a file object instantiated via open() will give you a list of lines from a file with \n already used as a delimiter for lines. As a result, there aren't any \n# for .startswith('\n' + '#')) to find.
General comments

*

*There is no need to specify the newline and # character separately like you did in .startswith('\n' + '#')). '\n#' would have been fine

*If you intend for the file to be run as a script, you really should put your code to be run in a if __name__ == "__main__": conditional. See What does if name == "main": do?

*It might be cleaner to move the reading of the file object into your giveFunctionData() function. It also eliminates having to to iterate over it multiple times.

Putting it all together
Note that this script isn't able to ignore comments placed in the same line as code, (eg. some = statement # With comments won't be comment-stripped)
def giveFunctionData(data, function):
    function_content = ''
    # Tells us whether to append lines to the `function_content` string
    record_content = False
    for line in data:
        if not record_content:
            # Once we find a match, we start recording lines
            if function in line:
                record_content = True
        else:
            # We keep recording until we encounter another function
            if line.startswith('def'):
                break
            elif line.isspace():
                continue
            elif '#' not in line:
                # Add line to `function_content` string
                function_content += line

    return function_content

if __name__ == "__main__":
    data = []
    script = open("TestFile.py")
    output = giveFunctionData(script, 'sub')
    print(output)

A: I have generated code which an do your task. I don't think you require 2 different processing part like function and code to fetch data.
You can do one thing, create a function which accept 2 arguments i.e. File Name and Function Name. Function should return the code you want.
I have created function getFunctionCode(filename,funcname). Code is working well.
def getFunctionCode(filename, funcname):
    data = []
    with open(filename) as fp:
        line = fp.readlines()
        startIndex = 0 #From where to start reading body part
        endIndex = 0 #till what line because file may have mult
    for i in range(len(line)): #Finding Starting index
        if(line[i].__contains__(funcname)):
            startIndex = i+1
            break

    for i in range(startIndex,len(line)):
        if(line[i].__contains__('def')): #Find end in case - multiple function
            endIndex = i-1
            break
        else:
            endIndex = len(line)

    for i in range(startIndex,endIndex):
        if(line[i] != None):
            temp = "{}".format(line[i].strip())[0]
            if(temp != '\n' and  temp != '#'):
                data.append(line[i][:-1])
    return(data)

I have read the file provided in first argument.
Then Found out the index where function is location. Function is provided in second arguement.
Starting from the index, I cleared string and checked first character to know about comment (#) and new line (\n).
Finally, the lines without these are appended.
Here, you can find file TestFile.py :
def sub(self,num1,num2):
    # Subtract two numbers
    answer = num1 - num2
    # Print the answer
    print('Difference = ',answer)

def add(self,num1,num2):
    # addition of two numbers
    answer = num1 + num2
    # Print the answer
    print('Summation = ',answer)

def mul(self,num1,num2):
    # Product of two numbers
    answer = num1 * num2
    # Print the answer
    print('Product = ',answer)

Execution of function :
getFunctionCode('TestFile.py','sub')
['    answer = num1 - num2', "    print('Difference = ',answer)"]

getFunctionCode('TestFile.py','add')
['    answer = num1 + num2', "    print('Summation = ',answer)"]

getFunctionCode('TestFile.py','mul')
['    answer = num1 * num2', "    print('Product = ',answer)"]

Solution by MoltenMuffins is easier as well.

A: Your implementation of this function would fail badly if you have multiple functions inside your TestFile.py file and if you are intending to retrieve the source code of only specific functions from TestFile.py. It would also fail if you have some variables defined between two function definitions in TestFile.py
A more idealistic and simplistic way to extract the source code of a function from TestFile.py would be to use the inspect.getsource() method as follows:
#Import necessary packages
import os
import sys
import inspect

#This function takes as input your pyton .py file and the function name in the .py file for which code is needed
def giveFunctionData(file_path,function_name):
    folder_path = os.path.dirname(os.path.abspath(file_path))
    #Change directory to the folder containing the .py file
    os.chdir(folder_path)
    head, tail = os.path.split(file_path)
    tail = tail.split('.')[0]
    #Contruct import statement for the function that needs to be imported
    import_statement = "from " + tail + " import " + function_name
    #Execute the import statement
    exec(import_statement)
    #Extract the function code with comments
    function_code_with_comments = eval("inspect.getsource("+function_name+")")
    #Now, filter out the comments from the function code
    function_code_without_comments = ''
    for line in function_code_with_comments.splitlines():
        currentstr = line.lstrip()
        if not currentstr.startswith("#"):
                                     function_code_without_comments = function_code_without_comments + line + '\n'
    return function_code_without_comments

#Specify absolute path of your python file from which function code needs to be extracted
file_path = "Path_To_Testfile.py"
#Specify the name of the function for which code is needed
function_name = "sub"

#Print the output function code without comments by calling the function "giveFunctionData(file_path,function_name)"
print(giveFunctionData(file_path,function_name))

This method will work for any kind of function code that you need to extract irrespective of the formatting of the .py file where the function is present instead of parsing the .py file as a string variable.
Cheers!


text:
Q: Next Export fails when using appdir - "PageNotFoundError: Cannot find module for page /(...) I'm using NextJS with the experimental appDir flag, I've added my pages like so:

Where layout.tsx on root and onboard look like:
export default function DefaultLayout({ children }) {
    return (
        <>
            {children}
        </>
    )
}

and the onboarding page looks like:
export default function Onboard() {
    return
onboarding page

}

This works fine in the browser when I hit localhost:3000/public/onboard - however when attempting to do a next build I get the error:
PageNotFoundError: Cannot find module for page: /public/onboard
    at Object.getPagePath (...)

Not sure if this has to do with appDir next build being sunupported?


text:
Q: Windows 7 PC with added graphics card, unable to see on-board graphics I have a new Windows 7 (64) PC which has built-in graphics on its (MSI H61M-P31/W8 (MS-7788)) motherboard. I have also added an NVIDIA GeForce 8500 GT graphics card, which is working fine, driving two monitors.
Now I wish to have a third monitor attached to the motherboard graphics, but it appears that my system doesn't know of the existence of the motherboard graphics. If I look at "Display Adapters" in Device Manager, I only see the NVIDIA card. What have I done wrong?
EDIT: There was a similar question on SU here, but the accepted answer did not indicate exactly what to do to make it work, i.e., no mention of BIOS settings.

A: Most motherboards do not allow you to use both the on-board graphics chip and an installed card.  It's usually one or the other, with very few exceptions that I've found.  In order to add additional monitors, you'll have to add another graphics card.
Your motherboard's manual doesn't state specifically one way or the other, but you can try an experiment.  Go into your BIOS settings and look for graphics settings.  In the settings, make sure the on-board graphics are enabled, then save your settings and reboot.  Make sure you have a monitor attached to the onboard output.  In all likelihood, only the on board graphics will now work and nothing will show on the monitors attached to your NVIDIA card.  If all three screens show up, then congrats it worked!  Otherwise, go back and disable the on-board graphics.  You'll have to wait until you can add a second graphics card.

A: First make sure you actually HAVE on-board graphics.
Even though the connector is on the motherboard the actual IGP (Integrated Graphics Processor) is build inside the processor. You will need to check if your CPU actually has one. Not all Intel CPU's do. It depends on the model-number of the CPU. You can use a utility like CPU-Z to check what exact variant of CPU you have.
Second the motherboard must support using the IGP and the GeForce in parallel. If it doesn't you are out of luck.
If it does, you will most likely have to enable that feature in the Bios first.
If is usually set to "Use PCIe, fall back to IGP". This needs to be changed to "Use IGP + PCIe".
(That's most likely not the exact text. How the setting is called in your Bios I don't know.)

A: The manual for your motherboard (MS-7788) says that the graphics ports only work with an Integrated Graphics Processor - i.e. on your CPU.
So, check what CPU you've got and see if it has Integrated Graphics.


text:
Q: MOS Amplifier Circuits with Feedback The following images show NMOS amplifiers circuits with feedback:
a)Transconductance (tension source, current output (RL)) -> current sampling, tension mixing
b)Transresistance (current source, tension output) -> tension sampling, current mixing
c)Current (current source, current output (RL)) -> current sampling, current mixing
.
However, I am not understanding the feedback networks, underlined in a different blue.
a) how is the current sampled?
b) how is the current mixed?
c) how is the current sampled and mixed?
.
I am following 'Microelectronic Circuits' by Sedra Smith, but i am still not understanding

A: Basic question: What is the meaning of the term "feedback"?
Answer: We have feedback when (a part of) the output signal is coupled back to the input. Therefore, at first we need a definition of the output signal.
(a) Answer to (a) :
Well, the answer is not too evident - as far as the given example (first circuit) is concerned. For a decision - feedback current-controlled or voltage-controlled - it is necessary to know if the output signal is defined  as (a) a voltage across a certain load which is connected between the output node and ground or (b) as a current through a certain load.  This seems not to be 100% clear with the shown circuit (because the output quantity is bot mentioned explicitely), however, we can see a resistor named RL (load?) - and this is an indication that the output quantity is a CURRENT (Io) resp. the corresponding voltage across this resistor (and NOT the collector voltage of the pnp transistor, see also the small circled nodes across this resistor RL).
This observation allows the conclusion that the output current Io (which is nearly independend on the value of RF (BJT is acting as a voltage-controlled current source) is "sampled" - that means: A voltage proportional to the output current Io is fed back to the input of the whole circuit.
I think, it is not a problem to verify that we have, indeed, negative feedback (output current-controlled voltage feedback).
In the second circuit, it is clear that the output quantity is the voltage Vo and that we have, therefore, voltage-controlled current feedback.
(b) Answer to (b): A "mixing" of two currents (input and feedback current) is performed when two currents meet in a common node. I think, it is not too difficult to see how this happensat the input node of the two last circuits.
(c) I do not understand this question. Either a current (or a voltage derived from this current) is sampled - or it is mixed with another current. A combination of these two effects does not take place.

COMMENT 1: A decision if we have current- or voltage-controlled feedback is possible also applying the rules for calculating input or output resustances.
(1) for a voltage (or current) controlled feedback (sampling the output voltage or the output current) the output resistance goes down (or high);
(2) for a combination of voltages (or currents) at the input the input resistance goes high (or low).
COMMENT 2: For improving the undestanding of the different feedback schemes, it is helpful to realize the following: For the first circuit, without any change of the parts arrangements, we would have voltage-controlled feedback (output voltage sampling) when the source of Q1 is connected directly to the drain of Q2.

Does this answer your question?


text:
Q: How set lockAspectRatio for gridItem in react-grid-layout I'm new in React and I tried use react-grid-layout. I can't create gridItem (className='block') with a fixed aspect ratio. I think lockAspectRatio prop from Resizable component must be use.
How create div (key="a","b","c","d") with lockAspectRatio=true?
import React, {Component} from 'react'
import GridLayout from 'react-grid-layout';
import Draggable from 'react-draggable';

import '../../../node_modules/react-grid-layout/css/styles.css'
import '../../../node_modules/react-resizable/css/styles.css'
import './dashboard.css'

class Dashboard extends Component {
  render() {
    // layout is an array of objects, see the demo for more complete usage
    const layout = [
      {i: 'a', x: 0, y: 0, w: 6, h: 8, minW: 4, maxW: 8},
      {i: 'b', x: 8, y: 0, w: 6, h: 8, minW: 4, maxW: 8},
      {i: 'c', x: 0, y: 0, w: 6, h: 8, minW: 4, maxW: 8},
      {i: 'd', x: 8, y: 0, w: 6, h: 8, minW: 4, maxW: 8}
    ];

    return (

      <Draggable>

Hello!

            <button>Push</button>

      </Draggable>
      <GridLayout
        className="layout"
        layout={layout}
        cols={12}
        rowHeight={30}
        width={1200}
        draggableHandle = '.MyDragHandle'
        draggableCancel = '.MyDragCancel'

      >

Window 1

Window 2

Window 3

Window 4

      </GridLayout>

    )
  }
}

export default Dashboard

A: I hope somebody could use this as answer to the question. I found a way to implement my own resize with preserving aspect ratio in react-grid-layout:
const handleResize = useCallback(
    (l, oldLayoutItem, layoutItem, placeholder) => {
      const heightDiff = layoutItem.h - oldLayoutItem.h;
      const widthDiff = layoutItem.w - oldLayoutItem.w;
      const changeCoef = oldLayoutItem.w / oldLayoutItem.h;
      if (Math.abs(heightDiff) < Math.abs(widthDiff)) {
        layoutItem.h = layoutItem.w / changeCoef;
        placeholder.h = layoutItem.w / changeCoef;
      } else {
        layoutItem.w = layoutItem.h * changeCoef;
        placeholder.w = layoutItem.h * changeCoef;
      }
    },
    []
  );

There is no working way to pass down lockAspectRatio. If anyone could improve my method, feel free to comment!


text:
Q: how to run maven project from github in eclipse I use eclipse and I want to compile and run this code from gitub https://github.com/openphacts/Validator ,it needs maven project to build it but unfortunately I don't know how to proceed with it. Can someone help me how to get this project into eclipse to run it and test it in my machine please? It's emergency

A: Once you've checked out the project from github, you need to utilize maven to install the dependencies and build the project. In the root folder of the project (where the pom.xml is located), enter the following in your command line:
mvn install

More details can be found here: https://maven.apache.org/run-maven/
Additionally, you must first download the maven command line tool: https://maven.apache.org/download.cgi
And install it: https://maven.apache.org/install.html


text:
Q: Why can't the program recognize pygame? I have downloaded and installed pygame and I know where it is (/usr/lib/python2.7/dist-packages). I am trying to get the program consisting of the line 'import pygame' to recognize its existence but I keep getting 'ImportError: No module named pygame'. How would I get it to work?

A: The installation packages for pygame are incompatible with python 3.x  However, the vast majority of the pygame modules have been ported to python 3.x, so really it's simply a matter of moving the Pygame modules to your python 3.x dist-packages.
The scrap, _movie, surfarray for Numeric, and threads modules are the ones that have NOT been ported yet.


text:
Q: ionic serve don't run give me "Error: ENOENT: no such file or directory" I work in ionic framework and create new project
after that when i run

ionic serve

the browser open and give me this msg
Error: ENOENT: no such file or directory, open '/Users/.../ionicProject/www/index.html'

A: File names are case sensitives, maybe you should go to check it.


text:
Q: Using opencv's calcHist with UMat for calculating a percentile I am writing a function that gets a given percentile of an image (gray).
For that I wanted to use calcHist() with UMat in order to accelerate my code.
But in all the ways I've tried to do that - it took much more time when I used UMat (instead of Mat).
I am new here - any help would be highly appreciated.
Here is my code:
int CalcPercentile(UMat gray, float fPercent)
{
    int hSize = 256;
    UMat hist;
    Mat histMat;

    calcHist(vector<UMat>{gray}, vector<int>{0}, UMat(), hist, vector<int>{hSize}, vector<float>{0,255});
    int iNumPixels = gray.rows * gray.cols;
    float fSumFreqNeeded = (float)iNumPixels * fPercent;

    histMat = hist.getMat(ACCESS_READ); // or: hist.copyTo(histMat);

    int iSumFreq = 0, iVal;

    for (iVal = 0; iVal < iHistSize; iVal++)
    {
        int iCurrFreq = (int)(histMat.at<float>(iVal));
        iSumFreq += iCurrFreq;
        if (iSumFreq >= fSumFreqNeeded)
            break;
    }
    return iVal;
}

a corresponding function with Mat instead of UMat was much faster.
(But my code uses UMat gray image as input - and converting to Mat again takes too much time).


text:
Q: Consistency of user data between all his sessions I'm developing a site in PHP. When the user session starts I load all his db row in the $_SESSION var. When the user changes a db value I update the $_SESSION var too.
The problem starts when more than one session is active for the same user. Is there a way to update the data for all the sessions of the same user without overloading the database? Or, alternatively, is there a way to force php to use the same session file for all the session that belongs to the same user? Or I must simply query the db every time a session continues?
And another dilemma is: is it worth it? I mean, I do not know how much this mechanism could alleviate the server load, and I do not know if this mechanism is applicable to file-based sessions or I must use another session storing type.
This question is somewhat related to this other question on mine (even if the workaround for this is simply to delete all session files).

A: It really reaches the question why would you need to many data in a $_SESSION. And you should really take a time to decide which data is so often needed to be displayed.
In most of the cases you only need session identifier that keeps the user logged in, containing user_id, to take the needed data directly from the database.
Assuming the user can change its avatar, and you haven't go so many places to display this avatar, you don't need to store it in session, nor to SELECT it at the very same time. For instance, you can have a trigger page, which SELECTS the avatar by $_SESSION['user_id'] when he tries to send personal message to another user. Otherwise, you can put a cache (i.e. using memcached) where a query, which selects the user avatars should not be made more often than once an hour.
If user changes an email, it's the same. If somebody else tries to send him message, you trigger the SELECT query. Otherwise a cache is set.
So, let's say the user has changed his avatar, email, some other trivial info, then accessed your index page. In his session you load only the identifier. In the db the records are present, but they are not selected yet. So you have neither server load, because the session is light, nor database load, because no SELECT queries were sent.
No matter how many times the user tries to set his session (in this case logs second time), you have a present data in the db, and a session only with identifier. You can identify all his instances, but never use a data, which is not needed.

A: 1 Well, I (don't, but) could do this with my session handler. I use databased SESSIONS with some extra information/columns like username and userid. That way I can exactly determine which session belongs to which user without fiddeling around with the serialized data.
http://php.net/manual/de/function.session-set-save-handler.php
2 But in your case it might be simpler to update your user table and then SELECT the user again to put the (new) data to $_SESSION['user']. (You will need some "user data was updated" info, to reload new data for all sessions).
3 Or you just avoid that a user can login more than once.