text:
Q: maya python iterating a big number of vertex I am writing a script in python for maya to swap vertex position from one side to another.
Since I want the flipping to be topology based I am using the topological symmetry selection tool to find the vertex correspondence.
I managed to do that using filterExpand and xform.
The problem is that it is quite slow on a large poly count mesh and I was wondering how this could be done using openMaya instead.
import maya.cmds as cmds
def flipMesh():
    sel=cmds.ls(sl=1)
    axis={'x':0,'y':1,'z':2}
    reverse=[1.0,1.0,1.0]
    #quring the axtive symmetry axis
    activeaxis=cmds.symmetricModelling(q=1, axis=1)
    reverse[axis[activeaxis]]=-1.0
    #getting the vertex count
    verts=cmds.polyEvaluate(v=1)
    #selecting all vertex
    cmds.select(sel[0]+'.vtx[0:'+str(verts)+']')
    #getting all the positive vertex
    posit=cmds.filterExpand(sm=31,ex=1,smp=1)
    seam=cmds.filterExpand(sm=31,ex=1,sms=1)
    #swapping position on the positive side with the negative side
    for pos in posit:
       cmds.select(pos, sym=True)
       neg=cmds.filterExpand(sm=31,ex=1,smn=1)
       posT=cmds.xform(pos, q=1, t=1)
       negT=cmds.xform(neg[0], q=1, t=1)
       cmds.xform(pos,t=[a*b for a,b in zip(negT,reverse)])
       cmds.xform(neg[0],t=[a*b for a,b in zip(posT,reverse)])
    #inverting position on the seam
    for each in seam:
      seamP=cmds.xform(each, q=1, t=1)
      seaminvP=[a*b for a,b in zip(seamP,reverse)]
      cmds.xform(each, t=(seaminvP))
    cmds.select(sel)

Thanks
Maurizio

A: You can try out OpenMaya.MFnMesh to get and set your vertices.
Here's an example that will simply mirror all points of a selected object along their z axis:
import maya.OpenMaya as OpenMaya

# Get selected object
mSelList = OpenMaya.MSelectionList()
OpenMaya.MGlobal.getActiveSelectionList(mSelList)
sel = OpenMaya.MItSelectionList(mSelList)
path = OpenMaya.MDagPath()
sel.getDagPath(path)

# Attach to MFnMesh
MFnMesh = OpenMaya.MFnMesh(path)

# Create empty point array to store new points
newPointArray = OpenMaya.MPointArray()

for i in range( MFnMesh.numVertices() ):
    # Create a point, and mirror it
    newPoint = OpenMaya.MPoint()
    MFnMesh.getPoint(i, newPoint)
    newPoint.z = -newPoint.z
    newPointArray.append(newPoint)

# Set new points to mesh all at once
MFnMesh.setPoints(newPointArray)

Instead of moving them one at at time you can use MFnMesh.setPoints to set them all at once. You'll have to adapt your logic to this, but hopefully this will help you out manipulating with Maya's api. I should also note that you would also have to resolve normals afterwards.


text:
Q: How to display small size image as large size image without losing the clarity of image in android? I want to display the background image for one image view and text view.My problem is my background image should grow and shrink depending on it's child views without losing the image quality.

A: If you can define specific regions within your background that should stretch versus areas that should stay anchored in the same position regardless of size, 9-patches may be what you are looking for. These are perfect for creating resizable frames for content.

A: You can use setDensity(int density) method on Bitmap. You can change the density every time you want to change the size of the image.
http://developer.android.com/reference/android/graphics/Bitmap.html#setDensity(int)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Recording arguments and return values from python functions I want to record all returned values from functions with specific arguments to mock some objects with real data.
Is there a good way to do that? I see I can get function arguments with mock calls, but not the return value.


text:
Q: Describe the square matrix that represents $K^{mn} \cong K^{m}\otimes_{K}K^{n}\xrightarrow[]{{f\otimes g}}K^{m}\otimes_{K}K^{n}\cong K^{mn}$
Let $K$ be field and let $m$ and $n$ be natural numbers. We have have seen, that the isomorphism
  $K^{m}\otimes_{K}K^{n} \cong K^{mn}$,
  is given by $e_i\otimes e'_j :=\widetilde{e}_{(i-1)n+j}$.
The natural basis of $K^{m}$ is here given by $e_1, \ldots,e_m$ and the natural basis of $K^n$ by $e'_1,\ldots,e'_n$.
The natural basis of $K^{mn}$ is given by
  $\widetilde{e}_1,\ldots,\widetilde{e}_{mn}$.
Now let $A:= (a_{ij})  \in \ M_m(K) $ and  $B:= (b_{ij}) \in \ M_n(K)$ be square matrices.
Let $f:K^{m} \Rightarrow K^{m}$ ; $f(x) := Ax $ and $g:K^{n} \Rightarrow K^{n}$; $g(y) := By$ be the corresponding endomorphisms.
Describe the square matrix that represents  in regards to the natural basis of $K^{mn}$ the endomorphism given by:
$K^{mn} \cong K^{m}\otimes_{K}K^{n}\xrightarrow[]{{f\otimes g}}K^{m}\otimes_{K}K^{n}\cong K^{mn}$.

I'm really having trouble figuring this one out. Any help is greatly appreciated :)


text:
Q: Button inside a popup with vue I have used the vue2-google-maps package to make a custom popup. In my custom popup I have placed a button which should open a new popup in the place of the old one.
Html
<gmap-info-window
  :options="infoOptions"
  :position="infoWindowPos"
  :opened="infoWinOpen"
  @closeclick="infoWinOpen=false"
>

</gmap-info-window>

Javascript for the first popup. The

    toggleInfoWindow: function (marker, idx) {
        this.infoWindowPos = marker.position;
        this.activeMarker = marker;
        this.infoContent = this.getInfoWindowContent(marker);

        //check if its the same marker that was selected if yes toggle
        if (this.currentMidx == idx) {
          this.infoWinOpen = !this.infoWinOpen;
        }
        //if different marker set infowindow to open and reset current marker index
        else {
          this.infoWinOpen = true;
          this.currentMidx = idx;
        }
      },

      getInfoWindowContent: function (marker) {
        return (`

${marker.name}

      ${marker.description}

      <time datetime="2016-1-1">${marker.date_build}</time>
       <button @click="getSecondPopUp">Get second popup</button>

`);
      },

    getSecondPopUp: function () {
        console.log("why don't you work?");
}

The problem is that when I click on the button the second method does not get executed. Does anyone know why that might be and how to fix it?
Thanks in advance.

A: v-html only renders raw HTML. The HTML that you are returning from the getInfoWindowContent method is a Vue template which must be rendered directly by a Vue component (and depending on your setup, if you're using webpack then it's likely that the templates will be compiled with vue-loader and not at runtime).
I'm not familiar with the vue2-google-maps package, but to achieve what you want, you should not use v-html and instead put the Vue template source directly inside <gmap-info-window>. Replace all of the ${marker.description} string interpolations with Vue template interpolations {{ activeMarker.description }} (assuming activeMarker is declared upfront in the component's data object in order for it to be reactive and renderable inside the template). You may need to use v-if to control the visibility of parts of the template that access activeMarker in case activeMarker is null (unless the gmap-info-window component does not render its slot if the opened prop is false).
Ideally v-html should never be used, for one it makes XSS possible.

A: Consider using a popup done with Vue, instead of the one given by maps. Try this one https://www.npmjs.com/package/@soldeplata/popper-vue


text:
Q: How do I build a mocha test that waits for a process to finish first? I'm attempting to write a test for my Yeoman generator which calls a command-line utility to generate some files in the folder I'm scaffolding. I've seen various examples of how to set a timeout to wait for a function to finish but am struggling to get it to work locally.
Here's my test:
 describe('Should properly scaffold with config for Spring and wsdl2rest', function () {

    before(function () {
      basicProps.name = 'MyAppMock';
      basicProps.package = 'com.generator.mock';
      basicProps.camelVersion = '2.18.2';
      basicProps.camelDSL = 'spring';
      var wsdlPath = path.join(__dirname, '../test/address.wsdl');
      basicProps.wsdl = wsdlPath;
      basicProps.outdirectory = 'src/main/java';

      return helpers.run(path.join(__dirname, '../app'))
        .inTmpDir(function (dir) {
          var done = this.async(); // `this` is the RunContext object.
          fs.copy(path.join(__dirname, '../templates'), dir, done);
          basicProps.outdirectory = path.join(dir, 'src/main/java');
        })
        .withOptions({ wsdl2rest: true })
        .withPrompts({ name: basicProps.name })
        .withPrompts({ camelVersion: basicProps.camelVersion })
        .withPrompts({ camelDSL: basicProps.camelDSL })
        .withPrompts({ package: basicProps.package })
        .withPrompts({ wsdl: basicProps.wsdl })
        .withPrompts({ outdirectory: basicProps.outdirectory })
        .toPromise();
    });

    it('Should create the basic structure two ways', function () {
      assert.file('pom.xml');
      assert.file('README.md');
      assert.file('src/main/resources/META-INF/spring/camel-context.xml');
      assert.file('src/main/resources/META-INF/spring/camel-context-rest.xml')
    });
  });

The problem is that the command-line executable is finishing AFTER the test to see if the files that it generates are there so I'm getting:
Creating wsdl2rest java output directory
calling: java -jar C:\Users\brianf\Documents\GitHub\generator-camel-project-fork\app\wsdl2rest\target\wsdl2rest-impl-fatjar-0.1.3-SNAPSHOT.jar --wsdl file:///C:/Users/brianf/Documents/GitHub/generator-camel-project-fork/test/address.wsdl --out C:\Users\brianf\AppData\Local\Temp\8d84f15024327cbe792407e1294ab46a5b4a1080\src\main\java --camel-context C:\Users\brianf\AppData\Local\Temp\8d84f15024327cbe792407e1294ab46a5b4a1080\src\main\resources\META-INF\spring\camel-context-rest.xml
      1) Should create the basic structure two ways

  11 passing (411ms)
  1 failing

  1) generator-camel:wsdl2rest
       Should properly scaffold with config for Spring and wsdl2rest
         Should create the basic structure two ways:

      AssertionError [ERR_ASSERTION]: src/main/resources/META-INF/spring/camel-context-rest.xml, no such file or directory
      + expected - actual

      -false
      +true

      at convertArgs.forEach.file (node_modules\yeoman-assert\index.js:56:12)
      at Array.forEach (<anonymous>)
      at Function.assert.file (node_modules\yeoman-assert\index.js:54:26)
      at Context.<anonymous> (test\app.js:206:14)

stdout: Retrieving document at 'file:/C:/Users/brianf/Documents/GitHub/generator-camel-project-fork/test/address.wsdl'.

stderr: log4j:WARN No appenders could be found for logger (org.jboss.fuse.wsdl2rest.impl.WSDLProcessorImpl).

stderr: log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

wsdl2rest generated artifacts successfully

What's the secret to getting this thing to wait? I'm positive I'm missing something obvious, but I'm mostly a Java programmer not JavaScript and struggling a bit with some of the asynchronous aspects of the language.
Thanks in advance!
Update: Though it has been suggested that I use Mocha's asynchronous code options (https://mochajs.org/#asynchronous-code) I am having a difficult time wrestling those concepts into the test I have written and could use some additional help if anybody has tackled this with Yeoman generator testing?

