text:
Q: Using base class function with derived class values I'm having problems getting a vector of objects to print the name of the derived class rather then the base class.
These are my classes
#include <vector>
#include <iostream>

using namespace std;

class Object
{
    string name;
public:
    string getName()
    {
        return name;
    }
};

class Flashlight : public Object
{
    string name = "Flashlight";
public:
    string getName();
};

This is my main, it has a vector of the objects and at this point just needs to print out their names.
int main()
{
    vector<Object> items;
    items.push_back(*new Flashlight);

    for(int i = 0; i < items.size(); i++)
    {
        cout << i+1 << " " << items.at(i).getName();
    }
}

Right now if I assign something to the name in Object it will print that but its not using the derived classes values, I just want it to inherit the function then use its own values with it. I've tried implementing the function in the base classes(but seeing as I could have a lot of those in future it would lead to lots of redundant code) but that doesn't work either.

A: Instead of declaring variable 'name' in derived classes, initialize the variables value as custom value for that derived class. Also I would suggest you to make getName method as virtual. You also do not need to override getName method in derived classes if you just want to output name.

A: Try this way:
int main()
{
    vector<Object *> items;
    items.push_back(new Flashlight);

    for(int i = 0; i < items.size(); i++)
    {
        cout << i+1 << " " << items.at(i)->getName();
    }
}

Also as mentioned in another answer it would be good to use virtual methods read about it here.
What is more you need to use constructor to set value for variable name. You can read about them here
You should try this way:
class Object
{
private:
    string name;
public:
    Object() : name("Object")
    {}
    Object(string str) : name(str)
    {}

    string getName()
    {
        return name;
    }
};

class Flashlight : public Object
{
public:
    Flashlight() : Object("Flashlight")
    {}

    string getName();
};

A: Your code has two problems:

*

*getName() is not virtual. This means that the actual function called is decided at compile time, based on the variable static type. So, if your variable is of type Object, Object& or Object* (or any const variation on those), function Object::getName() will be called, regardless of the actual type of the object referred to or pointed to by your variable (the dynamic type).

*You have a vector<Object>, which means that all objects stored in it are of type Object. You can try to put a Flashlight object in it, but only the Object part will be copied into the vector. If you need polymorphism in a vector<>, you need a vector of pointers (or even better, smart pointers).

So you have to do two things to get the desired behaviour:

*

*Declare function getName() as virtual string getName() (even
better, virtual const string& getName() const)

*Declare items as vector<Object*> items (even better, use an
appropriate smart pointer such as unique_ptr<> instead of a raw
pointer)


text:
Q: C# - In debugger, as soon as execution gets to method, attributes set to 0. Then after, they are back During defineMapCellPositions() and defineMapCellWalls(), map.cols and map.rows change from values such as 4 and 5 to 0, only for the step through of the methods. A step through the debugger confirms this. Why is this?
Any Help Appreciated, thanks!
Whole Map class
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

public class Map
{
    public Map()
    {
    }
    public int rows { get; set; }
    public int cols { get; set; }
    public int boardXPos { get; set; }
    public int boardYPos { get; set; }
    public int squareSize { get; set; }

    private List<List<int>> m_cellPositions = new List<List<int>>();
    public List<List<int>> cellPositions
    {
        get
        {
            return m_cellPositions;
        }
        set
        {
            m_cellPositions = value;
        }
    }

    private List<List<int>> m_cellWalls = new List<List<int>>();
    public List<List<int>> cellWalls
    {
        get
        {
            return m_cellWalls;
        }
        set
        {
            m_cellWalls = value;
        }
    }
}

Start of MapController Class
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

public class MapController
{
    public MapController()
    {
    }

    Map map = new Map();

Method to set map.cellWalls
public void defineCellWallsList()
{
    //map.cellWalls.Clear();
    for (int row = 0; row < (map.rows * map.cols); row++)
    {
        map.cellWalls.Add(new List<int> { 0, 0 });
    }
}

Method to set map.cellPositions
public void defineCellPositionsList()
{
    //map.cellPositions.Clear();
    for (int row = 0; row < map.rows; row++)
    {
        for (int col = 0; col < map.cols; col++)
        {
            map.cellPositions.Add(new List<int> { col, row });
        }
    }
}

A: To expose the instance of Map in your MapController either make it a public field, or put it in a property.  example:
public class MapController
{
    public MapController()
    {
    }

    //here you make it "public" so it is visible to outside classes
    public Map map = new Map();

    // the rest of your code for this class...

Then to access that instance (assuming you are holding onto an instance of the controller)
var controller = new MapController();
controller.map.rows = 5; // now you can access that instance of map.
controller.map.rows = 123;

Now, to inject the Map into the controller (meaning that it is newed up somewhere else in your code, and the same instance can then be shared accross multiple classes using similar injection procedures) you would do something like this...
public class MapController
{
    //here you make it "private" cause it doesn't need to be public anymore,
    //you also don't new it up here, you are passing in a new on during construction.
    private Map map;
    public MapController(Map map)
    {
        this.map = map
    }

    // the rest of your code for this class...

Now in the code where you new up the objects and stuff...
var map = new Map();
var controller = new MapController(map);
map.rows = 5; // now you can access that instance of map.
map.rows = 123;
// and you can easily share that same instance with other classes
var otherClass = new SomeOtherClassThatNeedsTheMap(map);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I import data from an XLS file to MySQL? As I am trying to import MS Excel data to MySQL data base
using the following code:
<?php
    $db_username="root"; //database user name
    $db_password="";//database password
    $db_database="hr_mysql"; //database name
    $db_host="localhost";

    mysql_connect($db_host,$db_username,$db_password);
    @mysql_select_db($db_database) or die( "Unable to connect to database.");

    $handle = fopen("UploadIt.xls", "r"); //test.xls excel file name
    if ($handle)
    {
        $array = explode("\n", fread($handle, filesize("UploadIt.xls")));
    }

    $total_array = count($array);
    $i = 0;
    $Leave_Type_Id1="LTY001";
    $Leave_Type_Id2="LTY002";

    while($i < $total_array)
    {
    $data = explode(",", $array[$i]);
    //$sql = "insert into test values ('$data[0]','$data[1]')";
    $sql = "update `hs_hr_employee_leave_quota` set `no_of_days_allotted`= {$data[0]} WHERE `employee_id`= {$data[0]} and `leave_type_id`= '{$Leave_Type_Id1}'";
    $result = mysql_query($sql);
    $sql = "update `hs_hr_employee_leave_quota` set `no_of_days_allotted`= {$data[2]} WHERE `employee_id`= {$data[0]} and `leave_type_id`= '{$Leave_Type_Id2}'";
    $result = mysql_query($sql);
    $i++;
    }
    if($result==false)
            echo "Not succed";
    else
    {
        echo "completed";
    }

?>

And my .xls sheet is:
But I am getting error saying
htdocs\Verify\XL_To_DBTable.php line 28 - Undefined offset:  2
|1|2|5|
|2|3|5|
|3|3|4|
|4|3|9|
|5|4|1|
(Assume above one as xls sheet only)

A: You need to properly read the file as an MS Excel file.  You are treating it as an ascii text file.  You could manually dump the file to CSV format and parse it using similar logic to what you have already.  Or you could use:
PHP Excel File Reader
and use that to parse the file, get the contents and then create the appropriate queries to be executed in mysql.


text:
Q: Difficulty figuring out an app/webpage to webpage interaction Context:
The page I'm making should take in graph data from a JSON format from an outside application/webpage.  Queries to Parse.com will gather the initial data, so I can avoid setting up the graph page with a connection to the Parse database.
A webpage OR android application currently submits a request to the Parse system and get back a response formatted in JSON, then it must send that information to a webpage with graphing JavaScript for it to read and build the graph from.
I've explored the possibility of sessions or cookies, but it doesn't seem compatible with the android application end (unless webview can do something?).  GET looked like a good alternative originally but the size of some URI query strings would easily be too large.  POST, upon review, is impossible for me to use in this case.
Question:
Is there still another way to send this information without AJAX, PHP or some other server-side code?  Or would i need to scrap the idea as it stands, and just implement it all on the graph page anyway?


text:
Q: C2676 binary '++': 'NumSet' does not define this operator or a conversion to a type acceptable to the predefined operator I'm trying to override the ++ operation in C++, but I'm getting error C2676 on my usage of ++ on my class.
The way I overrode the command:
void NumSet::operator++() {

int newVal;

for (int i = 0; i < this->_filledCells; i++)
{
    newVal = this->_nums[i] + 1;

    if (this->isValid(this->_nums[i] + 1))
    {
        this->_nums[i] = newVal;
    }
    else
    {
        cout << "Number " << newVal << " isn't valid" << endl;
    }
}
}

The place I used the command, that is giving me the error:
NumSet* mySet = new NumSet();
mySet->insert(1);
mySet->insert(3);
mySet->insert(5);
mySet->insert(5);
mySet->insert(8);

// Check operator ++ - Increase each cell value by one.
(*mySet)++;
cout << *mySet << endl;

I overrode a number of operators, the only ones giving me errors (at least for now) are '++' and '--' which I wrote almost identically. I can't figure out what I did wrong here.


text:
Q: Envelope Distortion with .Net Graphicspath I'm trying to figure out the best way to accomplish warping a GraphicsPath in .net to a specific shape.  The result I'm trying to achieve is warping text to curve up, down, fan left, right, and things like a wave.  All of these can be achieved in Adobe Illustrator using the envelope distort feature.
I have considered rolling my own method of doing this using some of predefined grid and point mapping system to transform points.  However, it seems like there would be some algorithms or samples as to how to do this already available?

A: I wanted to follow up to this post I made some time ago. I have had worked out a few other ways to accomplish what I wanted to do originally in this post.  First off GraphicsPath has a nice warp() method which performs just that, warping any path into the 4 points of a rectangle.  Using this idea you can accomplish this below.

Here is the same warp applied to a path with text arched up

This is the classic star wars text warp by just setting the 4 points of the rectangle in the warp() method

The same warp applied to a path that is arched up.

What I have concluded is a lot of warps can be accomplished by first typing on a path such as an arch or a wave, then applying the warp() method in a GraphicsPath.
Updated
I finally got around to actually coming up with a real solution to this almost 2 years later.  I posted an in depth explanation with code on my blog.  Read it here

A: Here's a couple of methods from a captcha generator we use that might steer you in the right direction:
    internal static void DrawPhrase(
        this Graphics graphics,
        int width,
        int height,
        string phrase)
    {
        graphics.FillRectangle(
            Brushes.White,
            0,
            0,
            width,
            height);

        using (var gp = new GraphicsPath())
        {
            gp.AddString(phrase,
                         FontFamily.GenericMonospace,
                         (int)FontStyle.Bold,
                         33f,
                         new Point(0,
                                   0),
                         StringFormat.GenericTypographic);

            using (var gpp = gp.Deform(width, height))
            {
                var bounds = gpp.GetBounds();
                var matrix = new Matrix();
                var x = (width - bounds.Width) / 2 - bounds.Left;
                var y = (height - bounds.Height) / 2 - bounds.Top;
                matrix.Translate(x,
                                 y);
                gpp.Transform(matrix);
                graphics.FillPath(Brushes.Black,
                                  gpp);
            }
        }

        graphics.Flush();
    }
    internal static GraphicsPath Deform(
        this GraphicsPath path,
        int width,
        int height)
    {
        var WarpFactor = 4;
        var xAmp = WarpFactor * width / 300d;
        var yAmp = WarpFactor * height / 50d;
        var xFreq = 2d * Math.PI / width;
        var yFreq = 2d * Math.PI / height;
        var deformed = new PointF[path.PathPoints.Length];
        var xSeed = rng.NextDouble() * 2 * Math.PI;
        var ySeed = rng.NextDouble() * 2 * Math.PI;
        var i = 0;
        foreach (var original in path.PathPoints)
        {
            var val = xFreq * original.X + yFreq * original.Y;
            var xOffset = (int)(xAmp * Math.Sin(val + xSeed));
            var yOffset = (int)(yAmp * Math.Sin(val + ySeed));
            deformed[i++] = new PointF(original.X + xOffset,
                                     original.Y + yOffset);
        }

        return new GraphicsPath(deformed,
                                path.PathTypes);
    }


text:
Q: ExtJS form sended twice I have a form with search (filtering) fields like this:
xtype: 'form',
id: 'searchPanel',
title: 'Search',
collapsible: true,
bodyPadding: 10,

height: 210,
buttonAlign: 'left',
defaults: {
    width: 400,
    labelWidth: 120,
    allowBlank: true,
    enableKeyEvents: true
},
layout: {
    type: 'table',
    columns: 2
},
items: [
    {
        xtype: 'textfield',
        name: 'txtFltrSiteName',
        fieldLabel: 'Site name or alias',
        id: 'txtFltrSiteName'
    },

    {
        xtype: 'textfield',
        name: 'txtMonthTraffic',
        fieldLabel: 'Month traffic',
        id: 'txtMonthTraffic',
        style: 'margin-left: 100px;'
    },

    {
        xtype: 'combo',
        id: 'ddlFltrPM',
        name: 'ddlFltrPM',
        fieldLabel: 'Project manager',
        displayField: 'display_name',
        valueField: 'user_id',
        editable: false,
        store: new storeOfUsers({ filters: [{ property: 'user_group_code', value: 'projectmanager', exactMatch: true }] })
    },

    // and many other fields below

But when i click on search button, i have two post request. One - with filter in it, second is without.
My code for send button action:

xtype: 'button',
id: 'btn_srch_set',
text: 'Searh',
margin: '10 7 0 0',
width: '',
handler: function() {
    var filters = new Array();

    var site_name = Ext.getCmp('txtFltrSiteName').getValue();
    if(site_name.length > 0)
        filters.push({dataIndex: 'site_name', type: 'string', value: site_name});

    var project_name = Ext.getCmp('txtFltrProjectName').getValue();
    if(project_name.length > 0)
        filters.push({dataIndex: 'project_name', type: 'string', value: project_name});

    var pm = Ext.getCmp('ddlFltrPM').getValue();
    if(pm && pm > 0)
        filters.push({dataIndex: 'project_manager_id', type: 'int', value: {'eq':pm}});

    // many other fields

    listOfSites.filters.removeAll();
    if(filters.length > 0)
        listOfSites.filters.addFilters(filters);
    listOfSites.store.load();
}

P.S.
When I overwrite in search button handler function this line:
filters.push({dataIndex: 'project_manager_id', type: 'string', value: pm});
Evrything is ok and there is only one request, so problem might be here. But i'm stuck and have no idea why it works such way.

Thanks for any help,
Stanislav.
UPD*
        var filters = {
        ftype: 'filters',
        // encode and local configuration options defined previously for easier reuse
        encode: true, // json encode the filter query
        local: false,
        filters: [{
            type: 'string',
            dataIndex: 'site_name'
        }, {
            type: 'date',
            dataIndex: 'startdate'
        }, {
            type: 'string',
            dataIndex: 'project_name'

        // more fields below

A: Try following
if(filters.length > 0)
    listOfSites.filters.addFilters(filters);
else
    listOfSites.store.load();

addFilters() may already call sync()


text:
Q: IF statement combo-box filled from sql c# Hi there i have a combobox filled with table from the SQL
and with this particular combobox i want to use a if statement
for example
if (comboBox2.Text is filled from sqL)
{
//then new form will pop out
}
Else
{
//no nothing
}

A: Do you wish to add items from datasource other than SQL Table? I assume you dont, this if condition is a bad idea. Whether filling items from sqldata or manually adding items to the combobox, as @farhad Jabiyev suggested, you get the count of items first or check the associated datasource is null or empty rather than accessing combobox control directly if you are using multithreaded application.
if (comboBox2.Items.Count > 0)
    {
      //then new form will pop out
    }
Else
    {
      //no nothing
    }


text:
Q: Change XMLGregorianCalendar to Date using external binding file (XJB) In my maven project, I want all my datetime entries should be generated as java.util.date instead of XMLGregorianCalendar. As you might know XMLGregorianCalendar gets generated by default.
We can take example project provided here.
Here in the CustomersOrders.xsd, you can see attriute ShippedDate is of type dateTime.
<xs:attribute name='ShippedDate' type='xs:dateTime' />

To convert its data type into java.util.date, I'm following approach provided in documentation here. i.e. by using external binding file, like:
Customer.xjb
<bindings xmlns="http://java.sun.com/xml/ns/jaxb" version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <globalBindings>
    <javaType name="java.util.date" xmlType="xs:datetime"
      parseMethod="javax.xml.bind.DatatypeConverter.parseDate"
      printMethod="javax.xml.bind.DatatypeConverter.printDate"
    />
  </globalBindings>
</bindings>

Then I mapped Customer.xjb file in pom.xml like:
<executions>
    <execution>
        <goals>
            <goal>generate</goal>
        </goals>
        <configuration>
            <!-- the package for the generated java classes -->
            <generatePackage>com.dimitrisli.jaxb.producedClasses</generatePackage>
            <!-- If the following not specified all xsd in resources are included -->
            <schemaIncludes>
                <include>sampleJaxb/CustomersOrders.xsd</include>
            </schemaIncludes>
            <!-- if you don't want old output -->
            <removeOldOutput>true</removeOldOutput>
            <!-- if you want verbosity -->
            <!-- verbose>true</verbose -->

            <xjbSources>
                <xjbSource>sampleJaxb/Customers.xjb</xjbSource>
            </xjbSources>

        </configuration>

    </execution>
</executions>

But when I do mvn clean install, I'm still not able to see any difference in ShippedDate, which is still being generated as XMLGregorianCalendar.
Please suggest what am I missing.
Thank You

A: *

*If you use the org.jvnet.jaxb2.maven2:maven-jaxb2-plugin then you should use bindingIncludes instead of xjbSources (it's for org.codehaus.mojo:jaxb2-maven-plugin).
<bindingIncludes>
    <include>sampleJaxb/Customers.xjb</include>
</bindingIncludes>`

*Also, you have to implement a custom adapter for java.util.Date like you have seen in the tutorial or convert to java.util.Calendar:
<javaType name="java.util.Calendar" xmlType="xsd:dateTime"
parseMethod="javax.xml.bind.DatatypeConverter.parseDateTime"
printMethod="javax.xml.bind.DatatypeConverter.printDateTime" />`

Hope it helps!


text:
Q: Getting Null value error with Python Parser in field calculator? I'm trying to calculate the angle between two line segments in ArcMap 10.0. I have a point shapefile, so I'm using the xy coordinates of 3 successive points to calculate the angle. I'm trying to use Python in the Field Calculator, because I'm not good with Python and I'm not sure how to use the Python window. I finally got my code to work, but encountered an error when two successive points have the exact same coordinates. This creates a null value, and I get the error "The field is not nullable". I tried to put in an if statement to change nulls to 0s, but I still get the same error. I'm not sure if I'm identifying null values correctly, though, because I've found conflicting ways to represent them, and have tried "None" and ' ' and "Null" to no avail. It seems like there should be some way to just replace the angle value with 0 if the calculation returns a null value.
Does anyone have any ideas on how to get past the null values?
My code is below.
Record = 0
def turnangle(X3, Y3):
  import math
  global X1, Y1, X2, Y2, Record
  if Record == 0:  #first two rows aren't calculated
    angle = 0
    X1 = X3
    Y1 = Y3
  elif Record == 1:
    angle = 0
    X2 = X3
    Y2 = Y3
  else:               #calculating angle
    BAx = X1 - X2
    BAy = Y1 - Y2
    BCx = X3 - X2
    BCy = Y3 - Y2
    dotprod = BAx * BCx + BAy * BCy
    lenA = math.sqrt((X1-X2)**2+(Y1-Y2)**2)
    lenB = math.sqrt((X2-X3)**2+(Y2-Y3)**2)
    angle = math.acos((dotprod)/(lenA*lenB))*180/math.pi
    X1 = X2       #advancing to next coordinates
    Y1 = Y2
    X2 = X3
    Y2 = Y3
  Record = Record + 1
  if angle is not None:  #Here is where I'm trying to substitute 0 for null values
    return angle
  else:
    return 0

A: This is a quick and easy way to get around the problem..but doesn't fix the error. This method works in the python window.
This design is often used inside of loops, and I'm unsure if the Field Calculator will accept it.
try:
 #the code you want to work goes here

except: #handles the error
    #print "an error occurred, but I can continue to work"
    pass


text:
Q: How to arrayformula the unique values of 2 arrays of values from 2 tables Screenshot of Sample Sheet
Link to spreadsheet: https://docs.google.com/spreadsheets/d/19fSLDDp7k8JIgBsi0YCqJbz-Ue-pLruGv-Sjc3Eo_l0/edit?usp=sharing
There are 2 tables both having Color field which is an array of values separated by ";"
I2:I is a filtered list by a formula as shown in H2.
Now, I want to have an ARRAYFORMULA function in J2 to output the combined array of colors without duplicate.
The sample output is shown in J2:J3.
I can join the array but do not know how to eliminate duplicated values
ARRAYFORMULA(VLOOKUP(I2:I,A:B,2,FALSE)&";"&VLOOKUP(I2:I,E:F,2,FALSE)

I have two ideas but I do not know how to work it out

*

*use of UNIQUE, SPLIT, TRANSPOSE, TEXTJOIN

*use of REGEXREPLACE

A: Try this in I2 to get names and colors w/o duplicates at once:
=ARRAYFORMULA(
  REGEXREPLACE(
    SPLIT(
      TRANSPOSE(QUERY(
        QUERY(
          UNIQUE(
            SPLIT(
              FLATTEN(
                FILTER(
                  A2:A & "♦♥" & SPLIT(B2:B & IFNA(";" & VLOOKUP(A2:A, E:F, 2,)), ";"),
                  C2:C = True
                )
              ),
              "♥"
            ) & ";"
          ),
          "SELECT MAX(Col2)
           WHERE Col2 IS NOT NULL
           GROUP BY Col2
           PIVOT Col1",
        ),,
        10^7
      )),
      "♦"
    ),
    "^(?:;\s*)+|(?:;\s*)+$|(;)\s*(?:;\s*)*",
    "$1"
  )
)

You can decompose it (just remove one function after another from top to bottom) to figure out how it works.

A: Give a try on below formula-
=JOIN(";",UNIQUE(SPLIT(JOIN(";",FILTER($B$2:$B$4,$A$2:$A$4=B7),FILTER($E$2:$E$4,$D$2:$D$4=B7)),";"),TRUE))


text:
Q: Adding chosen to sweet alert I want to add select boxes to sweet alert, but when i add initialize chosen box container does not show it properly, do you have any suggestions?
Here is example

<select id="chosen-without-empty" class="chosen">
     <option value="2">example</option>
     <option value="3">example 2</option>
 </select>

asdasdasdasD

JS
$('#sa-basic').click(function(){
    var s = $('#content').html();
    swal({ html:true, title:'TEST', text:s});
    $('.chosen').chosen({
        width: '50%',
        allow_single_deselect: true
    });
});

Fiddle DEMO

A: I have the same problem. I try to modify your code with current latest version of sweet alert 2.

$('#swal-chosen').click(function(e){
  e.preventDefault();

  // create clone from existing element
  var s = $('#modal-content').clone();
  s.find('.chosen').addClass('swal');

  swal({
    html: s.html(),
    title: 'Please choose',
    preConfirm: function() {
      return new Promise(function(resolve) {
        resolve( $('.chosen.swal').val() );
      });
    }
  }).then(function(result) {
    // reset modal overflow
    $('.swal2-modal').css('overflow', '');
    swal('Your choice is: ' + result);
  });

  // allow dropdown overflow
  $('.swal2-modal').css('overflow', 'visible');

  // initialize chosen for cloned element
  $('.chosen.swal').chosen({
    width: '75%',
    allow_single_deselect: true
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/4.0.3/sweetalert2.css" rel="stylesheet"/>

  <select class="chosen">
    <option value=""></option>
    <option value="1">example 1</option>
    <option value="2">example 2</option>
    <option value="3">example 3</option>
    <option value="4">example 4</option>
    <option value="5">example 5</option>
    <option value="6">example 6</option>
    <option value="7">example 7</option>
  </select>

Select Example

A: I'm using this https://sweetalert.js.org/guides/ version and just had same problem as you
because i need to stick to sweetalert1 (those version). so i need to do more work to do like you are asking...
well the idea is very simple. you can understand by glance on it.
Basically my idea is to create a select on regular HTML then hide it. Then copy the generated chosen to the Sweet Alert, and retrieve the result on the basic select u've created.
I know this is not simple and not efficient :)) But i cant find any other solution in my case (cant upgrade to SweetAlert 2). comment below if you find better solution! i appreciate it!

HTML / Laravel
    // create dynamic users on html and hide it
    <select name="tujuan" id="tujuan-holder" class="hidden chosen-tujuan">
    @foreach ($users as $item)
        <option value="{{ $item->nama }}">{{$item->nama}}</option>
    @endforeach
    </select>

Javascript
    $(document).ready(function(){
        $(".chosen-tujuan").chosen({ //create the chosen
            width: "100%",
        });
        $("#tujuan_holder_chosen").addClass("hidden"); // then hide the chosen bar
    }); // if you dont hide it it will show up on your interface not on your swal

    $(".btn-process").click(function(){
        swal({
            title:"Apakah anda sudah mengirimkannya?",
            text:"Kepada siapa anda mengirimkan Dokumen ini?",
            icon:"warning",
            content: { //here is the element will be
                element:$("#tujuan_holder_chosen").removeClass("hidden")[0]
            }
        }).then((result)=>{
            alert($("#tujuan-holder").val()); // then retrieve the ouput by collecting the value on your original select, not the chosen,
        }); // because chosen create a new interface
    });

A: Triggering chosen select to a hidden element is useless.
That is why your dropdown is not chosen-activated.
The correct way is to trigger chosen after swal has been fired.
Like below sample

function PopupSelect() {
Swal.fire({
title: 'Give Kudos',
html:
<form method="post" action="/GiveKudosSend">' +

' +
Who
' +
<select class="form-control input-sm chosen-swal chosen" id="NRPReciever" name="NRPReciever" style="display: initial;" placeholder="Select">' +
<option disabled selected>Select Recipient</option>'+
<option value="EmpCode1">empName </option>' +
<option value="EmpCode2">empName2 </option>' +
</select>

' +

'+

' +
<input style="background: #007762 !important; font-size: 13px; color: white; border: none !important; padding: 10px; border-radius: 4px;" class="button button-primary" type="submit" value"Add Give Kudos">'+

</form>',
showCloseButton: true,
showCancelButton: false,
showConfirmButton: false,
focusConfirm: false,
allowOutsideClick: false,
confirmButtonText: '',
cancelButtonText: '',
});
//Trigger chosen after swal shown
$(".chosen-swal").chosen();
}


text:
Q: I want to make all queries using SQL on Android SQLite I don't want to use some extra codes to insert, select, update or delete to my database on Android. I want to use SQL for all of them. Is it possible? Also, could you give me some simple examples with your answers? Because, I'm new in Android development. Thank you...

A: Do you have any more information as to what you'd like to do? Do you mean you'd rather perform all queries as raw queries? If so, you can do it like this:
Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM table WHERE _id = ?", new String[] { id });


text:
Q: Is there a way to instantiate a class via Expression.New where 'ConstructorInfo' is supplied by an ExpressionParameter? I would like to instantiate a (non-generic) class in C# (ClassToBeInstantiated) that has a public non-parameterless constructor via LINQ Expression.New inside an Expression.Block.
see update below, based on answer from @sweeper
Description
According to the documentation, the only overloads for Expression.New that do accept arguments require a ConstructorInfo argument. As I do not have access to that info beforehand, but have to retrieve this inside the Expression.Block.
So I am able to use an Expression.Call on the type ClassToBeInstantiated that is passed into the block.
However, all Expression.New overloads only accept either ConstructorInfo as an argument or for an instantiation if I want to pass arguments to the constructor. Type is only available for using a parameterless constructor.
I cannot use a ParameterExpression holding a ConstructorInfo either.
Question
So my question: is there a way around this with Expression.New? I know I can use ConstructorInfo.Invoke via another Expression.Call. But this seems akward to me, as -at least in my opinion- the Expression.New API should exactly do this for me.
Am I missing something?
Thanks for your help, comments and reply.
The class to be instantiated
Here is some additional information to further illustrate the case:
public class ClassToBeInstantiated
{
  public ClassToBeInstantiated(int count) { }
}

Helper class to retrieve ConstructorInfo
public static class GetConstructor
{
  public static ConstructorInfo GetNonGenericConstructorInfo(Type type, params Type[] typeArguments) =>
    type.GetConstructor(typeArguments);
}

[Test]
public void InstantiateTypeViaExpressionNew()
{
  var typeExpression = Expression.Parameter(typeof(Type), "type");
  var countExpression = Expression.Parameter(typeof(int), "count");
  var ctorExpression = Expression.Variable(typeof(ConstructorInfo), "constructorInfo");
  var block = Expression.Block
  (
    new[] { ctorExpression },
    Expression.Assign(ctorExpression, Expression.Call(typeof(GetConstructor), nameof(GetConstructor.GetNonGenericConstructorInfo),
      Type.EmptyTypes, typeExpression, Expression.Constant(new[] { countExpression.Type }))),
    Expression.New(/* error - obviously does not compile: ctorInfo */, countExpression)
  );

  var lambda = Expression.Lambda<Func<Type, int, object>>(block, typeExpression, countExpression);
  var func = lambda.Compile();
  var o = func.Invoke(typeof(ClassToBeInstantiated), 4);
  var instance = o as ClassToBeInstantiated;
  Assert.NotNull(instance);
}

Update with Expression.Call instead of Expression.New
I updated the code example from my original question, based on the answer from @Sweeper to provide a full example (in case someone is interested):
Updated helper class
Here, I added the field constructorInfoInvokeMethodInfo for retrieval of the MethodInfo for the ConstructorInfo.Invoke() method (to be called from inside the Expression.Block:
public static class GetConstructor
{
  public static ConstructorInfo GetNonGenericConstructorInfo(Type type, params Type[] typeArguments) =>
    type.GetConstructor(typeArguments);

  public static readonly MethodInfo constructorInfoInvokeMethodInfo =
    typeof(ConstructorInfo).GetMethod(nameof(ConstructorInfo.Invoke), new[] { typeof(object[]) });
}

Updated test for Expression.Block
Here, I replaced the (non-working) Expression.New with an Expression.Call to instantiate the type via ConstructorInfo.Invoke():
[Test]
public void InstantiateTypeViaExpressionCall()
{
  var typeExpression = Expression.Parameter(typeof(Type), "type");
  var countExpression = Expression.Parameter(typeof(int), "count");
  var ctorExpression = Expression.Variable(typeof(ConstructorInfo), "constructorInfo");
var block = Expression.Block
(
  new[] { ctorExpression },
  Expression.Assign
  (
    ctorExpression,
    Expression.Call(typeof(Activator), nameof(GetNonGenericConstructorInfo), Type.EmptyTypes, typeExpression, Expression.Constant(new[] { countExpression.Type }))
  ),
  Expression.Call(ctorExpression, constructorInfoInvokeMethodInfo, Expression.NewArrayInit(typeof(object), Expression.Convert(countExpression, typeof(object))))
);

  var lambda = Expression.Lambda<Func<Type, int, object>>(block, typeExpression, countExpression);
  var func = lambda.Compile();
  var o = func.Invoke(typeof(ClassToBeInstantiated), 4);
  var instance = o as ClassToBeInstantiated;
  Assert.NotNull(instance);
}

A:
So my question: is there a way around this with Expression.New? I know I can use ConstructorInfo.Invoke via another Expression.Call.

This is exactly what you should do.
Think about the expression tree that you want to create. Since the final usage that you want to achieve looks like:
func.Invoke(typeof(ClassToBeInstantiated), 4);

func's expression must look like:
(type, count) => GetConstructor.GetNonGenericConstructorInfo(type, typeof(int)).Invoke(new object[] {count})

This seems to be what you were trying to do too, just with an extra local variable.
It cannot be:
(type, count) => new type(count)

Because new type(count) is not a valid expression. type is just a parameter.
This has nothing to do with new expressions that Expression.New creates. There are no NewExpressions in your desired expression at all. It would be very weird if Expression.New suddenly starts inserting ConstructorInfo.Invoke calls in the expression tree, because that is not what it is supposed to create at all.
You could use Expression.New here to create expressions such as:
(type, count) => new ClassToBeInstantiated(count)

But I don't think that's what you want... You want the type parameter to determine what type to instantiate, and assume that a one-parameter int constructor to be available, right?
Using sharplab.io, you can write the lambda expression you want, and see what code the compiler actually generates for building the expression tree. After cleaning up the code that generates for
Expression<Func<Type, int, object>> func =
        (type, count) => GetConstructor.GetNonGenericConstructorInfo(type, typeof(int)).Invoke(new object[] {count});

You get:
MethodInfo getConstructorMethod = typeof(GetConstructor).GetMethod(nameof(GetConstructor.GetNonGenericConstructorInfo));
MethodInfo invokeMethod = typeof(ConstructorInfo).GetMethod(nameof(ConstructorInfo.Invoke), new Type[] { typeof(object[]) });

ParameterExpression typeParam = Expression.Parameter(typeof(Type), "type");
ParameterExpression countParam = Expression.Parameter(typeof(int), "count");

// GetNonGenericConstructorInfo(type, typeof(int))
MethodCallExpression instance = Expression.Call(null, getConstructorMethod,
    typeParam, Expression.NewArrayInit(typeof(Type), Expression.Constant(typeof(int), typeof(Type)))
);
// // .Invoke(new object[] { count })
MethodCallExpression body = Expression.Call(instance, invokeMethod,
    Expression.NewArrayInit(typeof(object), Expression.Convert(countParam, typeof(object)))
);
Expression<Func<Type, int, object>> func = Expression.Lambda<Func<Type, int, object>>(body, typeParam, countParam);

And func.Compile()(typeof(ClassToBeInstantiated), 4) as ClassToBeInstantiated is not null.


text:
Q: Object detection loss not decreasing, AP increasing I'm trying to train an object detection model to detect and classify 10 classes. My original dataset is pretty sparse and unbalanced, containing a total of 3k tagged images with the following distribution between classes:
Class 1: 21
Class 2: 22
Class 3: 9
Class 4: 192
Class 5: 2240
Class 6: 319
Class 7: 56
Class 8: 190
Class 9: 44
Class 10: 167
Because of this sparsity, I have performed augmentation on all images, namely adding noise, blur, contrast, brightness, and horizontal flipping. I also augmented the flipped images further with noise, contrast, and brightness. The resulting dataset consists of 37k tagged images with the following distribution:
Class 1: 4235
Class 2: 5365
Class 3: 2385
Class 4: 10755
Class 5: 17185
Class 6: 4035
Class 7: 3150
Class 8: 3820
Class 9: 555
Class 10: 1500
The image below shows the different losses for 4 different sessions. The pink graph is the result from the augmented dataset of 37k images, and the other graphs are from previous runs on the original dataset of ~2.5k images. As you can see from the pink graph, the total loss is not decreasing at all from its initial value (as is the case for the blue and red graph from previous runs). The RPN loss is decreasing, but the box classifier loss is increasing, what can be the reason for this?

I have also included an image of the average precision for each class. The fact that the precision for most classes increases steadily the whole time while the loss is not decreasing seems to me like the model is overfitting? Is it a bad idea to 10x the dataset by augmenting every like I've done? I've also included the config file I'm using below. Any suggestions as to how to improve my training result is appreciated!

 model {
  faster_rcnn {
    num_classes: 10
    image_resizer {
     fixed_shape_resizer {
       height: 300
       width: 500
     }
    }
    feature_extractor {
      type: 'faster_rcnn_inception_resnet_v2'
      first_stage_features_stride: 8
    }
    first_stage_anchor_generator {
      grid_anchor_generator {
        scales: [0.25, 0.5, 0.75, 1.0, 1.5,2,3]
        aspect_ratios: [0.5,1,2,3]
        height: 32
        width: 32
        height_stride: 8
        width_stride: 8
      }
    }
    first_stage_atrous_rate: 1
    first_stage_box_predictor_conv_hyperparams {
      op: CONV
      regularizer {
        l2_regularizer {
          weight: 0.0
        }
      }
      initializer {
        truncated_normal_initializer {
          stddev: 0.01
        }
      }
    }
    first_stage_nms_score_threshold: 0.0
    first_stage_nms_iou_threshold: 0.5
    first_stage_max_proposals: 300
    first_stage_localization_loss_weight: 2.0
    first_stage_objectness_loss_weight: 1.0
    initial_crop_size: 17
    maxpool_kernel_size: 1
    maxpool_stride: 1
    second_stage_box_predictor {
      mask_rcnn_box_predictor {
        use_dropout: True
        dropout_keep_probability: 0.6
        fc_hyperparams {
          op: FC
          regularizer {
            l2_regularizer {
              weight: 0.0
            }
          }
          initializer {
            variance_scaling_initializer {
              factor: 1.0
              uniform: true
              mode: FAN_AVG
            }
          }
        }
      }
    }
    second_stage_post_processing {
      batch_non_max_suppression {
        score_threshold: 0.3
        iou_threshold: 0.5
    #    soft_nms_sigma: 0.5
    #   use_class_agnostic_nms: True
    #    max_classes_per_detection: 1
        max_detections_per_class: 100
        max_total_detections: 100
      }
      score_converter: SOFTMAX
    }
    second_stage_localization_loss_weight: 2.0
    second_stage_classification_loss_weight: 1.0
  }
}
train_config: {
  batch_size: 1
  use_multiclass_scores : False
  optimizer {
    #momentum_optimizer: {
    adam_optimizer: {
      learning_rate: {
        manual_step_learning_rate {
          initial_learning_rate: 0.0001
          schedule {
            step: 150000
            learning_rate: .00001
          }
          schedule {
            step: 250000
            learning_rate: .000001
          }
        }
      }
      #momentum_optimizer_value: 0.9
    }
    use_moving_average: false
  }
  gradient_clipping_by_norm: 10.0
  from_detection_checkpoint: false

  data_augmentation_options {
    random_horizontal_flip {}
  }

  data_augmentation_options {
    random_crop_image {
      min_object_covered : 1.0
      min_aspect_ratio: 1
      max_aspect_ratio: 1
      min_area: 0.5
      max_area: 1
       random_coef: 0.5
     }
  }
}

A: Unfortunately with deep learning, it can often times be difficult to distinguish what exact parameter is causing you an issue. From looking at your question, it seems that even with the data augmentation, which is a great thing to do, is that the number of images that you have per class varies very heavily.
For example after you augment your data, you end up with these to classes with images in them
Class 5: 17185
Class 9: 555
Class 5 has 17,185 images, while class 9 only has 555. There is a huge imbalance in the number of images, and its often times preferred to have as close as possible the same amount of images for each class.
When you are training, you will have a validation section, where a pool of images from all classes will be used to test the model at that instance. If you have a bunch of images in one class and not the other, the model will do fairly better validating the images from the larger class, while struggling with the validation of the image from the smaller class because the model didn't have many examples to train with, and or it started to train heavier with the larger class because there are more training examples in there.


text:
Q: generate links with a greasemonkey script I'm trying to write a script in Greasemonkey that will generate link's in  a frame, but with my limited Javascript knowledge I don't really know how to do this.
Example of subject:

<frameset border="0" frameborder="no" framespacing="0" cols="*,280" rows="*">
<frameset border="0" frameborder="NO" framespacing="0" cols="*" rows="*,200">
<frameset border="0" frameborder="NO" framespacing="0" cols="*" rows="75,*">
<frame scrolling="NO" name="bannerFrame" src="banner.php">
<frame scrolling="auto" name="mainFrame" src="main.php">
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

Text:

Text
Text -
Attack
-
Quickattack

Text

<form name="formular">

</frame>
</frameset>
<frameset border="0" frameborder="NO" framespacing="0" cols="*" rows="*,0">
</frameset>
<frameset border="0" frameborder="NO" framespacing="0" cols="*" rows="*,360">
</frameset>
<noframes> Text </noframes>

Example of desired Output :

<frameset border="0" frameborder="no" framespacing="0" cols="*,280" rows="*">
<frameset border="0" frameborder="NO" framespacing="0" cols="*" rows="*,200">
<frameset border="0" frameborder="NO" framespacing="0" cols="*" rows="75,*">
<frame scrolling="NO" name="bannerFrame" src="banner.php">
<frame scrolling="auto" name="mainFrame" src="main.php">
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

Text:

Text
Text -
Attack
-
Quickattack
-
Hit
-
Chase

Text

<form name="formular">

</frame>
</frameset>
<frameset border="0" frameborder="NO" framespacing="0" cols="*" rows="*,0">
</frameset>
<frameset border="0" frameborder="NO" framespacing="0" cols="*" rows="*,360">
</frameset>
<noframes> Text </noframes>

This Links should be generated:
-
Hit
-
Chase

The 'checkid=...' and the 'npc_id=...' must be the same value as in this link:
Quickattack

A: OK, this is really just basic HTML DOM manipulation, there's nothing GreaseMonkey-specific here.
First, I'm going to assume that the link you want to copy the URL parameters from is the only one with class="fastattack", since that makes finding it easy:
var link = document.getElementsByClassName( 'fastattack' )[0];
if ( link ) {
    // we found the link, do stuff with it...

Next, we need to generate the first new link:
    var newlink = document.createElement( 'a' );

...make it point to the URL we want:
    newlink.href = link.href.replace( 'action=attacknpc', 'action=slapnpc' );

...and give it the link text we want:
    newlink.textContent = 'Hit';

Next, we insert the new link into the DOM just after the original link, like this:
    var nextNode = link.nextSibling;
    link.parentNode.insertBefore( newlink, nextNode );

Oops, we forgot to insert the delimiter first!  No worries, we can still do that:
    var delim = document.createTextNode( ' - ' );
    link.parentNode.insertBefore( delim, newlink );

Now we can just do the same for the other link:
    var newlink2 = document.createElement( 'a' );
    newlink2.href = link.href.replace( 'action=attacknpc', 'action=chasenpc' );
    newlink2.textContent = 'Chase';
    link.parentNode.insertBefore( delim.cloneNode( true ), nextNode );
    link.parentNode.insertBefore( newlink2, nextNode );

This time, I remembered to insert the delimiter first.  I used the same delim node as above, but I made a copy of it because I wanted to insert another identical delimiter, not move the original delimiter to a new position in the DOM.
Finally, we need to close the if block, and that's it:
}

(Disclaimer: I have not actually tested the code above.  I think it should work, but there might be bugs or typos that I've missed.)
Edit: Changed the code to insert the new links just after the original, rather than at the end of the parent paragraph.
Addendum:
If you have multiple links with class="fastattack" in the document, and wish to apply the code above to each of them, you can do that by replacing the first two lines above with a loop over all the links, instead of just the first one:
var links = document.getElementsByClassName( 'fastattack' );
for ( var i = 0; i < links.length; i++ ) {
    var link = links[i];
    // now do stuff with link just like above


text:
Q: Adding annotations in order -but map view does not return annotation in same order I add my annotations as follows:
 [mapView addAnnotations:annotationArray];

then I want to access each and individual annotations on the mapView as follows:
for (id<MKAnnotation> ann in mapView.annotations)

the problem is annotations on map view is not added in a way linked list. That is why it is not returning in same order that I add annotations to annotationsArray.
to illustrate:,
 [annotationArray addObject: annotation1];

 [annotationArray addObject: annotation2];

 [annotationArray addObject: annotation3];

 [mapView addAnnotations:annotationArray];

 for (id<MKAnnotation> ann in mapView.annotations)
 {

  //not returning in same order as added above//

  }

Is there a bug in mapView annotation?
original code:
    NSMutableArray *attrArray=[[NSMutableArray alloc]init];
for (NSArray *row in latt)
{
    NSNumber *attr=[row valueForKey:@"attr"];
    NSNumber *attr2=[attr valueForKey:@"ozone_level"];
    NSLog(@"values:%@",attr2);
    NSNumber *comp=[NSNumber numberWithInt:-1];
    if(attr2!=comp)
    {
        if([attrArray count]==0)
        {attrArray=[[NSMutableArray alloc]initWithObjects:attr2, nil];
        }
        else
        {
            [attrArray addObject:attr2];
        }
        NSNumber *latt2=[row valueForKey:@"lat"];
        NSNumber *longt2=[row valueForKey:@"lng"];
        CLLocationCoordinate2D coordinate;
        coordinate.latitude=latt2.doubleValue;
        coordinate.longitude=longt2.doubleValue;
        if(test<5)
        {
        Annotation *annotation = [[Annotation alloc] init];
        annotation.coordinate = coordinate;
        annotation.title = [attr2 stringValue];
        int colorvalue=[attr2 intValue];
        pinColor = [self colorForAcceleration2:colorvalue];
        annotation.color = pinColor;

            if([annotationArray count]==0)
            {
                annotationArray=[[NSMutableArray alloc]initWithObjects:annotation,nil];
               // NSMutableArray *ad =[[NSMutableArray alloc]init];
            }
            else
            {
                [annotationArray addObject:annotation];

            }

        }

        test++;

    }//if attr2
}//for
if( test == 5)
{
  [mapView addAnnotations:annotationArray];
}
if(test>=5)
{
    //for (id<MKAnnotation> ann in mapView.annotations)
    for(int i=0;i<5;i++)
    {   //Annotation *a = (Annotation *)ann;
         Annotation *a = ((Annotation*)[annotationArray objectAtIndex:i]);

        //((Annotation *)mapView.annotations).
        NSLog(@"%@",((Annotation*)[annotationArray objectAtIndex:i]).title);
        NSLog(@"%@",[attrArray objectAtIndex:i]);
        //NSLog(@"annotation array size:%d",[annotationArray count]);
       // NSLog(@"attr array size:%d",[attrArray count]);
        if([((Annotation*)[annotationArray objectAtIndex:i]).title isEqualToString:[[attrArray objectAtIndex:i] stringValue]])
        {
        }
        else{
            MKAnnotationView *av1=[mapView viewForAnnotation:((Annotation*)[annotationArray objectAtIndex:i])];
                a.title=[NSString stringWithFormat:[[attrArray objectAtIndex:i] stringValue]];
                int colorvalue=[[attrArray objectAtIndex:i] intValue];
                pinColor = [self colorForAcceleration2:colorvalue];
                a.color=pinColor;
                av1.image=[ZSPinAnnotation pinAnnotationWithColor:a.color];
                av1.annotation=a;}//else

        }//for
    }//if

A:
Is there a bug in mapView annotation?

Not unless you can find some documentation that says a map view will preserve the order in which you added the annotations. MKMapView very probably stores them in some internal structure that can efficiently select just those annotations that will actually appear on the map.
Don't use a map view as your mechanism for storing annotations. Store them yourself in whatever order you like, so that you don't have to rely non-existant behavior in MKMapView.

A: MKMapView add annotations to its internal list, then display these annotation views by its own logic. You can retrieve the list of annotations by MKMapView's property "annotations". However there is no straight method to change the z-order of annotation views.


text:
Q: How to setup Teamviewer on remote server (SSH only)? I have a VPS with Debian 9 and want to run Teamviewer with XFCE. Having only SSH access makes this difficult. (I have read Teamviewer's guides but they didn't help) Here is what I have tried so far:

*

*After creating a fresh instance I have simply installed XFCE4 like so:
sudo apt-get install xfce4

*Installed teamviewer from www.teamviewer.com/en/download/linux/
sudo dpkg -i teamviewer-<version>.deb # complaint about dependencies
 sudo apt-get install -f
 sudo dpkg -i teamviewer-<version>.deb # works now

*Reboot

*Run teamviewer (teamviewerd and lightdm auto started)
sudo teamviewer passwd <password>
 sudo teamviewer info # shows me the teamviewer-id for connection

*Connect with teamviewer-id on other computer and enter teamviewer password

*Enter user and password in Linux XFCE login screen (lightdm)

*Teamviewer hangs and only shows Debian desktop background
My guess is Teamviewer has a problem with the fact that the VPS doesn't have a display.


text:
Q: openpyxl showing '=' instead of formula I'm using openpyxl to read an Excel spreadsheet with a lot of formulas. For some cells, if I access the cell's value as e.g. sheet['M30'].value I get the formula as intended, like '=IFERROR(VLOOKUP(A29, other_wksheet, 9, FALSE)*E29, "")'. But strangely, if I try to access another cell's value, e.g. sheet['M31'].value all I get is =, even though in Excel that cell as essentially the same formula as M30: '=IFERROR(VLOOKUP(A30, other_wksheet, 9, FALSE)*E29, "")'.
This is happening in a bunch of other sheets with a bunch of other formulas and I can't seem to find any rhyme or reason for it. I've looked through the docs and I'm not loading data_only=True so I'm not sure what's going wrong.

A: This sounds very much like you are looking at cells using "shared formulae". When this is the case the same formula is used by several cells. The formula itself is only stored with one of those cells and all others are marked as formulae but just contain a reference. Until version 2.3 of openpyxl all such cells would return "=" as their value. However, version 2.3 now performs the necessary transformation of the formula for dependent cells. ie. a shared formula of say "=A1+1" for A1 will be translated to "=B1+1" for B1.
Please upgrade to 2.3 if you are not already using it.
If this is not the case then please submit a bug report with the sample file.


text:
Q: Citations for Weighted Cross Entropy I am doing binary classification on an extremely unbalanced data set where only 2% of the data points are positive. I have found online that 1) the default cross entropy loss assumes equal weights of both classes and that 2) a common way to combat this problem is by re-weighting the scores inside the loss function based on the class imbalance. Indeed most pre-packaged ML softwares include a way to easily implement this reweighing. For example check that the first argument for the BCELoss in Pytorch is the weight parameter specifically for this purpose.
Now I am trying to write up my experiment and I would like citations for both 1) (that the default loss function assumes equal weights) and 2) ( that this re-weighing is a commonly accepted solution). I find a ton of web pages and code about this about I would like some better sources like text books that explain how this works. Can anyone help me? Thanks.


text:
Q: Copying a range of column using a loop Hi I want to copy all the columns of a worksheet in to another worksheet one below the another.
                                  Sheet A

Column          A            B             C  ....................BL

             ValueA        ValueB       ValueC..................ValueBL
             ValueA2       ValueB2      ValueC2.................ValueBL2
                 .             .            .                        .
                 .             .            .                        .
             ValueA10       ValueB10     ValueC10...............ValueBL10

                                Target Sheet

            Value A
               .
               .
            Value A10
            Value B
               .
               .
            Value B10
            Value C
               .
               .
            Value C10

and so on. Basically each column has multiple values(rows) and there are hundreds of column. I want to copy all the columns one below the another. This will require a loop , but I don't understand as how to use it. Because
set ws1 As SheetA
set ws2 As Target
With ws1
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
Lastrow = period.Range("B" & Rows.Count).End(xlUp).Row

For i=1 to Lastcol
    ws1.Range("?" & lastrow).copy  ws2.Range("a65536").End(xlUP).Offset(1,0)
Next i

I am not getting as what to put instead of "?". Appreciate any help. Thanks.
Edit :
set ws1 As SheetA
set ws2 As Target
With ws1
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
Lastrow = ws1.Range("B" & Rows.Count).End(xlUp).Row
For i = 1 To Lastcol
    For l = 4 To lastrow
        ws1.Cells(l, i).Copy ws2.Range("a65536").End(xlUp).Offset(1, 0)
    Next l
Next i

My data starts from 4th row and that's the reason I start l from 4

A: It looks to me like you need two FOR loops... one to loop through the columns then the rows.  Also, I would use "Cells" versus "Range" in this case, and use the column number in the loop.  There are also ways to lookup the first and last rows and columns, but you didn't ask about that...
Sub test()
Set ws1 = Sheets(1)
Set ws2 = Sheets(2)
Lastcol = 5
lastrow = 10

For i = 1 To Lastcol
    For l = 1 To lastrow
        ws1.Cells(l, i).Copy ws2.Range("a65536").End(xlUp).Offset(1, 0)
    Next l
Next i

End Sub


text:
Q: Tracking celestial objects using GPS location I am trying to create a little app that mimics several that are out there. I have not downloaded any of the APK's to try and de-compile them yet. I will try that if this question does not get any answers.
So, I'd like to create a simple app to start that will just find the sun. Should be pretty easy, right? I am not sure if there is a pre-built API that I can use or if there are static calculations I can use, or how this is being done.
I'm guessing the GPS on a device would provide location and time. This should be the only thing needed from the device, and the rest can be calculated then displayed to the user.
I am doing this to learn some things about app creation, dynamic locations, and just something fun to do.
Any help is greatly appreciated.
Thanks fellow Stackers!

A: Just one thought: Location and time are not enough if you're trying to point to the sun.
Besides the position of the device (its coordinates) at a given time, you'll also need its orientation, which can be computed using SensorEvent.


text:
Q: How to test a job failing functionality I have this job:
class ProcessFileJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $file;

    public function __construct(File $file)
    {
        $this->file = $file;
    }

    public function handle()
    {
        $this->file->update([
            'status' => 'procssing',
        ]);

        $this->start();

        $this->file->update([
            'status' => 'success',
        ]);
    }

    public function failed(Exception $exception)
    {
        $this->file->update([
            'status' => 'un-procssed',
        ]);
    }

    protected function start()
    {
        return true;
    }
}

I am trying to test the code in the failed method:
/** @test */
public function it_will_set_status_to_un_procssed_when_failing()
{
    $file = factory(File::class)->create();

    $mock = Mockery::mock(ProcessFileJob ::class, [$file])->shouldAllowMockingProtectedMethods()->makePartial();
    $mock->shouldReceive('start')->once()->andThrow(new CustomException('test'));

    $mock->handle($file);

    $this->assertEquals('un-processed', $file->fresh()->status);
}

but this will always throw the CustomException and the test will fail.. even If I use withExceptionHandling method. I just want to test the code in the failed method to make sure when the job is failed the status of the file will change.


text:
Q: Bootstrap col-sm-* not applying to tablet I am using the Bootstrap V4.1.2 framework, and am experiencing the col-sm-* class not applying on tablet... meaning it's collapsing on tablet when it shouldn't be.  See my code below.
Thank you in advance for any/all guidance!

Herd Sires

2-Year Old Bulls

Yearling Bulls

Females


text:
Q: Fidelity of sound created from frequency domain data I know it is possible to create .wav file from frequency domain data (magnitude + phase) but I would like to know how close would that be to the real(orginal) sound ? Does it depend on the frequency step for example (or something else).
Second question:
I need to write a code that takes a frequency domain data (magnitude + phase) to build a wav file.
In order to do so, I started by the following code which creates a fake signal --> fft (at this point I have the kind of input(mag + phase) that I would expect for my target code). But it doesn't seem top work fine, could you please help
import numpy as np
from scipy import pi
import matplotlib.pyplot as plt
#%matplotlib inline
from scipy.fftpack import fft

min=0
max=400

def calculateFFT (timeStep,micDataX,micDataY):

    n=micDataX.size

    FFT=np.fft.fft(micDataY)
    fft_amlitude=2*abs(FFT)/n
    fft_phase=np.angle(FFT)
    fft_freq= np.fft.fftfreq(n, d=timeStep) #not used created manually (7 lines) check pi_fFreqDomainCreateConstantBW it is kept here to compare sizes
    upper_bound=int((n)/2)

    return fft_freq[1:upper_bound],fft_amlitude[1:upper_bound],fft_phase[1:upper_bound]

def calculateI_FFT (n,amplitude_spect,phase_spect):

    data=list()

    for mag,phase in zip(amplitude_spect,phase_spect):
        data.append((mag*n/2)*(np.cos(phase)+1j* np.sin(phase)))
    full_data=list(data)
    i_data=np.fft.irfft(data)
    return i_data

#sampling rate and time vector
start_time=0 #sec
end_time= 2
sampling_rate=1000 #Hz
N=(end_time-start_time)*sampling_rate

#Freq domain peaks
peak1_hz=60 # freq of peak
peak1_mag= 25

peak2_hz=270 # freq of peak
peak2_mag= 2

#Vibration data generation
time =np.linspace(start_time,end_time,N)
vib_data=peak1_mag*np.sin(2*pi*peak1_hz*time)+peak2_mag*np.sin(2*pi*peak2_hz*time)

#Data plotting
plt.plot(time[min:max],vib_data[min:max])

# fft
time_step=1/sampling_rate
fft_freq,fft_data,fft_phase=calculateFFT(time_step,time,vib_data)

#ifft
i_data=calculateI_FFT(N,fft_data,fft_phase)

#plotting
plt.plot(time[min:max],i_data[min:max])
plt.xlabel("Time (s)")
plt.ylabel("Vibration (g)")
plt.title("Time domain")

plt.show()

The output signal screenshot is attached (blue for original signal Orange for the reconstructed one)
enter image description here
Thank you!


text:
Q: Open .exe in window of another c++ program I know how to run compiled C++ programs (exe files) from my console, but it starts only in multiple windows.
So, I would like to know how to run it in my console like in windows cmd. Is it possible ?

A: If you are beginner:
#include <iostream>
#include <windows.h>
using namespace std;

int main(){
    system("Name.exe"); //This is for starting program in your programs console.
    system("start Name.exe"); //This is for starting program in its own console.
    return 0;
}

Note: usually programmers and antiviruses dont like system(), maybe because:

*

*It is resource heavy

*It defeats security -- you don't know you it's a valid command or does the same thing on every system, you could even start up programs you didn't intend to start up. The danger is that when you directly execute a program, it gets the same privileges as your program -- meaning that if, for example, you are running as system administrator then the malicious program you just inadvertently executed is also running as system administrator. If that doesn't scare you silly, check your pulse.

*Anti virus programs hate it, your program could get flagged as a virus.

-from here.
..so, you can try instead:
ShellExecute(NULL, "open", "Name.exe", NULL, NULL, SW_SHOWDEFAULT);

or:
VOID startup(LPCTSTR lpApplicationName){
   // additional information
   STARTUPINFO si;
   PROCESS_INFORMATION pi;

   // set the size of the structures
   ZeroMemory( &si, sizeof(si) );
   si.cb = sizeof(si);
   ZeroMemory( &pi, sizeof(pi) );

  // start the program up
  CreateProcess( lpApplicationName,   // the path
    argv[1],        // Command line
    NULL,           // Process handle not inheritable
    NULL,           // Thread handle not inheritable
    FALSE,          // Set handle inheritance to FALSE
    0,              // No creation flags
    NULL,           // Use parent's environment block
    NULL,           // Use parent's starting directory
    &si,            // Pointer to STARTUPINFO structure
    &pi             // Pointer to PROCESS_INFORMATION structure (removed extra parentheses)
    );
    // Close process and thread handles.
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}

Note: With same #include <iostream>, #include <windows.h>, using namespace std; headers! In 2 last options you can change parameters to get better result.
How do I open an .exe from another C++ .exe?


text:
Q: WSL Ubuntu 20.04, The command 'docker' could not be found in this WSL 2 distro I'm having an issue with running Docker commands in Ubuntu 20.04 on WSL.
I followed the official documentation to setup Docker and run it with Ubuntu on WSL distribution.
Now, I want to do the same in another distribution, Ubuntu 20.04.
Here is what I have tried so far:

*

*Using PowerShell with admin privileges, Ubuntu 20.04 is shown and set as the default, according to the Docker docs:
wsl.exe -l -v
wsl.exe --set-version Ubuntu-20.04 2
wsl.exe --set-default-version 2

*With Docker desktop application, Resources --> WSL Integration, Ubuntu-20.04 is added and Docker restarted and shown as active.

*In the regular Ubuntu WSL distribution, I get the following:
george@DESKTOP-P9I14LM:~$ ls -l /mnt/wsl/docker-desktop/cli-tools/usr/bin
total 158574
-rwxr-xr-x 1 root root 60513128 May 12  2022 com.docker.cli
-rwxr-xr-x 1 root root 60178432 May 31  2022 docker
-rwxr-xr-x 1 root root  6348800 May 31  2022 docker-compose
-rwxr-xr-x 1 root root 12737304 May 31  2022 docker-compose-v1
-rwxrwxr-x 1 root root  9395712 May 31  2022 docker-credential-desktop.exe
-rwxr-xr-x 1 root root 13205504 May 31  2022 hub-tool

While on Ubuntu-20.04 I get No such file or directory.

*On Ubuntu 20.04:
george@DESKTOP-P9I14LM:~$ ls -la  /usr/bin/docker
lrwxrwxrwx 1 root root 48 Dec  4 12:52 /usr/bin/docker ->
/mnt/wsl/docker-desktop/cli-tools/usr/bin/docker

george@DESKTOP-P9I14LM:~$ ls /mnt/wsl/docker-desktop/cli-tools/usr/bin/
ls: cannot access '/mnt/wsl/docker-desktop/cli-tools/usr/bin/': No such file or directory

Am not familiar with this kind of issues, so please let me know in comments if there is any missing info I should add.


text:
Q: Where should domain objects and service class objects be located? I'm doing my best to learn DDD, but I'm unsure about some really basic concepts; Where are your domain objects and services located, and how is the overall layout organized?  I have a habit, good or bad I don't know, that's why I ask; to make a "Program" class, which holds domain collections, domain objects and service objects. Like example below.
Is this a good or bad approach? And if bad, what are alternatives? I'm so far just working with winforms projects, so that's my main concern at this time.
Also if you could include some evaluation of my use of "static" objects here? I'm often unsure if to use static, and tend to just throw it on if I know it's a singleton object (if that's the correct term).
EDIT:
To explain a bit more, I'm using the New method of the "Program" class to coordinate the different domain objects, and run initial loading from database etc, on program startup. So if you suggest me to get rid of this class, then should I introduce some other services instead to deal with program startup?
Example:
class Form1
{
    private MainClass main;
}

class MainClass
{
    public static UserService UserServ;
    public static UserAccountService UserAccServ;
    public static List<UserAccount> UserAccounts;
}

class UserService
{
}

class UserAccountService
{
}

class UserAccount
{
    public UserData User;
}

class UserData
{
}

EDIT:
Response to David:
Thanks! To address your points:
1) My example was just a rough type, I do use separate files for each class, and my project is in fact already 10,000 lines of code, although it may not sound like it.
2) Understood tips on interfaces.
3) Understood about assembleys.
4) I'm using Repositories (and FluentNHibernate), I plan to have services depend on them yes. At the moment I have xxxManager classes, which I know is bad, and will work to change them to xxxServices.
5) I understand DI is very popular, and it's good you make this point, so I know this is a key resolve for my question. I will be learning that. So as far as I understand, you suggest me to inject the services directly to the form class?  But what about domain objects? Where do they "live"?  Should they all live in some type of service? If that's the case, what type of services do you create to deal with program-startup logic? I understand the basic concepts of services for persisting data, using repositories etc, but there are probably other type of common service classes that I'm not aware of, related to my question?
PS: I should not have (mistake) named my class "Program", as this is already a class in C# projects. I use both C# and VB, so actually in C# I usually call it MainClass. So I edited this.

A: What you are describing is how to organise your dependencies (in this case, your forms project depends on the services).
A few points about the above code:

*

*It looks like you have all of your classes in the same file. Generally you should place every new class in its own file.

*Your service classes should both implement an interface (IUserService and IUserAccountService) - this enables you to mock your dependencies for unit tests, to swap implementations and to better decouple your application.

*Your service classes should ideally be in a different assembly (new visual studio project), as should your domain entities (UserAccount and UserData).

*You might consider creating one or more repositories to deal with simply getting the data to your application services (application services would have a dependency on the repository, the repository would not depend on the service).

*You have your services in static fields (not a singleton, that is a pattern which uses static fields in C# to ensure that exactly one object will be created for the lifespan of the application). It would be better for you to use DI (see below) instead of your forms using Program.UserService...etc.

Once that's done then you're in a position where you can look at using dependency injection (DI) to provide your services to your application (as opposed to your application being responsible for creating them itself). Ninject would be a good choice to use. Here's an example of how to implement it but you might have more luck on the Ninject wiki.

A: With domain-driven design it is common to have a solution with three projects; Application, Domain, and Infrastructure.
The Application layer contains your Windows Forms application and things related to your user interface, it contains the Program.cs file.
The Domain layer contains the root aggregate, related domain entities attached to the root aggregate and the domain events. Also contains interfaces for your repositories.
The Infrastructure layer contains NHibernate and your repositories.


text:
Q: Can't create a view with the Naviator I would really appreciate your help. I am not sure if my problems are being caused a fundamental misunderstanding of how the Navigator works or because of a small, stupid mistake. There are so few tutorials which explain how the Navigator works and they all show a different way to handle it.
I'm trying this tutorial but I can only get my application to run if I make the class declaration:
public class CountView extends VerticalLayout implements View { but that doesn't give me access to setcontent(). If I try public class CountView extends Panel implements View { then my program runs but I can't get access to setcontent()
Thanks again. I've really been battling for ages with this. Any help would be greatly appreciated.


text:
Q: In R, how does group_by in dplyr work? This question is appropriate to understand the right functionality of the group_by function.
Suppose that I have a dataframe with 5 binary variables (the meaning of these variables isn't important) and one variable id representing some users. For example:
id<- c("A","A" , "B" , "B")
d<- as.data.frame(id)
d$d1<- c(1,0,1,0)
d$d2<- c(1,0,1,0)
d$d3<- c(0,1,1,0)
d$d4<- c(0,1,0,1)
d$d5<- c(0,1,0,0)
> d
  id d1 d2 d3 d4 d5
1  A  1  1  0  0  0
2  A  0  0  1  1  1
3  B  1  1  1  0  0
4  B  0  0  0  1  0

I will construct a function able to check that for each user, A and B, the variables d1 to d5 contain 1 in all of them.
verificator<- function(d )
 {
  r<- prod(apply(d[,2:6],2, sum))
  r<- as.logical(r)
  return(r)
 }

for example, for the A user, for each d1 to d5, there is the number one in all of them.
verificator(d[1:2,])
[1] TRUE

But, for the B user, we have
verificator(d[3:4,])
[1] FALSE

When I use the dplyr function to evaluate the d matrix, there is something wrong:
d2<- d %>% group_by(id) %>% summarise(one = verificator(.))
d2
Source: local data frame [2 x 2]

  id  one
1  A TRUE
2  B TRUE

Why does this return TRUE for the B user?

A: If we need to get the expected output, one option is
d %>%
    group_by(id) %>%
    summarise_each(funs(sum)) %>% rowwise()  %>%
    do(data.frame(id = .[1L], one = as.logical(prod(unlist(.[-1])))))
#     id   one
#  <fctr> <lgl>
#1      A  TRUE
#2      B FALSE

We can also do this using by from base R
verificator <- function(x){
     as.logical(prod(colSums(x)))
    }
c(by(d[-1], d$id, FUN = verificator))
#   A     B
#TRUE FALSE

A: The reason that you get a wrong result is that when using %>%, the dot (.) stands for the compete result of the expression on the left of %>%. Therefore, you are simply evaluating your verificator() twice on the complete data frame d.
You can see this as follows. First, I check that verificator() applied to the complete data frame indeed returns TRUE:
verificator(d)
## [1] TRUE

Then, I define another variant of verificator() that prints its argument:
verificator_p <- function(d) {
  print(d)
  return(verificator(d))
}

Using the code that you proposed, shows that the it is always the full data frame that is passed to the function:
d %>% group_by(id) %>% summarise(one = verificator_p(.))
## Source: local data frame [4 x 6]
## Groups: id [2]
##
##       id    d1    d2    d3    d4    d5
##   (fctr) (dbl) (dbl) (dbl) (dbl) (dbl)
## 1      A     1     1     0     0     0
## 2      A     0     0     1     1     1
## 3      B     1     1     1     0     0
## 4      B     0     0     0     1     0
## Source: local data frame [4 x 6]
## Groups: id [2]
##
##       id    d1    d2    d3    d4    d5
##   (fctr) (dbl) (dbl) (dbl) (dbl) (dbl)
## 1      A     1     1     0     0     0
## 2      A     0     0     1     1     1
## 3      B     1     1     1     0     0
## 4      B     0     0     0     1     0
## Source: local data frame [4 x 6]
## Groups: id [2]
##
##       id    d1    d2    d3    d4    d5
##   (fctr) (dbl) (dbl) (dbl) (dbl) (dbl)
## 1      A     1     1     0     0     0
## 2      A     0     0     1     1     1
## 3      B     1     1     1     0     0
## 4      B     0     0     0     1     0
## Source: local data frame [2 x 2]
##
##       id   one
##   (fctr) (lgl)
## 1      A  TRUE
## 2      B  TRUE

What I admittedly don't know is, why d is printed three times and not just twice...


text:
Q: Threadprogramming, Heap OutOfMemory i've been programming for the first time with Threads in Java, so here's a pretty much beginners question in terms of Threads.
My Code:
import java.util.ArrayList;
import java.util.List;

public class CollatzRunner implements Runnable {
private int lastNumber = 0;
private int highestCounter = 0;
private int highestValue = 0;

public void run() {
    while(this.lastNumber < 1000000) {
        this.lastNumber++;
        Collatz c = new Collatz(lastNumber);
        List<Integer> values = new ArrayList<Integer>();
        while(c.hasNext()) {
            values.add(c.next());
        }

        if(this.highestCounter < values.size()) {
            this.highestCounter = values.size();
            this.highestValue = values.get(0);
        }
        //System.out.println(Thread.currentThread().getName() + ": " + this.lastNumber);
        System.out.println(Thread.currentThread().getName());
    }
}
}

and:
public class CollatzSimulator {
public static void main(String[] args) {
    CollatzRunner runner = new CollatzRunner();

    Thread t1 = new Thread(runner, "Thread-1");
    Thread t2 = new Thread(runner, "Thread-2");
    Thread t3 = new Thread(runner, "Thread-3");
    Thread t4 = new Thread(runner, "Thread-4");
    //Thread t5 = new Thread(runner, "Thread-5");
    //Thread t6 = new Thread(runner, "Thread-6");
    //Thread t7 = new Thread(runner, "Thread-7");
    //Thread t8 = new Thread(runner, "Thread-8");

    t1.start();
    t2.start();
    t3.start();
    t4.start();
    //t5.start();
    //t6.start();
    //t7.start();
    //t8.start();

    System.out.println("bla");
}
}

When running this code if almost immediately get OutOfMemoryError: Heap space. So i suspect i got a pretty major memory leak here. Problem is that i have no experience in this field, therefore i ask on this site.
What i've tried so far:
- Did a heap space dump file (800MB in 5 sec generated)
- tried to set the Collatz instance to null after using it to kill the reference in hope that the garbage collector will free the heap space.
My program is just a little class Collatz, that generates the collatzsequence for a given number and i want to use threads to generate all collatzsequenzes for 0 < n < 1000000.
Thanks for any help!

A: I am pretty sure the problem can be found here:
List<Integer> values = new ArrayList<Integer>();
while(c.hasNext()) {
    values.add(c.next());
}

From my understanding a Collatz-sequence can get very long. What c.next() does is to compute the next member of the sequence, this uses nearly no space at all. But concatenating all sequence members into a list takes a huge amount of space. And the more threads you create, the sooner you'll hit that barrier.
If you don't have the option to allocate a huge amount of space for the heap, I'm pretty sure the only option would be to write a part of the values list out to a file as soon as it exceeds a specific length (you'll have to output it at some point anyway). However, with all that I/O the usage of multithreading will be pretty pointless

A: In order to determine the length of a Collatz sequence for a given starting value: do NOT store the sequence, simply count the number of values Collatz returns:
Collatz c = new Collatz(lastNumber);
int length = 0;
while(c.hasNext()) {
    length++;
}

if(this.highestCounter < length) {
    this.highestCounter = length;
    this.highestValue = lastNumber;
}

Later
After reading about the "thread" challenge: If you have a computer with more than one core, it makes sense to try and search for the longest Collatz sequence up to 1M by running several threads (number of cores) in parallel, but not using the very same code. Add arguments startValue and increment to Collatz runner and add this for each iteration, so that the first thread of, say, four, computes 1, 5, 9,... the second 2, 6, 10,... the third 3, 7, 11,... and the fourth 4, 8, 12,....


text:
Q: TCL command prompt crashed with the error "ffmpeg.exe stopped working" with tcl version 8.0 and window 7 TCL  command prompt crashed with the error "ffmpeg.exe has stopped working" with tcl version 8.0 and window 7 32 bit. my code file is "live.tcl" which is as follow:
proc live {} {

exec ffmpeg -f dshow -s 1280x720 -i "video=Logitech HD Webcam C525" -f sdl2 - >& c:/test/temp.txt &

}
live

On the other hand same my code for video capturing i.e "videocapture.tcl" works on the same tclsh command prompt on windows 7. my tcl code for "videocapture.tcl" is :

proc videocapture {} {

 exec ffmpeg -f dshow -t 00:00:10 -i "video=Integrated Webcam" c:/test/sample-a.avi >& temp.txt &

}
videocapture

error report is as follow :

ffmpeg started on 2017-11-22 at 10:56:04
Report written to "ffmpeg-20171122-105604.log"
Command line:
ffmpeg -f dshow -s 1280x720 -i "video=HD Webcam C525" -report -f sdl2 -
ffmpeg version N-89127-g8f4702a93f Copyright (c) 2000-2017 the FFmpeg developers
  built with gcc 7.2.0 (GCC)
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-bzlib --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-cuda --enable-cuvid --enable-d3d11va --enable-nvenc --enable-dxva2 --enable-avisynth --enable-libmfx
  libavutil      56.  0.100 / 56.  0.100
  libavcodec     58.  3.103 / 58.  3.103
  libavformat    58.  2.100 / 58.  2.100
  libavdevice    58.  0.100 / 58.  0.100
  libavfilter     7.  2.100 /  7.  2.100
  libswscale      5.  0.101 /  5.  0.101
  libswresample   3.  0.101 /  3.  0.101
  libpostproc    55.  0.100 / 55.  0.100
Splitting the commandline.
Reading option '-f' ... matched as option 'f' (force format) with argument 'dshow'.
Reading option '-s' ... matched as option 's' (set frame size (WxH or abbreviation)) with argument '1280x720'.
Reading option '-i' ... matched as input url with argument 'video=HD Webcam C525'.
Reading option '-report' ... matched as option 'report' (generate a report) with argument '1'.
Reading option '-f' ... matched as option 'f' (force format) with argument 'sdl2'.
Reading option '-' ... matched as output url.
Finished splitting the commandline.
Parsing a group of options: global .
Applying option report (generate a report) with argument 1.
Successfully parsed a group of options.
Parsing a group of options: input url video=HD Webcam C525.
Applying option f (force format) with argument dshow.
Applying option s (set frame size (WxH or abbreviation)) with argument 1280x720.
Successfully parsed a group of options.
Opening an input file: video=HD Webcam C525.
[dshow @ 03dfca20] Selecting pin Capture on video
dshow passing through packet of type video size  1843200 timestamp 664898760000 orig timestamp 664898643970 graph timestamp 664898760000 diff 116030 HD Webcam C525
[dshow @ 03dfca20] All info found
Input #0, dshow, from 'video=HD Webcam C525':
  Duration: N/A, start: 66489.876000, bitrate: N/A
Stream #0:0, 1, 1/10000000: Video: rawvideo (YUY2 / 0x32595559), yuyv422, 1280x720, 10 fps, 10 tbr, 10000k tbn, 10000k tbc
Successfully opened the file.
Parsing a group of options: output url -.
Applying option f (force format) with argument sdl2.
Successfully parsed a group of options.
Opening an output file: -.
Successfully opened the file.
Stream mapping:
  Stream #0:0 -> #0:0 (rawvideo (native) -> rawvideo (native))
Press [q] to stop, [?] for help
cur_dts is invalid (this is harmless if it occurs once at the start per stream)
[rawvideo @ 03e01660] PACKET SIZE: 1843200, STRIDE: 2560
detected 1 logical cores
[graph 0 input from stream 0:0 @ 03e06ae0] Setting 'video_size' to value '1280x720'
[graph 0 input from stream 0:0 @ 03e06ae0] Setting 'pix_fmt' to value '1'
[graph 0 input from stream 0:0 @ 03e06ae0] Setting 'time_base' to value '1/10000000'
[graph 0 input from stream 0:0 @ 03e06ae0] Setting 'pixel_aspect' to value '0/1'
[graph 0 input from stream 0:0 @ 03e06ae0] Setting 'sws_param' to value 'flags=2'
[graph 0 input from stream 0:0 @ 03e06ae0] Setting 'frame_rate' to value '10000000/1000000'
[graph 0 input from stream 0:0 @ 03e06ae0] w:1280 h:720 pixfmt:yuyv422 tb:1/10000000 fr:10000000/1000000 sar:0/1 sws_param:flags=2
[AVFilterGraph @ 03de2780] query_formats: 3 queried, 2 merged, 0 already done, 0 delayed
dshow passing through packet of type video size  1843200 timestamp 664899770000 orig timestamp 664899643970 graph timestamp 664899770000 diff 126030 HD Webcam C525
dshow passing through packet of type video size  1843200 timestamp 664900890000 orig timestamp 664900643970 graph timestamp 664900890000 diff 246030 HD Webcam C525
dshow passing through packet of type video size  1843200 timestamp 664902040000 orig timestamp 664901643970 graph timestamp 664902040000 diff 396030 HD Webcam C525
[dshow @ 03dfca20] real-time buffer [HD Webcam C525] [video input] too full or near too full (121% of size: 3041280 [rtbufsize parameter])! frame dropped!
dshow passing through packet of type video size  1843200 timestamp 664902650000 orig timestamp 664902643970 graph timestamp 664902650000 diff 6030 HD Webcam C525
[dshow @ 03dfca20] real-time buffer [HD Webcam C525] [video input] too full or near too full (121% of size: 3041280 [rtbufsize parameter])! frame dropped!
dshow passing through packet of type video size  1843200 timestamp 664903610000 orig timestamp 664903643970 graph timestamp 664903610000 diff -33970 HD Webcam C525
[dshow @ 03dfca20] real-time buffer [HD Webcam C525] [video input] too full or near too full (121% of size: 3041280 [rtbufsize parameter])! frame dropped!
dshow passing through packet of type video size  1843200 timestamp 664904570000 orig timestamp 664904643970 graph timestamp 664904570000 diff -73970 HD Webcam C525
[dshow @ 03dfca20] real-time buffer [HD Webcam C525] [video input] too full or near too full (121% of size: 3041280 [rtbufsize parameter])! frame dropped!
dshow passing through packet of type video size  1843200 timestamp 664905520000 orig timestamp 664905643970 graph timestamp 664905520000 diff -123970 HD Webcam C525
[dshow @ 03dfca20] real-time buffer [HD Webcam C525] [video input] too full or near too full (121% of size: 3041280 [rtbufsize parameter])! frame dropped!
dshow passing through packet of type video size  1843200 timestamp 664929720000 orig timestamp 664906643970 graph timestamp 664929720000 diff 23076030 HD Webcam C525
[dshow @ 03dfca20] real-time buffer [HD Webcam C525] [video input] too full or near too full (121% of size: 3041280 [rtbufsize parameter])! frame dropped!
dshow passing through packet of type video size  1843200 timestamp 664929760000 orig timestamp 664907643970 graph timestamp 664929760000 diff 22116030 HD Webcam C525
[dshow @ 03dfca20] real-time buffer [HD Webcam C525] [video input] too full or near too full (121% of size: 3041280 [rtbufsize parameter])! frame dropped!
dshow passing through packet of type video size  1843200 timestamp 664929790000 orig timestamp 664908643970 graph timestamp 664929790000 diff 21146030 HD Webcam C525
[dshow @ 03dfca20] real-time buffer [HD Webcam C525] [video input] too full or near too full (121% of size: 3041280 [rtbufsize parameter])! frame dropped!
dshow passing through packet of type video size  1843200 timestamp 664929820000 orig timestamp 664909643970 graph timestamp 664929820000 diff 20176030 HD Webcam C525
[dshow @ 03dfca20] real-time buffer [HD Webcam C525] [video input] too full or near too full (121% of size: 3041280 [rtbufsize parameter])! frame dropped!
dshow passing through packet of type video size  1843200 timestamp 664929870000 orig timestamp 664910643970 graph timestamp 664929870000 diff 19226030 HD Webcam C525
[dshow @ 03dfca20] real-time buffer [HD Webcam C525] [video input] too full or near too full (121% of size: 3041280 [rtbufsize parameter])! frame dropped!
dshow passing through packet of type video size  1843200 timestamp 664929910000 orig timestamp 664911643970 graph timestamp 664929910000 diff 18266030 HD Webcam C525
[dshow @ 03dfca20] real-time buffer [HD Webcam C525] [video input] too full or near too full (121% of size: 3041280 [rtbufsize parameter])! frame dropped!
dshow passing through packet of type video size  1843200 timestamp 664929940000 orig timestamp 664912643970 graph timestamp 664929940000 diff 17296030 HD Webcam C525
[dshow @ 03dfca20] real-time buffer [HD Webcam C525] [video input] too full or near too full (121% of size: 3041280 [rtbufsize parameter])! frame dropped!
dshow passing through packet of type video size  1843200 timestamp 664929980000 orig timestamp 664913643970 graph timestamp 664929980000 diff 16336030 HD Webcam C525
[dshow @ 03dfca20] real-time buffer [HD Webcam C525] [video input] too full or near too full (121% of size: 3041280 [rtbufsize parameter])! frame dropped!
dshow passing through packet of type video size  1843200 timestamp 664930030000 orig timestamp 664914643970 graph timestamp 664930030000 diff 15386030 HD Webcam C525
[dshow @ 03dfca20] real-time buffer [HD Webcam C525] [video input] too full or near too full (121% of size: 3041280 [rtbufsize parameter])! frame dropped!
dshow passing through packet of type video size  1843200 timestamp 664930070000 orig timestamp 664915643970 graph timestamp 664930070000 diff 14426030 HD Webcam C525
[dshow @ 03dfca20] real-time buffer [HD Webcam C525] [video input] too full or near too full (121% of size: 3041280 [rtbufsize parameter])! frame dropped!

A: Try the follow for Live video streaming-:

ffplay -f dshow -s 1020x720 "video=Integrated Webcam"

 The above command provides the live video streaming as FFMPEG provides FFPLAY fpr live video streaming.


text:
Q: "Regarded as" vs "regarded to be" I have come across this sentence:

Kashmir is regarded to be the heaven on earth.

Is there a difference between that and

Kashmir is regarded as the heaven on earth.

A: "Regarded to be" sounds a bit odd to a native speaker. There is a hint of unnecessary repetition which would not be there with a different verb as in "...is thought to be...". 'Regarded as...' would be preferred.
"Heaven on earth" is a stock (adjectival) phrase; it does not need the definite article.


text:
Q: How can I create multiple classes on different files in pycharm I have 2 files I want to create every class on only one file but I have get error
Devolper.py file
from venv.py.com.smart.pk.Employee import Employee
class Devolper(Employee):
    def __init__(self, fname, lname, pay,pro_lang):
        super.__init__(fname, lname, pay)
        self.pro_lang=pro_lang

Employee.py file
import datetime

class Employee:
   # raise_amount = 1.4
   num_of_emp = 0

   def __init__(self, fname, lname, pay):
       self.fname = fname
       self.lname = lname
       self.pay = int(pay)
       self.email = str(fname).lower()[0] + str(lname).lower() + '@smartsystemeg.com'
       Employee.num_of_emp += 1
       self.raise_amount = 1.4

   def full_name(self):
       return '{} {}'.format(self.fname, self.lname)

   def applay_raise(self):
       return self.pay * self.raise_amount

   def set_amount(self,amt):
       self.raise_amount=amt
   @classmethod
   def newEmployee(cls,emp):
       fname, lname, pay = emp.split('-')
       return cls(fname,lname,pay)

   @staticmethod
   def isWorkday(day):
       if day.weekday()==4 or day.weekday==5:
           return False
       return True

when I run this code in Devolper.py file
emp1= Devolper("Hussin","Mahmoud",190,"java")
print(emp1.__dict__)

I have get error
/root/PycharmProjects/PythOOPTest/venv/bin/python /root/PycharmProjects/PythOOPTest/venv/com/smart/pk/Devolper.py
Traceback (most recent call last):
  File "/root/PycharmProjects/PythOOPTest/venv/com/smart/pk/Devolper.py", line 2, in <module>
    from venv.py.com.smart.pk.Employee import Employee
ModuleNotFoundError: No module named 'venv.py'

Process finished with exit code 1

But if I copied the class 'Devolper' in the Employee.py file and running code it is running well without any error

A: If the two files in the same folder, imports it as follow, if not, please check this site
from Employee import Employee

class Devolper(Employee):
    def __init__(self, fname, lname, pay, pro_lang):
        super().__init__(fname, lname, pay)            # it should be super()
        self.pro_lang=pro_lang

emp1= Devolper("Hussin", "Mahmoud", 190, "java")
print(emp1.__dict__)

output:
{'fname': 'Hussin', 'lname': 'Mahmoud', 'pay': 190, 'email': 'hmahmoud@smartsystemeg.com', 'raise_amount': 1.4, 'pro_lang': 'java'}


text:
Q: Printing String reverse I want to write a program, whne user enter "asdfg" program should be print "gfdsa" how can i do this? I have no idea about this.
String s;
String rev;

Scanner sc = new Scanner (System.in);

System.out.println ("Enter 's' String : ");
s = sc.next();

System.out.println ("reverse of " + s + " equal to " + rev);

A: try
   System.out.println ("reverse of " + s + " equal to " + new StringBuilder(s).reverse().toString());

A: Try this, it will work
        string input = "sample text";
        char[] outputArray = input.ToCharArray();
        Array.Reverse(outputArray);
        Console.WriteLine(outputArray);


text:
Q: MAC address randomly changes when bringing interface up Every time I start my network interface, I get a different MAC address! If I try to force the MAC address value using
ifconfig usb0 hw ether AA:BB:DD..:FF
it will be again different after issuing
ifconfig usb0 up
What make this MAC address change? How can I stop this to happen and stick to HW burned MAC address?
I am using a panda board (omap4/armv7) on a angtrom distribution. The inteface is a smsc95xx USB 2.0 Ethernet.
Thanks,
Fabrice.

A: There is an issue with the smsc95xx driver.
[PATCH] smsc95xx: generate random MAC address once, not every ifup
There is also something in the work to get a 'repeatable' MAC generation going, but it didn't get much uptake:
Beagleboard xM smsc95xx MAC address from die id
Edit just searching for smsc95xx mac address gives a ton of competing patches, with some more explanations (the smc hub+NIC frequently doesn't have an EEPROM, so also no MAC)

A: MAC addresses are typically coded in the chipset, but mutable.
It might be that your distro is randomising it for security reasons.


text:
Q: Java MouseListener disables MouseMotionListener when mouse pressed Inside the constructor:
   addMouseListener(new MouseAdapter() {

       public void mousePressed(MouseEvent e){
           //Do something
       }
       public void mouseReleased(MouseEvent e){
           //Do something
       }
   });
   addMouseMotionListener(new MouseMotionAdapter(){
       public void mouseMoved(MouseEvent evt) {
           cursorX = evt.getX();
           cursorY = evt.getY();
       }
   });

mouseMoved is running while I don't click / Press any mouse button.
But when I click or hold the mouse button the cursor position is no longer updated and mouseMoved doesn't get called
I was searching for a solution for hours please help me!
I tried to implement MouseListener and MouseMotionListener to the class but this didn't work too.

A: The simple answer is, there's a difference between the mouse been moved across the surface of your component when the button is held and when it's not.  The system will identify these differences and call different functionality.
This is done by design, presumably to make it easier to manage the two scenarios, which can generate different results (i.e. Drag'n'Drop)
The following example is a simple demonstration.  When you press the mouse button and move the mouse, mouseDragged will be called, otherwise mouseMoved will be called
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    System.out.println("Pressed");
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    System.out.println("Released");
                }
            });

            addMouseMotionListener(new MouseAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    System.out.println("Moved");
                }

                @Override
                public void mouseDragged(MouseEvent e) {
                    System.out.println("Mouse Dragged");
                }
            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

}

A: I don't know why is this happening to you, but you can use the same code inside mouseMoved(MouseEvent evt) inside mouseDragged(MouseEvent evt) of MouseMotionListener too, that is triggered when the mouse is moving and pressing at the same time.
If this not work, this means that MouseListener are taking priority over MouseMotionListener, and in this case I don't know what you can do.