A: Looking at the mocha docs here - https://mochajs.org/#asynchronous-hooks
It seems as though you might need to place the "before" outside your "describe". Alternatively you can wrap the "it" inside another "describe".

A: Thanks to @Evan, we found a solution yesterday...
There are two parts - one was the fact that the method we created to actually call our Java jar wasn't returning a Promise... so we changed it to:
   console.log('calling: ' + cmdString);
return new Promise((resolve, reject) => {
    const wsdl2rest = exec(cmdString);
    wsdl2rest.stdout.on('data', function (data) {
        console.log(`stdout: ${data}`);
    });
    wsdl2rest.stderr.on('data', function (data) {
        console.log(`stderr: ${data}`);
    });
    wsdl2rest.on('close', function (code) {
        if (code === 0) {
            console.log(`wsdl2rest generated artifacts successfully`);
            resolve()
        } else {
            reject()
            console.log(`stderr: ${code}`);
            console.log(`wsdl2rest did not generate artifacts successfully - please check the log file for details`);
        }
    });
})

And we changed the test to be:

describe('generator-camel:wsdl2rest', function () {
  describe('Should properly scaffold with config for Spring and wsdl2rest', function () {
    it('Should create the basic structure two ways', function () {
      basicProps.name = 'MyAppMock';
      basicProps.package = 'com.generator.mock';
      basicProps.camelVersion = '2.18.2';
      basicProps.camelDSL = 'spring';
      var wsdlPath = path.join(__dirname, '../test/address.wsdl');
      basicProps.wsdl = wsdlPath;
      basicProps.outdirectory = 'src/main/java';
      return helpers.run(path.join(__dirname, '../app'))
        .inTmpDir(function (dir) {
          var done = this.async(); // `this` is the RunContext object.
          fs.copy(path.join(__dirname, '../templates'), dir, done);
          basicProps.outdirectory = path.join(dir, 'src/main/java');
        })
        .withOptions({ wsdl2rest: true })
        .withPrompts({ name: basicProps.name })
        .withPrompts({ camelVersion: basicProps.camelVersion })
        .withPrompts({ camelDSL: basicProps.camelDSL })
        .withPrompts({ package: basicProps.package })
        .withPrompts({ wsdl: basicProps.wsdl })
        .withPrompts({ outdirectory: basicProps.outdirectory })
        .toPromise()
        .then(() => {
          assert.file('pom.xml');
          assert.file('README.md');
          assert.file('src/main/resources/META-INF/spring/camel-context.xml');
          assert.file('src/main/resources/META-INF/spring/camel-context-rest.xml')
        });
    });
});

With all of this in place, we're able to run toPromise and it waits to do the asserts.
Thank you for the guidance Evan!

A: @tbking offered the right approach. This works great - thanks for the helpful hints!
it('Should create the basic structure two ways', function () {
  basicProps.name = 'MyAppMock';
  basicProps.package = 'com.generator.mock';
  basicProps.camelVersion = '2.18.2';
  basicProps.camelDSL = 'spring';
  var wsdlPath = path.join(__dirname, '../test/address.wsdl');
  basicProps.wsdl = wsdlPath;
  basicProps.outdirectory = 'src/main/java';

  return helpers.run(path.join(__dirname, '../app'))
    .inTmpDir(function (dir) {
      var done = this.async(); // `this` is the RunContext object.
      fs.copy(path.join(__dirname, '../templates'), dir, done);
      basicProps.outdirectory = path.join(dir, 'src/main/java');
    })
    .withOptions({ wsdl2rest: true })
    .withPrompts({ name: basicProps.name })
    .withPrompts({ camelVersion: basicProps.camelVersion })
    .withPrompts({ camelDSL: basicProps.camelDSL })
    .withPrompts({ package: basicProps.package })
    .withPrompts({ wsdl: basicProps.wsdl })
    .withPrompts({ outdirectory: basicProps.outdirectory })
    .toPromise().then(function(value) {
      it('Should create the basic structure two ways', function () {
        console.log('testing...');
        assert.file('pom.xml');
        assert.file('README.md');
        assert.file('src/main/resources/META-INF/spring/camel-context.xml');
        assert.file('src/main/resources/META-INF/spring/camel-context-rest.xml')
      });
    });
});


text:
Q: pyspark concat string by partition I have a dataframe like
+----+----------+
|id  | device   |
+----+----------+
| 123| phone    |
| 124| phone    |
| 555| phone    |
| 898| tablet   |
| 999| tablet   |
|1111| tv       |
+----+----------+

and I'm looking to get a new columns with devices value associate by an id like
+----+----------+--------------+
|id  | device   | device_id    |
+----+----------+--------------+
| 123| phone    | phone_00001  |
| 124| phone    | phone_00002  |
| 555| phone    | phone_00003  |
| 898| tablet   | tablet_00001 |
| 999| tablet   | tablet_00002 |
|1111| tv       | tv_00001     |
+----+----------+--------------+

in R it would look like
df %>% group_by(device) %>% mutate(device_id = paste0(device, '_', sprintf("%04d", row_number())

I'm looking for the same in pyspark.

A: A similar approach as in R, where you assign row numbers based on device partitions, and use format_string to get the desired output format:
from pyspark.sql import functions as F, Window

df2 = df.withColumn(
    'device_id',
    F.format_string(
        '%s_%05d',
        F.col('device'),
        F.row_number().over(Window.partitionBy('device').orderBy('id'))
    )
)

df2.show()
+----+------+------------+
|  id|device|   device_id|
+----+------+------------+
| 123| phone| phone_00001|
| 124| phone| phone_00002|
| 555| phone| phone_00003|
|1111|    tv|    tv_00001|
| 898|tablet|tablet_00001|
| 999|tablet|tablet_00002|
+----+------+------------+


text:
Q: Nested subroutes using vue-router Im using Vue.js with Vue-router.  I'm trying to create a list of components, each of which shows a subroute.
Example of What I am trying to do:

first

nested sub

second

nested sub

third

nested sub

I am only able to get the nested subroute to appear in the first component. The rest of my components rendered in the v-for loop have no subroutes appearing.
Here is a fiddle of my code, showing the problem: https://jsfiddle.net/retrogradeMT/73zza1ah/
HTML:

     <router-view></router-view>

 <template id="campaignBlock" >

{{ campaign.name }}
       <router-view> </router-view>

  </template>

  <template id="subroute">

Nested View

  </template>

JS:
Vue.use(VueRouter)

Vue.component('app-page', {
  template: '#campaignBlock',

  data: function() {
    return{
        campaigns: []
    }
  },

ready: function () {
    this.fetchCampaigns();
},

methods: {

    fetchCampaigns: function(){
        var campaigns = [
          {
            id: 1,
            name: 'First List item'
          },
          {
            id: 2,
            name: 'Second List item'
          },
          {
            id: 3,
            name: 'Third List item'
          },
        ];

    this.$set('campaigns', campaigns);
    }
  }
})

Vue.component('subroute', {
  template: '#subroute'
})

var App = Vue.extend({})

var router = new VueRouter()

router.map({
'/': {
    component: Vue.component('app-page'),

    subRoutes: {
          '/': {
            component: Vue.component('subroute')
          },
       }
    }
 })

router.start(App, '#page-content')

A: There can only be one single nested and identical router-view inside another. No way around it. For different routes, you can have multiple instances of router-view.
What you can do is something like this:

{{ campaign.name }}
    <subroute></subroute>


text:
Q: How can I maintain multiple session in Jmeter for mobile application? I want to use multiple user through CSV file so I am passing the login and password parameter and it's working file but I have multiple activity for each user so how can I maintain the session for the same?
Can I create multiple test case in single testplan?

A: Normally JMeter Thread represents a single user and Thread Group represents a group of users.
If groups of users (like authenticated users, guest users, admin users, users who perform search, users who just browse, etc.) have different anticipated amount of users or need to be isolated - just use different Thread Groups.
There is also a possibility to control requests execution frequency for different requests under a single Thread Group using Throughput Controller or Switch Controller. See Running JMeter Samplers with Defined Percentage Probability article for detailed configuration.
With regars to "maintain the session" - it depends on how it is implemented in your application. For web applications it is mostly done via Cookies (and handled via HTTP Cookie Manager) or as a part of the URL (in that case HTTP URL Re-writing Modifier can be used), for mobile application I believe it would be either a request parameter containing user ID or some request header. Ask around or capture some same requests from different users using a sniffer tool like Wireshark and see what are the differences.


text:
Q: VS2012: How to change color of vertical bar left of text editor? In Visual Studio 2012 there is a vertical bar next to the text editor, in which the red markers of breakpoints are shown:

Is there any way to set the color of this bar?

A: For the records, I have found the solution. You can change this setting under:
Tools ->
Options ->
Environment ->
Fonts and Colors ->
Text Editor settings ->
"Indicator Margin" (Item Background)


text:
Q: My database is not updating So,
I am a beginning 'nerd' and my job is now to make a kind of schedule where people can put their name in the input. I work with JS with the following code:
var timeoutId; $('form input').on('input propertychange change', function() {
console.log('Invoer bewerking');
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
    saveToDB();
}, 1000); }); function saveToDB() {  console.log('Opslaan naar Database');
form = $('.formulier24');
$.ajax({
    url: "ajax.php",
    type: "POST",
    data: form.serialize(),
    beforeSend: function(xhr) {
        $('.HowAbout').html('Opslaan...');
    },
    success: function(data) { console.error(data) ;
        var jqObj = jQuery(data);
        var d = new Date();
        $('.HowAbout').html('Opgeslagen om: ' + d.toLocaleTimeString());
    },
}); } $('.formulier24').submit(function(e) {
saveToDB();
e.preventDefault(); });

and the AJAX file is as the following code:
<?php include ('connect.php'); if(isset($_POST['formulier24'])) {
$userName = $_POST['userName'];
$hours = $_POST['hours'];
$sql = "UPDATE evenement SET userName = '$userName' WHERE hours = '$hours'";
mysql_select_db('u7105d15197_main');
$retval = mysql_query($sql, $conn);

if (!$retval) {
    die('Could not update data: ' . mysql_error());
}
echo " Updated data successfully\n";

mysql_close($conn); } ?>

The website says it is saving, but the updated information won't show up in the database. Does anybody know what I am doing wrong in this situation? P.S. it is a auto update form without a button.

A: I suspect your problem is that your UPDATE query is trying to update a row that doesn't exist. A REPLACE query will insert data, or replace it if there is a conflict with a table key.
While you're fixing that, you may as well toss out the code you have above. Give me 30 seconds with that web page and I could erase your whole database. (For example, what would happen if someone posted Hours as foo' OR 1=1 OR 'foo?)
It's a matter of personal preference, but I find PDO much easier to work with. It's less verbose and allows for much easier building of prepared statements, which are an essential security measure for any web application. It also allows you to use modern error handling methods like exceptions.
<?php
/* this block could be in a separate include file if it's going to be reused */
$db_host = "localhost";
$db_name = "u7105d15197_main";
$db_user = "user";
$db_pass = "asldkfjwlekj";
$db_opts = array(
    PDO::ATTR_ERRMODE          => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false,
);
$conn = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass, $db_opts);

if(isset($_POST['formulier24'])) {
    $sql = "REPLACE INTO evenement SET userName = ?, hours = ?";
    $parameters = array($_POST["userName"], $_POST["hours"]);
    try {
        $stmt = $conn->prepare($sql);
        $result = $stmt->execute($parameters);
        $return = "Updated data successfully!";
    } catch (PDOException $e) {
        $return = "Could not update data! Error: " . $e->getMessage();
    }

    header("Content-Type: application/json");
    echo json_encode($return);
}


text:
Q: How to set background realy full of the page in HTML when i want to set the background for my page,  i coded like this code! But it's just quite close to be full , it still has a small " White BackGround " maybe only 5px or 7px on the right , left, top and bottom also :(
#background{8
    background-image: url('picture/background.jpg') ;
    background-repeat: no-repeat;
    width : 100%;
    height : 100%;
    background-size : cover;
    background-attachment: fixed;
    top : 0px;
    left : 0px;
}

A: Make sure that both the background div and whatever may be wrapping it has both margin and padding set to 0.

A: It should be because of default margin/padding added by browser.
So please add margin:0 and padding:0 as below
 #background{
    background-image: url('picture/background.jpg') ;
    background-repeat: no-repeat;
    width : 100%;
    height : 100%;
    background-size : cover;
    background-attachment: fixed;
    top : 0px;
    left : 0px;
    margin: 0;
    padding: 0;
}

else just
body {
  margin: 0;
  padding: 0;
}

A: Try adding margin:0; padding:0; as below:
#background{8
background-image: url('picture/background.jpg') ;
background-repeat: no-repeat;
width : 100%;
height : 100%;
background-size : cover;
background-attachment: fixed;
top : 0px;
left : 0px;
margin: 0;
padding: 0;
}


text:
Q: Failed executing DbCommand ON DELETE NO ACTION I am working on an ASP.NET Core project using code first I want to alter database design.
I have a case were I need to add two foreign keys to the same table, even I used DeleteBehavior.Restrict, still the error occurred when I update database.
Models:
 public class Languages
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Projects> PFromLanguages { get; set; }
        public virtual ICollection<Projects> PToLanguages { get; set; }
    }

public class Projects
    {
        public int Id { get; set; }
        public int FromLanguageId { get; set; }
        public int ToLanguageId { get; set; }

        public virtual Languages FromLanguage { get; set; }
        public virtual Languages ToLanguage { get; set; }

    }

Db Context:
  protected override void OnModelCreating(ModelBuilder builder)
  {

            builder.Entity<Projects>()
                .HasOne(p => p.FromLanguage)
                .WithMany(b => b.PFromLanguages)
                .HasForeignKey(b => b.FromLanguageId)
                .OnDelete(DeleteBehavior.Restrict);

            builder.Entity<Projects>()
                .HasOne(p => p.ToLanguage)
                .WithMany(b => b.PToLanguages)
                .HasForeignKey(b => b.ToLanguageId)
                .OnDelete(DeleteBehavior.Restrict);
  }

Migration:
 protected override void Up(MigrationBuilder migrationBuilder)
 {
           migrationBuilder.AddForeignKey(
                name: "FK_Projects_Languages_FromLanguageId",
                table: "Projects",
                column: "FromLanguageId",
                principalTable: "Languages",
                principalColumn: "Id",
                onDelete: ReferentialAction.Restrict);

            migrationBuilder.AddForeignKey(
                name: "FK_Projects_Languages_ToLanguageId",
                table: "Projects",
                column: "ToLanguageId",
                principalTable: "Languages",
                principalColumn: "Id",
                onDelete: ReferentialAction.Restrict);
  }

Error:
Failed executing DbCommand (17ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
ALTER TABLE [Projects] ADD CONSTRAINT [FK_Projects_Languages_FromLanguageId] FOREIGN KEY ([FromLanguageId]) REFERENCES [Languages] ([Id]) ON DELETE NO ACTION;

A:
I am working on an ASP.NET Core project using code first I want to
alter database design. I have a case were I need to add two foreign
keys to the same table, even I used DeleteBehavior.Restrict, still the
error occurred when I update database

This is officially known issue. Because Primary keys are mapped by default convention please have a look here. You can't have single collection referenced by two FKs. Projects is mapped without cascading delete because it doesn't work in these self referencing many-to-many. Therefore, We have two ways to handle this scenario thus the error:
1. Change one or more of the relationships to not cascade delete.
In this scenario, we could make the Projects relationship with Languages  optional by giving it a nullable foreign key property: for instance we can do something like:
.WillCascadeOnDelete(false);// Or you can try
.IsRequired(false)

Note: Either of one .WillCascadeOnDelete(false); or .IsRequired(false) should resolve your issue. You can check our official document for more details.
2. Configure the database without one or more of these cascade deletes,
then ensure all dependent entities are loaded so that EF Core can
perform the cascading behavior.
Considering this appreach we can keep the Projects, and Languages relationship required and configured for cascade delete, but make this configuration only apply to tracked entities, not the database: So we can do somethng like below:
protected override void OnModelCreating(ModelBuilder builder)
  {

            builder.Entity<Projects>()
                .HasOne(p => p.FromLanguage)
                .WithMany(b => b.PFromLanguages)
                .HasForeignKey(b => b.FromLanguageId)
                .OnDelete(DeleteBehavior.Restrict);
                .WillCascadeOnDelete(false);// Or .IsRequired(false)

            builder.Entity<Projects>()
                .HasOne(p => p.ToLanguage)
                .WithMany(b => b.PToLanguages)
                .HasForeignKey(b => b.ToLanguageId)
                .OnDelete(DeleteBehavior.Restrict);
                .WillCascadeOnDelete(false); // Or .IsRequired(false)
  }

Note: As you may know OnDelete(DeleteBehavior.ClientCascade); or ClientCascade allows the DBContext to delete entities even if there is a cyclic ref or LOCK on it. Please read the official guideline for more details here . In addition, as you haven't share your detele operation code while, executing your project make sure you are also removing language from context like here.

A: The error occurred because I am trying to modify the relations between tables while there are some records already inserted into the targeted tables which violating new foreign key.
The solution was simply to clear existing records in those tables and then apply the migration..
Thank you all for your kind support.


text:
Q: Weblogic Message Driven Bean reading from a secured queue @RunAs does not work I have a MDB very simple which works fine as long as the queue from where it reads messages is not secured
After I secure the Queue with a username it can;t read messages anymore
@MessageDriven(mappedName = "DistributedQueueTest")

public class MdbReceiver implements MessageListener {
@Resource
private MessageDrivenContext mdc;

@Override
public void onMessage(Message inMessage) {
TextMessage msg = null;
try {
msg = (TextMessage) inMessage;
System.out.println("Test MdbReceiver Message received : " + msg.getText());
} catch (JMSException e) {
e.printStackTrace();
mdc.setRollbackOnly();
}
}

}

I tried with all kind of @RunAs annotations
@weblogic.jws.security.RunAs(role="Joan",mapToPrincipal="ccc_user") where ccc_user is alowed to read messages from the queue
import javax.annotation.security.RunAs;
@RunAs("SomeRole") gives me an error on deployment
Unable to deploy EJB: MdbReceiver from mdbReceiver.jar: Expected role in mapping
Any idea how can i do this with annotations ? I tried even without annotations
...same the exeption in weblogic console is
weblogic.jms.common.JMSSecurityException: Access denied to resource: type=<jms>, application=UNIV_REC_Module, destinationType=queue, resource=DistributedQueueTest, action=receive
Thank you

A: I answer to my question cause i found a solution :
The problem is that annotations or are buggy in weblogic or are not implemented as I expected.
Solution is to do this without annotations in old style
so MDB is:
public class MdbReceiver implements MessageListener ,MessageDrivenBean{

    MessageDrivenContext mdc;

    @Override
    public void onMessage(Message inMessage) {
        TextMessage msg = null;
        try {
            msg = (TextMessage) inMessage;
            System.out.println("qwerty1");
            System.out.println("Test MdbReceiver Message received : " + msg.getText());
        } catch (JMSException e) {
            e.printStackTrace();
            mdc.setRollbackOnly();
        }
    }
    @Override
    public void ejbRemove() throws EJBException {
        // TODO Auto-generated method stub

    }
    @Override
    public void setMessageDrivenContext(MessageDrivenContext mdc) throws EJBException {
        this.mdc = mdc;

    }
}

Then we need two other files:
ejb-jar.xml
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd">
    <enterprise-beans>
        <message-driven>
            <ejb-name>MdbReceiver</ejb-name>
            <ejb-class>mdb.receiver.MdbReceiver</ejb-class>
            <transaction-type>Container</transaction-type>
            <message-destination-type>javax.jms.Queue</message-destination-type>
            <security-identity>
                <run-as>
                    <role-name>Loan</role-name>
                </run-as>
            </security-identity>
        </message-driven>
    </enterprise-beans>
    <assembly-descriptor>
         <security-role>
          <role-name>Loan</role-name>
         </security-role>
        <container-transaction>
            <method>
                <ejb-name>MdbReceiver</ejb-name>
                <method-name>onMessage()</method-name>
            </method>
            <trans-attribute>Required</trans-attribute>
        </container-transaction>
    </assembly-descriptor>

</ejb-jar>

and
weblogic-ejb-jar.xml
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-ejb-jar version="wls_10.3"
    xmlns="http://www.bea.com/ns/weblogic/weblogic-ejb-jar" xmlns:j2ee="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-ejb-jar http://www.bea.com/ns/weblogic/weblogic-ejb-jar.xsd http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd">
    <weblogic-enterprise-bean>
        <ejb-name>MdbReceiver</ejb-name>
        <message-driven-descriptor>
            <destination-jndi-name>DistributedQueueTest</destination-jndi-name>
        </message-driven-descriptor>
    </weblogic-enterprise-bean>
    <security-role-assignment>
        <role-name>Loan</role-name>
        <principal-name>test1234</principal-name>
    </security-role-assignment>

</weblogic-ejb-jar>

The role name does not matter as i can see the principal name is important.
It needs to have the rights to read from the secured queue

A: If you annotate your MDB as follows it should work:
@MessageDriven(name = "MdbReceiver", mappedName = "DistributedQueueTest")
@DeclareRoles({"Loan"})
@RolesAllowed("Loan")
public class MdbReceiver implements MessageListener {
...
}


text:
Q: Implications std::mutex unlock synchronizes with lock to reacquiring After answering this question, one thing bugged me again and made me nuts:
If a thread_1 is currently trying to lock a mutex and another thread_2 unlocks this mutex, is there a guarantee, that thread_1 will get the mutex, before thread_2 could try to lock it again.
To ensure the currently trying to lock, I assume that std::condition_variable::wait has a equivalent part to std::mutex::lock and is not just a while(try_lock())
I assume the answer is no, because of the varying scheduling std::mutex implementations. But I'm not sure and try to not be a reputation whore but,

*

*This question didn't had the currently trying to lock

*This question clarified the unlock/lock synchronizes with part but nothing about this general problem

I just want to be sure. Maybe I got paranoid.
Demonstration-Code:
#include <thread>
#include <atomic>
#include <mutex>
#include <condition_variable>
#include <cassert>

std::mutex lock;
std::condition_variable ensure_in_lock;
std::atomic<int> invariant = 1;

void thread_1(){
    while (true){
        std::unique_lock<std::mutex> ul(lock);
        invariant++;
        ensure_in_lock.wait(ul);
        invariant++;
    }
}

void thread_2(){
    while (true){
        lock.lock();
        assert(invariant > 0); //<- This should be, in theory, able to break, shouldn't it?!
        ensure_in_lock.notify_all();
        lock.unlock();
        invariant--;
    }
}

int main(void)
{
    std::thread t1(thread_1);
    /*
    //make sure t1 really had started like with thread_once or pratically with this
    std::this_thread::sleep_for(std::chrono::seconds(1));
    */
    std::thread t2(thread_2);

    while (true);
    return 0;
}

A:
If a thread_1 is currently trying to lock a mutex and another thread_2 unlocks this mutex, is there a guarantee, that thread_1 will get the mutex, before thread_2 could try to lock it again.

Not only is there no guarantee, but such a guarantee would mandate a maximally terrible implementation, maximizing context switches rather than minimizing them. If a thread can keep going, you want to let it keep going and use up its timeslice. You don't want to keep switching between two threads letting each thread make a tiny increment of progress.
One of the benefits of locks is that they tend to deschedule contending threads, allowing threads to run for longer periods without suffering performance loss due to contention. Such an interleaving requirement would negate this benefit.


text:
Q: libGdx constructor crashing parameter: Color I've created a class with an attribute Color.
public class CurveParticle {
    private Circle c;
    private boolean collidable;
    private Color color;

    public CurveParticle(Circle c, boolean coll){
        this.c = c;
        this.collidable = coll;
    }
    public Color getColor() {
        return color;
    }

    public void setColor(Color color) {
        this.color = new Color(color);
    }
}

The Color is from import com.badlogic.gdx.graphics.Color.
Whenever I try to set the color with a setter method, or even pass in the color to the constructor(I've removed the parameter in this example), it gives me this kind of an exception:
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: java.lang.NoSuchMethodError: com.me.Kurve.CurveParticle.setColor(Lcom/badlogic/gdx/graphics/Color;)V
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
Caused by: java.lang.NoSuchMethodError: com.me.Kurve.CurveParticle.setColor(Lcom/badlogic/gdx/graphics/Color;)V
    at com.me.Kurve.Kurve.show(Kurve.java:67)
    at com.badlogic.gdx.Game.setScreen(Game.java:62)
    at com.me.Screens.EnterGame.create(EnterGame.java:12)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:136)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)

Should I instead of that passing a float array or something. It's really weird because without the color parameter everything worked fine. I don't think I'm to blame here am I?

A: All of the other instances that I can find of this error have to do with out-of-sync or old jars. Example: I have this issue java.lang.NoSuchMethodError
The Java documentation supports this:

Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.
  Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.

Do you have the latest release of libgdx? You might want to try downloading the newest and replacing what you have.
Also, specifically check for duplicate versions in your project setup: Interpreting java.lang.NoSuchMethodError message
Did you build your project manually, or use the project setup helper tool?


text:
Q: Extend Default Configuration of vim I've been using the default configuration of vim for a while and want to make a few changes. However, if I edit ~/.vimrc it seems to overwrite all other configuration settings of /etc/vimrc and such, e.g. now there is no syntax highlighting. Here is what vim loads:
:scriptnames
/etc/vimrc
/usr/share/vim/vimfiles/archlinux.vim
~/.vimrc
/usr/share/vim/vim80/plugin/... <there are a few>

In other words I want to keep whatever there is configured in vim, but simply make minor adjustments for my shell user.
What do I need to do to somehow weave ~/.vimrc into the existing configuration or what do I need to put into ~/.vimrc so it loads the default configuration?
EDIT:
My intended content of ~/.vimrc:
set expandtab
set shiftwidth=2
set softtabstop=2

A: You can source the global Vim configuration file into your local ~/.vimrc:
unlet! skip_defaults_vim
source $VIMRUNTIME/defaults.vim

set mouse-=a

See :help defaults.vim and :help defaults.vim-explained for details.

A: What I found out is that the default config (default.vim) is not loaded if you create a ~/.vimrc file, so what I did was to put the contents of the default config into vimrc and to add the modifications at the end.
I am assuming you have vim8 and are using default configurations (i.e. you don't have a ~/.vimrc file)
Copy default config to your user vimrc file:
cp /usr/share/vim/vim80/defaults.vim ~/.vimrc
Then open your ~/.vimrc file and add your configs at the end of it.


text:
Q: ssrs 2008 - Pass a parameter value to a variable in the dataset I have a variable in my dataset that is used to decide which query to run, something like:
DECLARE @Flag char(1);

BEGIN
 IF @Flag = 1
 (
    -- Run query1
 )
 ELSE
 (
   -- Run Query2
 )

 END

In the report I want have a parameter, either a drop down or checkbox (I'll figure out which), that passes a 1 or 0 to the @Flag variable in the dataset so the correct query will run.
I have tried adding a parameter to the report, set to boolean, with the name @Flag, hoping it will make the connection, but I am getting an error saying @Flag needs to be declared.  I have tried some other things but tracking it with SQL profiler shows no value getting there.  How do I get a value from a parameter to a dataset variable?

A: If you're using a text query embedded in an SSRS report, you shouldn't need to DECLARE a parameter you're referencing in that query - just remove that statement.
If you have a parameter called Flag (note - no @) you should just be able to use this in the report Dataset query by referencing it as @Flag without DECLARE.


text:
Q: Mongo connecting to localhost although the conn string is right accross the app So I have an Node API hosted on AWS' Beanstalk and it's connected to a DocumentDB database hosted within the same VPC, unfortunately I can't share too much info on the project since I've inherited it, but currently we have a terrible logic of creating a new db for each tenant in the system so when they sign in we create a new mongoose connection (with the proper string). Upon that there is also a global connection to a central db which is supposed to be established upon the initial start of the API - this works as expected. What doesn't work for some reason is that whenever I make a request that's supposed to go through for a certain tenant I get the following error on AWS Beanstalk logs:
ERROR IMAGE
Unfortunately, I can't fully disclose the connection strings, but I can tell you that there are no references to "locahost" within the project (noted in the picture):
PROJECT SEARCH RESULT
Has anyone encountered similar issues ?


text:
Q: ¿Cómo se puede hacer sombra alargada con CSS? ¿Cómo puedo añadir una sombra alargada usando CSS como se ve en la imagen?

Tengo el siguiente código:

body{background-color:red;}

HOLA

A: La idea seria ir colocando una sombra tras otra, bajando y moviéndonos a la derecha pixel tras pixel.
Mira este ejemplo básico con sombras al 20px:

body {
  background: #FF2E2E;
}

.texto-sombra{
  font-size: 100px;
  font-weight: 900;
  color: #fff;
  text-shadow: 1px 1px #881010, 2px 2px #881010, 3px 3px #881010, 4px 4px #881010, 5px 5px #881010, 6px 6px #881010, 7px 7px #881010, 8px 8px #881010, 9px 9px #881010, 10px 10px #881010, 11px 11px #881010, 12px 12px #881010, 13px 13px #881010, 14px 14px #881010, 15px 15px #881010, 16px 16px #881010, 17px 17px #881010, 18px 18px #881010, 19px 19px #881010, 20px 20px #881010;
  }

hola

Entonces text-shadow agrega sombra, los valores Xpx Ypx #color indican dirección y color de las sombras. si deseas que la sombra se extienda mas debes de seguir agregando sombras.
Con sombras al 100px

body {
  background: #FF2E2E;
}

.texto-sombra{
  font-size: 100px;
  font-weight: 900;
  color: #fff;
  text-shadow: 1px 1px #881010, 2px 2px #881010, 3px 3px #881010, 4px 4px #881010, 5px 5px #881010, 6px 6px #881010, 7px 7px #881010, 8px 8px #881010, 9px 9px #881010, 10px 10px #881010, 11px 11px #881010, 12px 12px #881010, 13px 13px #881010, 14px 14px #881010, 15px 15px #881010, 16px 16px #881010, 17px 17px #881010, 18px 18px #881010, 19px 19px #881010, 20px 20px #881010,21px 21px #881010, 22px 22px #881010, 23px 23px #881010, 24px 24px #881010, 25px 25px #881010, 26px 26px #881010, 27px 27px #881010, 28px 28px #881010, 29px 29px #881010, 30px 30px #881010, 31px 31px #881010, 32px 32px #881010, 33px 33px #881010, 34px 34px #881010, 35px 35px #881010, 36px 36px #881010, 37px 37px #881010, 38px 38px #881010, 39px 39px #881010, 40px 40px #881010,41px 41px #881010, 42px 42px #881010, 43px 43px #881010, 44px 44px #881010, 45px 45px #881010, 46px 46px #881010, 47px 47px #881010, 48px 48px #881010, 49px 49px #881010, 50px 50px #881010, 51px 51px #881010, 52px 52px #881010, 53px 53px #881010, 54px 54px #881010, 55px 55px #881010, 56px 56px #881010, 57px 57px #881010, 58px 58px #881010, 59px 59px #881010, 60px 60px #881010,61px 61px #881010, 62px 62px #881010, 63px 63px #881010, 64px 64px #881010, 65px 65px #881010, 66px 66px #881010, 67px 67px #881010, 68px 68px #881010, 69px 69px #881010, 70px 70px #881010,71px 71px #881010, 72px 72px #881010, 73px 73px #881010, 74px 74px #881010, 75px 75px #881010, 76px 76px #881010, 77px 77px #881010, 78px 78px #881010, 79px 79px #881010, 80px 80px #881010,81px 81px #881010, 82px 82px #881010, 83px 83px #881010, 84px 84px #881010, 85px 85px #881010, 86px 86px #881010, 87px 87px #881010, 88px 88px #881010, 89px 89px #881010, 90px 90px #881010,91px 91px #881010, 92px 92px #881010, 93px 93px #881010, 94px 94px #881010, 95px 95px #881010, 96px 96px #881010, 97px 97px #881010, 98px 98px #881010, 99px 99px #881010, 100px 100px #881010;
  }

hola

Uff!! pero que largo y tedioso es hacer esto.
Si quieres reducir el codigo podrias utilizar sass junto a un pre compilador como Koala

A: Mi respuesta es más bien un añadido a la respuesta proporcionada por @Shassain.
Lo que intento decir en mi comentario es que podemos apoyarnos en los pseudo elementos :after y :before para reducir al menos al triple el código necesario para obtener la sombra sólida sobre el elemento de texto.
Por ejemplo:

body {
  background: #FF2E2E;
}

.texto-sombra{
  font-size: 100px;
  font-weight: 900;
  color: #fff;
  text-shadow: 1px 1px #881010, 2px 2px #881010, 3px 3px #881010, 4px 4px #881010, 5px 5px #881010, 6px 6px #881010, 7px 7px #881010, 8px 8px #881010, 9px 9px #881010, 10px 10px #881010, 11px 11px #881010, 12px 12px #881010, 13px 13px #881010, 14px 14px #881010, 15px 15px #881010, 16px 16px #881010, 17px 17px #881010, 18px 18px #881010, 19px 19px #881010, 20px 20px #881010,21px 21px #881010, 22px 22px #881010, 23px 23px #881010, 24px 24px #881010, 25px 25px #881010, 26px 26px #881010, 27px 27px #881010, 28px 28px #881010, 29px 29px #881010, 30px 30px #881010, 31px 31px #881010, 32px 32px #881010;
  }

.texto-sombra:after, .texto-sombra:before {
  content: attr(data-text);
  z-index: -1;
  color: #881010;
  position: absolute;
}

.texto-sombra:after {
  left: 33px;
  top: 33px;
}

.texto-sombra:before {
  left: 66px;
  top: 66px;
}

hola

Como se observa en el código, establezco los pesudo elementos :after y :before para que su posición inicial (definida por left y top coincida con el final de la sombra inicial aplicada sobre el elemento anterior.
En mi ejemplo las posiciones son:

texto-sombra -> texto-sombra:after -> texto-sombra:before

Y el código CSS original aplicado a texto-sombra se reduce de 100 definiciones a sólo 32.
Luego posiciono adecuadamente y de forma absoluta el elemento :after justo donde termina la última sombra:
/* pseudo clase :after */
left: 33px;
top: 33px;

Este elemento a su vez tendrá aplicada una sombra (definida en la clase padre), y cuya posición puedo determinar sumando 32 + 33, dando como resultado que el siguiente elemento lo debo posicionar en
/* pseudo clase :before */
left: 66px;
top: 66px;

Ya con esto logramos prácticamente el mismo efecto pero con menor cantidad de código.

A: Propongo una alternativa usando un ciclo en jQuery. Se que el OP habla de usar solo html y css, pero es válido tener varias opciones.
El código de jQuery está comentado.

//definir una variable como un string vacío
let propiedad = '';
//crear el ciclo y almacenar los valores en la variable
for(let i = 1; i <= 100; i++){
  propiedad += '#000 '+i+'px '+i+'px,';
}
//eliminar la última coma
let sombra = propiedad.slice(0,-1);
//agregar la propiedad al css
$('.sombra').css({'text-shadow': sombra});
body{
  background-color: red;
}

.sombra{
  font-size: 90px;
  font-family: Helvetica;
  text-align: center;
  color: white;
}

HOLA


text:
Q: Remove quotes when converting array to txt file using fputcsv in PHP I have an array where one of the items is an string, I need to download that array through the web navigator as a text file (.txt) but the string item is having quotes in the text file. It is presented as 0000362367 "00100 E0.1.1"
I would like to have the result without the quotes: 0000362367 00100 E0.1.1
Thanks in advance!
This is my PHP code:
                   $ar_result=array();
                    $ar=array();

                    $ar['u_id']= str_pad('362367', 10, "0", STR_PAD_LEFT);
                    $ar['NODO']='00100 E0.1.1';
                    $ar_result[]=$ar;

                    $ar['u_id']= str_pad('4352746', 10, "0", STR_PAD_LEFT);
                    $ar['NODO']='00100 E0.1.1';
                    $ar_result[]=$ar;

                    $filename = "test.txt";
                    $delimiter=" ";
                    header('Content-Type: application/txt');
                    header('Content-Disposition: attachment; filename="'.$filename.'";');
                    $handle = fopen('php://output', 'w');
                    foreach ($ar_result as $line) {
                       stream_filter_register("newlines", "StreamFilterNewlines");
                       stream_filter_append($handle, "newlines");
                        fputcsv($handle, $line, $delimiter);
                    }

class StreamFilterNewlines extends php_user_filter {
    function filter($in, $out, &$consumed, $closing) {

        while ( $bucket = stream_bucket_make_writeable($in) ) {
            $bucket->data = preg_replace('/([^\r])\n/', "$1\r\n", $bucket->data);
            $consumed += $bucket->datalen;
            stream_bucket_append($out, $bucket);
        }
        return PSFS_PASS_ON;
    }
}


text:
Q: How to find out what is breaking Apache2 in Ubuntu? I had Apache2 with MySQL and PHP working perfectly fine in Ubuntu. I ran the command
"sudo pecl install pdo_dobc",
restarted Apache and now wont display any pages on the server as if it didn't restart properly.
When I restarted I had a message saying "httpd (no pid file) not running."
Any help will be most appreciated.

A: /var/log/apache2/error.log will probably tell you exactly what's gone wrong.


text:
Q: Planning to use real time streaming video. Alternatives Having a site written under ASP.NET MVC framework which alternatvies are there to integrate it with real-time video streaming?
I've heard about IIS Smooth Streaming. Also I've heard that it isn't a good way to use ASP.NET MVC here? How this gets resolved in a real world applications?
Thanks!
Environment (supposed..)
Windows Server 2008 R2;
IIS 7;
But maybe it is possible to use some service on crossdomain, I mean on other platform which supports the kind of services..

A: I've found this thing, similar to my question: How to implement live video broadcasting in C#?. Still searching for alternatives.

A: Did you check ASPNET Video ? http://www.aspnet-video.com/

A: Why not using simply Vimeo hosting for your videos? https://vimeo.com/.
It is not free for commercial purposes, but it is cheap enough and it allows high resolution video. Probably it is cheaper that handling streaming on your IIS if you have not a big big traffic ad sveral several videos.


text:
Q: How to have a specific function break free from the setInterval loop> I have the following code with a setInterval() method. However there is one function in between i.e audio.play(). Whenever setInterval is called the whole function is called again and so the audio plays again and again. Is there any way of run the setInterval() method but have an exception for the audio.play part?
Here is the code
setInterval(async () => {
    //api stuff
    const detections = await faceapi
      .detectAllFaces(video, new faceapi.TinyFaceDetectorOptions());
    const resizedDetections = faceapi.resizeResults(detections, displaySize);
    const happy  =resizedDetections[0].expressions.happy;

    //The Issue  starts from here
    if(happy>0.9)
    {
      audio.src="audios/happy_audio.wav";
      audio.play();
    }

    faceapi.draw.drawDetections(canvas, resizedDetections);
    faceapi.draw.drawFaceExpressions(canvas, resizedDetections);
  },1000)
})

A: If you want it not to play while it is playing you could check and see if the audio is currently playing by checking the paused property in the conditional:
setInterval(async () => {
    //api stuff
    const detections = await faceapi
      .detectAllFaces(video, new faceapi.TinyFaceDetectorOptions());
    const resizedDetections = faceapi.resizeResults(detections, displaySize);
    const happy  =resizedDetections[0].expressions.happy;

    //The Issue  starts from here
    if(!audio.paused && happy>0.9)
    {
      audio.src="audios/happy_audio.wav";
      audio.play();
    }

    faceapi.draw.drawDetections(canvas, resizedDetections);
    faceapi.draw.drawFaceExpressions(canvas, resizedDetections);
  },1000)
})

if you just want it to fire once use a flag:
let flag = false;

setInterval(async () => {
    //api stuff
    const detections = await faceapi
      .detectAllFaces(video, new faceapi.TinyFaceDetectorOptions());
    const resizedDetections = faceapi.resizeResults(detections, displaySize);
    const happy  =resizedDetections[0].expressions.happy;

    //The Issue  starts from here
    if(flag && happy>0.9)
    {
      audio.src="audios/happy_audio.wav";
      audio.play();
      flag = true;
    }

    faceapi.draw.drawDetections(canvas, resizedDetections);
    faceapi.draw.drawFaceExpressions(canvas, resizedDetections);
  },1000)
})

Note I'm not a big fan of variable flags that are globally scoped. In the above case I would recommend a closure, or binding your asynchronous function to an Object that houses the flag, but as an example this should be sufficient :)

A: As it was already said in comments, better is to move outside setInterval the code you want to run once.
But if you really want to keep it inside, then you can use a boolean variable which will allow to run only once.
Here is how:
let isFirstRun = true;

setInterval(async () => {
    //api stuff
    const detections = await faceapi
      .detectAllFaces(video, new faceapi.TinyFaceDetectorOptions());
    const resizedDetections = faceapi.resizeResults(detections, displaySize);
    const happy  =resizedDetections[0].expressions.happy;

    //The Issue  starts from here
    if(isFirstRun) {
        isFirstRun = false;

        if(happy>0.9)
        {
          audio.src="audios/happy_audio.wav";
          audio.play();
        }
    }
    faceapi.draw.drawDetections(canvas, resizedDetections);
    faceapi.draw.drawFaceExpressions(canvas, resizedDetections);
  },1000)
})

A: I got it. So you want to stop the interval as soon as the happy index is > 0.9
let intervalID = setInterval(async () => {
    //api stuff
    const detections = await faceapi
      .detectAllFaces(video, new faceapi.TinyFaceDetectorOptions());
    const resizedDetections = faceapi.resizeResults(detections, displaySize);
    const happy  =resizedDetections[0].expressions.happy;

    //The Issue  starts from here
    if(!audio.paused && happy>0.9)
    {
      audio.src="audios/happy_audio.wav";
      audio.play();
      clearInterval(intervalID); // to stop next interval
      return; // to stop current interval
    }

    faceapi.draw.drawDetections(canvas, resizedDetections);
    faceapi.draw.drawFaceExpressions(canvas, resizedDetections);
  },1000)
})


text:
Q: First letter cuts off with Italic font in UITextField I have added italic font to UITextField with UITextAlignmentLeft. When user type character for e.g. "j", this character cuts off in left side. I have tried to add padding, custom textrectBounds & editingtextRectBounds but none of them works.

A: You can create a super-simple subclass of UILabel:
class PaddingLabel: UILabel {
    override func drawText(in rect: CGRect) {
        let insets = UIEdgeInsets(top: 0, left: 2, bottom: 0, right: 2)
        super.drawText(in: rect.inset(by: insets))
    }
}

Then, make your UILabel class to PaddingLabel and adjust the insets values depending on your needs.


text:
Q: Sum up the tree nodes using Java 8 Streams Is it possible to sum up the nodes of a tree using Java 8 streams, if possible in a one liner ?
Here is a node class
public class Node
{
private int nodeNum;
ArrayList<Node> children = new ArrayList<>();

public Node(int num)
{
    this.nodeNum = num;
}

public int getNodeNum()
{
    return nodeNum;
}

public boolean addNode(Node node)
{
    return children.add(node);
}

public ArrayList<Node> getNodes()
{
    return this.children;
}
}

Normal way to solve this is using a recursion and sum up the node , like the code below.
int getNodeSum(Node node)
{
    int total = 0;

    if(node.children.isEmpty())
        return node.getNodeNum();
    else
    {
        for(Node tempNode:node.children)
        {
            total+= getNodeSum(tempNode);
        }
        return total+node.getNodeNum();
    }
}

We can use streams to sum up the immediate child nodes but I'm not getting how to move deep and do it recursively using Streams.
This code only solves the problem to a single level. Any ideas?
total = list.stream().filter(Node -> node.children.isEmpty()).map(Node:: getNodeNum).reduce(node.getNodeNum(), (a,b) -> a+b);

A: One solution to your problem would be to use recursion along with Stream.flatMap.
First, you'd need to add the following helper method to your Node class:
public Stream<Node> allChildren() {
    return Stream.concat(
        Stream.of(this),
        this.children.stream().flatMap(Node::allChildren)); // recursion here
}

This returns a Stream<Node> whose elements are this node and all its descendant nodes.
Then, you could rewrite your getNodeSum method as follows:
int getNodeSum(Node node) {
    return node.allChildren()
        .mapToInt(Node::getNodeNum)
        .sum();
}

This uses the above defined Node.allChildren method along with the Stream.mapToInt and IntStream.sum methods to calculate the total sum.

Alternatively, you could have a Function<Node, Stream<Node>> descendants attribute in your Node class that performs the recursion in place:
private Function<Node, Stream<Node>> descendants =
    node -> Stream.concat(
        Stream.of(node),
        node.children.stream()
            .flatMap(this.descendants)); // recursion here: function invoked again

This is a recursive lambda expression, since the function you are defining is at both sides of the = sign. This kind of lambda expressions are allowed only as attributes of a class, i.e. you cannot assign a recursive lambda expression to a local variable.
With that recursive function in place, you could rewrite the allChildren method as follows:
public Stream<Node> allChildren() {
    return descendants.apply(this);
}

Finally, the code for your getNodeSum method would be identical to the previous version:
int getNodeSum(Node node) {
    return node.allChildren()
        .mapToInt(Node::getNodeNum)
        .sum();
}

Note: while this approach might result attractive for some people, it might have some drawbacks, i.e. now every instance of the Node class has the descendants attribute, despite not being needed at all. You could circumvect this i.e. by having a Tree class with this recursive function as an attribute, and Node being an inner class (with the descendants attribute removed).

A: You need to add recusive method for Node class, which wil be join child streams
public Stream<Node> recursiveConcat() {
    return Stream.concat(
        Stream.of(this),
        children.stream().flatMap(Node::recursiveConcat));
}

Then do -
root.recusiveConcat().mapToInt(Node::getNodeNum).sum()

whole code
public class Node {

    private int nodeNum;
    ArrayList<Node> children = new ArrayList<>();

    public Node(int num) {
        this.nodeNum = num;
    }

    public int getNodeNum() {
        return nodeNum;
    }

    public boolean addNode(Node node) {
        return children.add(node);
    }

    public ArrayList<Node> getNodes() {
        return this.children;
    }

    public Stream<Node> recursiveConcat() {
        return Stream.concat(
                Stream.of(this),
                children.stream().flatMap(Node::recursiveConcat));
    }
}

Node root = new Node(1);
Node node1 = new Node(2);
Node node2 = new Node(3);
Node node3 = new Node(4);
node2.addNode(node3);
node1.addNode(node2);
root.addNode(node1);
System.out.println(root.recursiveConcat().mapToInt(Node::getNodeNum).sum());


text:
Q: python list comprehension products I'm trying to build a specific list comprehension to take data from list of lists/matrix A and matrix B to generate a third matrix, C.  I've annotated the code and provided the expected outcome, but as written, the list comprehension doesn't do what's expected and can can be expressed in more elegant code than I've attempted here.  Xt=transposed matrix X, Xs=sorted matrix X
# matrix A with row headings and values
A = [('Apple',0.95,0.99,0.89,0.87,0.93),
('Bear',0.33,0.25.0.85,0.44,0.33),
('Crab',0.55,0.55,0.10,0.43,0.22)]

#matrix B with row headings and values
B = [('Apple',1.00.0.99,1.00,0.95,0.99),
('Bear',0.99,0.99,0.99,0.99,0.99),
('Crab', 0.05,0.19,1.00,0.55,0.89)]

#transpose matrix A and B
At=zip(*A)
Bt=zip(*B)

#generate a new empty matrix, C, and give it the same heading labels as A and B
Ct=At[0:1]

#delete the heading labels on transposed matrices A and B
del At[0]
del Bt[0]

#List Comprehension Code
#multiply all the numbers in row [x] (i.e., apples) for matrix A = apple product A
#multiply all the numbers in row [x] for matrix B = apple product B
#A matrix row [x] product / B matrix row [x] product B = apple value for matrix C
#append apple value under apple heading
#do this for bear rows and crab rows, too
Ct.append((prod(x) for x in zip(*At))/(prod(x) for x in zip(*Bt)))

#untranspose matrix C to match the heading, value configuration of original matrices
C=zip(*Ct)

#sort matrix C rows in descending order based on comprehension [i][1] values
Cs = matrix(sorted(C, key=lambda item: item[1], reverse=True))

The final output should look like this for matrix Cs based on current values for matrix A and B:
'Apple' 0.7191   #(matrix A apple row product = 0.6696 / matrix B apple row product = 0.9311)
'Crab'  0.6170   #(matrix A crab row product = 0.0029 / matrix B cat row product = 0.0047)
'Bear'  0.0098   #(matrix A bear row product = 0.0093 / matrix B bear row product = 0.9510)

A: I'm not sure I understand what you're asking for, might be missing something.
Your posted code is replete with syntax errors and undefined functions.
However, this does what I think you're asking for, but with different results:
>>> from operator import mul
>>> A = [('Apple',0.95,0.99,0.89,0.87,0.93),('Bear',0.33,0.25,0.85,0.44,0.33),('Crab',0.55,0.55,0.10,0.43,0.22)]
>>> B = [('Apple',1.00,0.99,1.00,0.95,0.99),('Bear',0.99,0.99,0.99,0.99,0.99),('Crab', 0.05,0.19,1.00,0.55,0.89)]
>>> C = [ (a[0],reduce(mul,a[1:])/reduce(mul,b[1:])) for (a,b) in zip(A,B) ]
>>> C
[('Apple', 0.72737272727272728), ('Bear', 0.010706894358222457), ('Crab', 0.6153755174452985)]

Additionally:
Or what if I just dropped matrix B altogether and C 'Apple' row would equal:
0.95*0.99*0.89*0.87*0.83?
>>> prodA = [ (a[0],reduce(mul,a[1:])) for a in A ]
>>> prodA
[('Apple', 0.67725310950000006), ('Bear', 0.010182150000000001), ('Crab', 0.0028616500000000003)]

And
How would I modify this to obtain the product of each row for each A element divided by its paired B element? i.e., the C 'Apple' row would equal:
[('Apple', (0.95/1.00) * (0.99/0.99) * (0.89/1.00) * (0.87/0.95) * (0.93/0.99)]
>>> A_by_B = [ [x[0][0]]+[i/j for (i,j) in x[1:]] for x in [ zip(a,b) for (a,b) in zip(A,B) ]]
>>> A_by_B
[
 ['Apple', 0.94999999999999996, 1.0, 0.89000000000000001, 0.9157894736842106, 0.93939393939393945],
 ['Bear', 0.33333333333333337, 0.25252525252525254, 0.85858585858585856, 0.44444444444444448, 0.33333333333333337],
 ['Crab', 11.0, 2.8947368421052633, 0.10000000000000001, 0.78181818181818175, 0.24719101123595505]
]
>>> prod_A_by_B = [ (x[0],reduce(mul,x[1:])) for x in A_by_B ]
>>> prod_A_by_B
[('Apple', 0.72737272727272728), ('Bear', 0.010706894358222457), ('Crab', 0.61537551744529861)]

Each value of each row of A divided by that of B, then the product of each row, is the same as the product of each row of A divided by the product of each row of B.


text:
Q: Does clang on Mac not support uniform initialization? Is clang on Mac not support uniform initialization?
I tried compiling following code, But compiler raise a error.
#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<int> v = {3, 1, 9, 4};
    std::cout << v[1] << std::endl;
}

Error:
vector.cpp:9:22: error: non-aggregate type 'std::vector<int>' cannot be initialized with an initializer list
    std::vector<int> v = {3, 1, 9, 4};
                     ^   ~~~~~~~~~~~~
1 error generated.

OS: macOS 10.12.4
compiler version:
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.5.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

A: I suspect you are not compiling the code as C++11/14 (-std=c++11 or -std=c++14)? If not; do that. Clang does support what you are trying to do.


text:
Q: Read ElementList with optional parent tag using SimpleXml I need to read an ElementList that sometimes is wrapped in an outer element but can also exist without the outer wrapper. Specifically, this is about reading testsuites in a JUnit report.
They can exist as list of testsuites with outer wrapper:
<testsuites>
    <testsuite>
        <testcase></testcase>
        <testcase></testcase>
    </testsuite>
    <testsuite>
        <testcase></testcase>
    </testsuite>
</testsuites>

...but testsuite can also stand alone like this:
<testsuite>
    <testcase></testcase>
    <testcase></testcase>
</testsuite>

How could this be modelled as classes with the corresponding annotations? I can only get it to work with one or the other structure, but I struggle with the "optional" testsuites element.
The goal is to get a list of testsuite elements no matter how many there are or if the outer testsuites element exists.
I am using SimpleXml library to deserialize the XML file and it feels like this is a simple use case, but I could not find any solution so far.


text:
Q: Algebraic structures of greater cardinality than the continuum? Are there interesting algebraic structures whose cardinality is greater than the continuum? Obviously, you could just build a product group of $\beth_2$ many groups of whole numbers to get to such a structure, but the properties of this group seem to be not very different from those you get when you just put together $\beth_1$ many whole number groups here.

A: The MO question Martin is referring has several good examples of algebraic structures larger than the continuum; one that I did not see talked about there is Conway's field of surreal numbers.
The surreal numbers form a proper class, so their cardinality dwarfs the cardinality of any set.

A: This MO question "Cardinalities larger than the continuum in areas besides set theory" has recieved a couple of interesting answers, also algebraic ones (e.g. Zariski cotangent space of a manifold which is not smooth, automorphism tower length of a group)

A: The set $\beta\mathbb{N}$ of ultrafilters on $\mathbb{N}$ is not only a topological structure, but also an algebraic structure as well which is partialy compatible with the topological structure of $\beta\mathbb{N}$ (i.e. it is continuous in one variable). If $\mathcal{U},\mathcal{V}$ are ultrafilters on $\mathbb{N}$, then define an ultrafilter $\mathcal{U}+\mathcal{V}$ by letting $R\in\mathcal{U}+\mathcal{V}$ if and only if
$\{n|\{m|m+n\in R\}\in\mathcal{U}\}\in\mathcal{V}$. With this operation, $\beta\mathbb{N}$ becomes a well known semigroup of cardinality $2^{2^{\aleph_{0}}}$.
Also, Boolean algebras are interesting structures, but the cardinalities of Boolean algebras are often greater than the continuum. For instance, the weakly compact and strongly compact cardinals can be characterized in terms of Boolean algebras. An inaccessible cardinal $\kappa$ is strongly compact if and only if every Boolean algebra $B$ that satisfies the identity $$\bigwedge_{i\in I}\bigvee_{j\in J_{i}}x_{i,j}=\bigvee_{f}\bigwedge_{i\in I}x_{i,f(i)}$$ (where $|I|<\kappa,|J_{i}|<\kappa$ and $f\in\prod_{i\in I}J_{i}$) has a $\kappa$-complete ultrafilter. There is a similar characterization of weakly compact cardinals since for weakly compact cardinals the above holds only when $|B|\leq\kappa$.


text:
Q: How do I convert XML to JSON AWS API Gateway? I am trying to use Amazon's AWS API gateway to front legacy SOAP services with REST.  I am able to take a resource request and basically hard code SOAP request in a Body Mapping Template.  The SOAP service is called and the XML SOAP response is returned. So far so good.
In the Integration Response, I need to take this SOAP envelope (Basically just XML) and map that back to the JSON model.  I don't see how this can be done, but I must be missing something. The following code will get the raw response, but I don't see any way to access the elements:
#set($inputRoot = $input.path('$'))
{
 $input.body
}

Imagine my response looks like this:

<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
   <SOAP-ENV:Body>
      <ns1:getProdResponse xmlns:ns1="urn:productlist">
         <code xsi:type="xsd:string">100</return>
         <message xsi:type="xsd:string">this is a book</return>
      </ns1:getProdResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Then in a Body Mapping Template, I want to do something like this:
#set($inputRoot = $input.path('$'))
{
    "response-code" : "$input.Envelope.Body.getProdResponse.code",
    "response-message" : "$input.Envelope.Body.getProdResponse.message"
}

I know I can probably write a Lambda function to call the SOAP service, but that just doesn't seem reasonable.  Am I out of luck?

A: API Gateway does not currently support direct transformation of XML response bodies.  This is a commonly requested feature and is on our backlog, so it will likely get implemented eventually.  In the meantime, the only option is to us a Lambda function to call your SOAP back end, parse the response, and return JSON to API Gateway.


text:
Q: How to convert a xls/xlsx file using Syncfusion in C# I am getting the System out of memory exception. The size of my xls file is 357 mb. I am not sure what has to be configured to allow opening of heavy files.
I'm refering to the documentation available on this website https://help.syncfusion.com/file-formats/xlsio/excel-to-pdf-conversion
The stacktrace is as below:

at Syncfusion.XlsIO.Parser.Biff_Records.BiffContinueRecordRaw.ExtractContinueRecords()
     at Syncfusion.XlsIO.Parser.Biff_Records.MSODrawingGroupRecord.ParseStructure()
     at Syncfusion.XlsIO.Parser.Biff_Records.BiffRecordRawWithArray.ParseStructure(DataProvider provider, Int32 iOffset, Int32 iLength, ExcelVersion version)
     at Syncfusion.XlsIO.Parser.Biff_Records.BiffRecordRaw.FillRecord(BinaryReader reader, DataProvider provider, IDecryptor decryptor, Byte[] arrBuffer)

Please let me know if any information required.
Edit 2:
Code
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
**IWorkbook workbook = application.Workbooks.Open(src_file, ExcelOpenType.Automatic);**
ExcelToPdfConverter converter = new ExcelToPdfConverter(workbook);

The line at which the exception occurs has been marked with asteriks

A: We can reduce the usage of the memory consumption by using "ParseWorksheetsOnDemand" . Please refer the UG for more details, we have also discussed similar issue in the forum.
For further validation please provide us your input document through the Direct-Trac, we will analyze it further and provide more details.


text:
Q: How to access variable dynamically from vars.yml in ansible? I have below vars/main.yml file
OS_Version:
 Ubuntu:
    os_distro: "ubuntu"
    min_os_distro_version: 18
 Oracle:
  os_distro: "oraclelinux"
  min_os_distro_version: 7
Centos:
  os_distro: "centos"
  min_os_distro_version: 7

How do I pick these variales (os_distro and min_os_distro_version) based on target os? I tried below in tasks/main.yml but looks like ansible is checking each and every key.
- name: Get OS distribution
  debug:
    msg: "{{ ansible_distribution }}"
  register: os_type

- name: show dictionary
  ansible.builtin.debug:
    msg: "{{item.key}}: {{item.value}}"
  with_dict: "{{ OS_Version }}"

- name: Check OS distribution
  ansible.builtin.assert:
    that: ansible_distribution | lower == "{{ item.value.os_distro }}" if {{ item.key }} == {{ os_type.msg }}
    msg: "Expected {{ item.value.os_distro }} OS"
  with_dict: "{{ OS_Version }}"

I tried to run against oracle linux, below is the error
msg: 'The conditional check ''ansible_distribution | lower == "ubuntu" if Ubuntu == OracleLinux'' failed. The error was: Invalid conditional detected: invalid syntax (<unknown>, line 1)'


text:
Q: Cannot instantiate a PDO object in PHP MVC framework Can anyone help me with this?
I have this function in a singleton class. The error it is giving me back is that it cannot find the class.
First I thought it had something to do with the autoloader, but I did spl_autoload_unregister('libloader') and it still gives the same error?
The host is running php 5.
public static function getInstantie()
    {
        if (!self::$instantie)
        {
            $config = config::getInstantie();
            $db_type = $config->config_waarden['database']['db_type'];
            $hostnaam = $config->config_waarden['database']['db_hostnaam'];
            $dbnaam = $config->config_waarden['database']['db_naam'];
            $db_wachtwoord = $config->config_waarden['database']['db_wachtwoord'];
            $db_gebruikersnaam = $config->config_waarden['database']['db_gebruikersnaam'];
            $db_poort = $config->config_waarden['database']['db_poort'];

        self::$instantie = new PDO("$db_type:host=$hostnaam;port=$db_poort;dbname=$dbnaam",$db_gebruikersnaam, $db_wachtwoord);
            self::$instantie-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        return self::$instantie;
    }

thanks, Richard

A: is that function inside of a class that extends PDO? If not, can you try to make that function inside of a class that extends PDO and instead of self call the functions using keyword parent?

A: PDO is enabled by default with a set of database drivers:
http://au.php.net/manual/en/pdo.installation.php
But the build of PHP you are working with could have it disabled. Autoloading will have no effect on whether or not the PDO class will be found.
Create a PHP info file and check to see if the PDO section exists. If it doesn't, then your issue is most likely because it wasn't built into your php installation.


text:
Q: Finding similar items based on attributes I've been reading online and saw references to KNN to determine if an item is similar to other items. But it seems like KNN categorizes where an item belongs. I was thinking more in terms of given a movie
[director: "Henry Shingles", Starring-Actor: "Will Smith", Release-Date: "Jan 1828"]

I could find movies with similar attributes.
For example, the algorithm might return
[director: "Henry Shingles", Starring-Actor: "Will Smith", Release-Date: "Dec 1977"]

instead of
[director: "Henry Shingles", Starring-Actor: "Poop Macey", Release-Date: "Dec 1977"]

Because the former has two attributes "Henry Shingles" and "Will Smith" that matches.
Would Cosine Similarity work in my case?

A: KNN can be used for classification or regression. Categorizing would be classification, and it seems that you need regression.
Defining a right metric for KNN is an important part.
With the data that you provided, I don't think cosine similarity will work well. Usually, you would create a binary vector of all the features for an item, and the compare using cosine similarity. However, in your case Date is given as "Dec 1977", that means as that "Nov 1977" will be different feature, and the only way for similarity on Date to show up would if the movies were released in the same month, and you would be losing information. You probably would need to write something custom for dates.


text:
Q: Select the first element from a drop down with dynamically changing values Selenium Python Image of Dropdown
Description - Select the first element from the drop down on "Available Slots". The values of the drop down keeps changing. I am not able to select the first value. I am able do upto clicking on the drop down to see the elements using selenium. I am stuck there
Few observations -

*

*The IDs for the li tags keep changing.

*There is a ul li section on the code with the slots and also below there is "select" tag with multiple "option" tags with the available slots. I am confused as to which specific webelement's xpath I have to use.

Here below is the entire html code for the section I am working on. What can I do to select the first element from the dropdown.

<input class="select-dropdown dropdown-trigger" type="text" readonly="true" data-target="select-options-d78257d9-b2fd-a3cd-1678-8db6a678a01e">**

Select Slot

12pm-3pm

3pm-6pm

**<svg class="caret" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"></path><path d="M0 0h24v24H0z" fill="none"></path></svg><select name="id_slot" required="" tabindex="-1"><option value="" disabled="" selected="">Select Slot</option><option value="2">12pm-3pm</option><option value="3">3pm-6pm</option></select>

PS - All Ids are dynamically changing, so can't use that as an identifier
Few tries I have done and failed -

*

*Used Action Chains to send the down arrow. Manually when I do it, if I just press the down arrow and enter, it will select the option I want. Maybe we could simulate Down then Enter. But not working - It doesn't move to the option I want

body = driver.find_element("xpath","//*[@id='schedule_modal']/form/div[1]/div/div/div[4]/div/select")
body.send_keys(Keys.DOWN)

*

*Tried using the select tag by value and index. I get this error

select = Select(driver.find_element("xpath","//*[@id='schedule_modal']/form/div[1]/div/div/div[4]/div/select"))
driver.implicitly_wait(100)
select.select_by_value('1')
Message: element not interactable: Element is not currently visible and may not be manipulated


text:
Q: Auto added primary key trying to insert the value of NULL I have a Django site, and am using windows auth for it. When I try to logon as a new user it gives the error Cannot insert the value NULL into column 'id', table 'table.auth_user'; column does not allow nulls. INSERT fails. One other thing to mention is that that I have a separate db for my Auth (but the AuthDB is the default one).
models.py
class AuthUser(models.Model):
    password = models.CharField(max_length=128)
    last_login = models.DateTimeField(blank=True, null=True)
    is_superuser = models.BooleanField()
    username = models.CharField(unique=True, max_length=150)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=150)
    email = models.CharField(max_length=254)
    is_staff = models.BooleanField()
    is_active = models.BooleanField()
    date_joined = models.DateTimeField()

    class Meta:
        managed = False
        db_table = 'auth_user'

    def __str__(self):
        return self.username

In settings.py
DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': 'AuthDB',
        'HOST': 'MyHost',
        'USER': '',
        'PASSWORD': '',
        'OPTIONS': {
            'driver':"ODBC Driver 13 for SQL Server",
            },
        'CONN_MAX_AGE': 60,
    },

I am not sure why django is trying to insert the value of NULL into the the auto added primary key id. Maybe I am missing something? Does anyone have any idea why?
Thanks for the help!


text:
Q: file_get_contents HTTP request failed! HTTP/1.1 501 Method Not Implemented I am trying to grab some information from a json ecoded page, however I'm receiving the HTTP/1.1 501 Method Not Implemented error while assigning the value to the variable $data
   if(isset($_GET['xblaccount'])) {
        $gamertag = htmlspecialchars(strip_tags($_GET['xblaccount']));
        $url = 'http://www.xboxleaders.com/api/profile.json?gamertag=' . urlencode($gamertag);
        $data = file_get_contents($url);
   }

I've also tried
   $gamertag = 'kfj32j8fj23f';

And receive the same error

A: This is an interesting question because the code does work if you use an actual account name (e.g. Stallionh83 or Major Nelson).
Having discovered this I then checked the headers in a browser (FF) which also returned the 501 response header. I assume therefore that this is then a server side response for non-accounts.
Bearing that in mind I suggest editing your code to:
if(isset($_GET['xblaccount'])) {
    $gamertag = htmlspecialchars(strip_tags($_GET['xblaccount']));
    $url = 'http://www.xboxleaders.com/api/profile.json?gamertag=' . urlencode($gamertag);
    $data = @file_get_contents($url); // @ to suppress the warning
    if($data){
        //Account exists...
    }
    else{
        //Account doesn't exist...
    }
}

$data will return FALSE if the account doesn't exist, otherwise it will return the JSON string.


text:
Q: AccessViolationException goes away when native code debugging is enabled I get an AccessViolationException when I run the Google Drive API sample in Visual Studio 2012 on Windows 7 x64. My project is targeting .Net 4.5.  I get the exception on line 185:
await service.Files.Delete(file.Id).ExecuteAsync();

*

*It happens in both Debug and Release modes, and in all platforms (x86, x64, AnyCPU).

*It does NOT happen when I run without the debugger attached ("Start without Debugging").

*It does NOT happen when I enable the "Enable native code debugging" in the Project properties.

Any ideas why enabling native code debugging might prevent the exception?
Note: running the sample requires the NuGet package (prerelease): Google.Apis.Drive.v2

EDIT: I wish Google people would chime in and tell if they've seen this as well because the sample instructions say:

*

*Open the GoogleApisSamples.sln with Visual Studio

*Click on Build > Rebuild Solution

*Execute the .exe in Drive.Sample\bin\Debug

which is weird since they go out of their way to execute the exe directly from the debug folder instead of just saying "Run the sample".

A: It is just a shot in the dark, but I had a similar issue which turned out to be caused by the visual studio hosting process.
you can disable it and see if anything has changed.
You can do it from Project properties > Debug > uncheck the Enable the visual studio hosting service

A: I also had this problem although with a completely different project. for me the initial problem was that the wrapper library was a .net 2 assembly and my application was a .net 4 app. When i changed the wrapper to .net 4 i started getting stackunbalancedExceptions instead.
This turned out to because the callingconvention (and perhaps the charset) property for the DllImports was not set correctly. Once i fixed this i no longer get any exceptions in .net 4, however i still get them when compiling the wrapper library as .net 2.
There might be a compat settings that can make it work with mixed 2/4 framework, but since i was able to recompile i haven't really checked.


text:
Q: "Soft link" element in HTML Suppose that there is a given HTML subtree which is repeated across multiple points in my code:

    ...

This is repeated many times

    ....

This is repeated many times

    ...

This is repeated many times

Is there a way to create a kind of "soft link" for the first
 so that each repetition could just point to it? Or there is a better alternative for this kind of problem?
Update
It seems that my question is unclear, So I will try to clarify it by giving an example of a imaginary solution. Suppose that HTML provides an <alias>, which acts like a pointer to another element. So, instead of repeating the same element over and over, I could do something like that:

    ...

This is repeated many times

    ....
    <alias from='repeat'/>
    ...
    <alias from='repeat'/>

And the HTML would be rendered in the same way.

A: So, as @Cerbrus and @bfavaretto have commented, the answer unfortunally is no, there is no way to use something such as an <alias> without resorting to JavaScript. Since search engines ignore JavaScript, they would ignore part of the page, and that would really be bad for the site as a whole.

A: Try this:

    ...

This is repeated many times

    ...

This is repeated many times

    ...

This is repeated many times

Link to the first <p> tag.

Example

A: If I've understood the question.
same as others : cant do this in HTML.
because HTML havnt alias tag!
but i think it could be doing with linking "js" and "html events".
you must write a bridge.
for example: set id for your tagS. and set "change like event" for your alias tag!
and write a bridge js function to your ID.


text:
Q: insert a bash like widget into gtk When you write a program in c which has a lot of printf for a lot purpose: debuggin, information, etc. I would like to do something like that in gtk, having some widget that would display all the printf messages I usually would do in a normal c program
Thanks,
---UPDATE---
I'm using vte as ptomato advised. Although some problems came up.
I was using glade-3 and when the file glade was open the vte widget didn't show. I notice that a lot of Warning and 2 Critical errors would display while opening. One of those critical was
Unable to load module 'vte' from any search paths

I installed libvte-dev throug apt-get and know i see as in the widget palette

A: You can use VTE, a terminal emulator widget. I'm not sure, but I think you can redirect your program's stdout to the widget using vte_terminal_set_pty().

A: You can use asprintf() as a GNU extension to perform formatted output which it is stored in a new allocated memory and must be freed later.
char* str;
asprintf(&str, "It is a number %d\n", 1);
//...
free(str);

Instead that one, you can use snprintf() which didn't allocate anything for you, it just fill an array of chars for you (as a formatted output).
char str[100];
snprintf(str, 100, "It is number %d\n", 1);

Also you can use g_string_printf() which is a glib function, but it stores the formatted output to a GString variable.
GString str;
g_string_printf(&str, "It is number %d\n", 1);
//...
g_string_free(&str, TRUE);

When you got your string as a formatted output, you can use it as a text for any GTK widget.

A: You can either create a text view or use the label.
Add this text view to the parent window say Gtk Main window. You can decide which other widgets to add. (may be a scroll window and then a text view).
Use the api gtk_text_view_set_buffer to display the text on to the window everytime you want to display a log.

A: You should simply use a GtkTextView and use these functions to redirect your logging into it:

*

*g_log_set_default_handler() for g_message()/g_warning()/etc. (everything that goes through g_log())

*g_set_print_handler() (for g_print())

*g_set_printerr_handler() (for g_printerr())

Unfortunately, the simple printf() cannot be redirected easily (but g_print() is a good replacement for it).
PS: Sorry, I can only paste one link for you (new user)…


text:
Q: Data loss when loop-mounting a file on removable USB storage If I plug in a USB and modify files and unplug it I don't lose data. However if I use mount on a file on the USB I WILL lose data. What's with that? Is there anything I can do to prevent loss of data? It's weird that I can write a file and pull my usb out w/o loss of data but when using mount I will lose data. Here's the example
echo "Data Data Data" > /media/your-usb/data
#unplug your usb. plug into another computer
#you'll see you didn't lose any data

#Create a file, put ext4 filesystem on it
dd if=/dev/zero of='/media/your-usb/test.bin' count=100000;
losetup /dev/loop0 /media/your-usb/test.bin
mkfs.ext4 /dev/loop0
losetup -d /dev/loop0

#Mount FS
mkdir m
mount -o loop /media/your-usb/test.bin m

echo Test > m/test
umount m
#No loss of data

mount -o loop ./test.bin m
echo Test2 > m/test2
#wait a moment. You'd think the data will  flush

#unplug your USB
umount m
#plug your USB
mount -o loop ./test.bin m
cat m/test2 #error test2 is not a file

A: When Linux detects a removable drive, it's smart enough to know that it should flush the data frequently. When you're mounting a loopback, it doesn't know that the backing device is a file which could be removed at any time.
You can force the system to not cache writes using:
mount -o loop,sync /media/your-usb/test.bin m

This will result in slower performance, and also note this warning about wear and tear from the man mount page:
   sync   All  I/O to the filesystem should be done synchronously. In case
          of media with limited number of write cycles  (e.g.  some  flash
          drives) "sync" may cause life-cycle shortening.

An alternative would be to at least run sync before removing the device if you don't want to umount for some reason.

A:
If I plug in a USB and modify files and unplug it I don't lose data.

Correction: you haven't lost data yet. That you've noticed.
Presumably you, your distribution or the maintainer of the automounting program that you use has configured removable USB storage devices to be mounted with the sync option, which causes data to be written out immediately. The sync option has the advantage of writing out all data so that it isn't lost if the storage medium is pulled out suddenly or the system crashes, but it has many downsides:

*

*Flash-type storage will wear out sooner, because the data is written a few bytes at a time but the storage can only be updated by writing fairly large blocks each time, so each block ends up being rewritten many times. This can kill basic USB drives quickly.

*A filesystem that isn't unmounted properly will be marked as dirty. You can't distinguish a filesystem that was marked as dirty but contains consistent data from one that was pulled out in the middle of a write and contains inconsistent data. This doesn't apply to filesystems like FAT which don't have a "dirty" indicator.

*It's slower — potentially a lot slower.

Don't use sync. Unmount your devices before unplugging them.


text:
Q: How to find current limit or resistance of current path that is a polygon in PCB? I'm trying to understand what is the relevant path of current when I use polygons for PCB design.
Edit: I'm particularly interested in the current limit in that path without destroying it. Please ignore the thermal reliefs. I'll be removing them soon.
So in this example, I would like to know the current limits for the path connecting the two points of node A. I know the height of the copper, I'm assuming the length would be a straight line connecting them. But what is the "width" here?

Also, how different is the answer to above if the shape is not so nice. i.e. :

Examples/explanations using pictures would be appreciated.
I'm using Altium designer. Is there a built-in tool from there to do measure current limit or resistance between two contacts?

A: I would calculate the resistance due to the thermal reliefs, and the resistance due to the vias (if you want to include the vias in the path under consideration). The resistance due to the polygon will be negligible compared to these resistances.
If you want to figure out the contribution of the polygon anyway, first figure out the surface resistance of your copper, in ohms per square (You'll find that the resistance between opposite edges of a square of copper sheet will be equal, regardless of the size of the square). Then break up the polygon roughly into squares between the two vias. Then figure out the resistance between the two vias in terms of series and parallel combinations of copper squares.
Or, if you want a more accurate result, you'll need to resort to a finite elements model. This can also account for "spreading resistance" around the vias.


text:
Q: Is the discrete uniformity the only complete uniformity on the discrete topology? Here's a simple statement about uniformities that seems like it has to be true but which I can't quite seem to prove at the moment.  Say $X$ is a uniform space, and suppose 1. that $X$ is complete and that 2. considered as a topological space, $X$ is discrete.  Does $X$ have to be discrete as a uniform space?
Thank you all!
Edit: As per Mike F's answer, the statement is actually false.

A: A metric space is:

*

*topologically discrete if, for all $x$, there exists $\epsilon_x > 0$ such that $d(x,y)<\epsilon_x$ implies $x=y$. Equivalently, there is no accumulation point in the space.

*uniformly discrete if there exists a global $\epsilon > 0$ such that $d(x,y)<\epsilon$ implies $x=y$. Turning this around, a metric space is not uniformly discrete if and only if the distance function takes on arbitrarily small positive values.

We want a metric space which is (1) complete, (2) topologically discrete, (3) not uniformly discrete. Let's try to achieve this with a subspace $X \subseteq \mathbb{R}$, with the standard metric structure. Let $A$ denote the set of accumulation points of $X$ in $\mathbb{R}$.

*

*$X$ is complete if and only if it is closed in $\mathbb{R}$, i.e. $A \subseteq X$.

*$X$ is topologically discrete if and only if has no accumulation point in $X$, i.e. $A \cap X = \varnothing$.

*Combining the above, $X$ is complete and topologically discrete if and only if $A = \varnothing$.

So our goal is:

Find a subset $X$ of $\mathbb{R}$ which has no accumulation points in $\mathbb{R}$ and arbitrarily small positive distances between points.

Now that we know what we're looking for, it's not hard to think of examples. Here's one possiblity.

Take $X = \mathbb{N} \cup \{ n + \frac{1}{n} : n \in \mathbb{N}\}$, in the standard absolute value metric. Then $X$ is a complete metric space which is topologically discrete but not uniformly discrete.