text:
Q: How to compare the schema of two dataframes in SQL statement? There are many ways to verify the schema of two data frames in spark like here. But I want to verify the schema of two data frames only in SQL, I mean SparkSQL.
Sample query 1:
SELECT DISTINCT target_person FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME IN ('columnA','ColumnB') AND TABLE_SCHEMA='ad_facebook'

Sample query 2:
SELECT count(*) FROM information_schema.columns WHERE table_name = 'ad_facebook'

I know that there is no concept of a database (schema) in spark, but I read about metastore that it contains schema information etc.
Can we write SQL queries like above in SparkSQL?
EDIT:
I am just checking why show create table is not working on spark sql, is it because it's a temp table?
scala> val df1=spark.sql("SHOW SCHEMAS")
df1: org.apache.spark.sql.DataFrame = [databaseName: string]

scala> df1.show
+------------+
|databaseName|
+------------+
|     default|
+------------+

scala> val df2=spark.sql("SHOW TABLES in default")
df2: org.apache.spark.sql.DataFrame = [database: string, tableName: string ... 1 more field]

scala> df2.show
+--------+---------+-----------+
|database|tableName|isTemporary|
+--------+---------+-----------+
|        |       df|       true|
+--------+---------+-----------+

scala> val df3=spark.sql("SHOW CREATE TABLE default.df")
org.apache.spark.sql.catalyst.analysis.NoSuchTableException: Table or view 'df' not found in database 'default';
  at org.apache.spark.sql.catalyst.catalog.SessionCatalog.requireTableExists(SessionCatalog.scala:180)
  at org.apache.spark.sql.catalyst.catalog.SessionCatalog.getTableMetadata(SessionCatalog.scala:398)
  at org.apache.spark.sql.execution.command.ShowCreateTableCommand.run(tables.scala:834)
  at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:58)
  at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:56)
  at org.apache.spark.sql.execution.command.ExecutedCommandExec.executeCollect(commands.scala:67)
  at org.apache.spark.sql.Dataset.<init>(Dataset.scala:182)
  at org.apache.spark.sql.Dataset$.ofRows(Dataset.scala:67)
  at org.apache.spark.sql.SparkSession.sql(SparkSession.scala:623)
  ... 48 elided

A: Schema can be queried using DESCRIBE [EXTENDED] [db_name.]table_name
See https://docs.databricks.com/spark/latest/spark-sql/index.html#spark-sql-language-manual

A: Try this code of extracting each schema and compare. This compares name of column, datatype of column, nullable or not column.
val x = df1.schema.sortBy(x => x.name) // get dataframe 1 schema and sort it base on column name.
val y = df2.schema.sortBy(x => x.name) // // get dataframe 2 schema and sort it base on column name.

val out = x.zip(y).filter(x => x._1 != x._2) // zipping 1st column of df1, df2 ...2nd column of df1,df2 and so on for all columns and their datatypes. And filtering if any mismatch is there

if(out.size == 0) { // size of `out` should be 0 if matching
    println("matching")
}
else println("not matching")

A: We can get the schema in 2 ways in SparkSQL.
Method 1:
spark.sql("desc db_name table_name").show()

This will display only top 20 rows which is exactly similar to the dataframe concept of df.show()

(meaning, any table with more than 20 columns - schema will be shown
  only for first 20 columns)

For Ex:
+--------------------+---------+-------+
|            col_name|data_type|comment|
+--------------------+---------+-------+
|                col1|   bigint|   null|
|                col2|   string|   null|
|                col3|   string|   null|
+--------------------+---------+-------+

Method 2:
spark.sql("desc db_name table_name").collect().foreach(println)

This will display the complete schema of all the columns.
For Ex:
[col1,bigint,null]
[col2,string,null]
[col3,string,null]


text:
Q: Line is not drawn (It seems that pygame.draw.polygon is not running) I made Button frame. But Square is not drawn.
class button:
    def __init__(self,screen,size): # size -->(width,height)
        self.width = size[0]
        self.height = size[1]
        self.screen = screen
    def Buttongenerate(self,TEXT,POS):
        font = pygame.font.Font(None,self.height//3)
        text = font.render(TEXT,True,(250,250,250))
        textsize = font.size(TEXT)
        TEXTPOS = [self.width+(self.width-textsize[0])/2,\
           self.height+(self.height-textsize[1])/2]
        self.screen.blit(text,TEXTPOS)
        pygame.draw.polygon(self.screen, (250,250,250), [[POS[0],POS[1]],\
        [POS[0]+self.width,POS[1]],[POS[0]+self.width,POS[1]+self.height],\
        [POS[0],POS[1]+self.height]], 2)

while True:
    screen.fill((0,0,0))
    buttontest2 = button(screen,(200,100))
    buttontest2.Buttongenerate("TEST",(200,200))
    pygame.display.flip()
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            exit(0)

When I run this code , but It seems that pygame.draw.polygon is not running

A: pygame.draw.polygon works just fine.
Your problem is that you calculate TEXTPOS wrong (I just guess the text should be rendered inside the rectangle). You should use
TEXTPOS = [POS[0]+(self.width-textsize[0])/2, POS[1]+(self.height-textsize[1])/2]

which actually uses POS to calculate the final position of the text.
Otherwise, the text is rendered above the rectangle. Here's the full, running code:
import pygame
pygame.init()
screen = pygame.display.set_mode((600,600))
class button:
    def __init__(self,screen,size): # size -->(width,height)
        self.width = size[0]
        self.height = size[1]
        self.screen = screen
    def Buttongenerate(self,TEXT,POS):
        font = pygame.font.Font(None,self.height//3)
        text = font.render(TEXT,True,(250,250,250))
        textsize = font.size(TEXT)
        TEXTPOS = [POS[0]+(self.width-textsize[0])/2, POS[1]+(self.height-textsize[1])/2]
        self.screen.blit(text,TEXTPOS)
        pygame.draw.polygon(self.screen, (250,250,250), [[POS[0],POS[1]],[POS[0]+self.width,POS[1]],[POS[0]+self.width,POS[1]+self.height],[POS[0],POS[1]+self.height]], 2)

while True:
    screen.fill((0,0,0))
    buttontest2 = button(screen,(200,100))
    buttontest2.Buttongenerate("TEST",(200,200))
    pygame.display.flip()
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()

Note that it would be better to create a new surface for the text and rectangle once instead of loading the font, rendering the text, and drawing on the screen surface every iteration of the main loop.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wikitude not working after apply proguard Wikitude is not working after applying proguard. There is no error in log.
If I remove proguard then it works fine.

A: Please try:

-keep class com.wikitude.** { *; }

Find more details at the proguard website.


text:
Q: New-AzPolicyDefinition Creation of Azure policy definition through PowerShell I am trying to create a Azure policy definition but getting error. This JSON code is taken from a built-in script from Azure policy "IP Forwarding on your virtual machine should be disabled"
Below is my script
$Policy=
'{
  "properties": {
    "displayName": "Disable-IP-Forwarding",
    "policyType": "Custom",
    "mode": "All",
    "description": "Disable-IP-Forwarding-Test.",
    "metadata": {
      "version": "1.0.1",
      "category": "Security Center"
    },
    "parameters": {
      "effect": {
        "type": "String",
        "metadata": {
          "displayName": "Effect",
          "description": "Enable or disable the execution of the policy"
        },
        "allowedValues": [
          "AuditIfNotExists",
          "Disabled"
        ],
        "defaultValue": "AuditIfNotExists"
      }
    },
    "policyRule": {
      "if": {
        "field": "type",
        "in": [
          "Microsoft.Compute/virtualMachines",
          "Microsoft.ClassicCompute/virtualMachines"
        ]
      },
      "then": {
        "effect": "[parameters('effect')]",
        "details": {
          "type": "Microsoft.Security/complianceResults",
          "name": "disableIPForwarding",
          "existenceCondition": {
            "field": "Microsoft.Security/complianceResults/resourceStatus",
            "in": [
              "Monitored",
              "OffByPolicy",
              "Healthy"
            ]
          }
        }
      }
    }
  },
  "id": "/providers/Microsoft.Authorization/policyDefinitions/Disable-IP-Forwarding",
  "type": "Microsoft.Authorization/policyDefinitions",
  "name": "Disable-IP-Forwarding"
}'

$definition = New-AzPolicyDefinition    -Name "Disable-IP-Forwarding"  -Description "Disable-IP-Forwarding-Test." -Policy $Policy

Below are the pictures from Powershell showing error.1 & 2
https://i.stack.imgur.com/Ttj4w.png
https://i.stack.imgur.com/K0JCv.png
I also tried with removing single quotes in policy rule as in here(click Here)
**Error: After removing Single quote **
New-AzPolicyDefinition : InvalidPolicyRule : Failed to parse policy rule: 'Could not find member 'properties' on object of type 'PolicyRuleDefinition'. Path 'properties'.'.
CorrelationId: 7e754d56-2e8e-4323-8650-ae620bb60573
At line:70 char:15

*

*... efinition = New-AzPolicyDefinition    -Name "Disable-IP-Forwarding"   ...

*
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

*

*CategoryInfo          : CloseError: (:) [New-AzPolicyDefinition], ErrorResponseMessageException

*FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzurePolicyDefinitionCmdlet

A: As per the documentation, When you create the Policy definition using New-AzPolicyDefinition PowerShell Command . Your policy definition should be in the below format:
{
    "parameters": {
      "effect": {
        "type": "String",
        "metadata": {
          "displayName": "Effect",
          "description": "Enable or disable the execution of the policy"
        },
        "allowedValues": [
          "AuditIfNotExists",
          "Disabled"
        ],
        "defaultValue": "AuditIfNotExists"
      }
    },
    "policyRule": {
      "if": {
        "field": "type",
        "in": [
          "Microsoft.Compute/virtualMachines",
          "Microsoft.ClassicCompute/virtualMachines"
        ]
      },
      "then": {
        "effect": "[parameters('effect')]",
        "details": {
          "type": "Microsoft.Security/complianceResults",
          "name": "disableIPForwarding",
          "existenceCondition": {
            "field": "Microsoft.Security/complianceResults/resourceStatus",
            "in": [
              "Monitored",
              "OffByPolicy",
              "Healthy"
            ]
          }
        }
      }
    }
}

You can pass the description, mode, metadata, display name as the parameters in the command.
Another problem, removing the single quotes and passing "[parameters(effect)]", this will give you another error. So the best way to pass the policy definition is saving it in the json file and pass the path to the command.
$definition = New-AzPolicyDefinition    -Name "Disable-IP-Forwarding"  -Description "Disable-IP-Forwarding-Test." -Policy "D:\Learning\policy1.json"

A: I figured it out as per in below link, used a Here-String for the JSON body:
[link] (powershell.org/2019/04/hear-hear-for-here-strings)


text:
Q: How do I disable (video) thumbnails in Windows 7? I'd like to turn off Windows 7 (video) thumbnails displayed in Explorer.  I found this solution for Windows XP but it doesn't work for Windows 7 ("The module shmedia.dll failed to load").
Disable thumbnails in Windows XP?

A: To disable video thumbnails only, download and run ShellExView (a great system tool from NirSoft).
Disable the "MF XXX Property Handler" lines. Close and restart explorer windows. You are done :)
screenshot:

A: There are a couple of potential options.

*

*Open Explorer/Tools/Folder options/View and check the first box Always show icons, never thumbnails

*You can customize the way way each folder controls the display of the objects within. Right click on a folder and choose Properties then Customize In the drop down list for Optimize this folder for, select General items

*Changing the View type will work too.


text:
Q: Overhead in running multiple pods vs multiple (identical) processes in 1 pod? Context
I am running a job-processing task (specifically, Resque) in a kubernetes setup. This task sets up one or more workers to takes job messages off a queue and processes them. A typical invocation is to set your desired worker count, e.g. COUNT=8 QUEUE=* resque:work.
Of course, in Kubernetes, I am going to add autoscaling to the Deployment running this task.
There's a prevailing recommendation to run 1 process per pod (see below). My concern is that doing so can be wasteful when the process I wish to run has a built-in multi-process management system to run identical processes. I am trying to understand the theory & docs to inform decisions and experiments.
My motivation question is: is there any reason to continue setting worker count, or does it make more sense to use only one worker process per pod? I.e. is there significant overhead in each pod instance compared to letting Resque spawn multiple processes?
Question
The objective question is: where should I expect / look for overhead in running 1 process per pod vs letting 1 pod's main process spawn multiple children?
E.g. IIUC each pod is running its own version of the OS and other utils installed in the container. So that at least is some memory overhead vs running a single container, single OS, mutli-Resque-worker setup; is that correct? What else should I be looking at, prior to simply benchmarking a bunch of guesses, to model resource consumption for this setup?
More Context
I understand that small process count allows for more granular scaling. I don't consider scaling at a finer resolution than, say, 4 processes at a time to be much benefit, so I'd start there if pod overhead should be considered. Am I overthinking it, and should I forget about pod overhead and just use a worker count of 1 per pod?
This question is informed off of many "one process per pod" references out there. Many listed in this similar question and a stack exchange question linked therein.

*

*The linked question was concerned with scaling processes inside a pod to optimize node compute usage, which I get is well managed by k8s already

*The nested links are more about limiting to one concern per pod, which is the case in my question.

My question is about overhead of running 4 identical worker processes in 4 pods vs in 1 pod.

A: Either way is fine and I wouldn't expect it to make a huge difference, except maybe at large scale.
There is nothing architecturally wrong with running multiple worker tasks inside a single container, particularly within a framework that's specifically designed to do it.  As you note it's usually considered good form to run one concern per container, and there are various issues with running multiple processes (recovering from failed processes, collecting logs); but if you have a system that's specifically designed to launch and manage subprocesses, running it in a container is fine.
The questions I'd start asking here are around how many Resque workers you're planning to run at the same time.  If it's "thousands", then you can start hitting limits around the number of pods per node and pressure on the Kubernetes scheduler.  In that case, using multiple workers per container to cut down the number of pods can make some sense.  If it's "dozens" then limiting it to just one could make it a little easier to visualize and manage.
Starting up a new container can be somewhat expensive (I'm used to seeing 30-60s startup times, but depending heavily on the image) but having a running container isn't especially so.  It looks like Resque has a manager process on top of some number of workers so you'll have those extra Rubies, but that's probably not significant memory or storage.


text:
Q: How can I align a form label to the right of the control in Bootstrap 4? How can I align a form label to the right of the form control in Bootstrap 4.0, as per the "rooms" or "people" labels below:

Using the code below, it just comes out underneath:

    meeting rooms required
    <input type="textbox" id="roomsno" class="form-control col-md-4" type="number" />
    rooms

Here is my current code as a JsFiddle:
http://jsfiddle.net/nmg196/b4nqd5a6/4/

A: So.. there are a lot of ways to do that.
The one which I think better suits here is
add display: flex to the css for form-group class
For your jsfiddle example

      number of delegates

        <input type="textbox" ID="e1" class="form-control col-md-2" type="number" />
         people

CSS :
    .form-group1 {
      display: flex
 }

A: Add ml-auto to the label class attribute

A: You need to add a text-align: leftstyle to .control-label.
Because bootstrap gives labels within horizontal forms the text align style using the selector .form-horizontal .control-label, you need to use the same or a more specific selector:
.form-horizontal .control-label{ text-align: left !important; }
OR
Just add inline style="text-align: left" to your label.
Use "!important", if you need it to overwrite some default style to this.
Thanks!


text:
Q: Centre the nav bar I need to centre the links and logo in my navbar. I know one cannot centre it using float.
nav {
    float:left;
    padding:12px 0 0 0;

}

About Us

Services

Gallery

Contacts

A: Try this JSFiddle
CSS:
nav{
    text-align:center;
}

li{
    display:inline-block;
    padding:12px 0 0 0;
    vertical-align:middle;
}

A: If you know the width of your nav bar, you can use:
nav {
    width: 200px;
    margin: 0px auto;
}

JSFiddle: http://jsfiddle.net/4N6Wy/

A: You have to:
1) Wrap everything left from it in a class like "float-left", everything right in "float-right"
2) Float the two wrappers.
3) Then set
    nav { text-align: center; }

A: Try this: http://jsfiddle.net/RZ3ES/
nav {
    padding:12px 0 0 0;
    overflow: auto;
    text-align: center;
}

nav ul {
    display: inline-block;
    margin: 0 auto;
}

nav ul li {
    list-style-type: none;
    float: left;
}


text:
Q: Should moderators, who directly close a question, be forced to leave a comment? Moderators can directly close a question. This is OK, but I think it would be useful if they would be forced to leave a comment, if they do so.
I understand, that users who vote to close should not be forced. This is OK, because in this case there are several people with the same opinion, so the reason for the closure should be mostly obvious. But in case of direct closing by a moderator the situation might be not that clear.
Therefore I would suggest: Moderators should be able to vote to close a question whithout being forced to leave a comment. And they should be able to directly close a question, but then it should be mandatory (or encouraged?) to leave a comment.
What do you think?

A: This is already done in a sense —
When a question is closed without comment on a beta site, the system automatically flags the post to be sure someone is checking that there is sufficient guidance around any action taken. It's not forced, per se, because frankly, there are many times it is not needed.
There may already be sufficient discussion around the closure, or the reason for the closure may simply be self-evident. Leaving useful comments is good community/moderation practice in general, but forcing someone to leave a comment regardless of the surrounding circumstances could just be noise and busy work… where understanding the best practices of community moderation in general should be sufficient.

A: I don't think that's necessary (or productive).
The most common cases are already covered by the close reason messages (which have been improved quite a bit recently).
And in those rare cases where that alone is unclear, the moderator can still leave a comment.
And if it's really unclear, you can still raise a question on Meta.

A: It's expected that if a moderator takes a course of action that is not obviously prescribed by the quality or content of a post in the context of the explanation of the close reason that they'll leave a comment. If we were to make commenting mandatory when a single binding vote was used, we'd be putting metaphorical weights around the ankles of our moderators
Moderators have a saying, comments save lives, and they are consistently good at leaving them when they suspect that their decision might be called into question later. There will always be times when the reason for an action was so obvious to them that they fail to do this, but it's not very often.
Users have the ability to do the following things if they desire an explanation for, or wish to contest the actions of a moderator (preferably, in this order):

*

*Leave a comment to the moderator asking why the action was taken

*If unsatisfied, post a discussion on their meta site to see if the community agrees with the closing

*If still unsatisfied, contact us, the Stack Exchange community team directly

If a situation ever arose where a moderator misused their binding vote consistently enough to warrant a feature like this, then the proper course of action would be to find out why they felt that they need to take these actions, and get to the broader root of the problem - a point at which we'd definitely be involved.

A: I don't believe we should be forced to, but there are reasons why we sometimes will and sometimes won't leave a comment on a post.
I try to leave a comment when I close a question organically.  For instance, I just closed this question, and I left multiple comments explaining the problem.
The reason I [try to] leave a comment when I'm closing a question organically (as opposed to reacting to flags in the moderator queue) is that normally no one else has left a comment, and so it's conceivable the OP could be confused as to why their question is closed.  It's also because people tend to react more adversely to a moderator closing a question than they are if five people close it.
For me, putting a question 'on hold' is a way to help improve the community.  We get thousands of questions per day, and not nearly enough of them are in the shape we need them to be in to be useful to others.  By putting a question on hold, we enforce these minimum standards and shape behavior towards putting enough information in the question that others can solve it.
It's controversial, but it probably shouldn't be.

A: On beta sites, when a question is closed without a comment, the system automatically raises a flag to nag moderators into posting a comment. This happens whether the question is closed by 5 users, by a moderator, or any combination.
As a moderator on a beta sites, I find this flag almost always useless. I understand that it might sometimes prod inexperienced moderators to provide explanations, but in my experience, it isn't necessary. When I close a question, I usually have already left a comment, or have upvoted an existing a comment, or am about to post a comment, or have decided that the close reason was sufficient explanation. In my experience of Stack Exchange in general, I find it rare that a question that needs a comment on closure lacks that comment by the time five people have voted or a moderator has become involved.
Closures by a moderator are not less obvious than closures by non-moderators. If anything, moderators refrain to intervene in ambiguous cases, and have more training to explain their decisions, so questions closed by a moderator are more likely to either have a comment or not require one.


text:
Q: FPDF lib to create PDF for data with multiple pages This code works perfectly while creating a PDF for data that only fits on the first page. However, on getting on the second page everything disorganizes and and can not create proper PDFs. Even the data on the first page disorganizes.
Anyone help me sort this such that any data from page two leads to proper pdfs. Thank you.
<?php
ob_start();
require('fpdf/fpdf.php');

//database connection

//Select the Products you want to show in your PDF file
$result= mysqli_query($conn, "SELECT * FROM customer");

$number_of_products = mysqli_num_rows($result);

//Initialize the  columns and the total
$column_id = "";
$column_name = "";
$column_trans_id = "";

//For each row, add the field to the corresponding column
while($row = mysqli_fetch_array($result))
{
    $id = $row["id"];
    $name = $row["name"];
    $trans_id = substr($row["trans_id"],0,20);

    $column_id = $column_id.$id."\n";
    $column_name = $column_name.$name."\n";
    $column_trans_id = $column_trans_id.$trans_id."\n";
}
mysqli_close();

//Create a new PDF file
$pdf=new FPDF();
$pdf->AddPage();

//Fields Name position
$Y_Fields_Name_position = 20;
//Table position, under Fields Name
$Y_Table_Position = 26;

//First create each Field Name
//Gray color filling each Field Name box
$pdf->SetFillColor(232,232,232);
//Bold Font for Field Name
$pdf->SetFont('Arial','B',8);
$pdf->SetY($Y_Fields_Name_position);
$pdf->SetX(0);
$pdf->Cell(10,6,'ID',1,0,'L',1);
$pdf->SetX(10);
$pdf->Cell(30,6,'NAME',1,0,'L',1);
$pdf->SetX(40);
$pdf->Cell(20,6,'TRASACTION ID',1,0,'L',1);
$pdf->SetX(60);

$pdf->Ln();

//Now show the  columns
$pdf->SetFont('Arial','',8);
$pdf->SetY($Y_Table_Position);
$pdf->SetX(0);
$pdf->MultiCell(10,6,$column_id,1);
$pdf->SetY($Y_Table_Position);
$pdf->SetX(10);
$pdf->MultiCell(30,6,$column_name,1);
$pdf->SetY($Y_Table_Position);
$pdf->SetX(40);
$pdf->MultiCell(20,6,$column_trans_id,1);
$pdf->SetY($Y_Table_Position);
$pdf->SetX(60);

//Create lines (boxes) for each ROW (Product)
//If you don't use the following code, you don't create the lines separating each row
$i = 0;
$pdf->SetY($Y_Table_Position);
while ($i < $number_of_products)
{
    $pdf->SetX(0);
    $pdf->MultiCell(60,6,'',1);
    $i = $i +1;
}
ob_end_clean();
$pdf->Output();
ob_end_flush();
?>

A: The problem with your code is that you are putting all the result rows from the database into multi-line strings, and creating only one cell per column, which is bad. The cells may extend to more than one page. When adding a cell, it will start on the page the previous cell extended to. While it is possible to go back to the page where the table started, this is not the preferred way of outputting tables in FPDF.
A more common approach is to add a set of cells for each result rows you got from the database. This saves you the second iteration for painting the cell borders, and a lot of re-positioning.
<?php
require('fpdf/fpdf.php');

// Connect to database...

// Define your columns like so:
$columns = array(array("name" => "id",             "width" => 10),
                 array("name" => "name",           "width" => 30),
                 array("name" => "transaction_id", "width" => 20));

$pdf = new FPDF();
$pdf->AddPage();

// Table header
$pdf->SetFillColor(232, 232, 232);
$pdf->SetFont('Arial', 'B', 8);
foreach ($columns as $column)
{
    $pdf->Cell($column['width'], 6, strtoupper($column['name']), 1, 0, 'L', 1);
}
$pdf->Ln();

// Table rows
$pdf->SetFont('Arial', '', 8);
$result = mysqli_query($conn, "SELECT id, name, transaction_id FROM customers");
while ($row = mysqli_fetch_assoc($result))
{
    foreach ($columns as $column)
    {
        $pdf->Cell($column['width'], 6, $row[$column['name']], 1);
    }
    $pdf->Ln();
}

// Clean up
mysqli_free_result($result);
mysqli_close($conn);

$pdf->Output();


text:
Q: javac error message does not display entire filepath When using javac (or the ant task ), the error message does not include the entire filepath, it only includes the file name. For example,
$ javac src/path/to/Filename.java
Filename.java:1: package foo.bar does not exist
import foo.bar.Baz;
              ^

What I would like is,
$ javac src/path/to/Filename.java
src/path/to/Filename.java:1: package foo.bar does not exist
import foo.bar.Baz;
              ^

My problem is that vim quickfix does not work if it's not given the entire filepath, not just the filename. With just the filename, a new empty file is opened up after running :make.
I'm using:

*

*Debian wheezy

*openjdk-6-jdk v6b23~pre7-1

*javac v1.6.0_23

A: I don't think there is a simple way to do this.
However, I believe that there is a complicated way.  It basically involves writing your own compiler runner that makes use of a JDK installation's ability to load and run the Java compiler inside of a running program.  You need to implement a lot of stuff, but the key thing is a diagnostic processor that formats the compiler error messages in the way that you need them to be formatted.
Here are some relevant links:

*

*Package javax.tools - provides interfaces for tools which can be invoked from a program, for example, compilers.

*JavaCompiler - the interface implemented by the compiler

*FileObject - the interface that the compiler uses to represent source files; e.g. in diagnostics.  Note the toUri() method!


text:
Q: Characters formatting in Python I'm beginner to Python ... I'd like to format the characters in Python using basic concepts and operations of Tuples and Lists as below ...

*

*I enter 10 digit number and except last 4 digits remaining all the numbers should be replaced by 'X'. For e.g.

number = 1234567890

Expecting output as -

number = XXXXXX7890

*How to mask entered characters / numbers in Python using Tuples/Lists concept not using by importing any modules or existing high functions. Is it possible ?
For e.g. entered some characters , those should be masked using * (asterisk) or # (hashed) while entering. For e.g.

password : pa55w0rd

Expecting output while entering password as -

password : ********

OR

password: ########

A: It is always better to use built-in modules for things sensitive like password. One way of doing is following:
import getpass

number = 1234567890
first = 'X' * max(0,len(str(number)[:-4]))
last = str(number)[-4:]

n = first + last
print(n)

# part 2
p = getpass.getpass(prompt='Enter the number : ')

if int(p) == 123:
    print('Welcome..!!!')
else:
    print('Please enter correct number..!!!')

If you don't want to display typed password just print:
print('######')

It does not have to be of the same length you just have to print something.

A: Break down what's needed: you need to convert to a string, to figure out how many characters to replace, generate a replacement string of that length, then include the tail of the original string.  Also you need to be robust against, eg, strings too short to have any characters replaced.
'X' * max(0, len(str(number)) - 4) + str(number)[-4:]

For the second part: use a library.
Doing this directly is more complicated than it might seem to a beginner, because you're having to communicate with the systems which take text entry.  It's going to depend upon the operating system, Windows vs "roughly everything else".  For text entry outside of a web-browser or a GUI, most systems are emulating ancient text-only terminal devices because there's not yet enough reason to change that.  Those devices have modes of text input (character at a time, line at a time, raw, etc) and changing them to not immediately "echo" the character typed involves some intricate system calls, and then other programming to echo a different character instead.
Thus you're going to want to use a library to take care of all those intricate details for you.  Something around password entry.  Given the security implications, using tested and hardened code instead of rolling your own is something I strongly encourage.  Be aware that there are all sorts of issues around password handling too (constant time comparisons, memory handling, etc) such that as much as possible, you should avoid doing it at all, or move it to another program, and when you do handle it, use the existing libraries.
If you can, stick to the Python standard library and use getpass which won't echo anything for passwords, instead of printing stars.
If you really want the stars, then search https://pypi.org/ for getpass and see all the variants people have produced. Most of the ones I saw in a quick look didn't inspire confidence; pysectools seemed better than the others, but I've not used it.


text:
Q: Study continuity of $f$ from $\mathbb{R}\times \mathbb{Z} \to \mathbb{R}$.
Let $X=\mathbb{R}\times \mathbb{Z}$ and $\tau$ the product topology $\tau_u \times \tau_{CF}$ where $\tau_u$ is the usual topology on $\mathbb{R}$ and $\tau_{CF}$ the cofinite topology on $\mathbb{Z}$. Study the contiuity of $f : (X, \tau)\to (\mathbb{R},\tau_u)$ defined as
  $$(t,k)\mapsto t-k$$

What I tried was fixing the point $(t,k)=(0,0)$ and taking a general neighbourhood of $f(t,k)=0$ like $(-\varepsilon, \varepsilon)$ and a neighbourhood of $(0,0)$ like the product of $(-\delta, \delta)$ and $\mathbb{Z} \setminus \{1\}$ where $\varepsilon <\delta$. Then, take $r$ such that $\varepsilon < \delta -r$. Then
$$f(\delta -r, 0)=\delta -r > \varepsilon$$
so
$$f((-\delta, \delta) \times (\mathbb{Z}\setminus \{1\} )) \not \subset (-\varepsilon, \varepsilon)$$
and then $f$ is not continous.
But I'm not sure at all if this is right, so if you could help me with that I'd be grateful. Thanks in advance!

A: You have the right general idea, but you've not executed it quite right. In order to show that $f$ is not continuous at $\langle 0,0\rangle$, it's enough to find one open nbhd $U$ of $0$ such that $f^{-1}[U]$ is not open; let's try $U=\left(-\frac12,\frac12\right)$. Clearly
$$\begin{align*}
f^{-1}[U]&=\left\{\langle t,k\rangle\in X:-\frac12<t-k<\frac12\right\}\\
&=\left\{\langle t,k\rangle\in X:k-\frac12<t<k+\frac12\right\}\;.
\end{align*}\tag{1}$$
For what values of $k$ is it true that $\langle 0,k\rangle\in f^{-1}[U]$? From $(1)$ we see that $\langle 0,k\rangle\in f^{-1}[U]$ if and only if
$$k-\frac12<0<k+\frac12\;,$$
and clearly this is true only for $k=0$. On the other hand, every open nbhd of $\langle 0,0\rangle$ in $X$ contains a basic open nbhd of the form $(-\epsilon,\epsilon)\times C$ for some $\epsilon>0$ and cofinite $C\subseteq\Bbb Z$ and therefore contains a set of the form $\{0\}\times C$ for some cofinite $C\subseteq\Bbb Z$. Thus, on the one hand we have
$$\{k\in\Bbb Z:\langle 0,k\rangle\in f^{-1}[U]\}=\{0\}\;,$$
and on the other hand we know that if $V$ is any open nbhd of $\langle 0,0\rangle$ in $X$, the set
$$\{k\in\Bbb Z:\langle 0,k\rangle\in V\}$$
is a cofinite subset of $\Bbb Z$ and hence in particular is infinite. It follows that $f^{-1}[U]$ does not contain any open nbhd of $\langle 0,0\rangle$ and hence that $f$ is not continuous at $\langle 0,0\rangle$.
It's actually not hard to adapt this argument to show that $f$ is not continuous at any point of $X$.

A: Your idea is good, but you shouldn't consider a particular neighborhood of $(0,0)$.

Fix a point $(t_0,k_0)\in X$. A basic neighborhood of this point has the form $U=(t_0-\delta,t_0+\delta)\times C$, where $C$ is cofinite and $k_0\in C$, in particular both upper and lower unbounded.
Then
$$
f(U)=\bigcup_{k\in C}(t_0-k-\delta,t_0-k+\delta)
$$
which is unbounded, so it can't be contained in $(t_0-k_0-\varepsilon,t_0-k_0+\varepsilon)$, for any $\varepsilon>0$.


text:
Q: Sufficient condition for the union of submanifolds to be a submanifold I have two submanifolds $M^n,N^n\subset W^m$. What are some sufficient condition for their union to be a submanifold too? (by submanifold I always mean smooth)
My guess is that if $M \cap N$ is an n-submanifold which is open and $\overline{M}\cap \overline{N}=\overline{M \cap N}$, then $M\cup N$ is a submanifold. Does anyone have a reference for a statement similar to this one? Or a proof of this? My idea to prove this would be to find for each point on $M \cup N$ a neighborhood completely contained in either $M$ or $N$.
According to the accepted answer in this mathoverflow question which is very similar to mine (https://mathoverflow.net/questions/78733/when-is-the-union-of-embedded-smooth-manifolds-a-smooth-manifold), a sufficient condition would be that $M\cap N$ is a n-submanifold and $\overline{M}\cap N=\overline{M\cap N}\cap N$.
I think this is wrong: Consider $M=[-1,1] \subset \mathbb{R}^2$ and $N \subset \mathbb{R}^2$ to be the graph of the smooth function $f:[-1,1] \to \mathbb{R},t\mapsto \begin{cases} 0 \ \ \ \ \ \ \  \ \ if \ \ t \in [-1,0] \\ e^{-t^{-2}} \ \ \ if  \ \ t>0\end{cases}$. Then the previous conditions hold, but obviously $M \cup N$ does not define a submanifold (removing the point (0,1) produces 3 components). But I am looking for a similar condition.
Thanks for any help

A: For the purpose of my answer, all manifolds are assumed to have empty boundary.
Consider the following curves in the Cartesian plane:
$C$ is the unit circle centered at $(0,1)$, $J$ is the interval in the $x$-axis given by the inequalities $-1<x\le 0$. I let
$C_+$ denote the open semicircle in $C$ given by the inequality $0<x$.
I will define two smooth curves:
$$
M= J\cup C_+, N= C \setminus \{(0,0)\}.
$$
Remark. Note that $M$ is only $C^1$-smooth, but one can easily modify the example to achieve $C^\infty$-smoothness.
Clearly, both $M, N$ are diffeomorphic to the real line, hence, are 1-dimensional submanifolds in the plane. Their intersection is $C_+$, clearly also a 1-dimensional smooth submanifold in the plane. At the same time, $M\cup N$ is not a even a topological manifold (it is not locally Euclidean at the point $(0,0)$).
Now, let's check your condition:
$$
\bar{M}\cap \bar{N}=\overline{M\cap N}.
$$
Both sides are equal to $\overline{C_+}$, hence, your condition is satisfied. Thus, your conjecture is incorrect.
Let us test the same example agains the linked MO answer.  There, there were two requirements (not one):
(a) $\bar{M}\cap N= \overline{M\cap N} \cap N$,
(b) $\bar{N}\cap M= \overline{N\cap M} \cap M$.
It is straightforward to see that both are satisfied: The intersection in (a) equals the half-closed arc
$\overline{C_+}\setminus  \{(0,0)\}$ and the intersection in (b) equals the half-closed arc $C_+ \cup  \{(0,0)\}$. Hence, the linked answer is also wrong.

Edit. Here is a sufficient condition for $M\cup N$ to be a smooth submanifold, provided that $M$, $N$ are $n$-dimensional submanifolds in $W$ and $M\cap N$ is also an $n$-dimensional submanifold.
Assume that the pair $(M,N)$ satisfies the following property:
(a) For every sequence $(x_i)$ in $N$ converging to a point $x\in M$, for all sufficiently large $i$, $x_i\in M$.
(b) Same as (a) with the roles of $M, N$ swapped.
It is easy to see that under this condition, both inclusion maps $M\to M\cup N$, $N\to M\cup N$ are open. From this it is immediate that $M\cup N$ is a smooth submanifold of $W$. (The domain $U$ of an smooth chart $(U,\phi)$ in $M$ or $N$ is open in $M\cup N$, hence, $(U,\phi)$ is a smooth chart in $M\cup N$.)

A: Allowing the submanifolds to intersect in another submanifold allows too much. For example consider two lines intersecting once in the plane. The intersection point is just a 0-dimensional manifold. But its union is a cross smd so not a manifold.
I expect if the closure of a finite number of submanifolds has disjoint intersection then its union is a submanifold.


text:
Q: How many binary vectors $y$ of length $n$ such that the inner product of fixed $x$ and $y$ is $0$ I have a question that I'm trying to solve which is as following:
If $x$ is a fixed vector determine how many binary vectors $y$ of length $n$ do exist such that $\langle x,y\rangle = 0$

Inner product of two vectors is as following: $$\langle x,y\rangle = x_1y_1 + x_2y_2 + x_3y_3 + \cdots + x_ny_n$$

I tried and I got as following: $wt(x)2^{n-wt(x)}$ where $wt(x)$ is the number of $1$s in vectors and $n-wt(x)$ is the number of non-zero in $x$. And $2^{n-wt(x)}$ is the number of zeroes in x. It is correct for some values, but not for general! my way to do is to write two vectors of x and y and suppose x is fixed with different number of 0s and 1s. Then, if $x_i=0$, then $y_i=0$ or $y_i=1$ to get $\langle x,y\rangle=0$ So we have two possible values for y if $x_i=0$ and if $x_i=1$, then y must be equal 0. Thus, I calculate the number of zeros in $x$ as ($n-wt(x)$) and powered by $2$ since it has two possible values and times $wt(x)$ because if $x$ has $k$ number of $1$s, then we need $k$ number of $1$s for $y$ to make $\langle x,y\rangle=0$. Thus, we get $wt(x)2^{n-wt(x)}$.
Thank you!

A: Vectors orthogonal to $x$ always form an $n-1$ dimensional subspace if $x \neq 0$, and if $x=0$ then the while $n$-dimensional space is orthogonal to it.
An $m$-dimensional space over field of size $q$ has $q^m$ elements. In your case, $q=2$, and

*

*If $x\neq 0$ then $m=n-1$ and the answer is $2^{n-1}$.

*If $x=0$ then $m=n$ and the answer is $2^n$.


text:
Q: same height images with flexbox I'm trying to have same size images with flexbox. I give a display: flex; to my slick-track container and then flex: 1 0 auto to my img. I thought that with a flex-grow of 1 my image will increase if they are too small but it didn't happen.
the codepen here

$(".image-carousel").slick({
    // autoplay: true,
    dots: true,
 slidesToShow:3,

});
.slick-track {
  display: flex;
}
.slick-track .slick-slide img {
  flex: 1 0 auto;
  align-items: center;
  justify-content: center;
}

gene

chimie

cerveau

cropped-Science.jpg

ordi

astro

Einstein

gene

chimie

cerveau

cropped-Science.jpg

ordi

astro

A: Keep in mind that flex properties only work between parent and child.
You have display: flex on .slick-track. This means that the flex equal height feature (align-items: stretch) will apply to the child elements (.slick-slide).
And these child elements (flex items) are indeed equal height – once you remove the height: 100% on them, which overrides the equal height feature.
revised codepen
Your img elements are descendants of the flex container, but not children, so they don't recognize flex properties. You'll need to make each parent a flex container for the images to be full-height.
revised codepen

A: Here's another option, maintaining proportion and centering each image within the slide. This is probably as good as it gets unless you use background-image, which is more flexible when it comes to fitting inside of a container.
https://codepen.io/anon/pen/pRLXxz

A: I would suggest you to limit the width of the slider (the main container) so the slides, I mean the pictures, don't be so huge.
Then move the params you gave to the img to its parent element.
.slick-track {
    display: flex;
}
.slick-slide {
    flex: 1 0 auto;
    align-items: center;
    justify-content: center;
}
.slick-slide img {
    width: 100%;
}
.elementor-image-carousel-caption {
    text-align: center; /* just for aesthetics */
}

Hope it helps.


text:
Q: How to change order of elements in a row from horizontal to vertical? How I can change the order of elements using CSS. I cannot edit its HTML.
The quantity box is in line with add to cart button. I want it to appear it above Add to cart.
Live URL: https://mytimios.ml/baby-0-2-years/

Result i want to achieve using CSS:

A: I got it working using:
.astra-shop-summary-wrap {
  display:flex;
  flex-direction:column;
  align-items:center;
}

This also works:
.qib-container {
   display:flex;
   justify-content:center;
   width:100%;
   margin-bottom: .5rem;
}

I'm not sure why display:block does not work, but adding a with to it works as it is set to inline-block.

A: Add the following to your css:
div.qib-container {
    display: block;
}


text:
Q: Elements not adding to JList For some reason, I can't add anything to my JList. The JList is visible but simply shows white - nothing can be selected.
List list;
DefaultListModel listModel;
//...
list = new JList();
list.setBounds(220,20,150,200);
listModel = new DefaultListModel();
listModel.addElement("ONE");
panel.add(list);

Am I missing something?

A: The JList is not using the listModel.
One way is to initialize the JList by specifying a ListModel to use:
DefaultListModel listModel = ...
JList list = new JList(listModel);

Then, performing changes to the listModel (such as calling addElement) will cause the changes to appear on the JList.
For more information on using JLists, the How to Use Lists lesson from The Java Tutorials is a good source.

A: You never set the list's model to the ListModel you've constructed.


text:
Q: Unresolved reference, in wrong test scope - Android studio 3.5 Since I've updated to Android Studio 3.5, in my unit tests Android Studio shows unresolved reference for all the dependencies. The project compiles and the unit test runs successfully but Android Studio shows everything in red.
I've tried to clean, delete build and .gradle folder, invalidate caches but it doesn't work.

A: Only workaround to fix this until issue 140375151 is resolved is this:

*

*Put the cursor on one of the affected references

*Type alt/options + Enter

*Choose Inspection "Unresolved reference, in wrong test scope"

*Choose Edit inspection profile setting

*Remove the check from the inspection setting to disable it and click OK
The unresolved references should no longer show as unresolved.

A: This Google issue may be related.
https://issuetracker.google.com/issues/140375151


text:
Q: Trade show information exchange math/logic problem $n+1$ companies each send 2 representatives to a trade show. Example Inc. sends Bob and Kim, filling up the ranks of some $2n + 2$ attendees. Some people exchanged information. One did not exchange information with oneself and two people representing the same company did not exchange information with each other. At the end of the show, Bob asked each person other than himself as to how many people did they exchange information with. Interestingly, they all gave a different answer, i.e., each person other than Bob had exchanged information with a different number of people.
(a) If $n = 4$, how many people did Kim exchange information with?
(b) Generalize your solution for arbitrary $n$.
I'm mostly just stuck with a; I'm told getting it will essentially unlock b. So for $n=4$, I first thought that Bob must've received $9$ distinct answers from 0-8, since 0 would be the minimum and 8 the maximum (as one could only ask a max of 2n people). The problem with this is that if someone exchanged info with 0 people, then no one could've exchanged info with 8, limiting me to 0-7, one answer short. Similarly, if I just use 1-8, I face the same problem. Even if I find distinct answers, I'm at a loss as to how I can know which one is Kim's.
I can't really see a way past this, I'm assuming it may have something to do with specific answer sets being allowed, but it's just speculation. Any help or insight would be much appreciated.

A: Ill add an answer for completeness - As the number of exchanges for each person excluding Bob is distinct and there are $9$ such people, the number of exchanges for these people is some permutation of $\{0,1,2,\cdots,8\}$ because the minimum number of exchanges for a person is $0$, maximum is $8$ since a person cannot exchange with themself or their company partner and since we have 9 possible values and 9 people, each value must occur. Now look at the person with $8$ exchanges $P_8$. They must have exchanged info with everyone but their company partner, and the only person who they havent exchanged with is the person with $0$ exchanges $P_0$. So $P_8$ and $P_0$ must be partners. Similarly, the person with $7$ exchanges $P_7$ has exchanged information with all but $2$ people and one of them must be their partner. One of them is $P_0$ obviously, and the other is $P_1$ because $P_1$ has already exchanged with $P_8$ and can't exchange anymore. But $P_0$ is already paired up so $P_1$ and $P_7$ are partners. Continuing this way we can pair up $(P_0, P_8),(P_1,P_7),(P_2,P_6),$ and $(P_3,P_5)$ where $P_i$ is the person with $i$ exchanges. So we are left with $P_4$ with $4$ exchanges who must be Kim.

A: Still new to both the subject and the website, but wanted to post some of what I did because I know it's likely someone will search for this in the future: quasi's comment is correct and drawing out the solution on a piece of paper with that as a basis should be enough to make the answer clear; it also helps to remember that there are no limitations on how many people Bob's exchanged information with. From there, proving for b should be easy.
I'd have it drawn in pairs, starting with a $0/8$ and using dots/notches/whatever to mark interactions should reveal a pattern one can solve the problem with.


text:
Q: howto spec not all models I know
rake spec:models

to spec all models.
Is there a way to spec only one model, or only a given collection of models?
Something like this would be desirable:
rake spec:model user

or with a collection of models
rake spec:model user role order

BTW: Brian Hogan wrote created something similar (see here) but maybe there is something built-in in rspec2

A: use the rspec command line ( with Rspec 2)
rspec spec/models/user_spec.rb

or if you want several
rspec spec/models/user_spec.rb spec/models/role_spec.rb

If you want a task for that create. it.


text:
Q: How to find the client network speed I am sending a file from client to server. Both the client and server applications are running in the same machine. After a sending a file from client to server, now I need to show the time it will take to transfer the file from client to server in .Net. Same as copy box in windows xp.
Any idea would be appreciate.

A: You can remember the size of the file, and divide it by the time it took to transfer the file. This will give you a transfer speed estimate (for instance, kilobytes / second).


text:
Q: Send html and plain text email simultaneously with PHP Mailer I would like to send both html and plain text simultaneously in an email. I found this pretty straightforward tutorial but it used the mail() function to send the email.
How do I transform this code send an email with the PHP Mailer class?
//specify the email address you are sending to, and the email subject
$email = 'email@example.com';
$subject = 'Email Subject';

//create a boundary for the email. This
$boundary = uniqid('np');

//headers - specify your from email address and name here
//and specify the boundary for the email
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From: Your Name \r\n";
$headers .= "To: ".$email."\r\n";
$headers .= "Content-Type: multipart/alternative;boundary=" . $boundary . "\r\n";

//here is the content body
$message = "This is a MIME encoded message.";
$message .= "\r\n\r\n--" . $boundary . "\r\n";
$message .= "Content-type: text/plain;charset=utf-8\r\n\r\n";

//Plain text body
$message .= "Hello,\nThis is a text email, the text/plain version.
\n\nRegards,\nYour Name";
$message .= "\r\n\r\n--" . $boundary . "\r\n";
$message .= "Content-type: text/html;charset=utf-8\r\n\r\n";

//Html body
$message .= "
 Hello,
This is a text email, the html version.

Regards,
Your Name";
$message .= "\r\n\r\n--" . $boundary . "--";

//invoke the PHP mail function
mail('', $subject, $message, $headers);

A: There is a function for that in PHPMailer: msgHTML()
# Minimum code to send an email:
$phpmailer = new PHPMailer();

$phpmailer->From = $from;
$phpmailer->FromName = $from_name;

$phpmailer->AddAddress( $to, $to_name );

$phpmailer->Subject = $subject;

$phpmailer->CharSet = 'UTF-8';

$phpmailer->msgHTML( $htmlMessage ); # <- right here!

# Use PHP's mail() instead of SMTP:
$phpmailer->IsMail();

$phpmailer->Send();

Create a message from an HTML string.
    Automatically makes modifications for inline images and backgrounds
    and creates a plain-text version by converting the HTML.
    Overwrites any existing values in $this->Body and $this->AltBody

See full function's code on Github:
https://github.com/PHPMailer/PHPMailer/blob/master/class.phpmailer.php#L3299

A: See below:
$mail = new PHPMailer();

$mail->IsHTML(true);
$mail->CharSet = "text/html; charset=UTF-8;";
$mail->IsSMTP();

$mail->WordWrap = 80;
$mail->Host = "smtp.thehost.com";
$mail->SMTPAuth = false;

$mail->From = $from;
$mail->FromName = $from; // First name, last name
$mail->AddAddress($to, "First name last name");
#$mail->AddReplyTo("reply@thehost.com", "Reply to address");

$mail->Subject =  $subject;
$mail->Body =  $htmlMessage;
$mail->AltBody  =  $textMessage;    # This automatically sets the email to multipart/alternative. This body can be read by mail clients that do not have HTML email capability such as mutt.

if(!$mail->Send())
{
  throw new Exception("Mailer Error: " . $mail->ErrorInfo);
}

Thanks to http://snippets.aktagon.com/snippets/129-how-to-send-both-html-and-text-emails-with-php-and-phpmailer and Google. SMTP use might be optional for you.

A: Try this:
$mail->SMTPDebug = 2;

Debug levels
Setting the PHPMailer->SMTPDebug property to these numbers or constants (defined in the SMTP class) results in different amounts of output:

*

*SMTP::DEBUG_OFF (0): Disable debugging (you can also leave this
out completely, 0 is the default).

*SMTP::DEBUG_CLIENT (1): Output messages sent by the client.

*SMTP::DEBUG_SERVER (2): as 1, plus responses received from the
server (this is the most useful setting).

*SMTP::DEBUG_CONNECTION (3): as 2, plus more information about the
initial connection - this level can help diagnose STARTTLS failures.

*SMTP::DEBUG_LOWLEVEL (4): as 3, plus even lower-level
information, very verbose, don't use for debugging SMTP, only
low-level problems.

You don't need to use levels above 2 unless you're having trouble connecting at all - it will just make output more verbose and more difficult to read.
Note that you will get no output until you call send(), because no SMTP conversation takes place until you do that.
Link: https://github.com/PHPMailer/PHPMailer/wiki/SMTP-Debugging


text:
Q: Managing transactions in iPOJO I define a transaction is a set of continuous activities (one method or set of methods) in a component.
I wrote a simple example as follows:
//service interface
public interface Hello {
    String sayHello(String name);
    String sayBonjour(String name);
}

//service implementation
@Component
public class HelloImpl implements Hello {

    public String sayHello(String name) {
       //start local transaction
       return "hello " + name;
       //finish local transaction
    }
    public String sayBonjour(String name) {
       //start local transaction
       return "bonjour " + name;
       //finish local transaction
    }
}

//client
@Component
public class Client {

   Hello client;
   public Client() {
      //start local transaction
      client.sayBonjour(client.sayHello("world"));
      //finish local transaction
   }
  }

In this example, there are local transactions in the components HelloImpl and Client. I define that global transaction of the system consists of a set of local transactions through all components.
How to manage transactions (global transaction and the local transtions in this example) in OSGi or iPOJO ?
Regards,

A: As in the example, when the client calls "client.sayBonjour(client.sayHello("world"))" on HelloImpl component, the client initiates a transaction (T0) to send "world" and then send the result of sayHello("world") to the HelloImpl component. After receiving the "world", HelloImpl component initiates a subtransaction (T1) to process request and return the result "helloworld" to client. Then HelloImpl component receives also "helloworld" request (in the method sayBonjour) , it initiates a new subtransaction T2 to process it.  How to know T1 and T2 serve T0 if there many clients in the same time.


text:
Q: C++ - One-liner to iterate nested brace-enclosed lists? In Python we can do
for i, j in [(0, 0), (0, 1), (1, 0), (1, 1)]:
    ...

Is there something similar in C++?
In the non-nested case there is
for (auto i : {0, 1});

but extending to nested lists
for (auto [i, j] : {{0, 0}, {0, 1}, {1, 0}, {1, 1}});

doesn't compile.

A: This works:
#include <initializer_list>
#include <utility>

void foo() {
    for (auto [i, j] : std::initializer_list<std::pair<int,int>> {
           {0, 0}, {0, 1}, {1, 0}, {1, 1}}
        );
}

and note you have to include the two headers.
You can also use this shorter version:
#include <initializer_list>
#include <utility>

void bar() {
    for (auto [i, j] :  {std::pair{0, 0}, {0, 1}, {1, 0}, {1, 1}});
}

and again - you need to include both of these headers.
(See it all on Godbolt)


text:
Q: How can I hide feedback in CSV output of a hive query? I have a query.sql file which looks like this:
set feedback off
spool "path/to/output.csv"
select fieldname from tablename;
spool off;

And in SQL Developer (v. 18.3.0 on CentOS) I run scripts.sql which looks like this:
@query.sql

But I get the following message in the script output
set
--------------------------------------------------
feedback off is undefined

The saved CSV is perfect in every way except at the bottom it prints a blank row followed by "X rows selected." which is what I'd like to be rid of.

A: It's working for me, note i'm doing this on an Oracle connection, but it should work on hive as well since the SET commands are client based

This is running on version 19.4
clear screen
set sqlformat csv
set feedback off
spool /Users/thatjeffsmith/output.csv
select first_name, last_name from employees fetch first 3 rows only;
spool off
!cat /Users/thatjeffsmith/output.csv


text:
Q: C# Increase Heap Size - Is It Possible I have an out of memory exception using C# when reading in a massive file
I need to change the code but for the time being can I increase the heap size (like I would in Java) as a shaort term fix?

A: .Net does that automatically.
Looks like you have reached the limit of the memory one .Net process can use for its objects (on 32 bit machine this is 2 standard or 3GB by using the /3GB boot switch. Credits to Leppie & Eric Lippert for the info).
Rethink your algorithm, or perhaps a change to a 64 bit machine might help.

A: No, this is not possible. This problem might occur because you're running on a 32-bit OS and memory is too fragmented. Try not to load the whole file into memory (for instance, by processing line by line) or, when you really need to load it completely, by loading it in multiple, smaller parts.

A: No you can't see my answer here: Is there any way to pre-allocate the heap in the .NET runtime, like -Xmx/-Xms in Java?
For reading large files it is usually preferable to stream them from disk, reading them in chunks and dealing with them a piece at a time instead of loading the whole thing up front.

A: As others have already pointed out, this is not possible. The .NET runtime handles heap allocations on behalf of the application.
In my experience .NET applications commonly suffer from OOM when there should be plenty of memory available (or at least, so it appears). The reason for this is usually the use of huge collections such as arrays, List (which uses an array to store its data) or similar.
The problem is these types will sometimes create peaks in memory use. If these peak requests cannot be honored an OOM exception is throw. E.g. when List needs to increase its capacity it does so by allocating a new array of double the current size and then it copies all the references/values from one array to the other. Similarly operations such as ToArray makes a new copy of the array. I've also seen similar problems on big LINQ operations.
Each array is stored as contiguous memory, so to avoid OOM the runtime must be able to obtain one big chunk of memory. As the address space of the process may be fragmented due to both DLL loading and general use for the heap, this is not always possible in which case an OOM exception is thrown.

A: What sort of file are you dealing with ?
You might be better off using a StreamReader and yield returning the ReadLine result, if it's textual.
Sure, you'll be keeping a file-pointer around, but the worst case scenario is massively reduced.
There are similar methods for Binary files, if you're uploading a file to SQL for example, you can read a byte[] and use the Sql Pointer mechanics to write the buffer to the end of a blob.


text:
Q: How to pass jquery or javascript data to Ruby on Rails model? I'm working on a prototype in Rails 3 and ended up using some jquery (my first time and it's pretty sweet). Although, it appears that I am stuck when submitting the data from my view, which is from the Impromptu JQuery Survey, and into a my database (sqllite3). Let me explain how the page works:

*

*When a drop down item is selected the survey pops up. Also, this is a modal form and there's about 7 questions.

That's pretty much it. My desired outcome is after the user submits the form by clicking finish, each of the answered questions needs to do into the database. Some of the input fields are checkboxes and dropdowns.
Here is a sample of the code, from the last question of the survey:
state7: {
                    html:'Personality Type
<select name="personality" id="rate_find"><option value="enfp">ENFP</option><option value="INTJ">INTJ</option><option value="ESTJ">ESTJ</option><option value="INTP">INTP</option></select>
',
                    buttons: { Back: -1, Cancel: 0, Finish: 1 },
                    focus: 2,
                    submit: function(v, m, f){
                        if (v == 0)
                            $.prompt.close()
                        else
                            if (v == 1)
                                return true; //we're done
                            else
                                if (v = -1)
                                    $.prompt.goToState('state6');//go back
                        return false;
                    }
                }
            }

            $.prompt(temp,{
                callback: function(v,m,f){
                    var str = "You can now process with this given information:
";
                    $.each(f,function(i,obj){
                        str += i + " - " + obj + "
";
                    });
                    $.prompt(str)
                }
            });
        }

A: The key/value pairs containing the information you got through the impromptu popup need to be piled into a POST request like you might expect in a regular form. If you have an ActiveRecord model for the data going into your database, then you could make a form in the view that has the dropdown that triggers the popup, but just make the whole form hidden. Then at the end of your survey you can go through and assign values to the correct input (e.g.
$.each(f,function(i,obj){
     $('input#' + i).val(obj);
});

), and the final 'Finish' button can trigger the submit event on the form. You can look at this question to find out how to check checkboxes with jquery.
Hope that helps!


text:
Q: New custom action in MSP I'm trying to add custom action to the MSP, which didn't exist in the original MSI.
Does somebody knows how to do it?
Thanks,
Ievgen.

A: A .msp patch file is the delta between the original MSI file and the new MSI file. So you just build your new MSI file with the custom action in it and you'll end up with a patch that includes it.


text:
Q: integral inequality with maximum and derivative Let $[a,b]$ be a finite closed interval on $\mathbb{R}$, $f$ be a continuous differentible function on $[a,b]$. Prove that
$$\max_{x\in [a,b]} |f(x)|\le \Bigg|\frac{1}{b-a} \int_a^b f(x)dx\Bigg|+\int_a^b |f'(x)|dx$$
I think this is similar to Sobolev embedding theorem but have no idea about how to use it. I have also tried to transform the inequality into $$(b-a)\int_a^b (|f(t)|-|f'(x)|)dx\le \Bigg|\int_a^b f(x)dx\Bigg|,$$ where $f(t)$ is the maximum, but still don't know how to proceed. Thanks for any help.

A: There is a point $c\in (a,b)$ such that
$$f(c) = \frac{1}{b-a}\int_a^b f(x)\, dx$$
Let $x\in [a,b]$. Since
$$f(x) = f(c) + \int_c^x f'(t)\, dt$$
then
$$\lvert f(x)\rvert \le \lvert f(c)\rvert + \int_a^b \lvert f'(t)\rvert\, dt$$
Now finish the argument.

A: although Kobe has explained well. I had already started writing the answer.
So using triangle inequality we have $|f(c)| \leq |f(\xi)|+|f(c) - f(\xi)|$. By fundamental theorem of calculus $f(c) - f(\xi) = \int_{\xi}^cf'(x)dx$. Taking absolute values we have $$|f(c) - f(\xi)| = \int_{\xi}^cf'(x)dx \leq \int_{\xi}^c|f'(x)|dx \leq \int_a^b |f'(x)|dx \hspace{2mm} (A)$$.
Using mean value theorem we also have $$ f(\xi) = \frac{\int_a^bf(x)dx}{b-a}$$ therefore $$ |f(\xi)| \leq \frac{\int_a^b|f(x)|dx}{b-a} \hspace{3mm}(B)$$
Hence by(A) and (B) we have the result.


text:
Q: Updating and time delta in game I am making a Java game and I want my game to run the same on any FPS so I'm using time delta between each update. This is the update method of the Player:
public void update(long timeDelta) {

    //speed is the movement speed of a player on X axis
    //timeDelta is expressed in nano seconds so I'm dividing it with 1000000000 to express it in seconds

    if (Input.keyDown(37))
        this.velocityX -= speed * (timeDelta / 1000000000.0);

    if (Input.keyDown(39))
        this.velocityX += speed * (timeDelta / 1000000000.0);

    if(Input.keyPressed(38)) {
        this.velocityY -= 6;
    }

    velocityY += g * (timeDelta/1000000000.0); //applying gravity
    move(velocityX, velocityY); /*this is method which moves a player
                                    according to velocityX and velocityY,
                                    and checking the collision
                                */

    this.velocityX = 0.0;
}

This is how I calculate the timedelta and call update (this is in Main class):
lastUpdateTime = System.nanoTime();
while(Main.running) {

    currentTime = System.nanoTime();
    Update.update(currentTime - lastUpdateTime);

    Input.update();

    Render.render();

    measureFPS();

    lastUpdateTime = currentTime;
}

The strange thing is that when I have unlimited FPS (and update number) my player is jumping about 10 blocks. It jumps even higher when the FPS is increasing. If I limit FPS it is jumping 4 blocks. (BLOCK: 32x32)
I have just realized that the problem is this:
if(Input.keyPressed(38)) {
    this.velocityY -= 6;
}

I add -6 to velocityY which increases player's Y proportionally to the update number and not the time.
But I don't know how to fix this.


text:
Q: A Faster Way of Removing Unused Categories in Pandas? I'm running some models in Python, with data subset on categories.
For memory usage, and preprocessing, all the categorical variables are stored as category data type.
For each level of a categorical variable in my 'group by' column, I am running a regression, where I need to reset all my categorical variables to those that are present in that subset.
I am currently doing this using .cat.remove_unused_categories(), which is taking nearly 50% of my total runtime. At the moment, the worst offender is my grouping column, others are not taking as much time (as I guess there are not as many levels to drop).
Here is a simplified example:
import itertools
import pandas as pd
#generate some fake data
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
keywords = [''.join(i) for i in itertools.product(alphabets, repeat = 2)]
z = pd.DataFrame({'x':keywords})

#convert to category datatype
z.x = z.x.astype('category')

#groupby
z = z.groupby('x')

#loop over groups
for i in z.groups:
    x = z.get_group(i)
    x.x = x.x.cat.remove_unused_categories()
    #run my fancy model here

On my laptop, this takes about 20 seconds. for this small example, we could convert to str, then back to category for a speed up, but my real data has at least 300 lines per group.
Is it possible to speed up this loop? I have tried using x.x = x.x.cat.set_categories(i) which takes a similar time, and x.x.cat.categories = i, which asks for the same number of categories as I started with.

A: Your problem is in that you are assigning z.get_group(i) to x.  x is now a copy of a portion of z.  Your code will work fine with this change
for i in z.groups:
    x = z.get_group(i).copy() # will no longer be tied to z
    x.x = x.x.cat.remove_unused_categories()


text:
Q: Call java method on primefaces treeTable columns reorder For Primefaces treeTable component i ve added jquery ui droppable and draggable events so i can reorder columns.
tree.xhtml
<p:treeTable id="items" var="item" value="#{bean.root}" >
  <c:forEach var="column" items="#{bean.columns}" style="width:70px;">
    <p:column headerText="#{column.header}">
      <h:outputText value="#{some data}" />
    </p:column>
  </c:forEach>
</p:treeTable>

tree.js
$('.ui-resizable-column')
    .draggable(
    {
        appendTo : 'body',
        opacity : '0.6',
        cursor : 'pointer',
        scope : this.id,
    })
    .droppable(
    {
        drop : function(g, h) {
            .. implementation goes here...
            $.ajax().done(function(){
                alert( 'done!' );
            });
        }
    });

As a result I want to keep track of column order so I need an ajax event for this or any other remote method invocation back on Java back-end. How can I call function on a back end like. Is it possible with JS or primefaces?
public void reOrder( BehaviorEvent event ){

}

A: Solved - on jquery event completion make call to remoteCommand which will execute bean method.
tree.xhtml
$.ajax().done(function(){
   callToBean();
});

tree.js
<p:remoteCommand name="callToBean" actionListener="#{bean.reOrder/>


text:
Q: 500 Internal Server Error Laravel 4 I have project in Laravel 4. It's on bitbucket. I've downloaded it from my repo on my local machine, crated a local virtual host, working fine. But when I cloned the same project on my server and created a virtual host, 500 Internal Server Error is shown. On same domain another virtual host for the same project in laravel 5 is working fine.
This is my virtual host file code for laravel 4 project:
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName l4.mydomain
    ServerAlias l4.mydomain

    DocumentRoot /var/www/L4/public

    <Directory /var/www/L4/public/>
            AllowOverride All
    </Directory>

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

This is .htaccess code for laravel 4 project:
IfModule mod_rewrite.c>
  <IfModule mod_negotiation.c>
    Options -MultiViews
  </IfModule>

  RewriteEngine On

  # Redirect Trailing Slashes...
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)/$ /$1 [L,R=301]

  # Handle Front Controller...
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^ index.php [L]
</IfModule>

I've also changed the 'index.php' to 644 permission, but not worked
This is the warning and error found in log file:
PHP Warning:  require(/var/www/myproject/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /var/www/L4/bootstrap/autoload.php on line 17

PHP Fatal error:  require(): Failed opening required '/var/www/myproject/bootstrap/../vendor/autoload.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/L4/bootstrap/autoload.php on line 17

A: If you're getting

"PHP Fatal error: require(): Failed opening required '/var/www/L4/bootstrap/../vendor/autoload.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/L4/bootstrap/autoload.php on line 17"

in your error log, I'd say that it looks like you never ran composer install on the server.


text:
Q: Process very big csv file without timeout and memory error At the moment I'm writing an import script for a very big CSV file. The Problem is most times it stops after a while because of an timeout or it throws an memory error.
My Idea was now to parse the CSV file in "100 lines" steps and after 100 lines recall the script automatically. I tried to achieve this with header (location ...) and pass the current line with get but it didn't work out as I want to.
Is there a better way to this or does someone have an idea how to get rid of the memory error and the timeout?

A: I've used fgetcsv to read a 120MB csv in a stream-wise-manner (is that correct english?). That reads in line by line and then I've inserted every line into a database. That way only one line is hold in memory on each iteration. The script still needed 20 min. to run. Maybe I try Python next time… Don't try to load a huge csv-file into an array, that really would consume a lot of memory.
// WDI_GDF_Data.csv (120.4MB) are the World Bank collection of development indicators:
// http://data.worldbank.org/data-catalog/world-development-indicators
if(($handle = fopen('WDI_GDF_Data.csv', 'r')) !== false)
{
    // get the first row, which contains the column-titles (if necessary)
    $header = fgetcsv($handle);

    // loop through the file line-by-line
    while(($data = fgetcsv($handle)) !== false)
    {
        // resort/rewrite data and insert into DB here
        // try to use conditions sparingly here, as those will cause slow-performance

        // I don't know if this is really necessary, but it couldn't harm;
        // see also: http://php.net/manual/en/features.gc.php
        unset($data);
    }
    fclose($handle);
}

A: There seems to be an enormous difference between fgetcsv() and fgets() when it comes to memory consumption.
A simple CSV with only one column passed my 512M memory limit for just 50000 records with fgetcsv() and took 8 minutes to report that.
With fgets() it took only 3 minutes to successfully process 649175 records, and my local server wasn't even gasping for additional air..
So my advice is to use fgets() if the number of columns in your csv is limited. In my case fgets() returned directly the string inside column 1.
For more then one column, you might use explode() in a disposable array which you unset() after each record operation.
Thumbed up answer 3 @ndkauboy

A: I find uploading the file and inserting using mysql's LOAD DATA LOCAL query a fast solution eg:
    $sql = "LOAD DATA LOCAL INFILE '/path/to/file.csv'
        REPLACE INTO TABLE table_name FIELDS TERMINATED BY ','
        ENCLOSED BY '\"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES";
    $result = $mysqli->query($sql);

A: If you don't care about how long it takes and how much memory it needs, you can simply increase the values for this script. Just add the following lines to the top of your script:
ini_set('memory_limit', '512M');
ini_set('max_execution_time', '180');

With the function memory_get_usage() you can find out how much memory your script needs to find a good value for the memory_limit.
You might also want to have a look at fgets() which allows you to read a file line by line. I am not sure if that takes less memory, but I really think this will work. But even in this case you have to increase the max_execution_time to a higher value.

A: Oh. Just make this script called as CLI, not via silly web interface. So, no execution time limit will affect it.
And do not keep parsed results forever but write them down immediately - so, you won't be affected by memory limit either.


text:
Q: Unable to reach WAN from LAN host on IPv6 In my router, I have 2 interfaces enp1s0 (assumed as WAN) and enp4s0(assumed as LAN). I connected a LAN host and a WAN host. I can ping from LAN host to WAN port of the router but not to the gateway of WAN. The setting is as follows :

*

*LAN host IP : 8888::5/64

*LAN gateway IP (router's enp4s0) : 8888::1/64

*WAN port IP (router's enp1s0) : 2401:fb00:0:1ff::1fd/64

*WAN gateway IP : 2401:fb00:0:1ff::1fc/64

IPv6 forwarding is enabled in /etc/sysctl.conf i.e net.ipv6.conf.all.forwarding=1 and restarted the network service.
/proc/sys/net/ipv6/conf/enp1s0/forwarding = 1
/proc/sys/net/ipv6/conf/enp4s0/forwarding = 1
/proc/sys/net/ipv6/conf/default/forwarding = 1
/proc/sys/net/ipv6/conf/all/forwarding = 1

Ping happens from LAN host to LAN gateway and WAN port of router.
Default route is there in router to reach WAN gateway.
But still I can't access WAN gateway from LAN host.
Any help would be appreciated.
tcpdump on router WAN port(enp1s0) is when ping from 8888::5 to  2401:fb00:0:1ff::1fc runs.
11:40:26.986609 IP6 8888::5 > 2401:fb00:0:1ff::1fc: ICMP6, echo request, seq 632, length 64
11:40:27.597211 IP6 2401:fb00:0:1ff::1fd.35373 > 2401:fb00:0:1ff::1fc.domain: 41163+ A? relay-4a21c05c.net.anydesk.com. (48)
11:40:27.601687 IP6 2401:fb00:0:1ff::1fc > 2401:fb00:0:1ff::1fd: ICMP6, destination unreachable, unreachable port, 2401:fb00:0:1ff::1fc udp port domain, length 104


text:
Q: React-Router | How to delete route login from browser's back button after authentication? How can i delete route login from browser's back button after authentication of user?
I want that user should not able to go back to login component(after authentication) by using browser's back button. How can we achieve this?
I am trying to do
$(window).on("navigate", function (event, data)
{
    console.log(data);
    var direction = data.state.direction;
    if(direction == 'back')
    { // do something
    }
    if (direction == 'forward')
    {
    // do something else
    }
});

But its not working on componentDidMount
Where can I write this jquery in react component

A: you can use the transition for checking whether use is login or not on component you can check this way
  static willTransitionTo(transition) {
      // This method is called before transitioning to this component. If the user is not logged in, we'll send him or her to the Login page.
      if (!LoginStore.isLoggedIn()) {
        transition.redirect('/login');
      }
    }

for more information Auth


text:
Q: Cannot access the value of the kdb table column I am new to KDB and cannot understand why i can access the order column for the table stocks but not trader. The below is my code with the error.
q)trader
item     brand | price order
---------------| -----------
soda     fry   | 1.5   200
bacon    prok  | 1.99  180
mushroom veggie| 0.88  110
eggs     veggie| 1.55  210
tomatoes veggie| 1.35  100
q)trader.order
'order
  [0]  trader.order
       ^
q)stock.order
50 82 45 92
q)stock
item     brand  price order
---------------------------
soda     fry    1.5   50
bacon    prok   1.99  82
mushroom veggie 0.88  45
eggs     veggie 1.55  92
q)trader.order
'order
  [0]  trader.order
       ^

A: Your table trader is keyed and you cannot use trader.order to select the order column.
You can use this instead if you want
(0!trader)`order

The reason is because when you do trader.order what you actually do is you use indexing. It's the same as if you'd do list.index. A table is just a list of dictionaries and you use dot(.) to index into it. However a keyed table does not have the same structure so you'll have to unkey it first.


text:
Q: jQuery - pull navigational focus to a particular link on page load As soon as a page loads, I want the focus to jump to a particular link, so hitting enter will 'click' it.
I've tried
$('ul li a:first').focus();
without luck, but I think I may be misinterpreting the usage of .focus().
Any advice appreciated!
:s

A: Your code is almost right. You just miss $(document).ready.
To fix, use this:
$(document).ready(function(){
   $('ul li a:first').focus();
});

See example in jsfiddle.
The problem is when jquery is called the page doesn't have that link yet.
With $(document).ready. you call jquery only when page is complete.

A: Yeah, though it's a little odd how it works (and I found this on the jQuery focus docs, and don't claim to understand why it works):
$(document).ready(
  function() {
    $("a:first").attr("tabindex",'-1').focus();
  }
  );

Demo at: jsbin


text:
Q: How can I read the contents of stdin (up until EOF) into a string in PHP? How can I read the contents of stdin (up until EOF) into a string in PHP?

A: ended up figuring it out myself:
$input_data = file_get_contents("php://stdin");

A: Use some of the file reading functions (e.g. fgets(), fgetc(), fscanf()) and pass in STDIN as the file path (or php://stdin, depending on how new your version of PHP is).
You can test for the EOF using feof().
See the reference for command-line programming in PHP on PHP.net for more information.

A: Here's an alternative: You can use stream_get_contents to get everything from an open stream (AKA a file handle). STDIN is an already open handle equivalent to what you get if you call fopen('php://stdin') (see reference: Input/output streams)
So: you can use
$input_data = stream_get_contents(STDIN);

which is equivalent to the accepted answer.


text:
Q: is this conclusion true or false? Let $\mathcal{A}$ be a factor Von Neumann algebra and $\Phi$ is a map on  $\mathcal{A}$ which is injective and surjective and $\Phi(0)=0$. If $A, B, C \in \mathcal{A}$  and $\Phi(A+B)=\Phi(A)+\Phi(C)$, can we conclude that $B=C$? If yes, how can i prove it? and if no, is there any example to reject it?
thanks for your help.


text:
Q: Android force PreferenceActivity to reload my custom preference I 've created a custom Preference which displays some data. I want to force my parent PreferenceActivity to redraw myself (i.e. to call again getView()).
Is there a way to do that?


text:
Q: java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v4/os/BuildCompat I have updated the AppCompat libraries to 24.2.1 and the SDK to Android 7 in my Eclipse install.
Since that, I'm not capable to run any of my apps.
I appreciate if you can help a bit with that...
E/AndroidRuntime(17555): java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v4/os/BuildCompat;
E/AndroidRuntime(17555):    at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:196)
E/AndroidRuntime(17555):    at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181)
E/AndroidRuntime(17555):    at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521)
E/AndroidRuntime(17555):    at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:71)
E/AndroidRuntime(17555):    at com.ryosoftware.calendareventsnotifier.MainActivity.onCreate(MainActivity.java:844)
E/AndroidRuntime(17555):    at android.app.Activity.performCreate(Activity.java:5990)
E/AndroidRuntime(17555):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
E/AndroidRuntime(17555):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
E/AndroidRuntime(17555):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
E/AndroidRuntime(17555):    at android.app.ActivityThread.access$900(ActivityThread.java:154)
E/AndroidRuntime(17555):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
E/AndroidRuntime(17555):    at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(17555):    at android.os.Looper.loop(Looper.java:135)
E/AndroidRuntime(17555):    at android.app.ActivityThread.main(ActivityThread.java:5294)
E/AndroidRuntime(17555):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(17555):    at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime(17555):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
E/AndroidRuntime(17555):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
E/AndroidRuntime(17555): Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v4.os.BuildCompat" on path: DexPathList[[zip file "/data/app/com.ryosoftware.calendareventsnotifier-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
E/AndroidRuntime(17555):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
E/AndroidRuntime(17555):    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
E/AndroidRuntime(17555):    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
E/AndroidRuntime(17555):    ... 18 more
E/AndroidRuntime(17555):    Suppressed: java.lang.ClassNotFoundException: android.support.v4.os.BuildCompat
E/AndroidRuntime(17555):        at java.lang.Class.classForName(Native Method)
E/AndroidRuntime(17555):        at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
E/AndroidRuntime(17555):        at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
E/AndroidRuntime(17555):        at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
E/AndroidRuntime(17555):        ... 19 more
E/AndroidRuntime(17555):    Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

A: You are getting NoClassDefFoundError & ClassNotFoundException

NoClassDefFoundError in Java comes when Java Virtual Machine is not
  able to find a particular class at runtime which was available at
  compile time.

FYI
You are using Eclipse. Android Studio is a far simpler way to develop for Android if you manage to get the hang of it. For developers who have been using Eclipse, migrating to Studio is a nightmare for them. Eclipse is dead (My personal opinion).
For your NoClassDefFoundError problem goto rebuild option under Project > Clean and then select the project you want to clean up .Then Restart your Eclipse and run again .
Solutions

Check your classpath contains that jar (AppCompat), if your classpath
  doesn't contain the jar then just add that class in your classpath.

You should Use Android Studio instead of Eclipse . Read

*

*Support Library Features
The Gradle build script dependency identifier for this library is as follows:
com.android.support:appcompat-v7:24.2.1

Then Clean-Rebuild-Restart IDE

A: Another ugly reason for this to be caused is if you're trying to attach a debugger with breakpoint on something that happens during Activity creation.

A: I added two classes in my java package and its working fine, keep both class as showing in below image:

AsyncTaskCompat.java
public class AsyncTaskCompat {

/**
 * Executes the task with the specified parameters, allowing multiple tasks to run in parallel
 * on a pool of threads managed by {@link android.os.AsyncTask}.
 *
 * @param task The {@link android.os.AsyncTask} to execute.
 * @param params The parameters of the task.
 * @return the instance of AsyncTask.
 */
public static <Params, Progress, Result> AsyncTask<Params, Progress, Result> executeParallel(
        AsyncTask<Params, Progress, Result> task, Params... params) {
    if (task == null) {
        throw new IllegalArgumentException("task can not be null");
    }

    if (Build.VERSION.SDK_INT >= 11) {
        // From API 11 onwards, we need to manually select the THREAD_POOL_EXECUTOR
        AsyncTaskCompatHoneycomb.executeParallel(task, params);
    } else {
        // Before API 11, all tasks were run in parallel
        task.execute(params);
    }

    return task;
}
}

AsyncTaskCompatHoneycomb.java
class AsyncTaskCompatHoneycomb {

static <Params, Progress, Result> void executeParallel(
        AsyncTask<Params, Progress, Result> task, Params... params) {
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
}
}

A: In my case

*

*clean project

*invalidate and restart

it's work

A: In my case the error was caused due to the use of the entire gms:play-services library. Some components of gms:play-services refer to versions other than explicitly specified by you.
Use only the required play-services which are required e.g: 'com.google.android.gms:play-services-analytics:10.2.0' instead of 'com.google.android.gms:play-services:10.2.0'.
Also see: All com.android.support libraries must use the exact same version specification
Good read: https://blog.mindorks.com/avoiding-conflicts-in-android-gradle-dependencies-28e4200ca235

A: public class MApplication extends Application {

    @Override
    protected void attachBaseContext(Context paramContext) {
        super.attachBaseContext(paramContext);
        Helper.install(MApplication.this);
    }
}

Here we override the attachBaseContext() method to add the Helper.install(MApplication.this); line of code.
Note: Since some of SDK classes now need to be loaded before using, the loading process is done by Helper.install(). Developer needs to invoke this method before using any SDK functionality. Failing to do so will result in unexpected crashes.
reference
Unless the app crashes with java.lang.NoClassDefFoundError: Failed resolution of:....

A: Update implementation com.google.android.gms:play-services-maps in gradle to a newer version.
That worked for me.

A: I had a very similar issue, the problem was using an old (deprecated) package, more that 4 years without maintenance. Check your reciently added packages and check if they're compatible with you Android SDK.

A: In my case, just cleaning and rebuilding the project worked for me.


text: Q: How to package and deploy a Node/Express Web Application in some NON-CLOUD environment? I am a beginner in NodeJS. All the examples seen so far deploy the app in some Cloud environment. Coming from a Java background, deploying app in Jboss, is there anything similar for a Node/Express application ? Or running 'node server.js' is the only way to doit.


text:
Q: Find $c$ such that $ 0.05 = P \left( \sum_{i=1}^{10}X_i \geq c \right) $ I have to solve, for $c$, the equation
$$
0.05 = P \left( \sum_{i=1}^{10}X_i \geq c \right)
$$
where $X_i~~ i.i.d  \operatorname{Poisson}(1) \Rightarrow \sum_{i=1}^{10}X_i \sim \operatorname{Poisson}(10) $.
If the random variables were continuous I could calculate $c$ from the complement $0.95 = P(\sum_{i=1}^{10}X_i \leq c)$ but that is not the case.

A:
If the random variables were continuous I could calculate cc from the complement

of course you can also in a discrete case! in any case the probability over all the support is 1.
Easy find $C=16$.
To speed up the calculation (I did it with a poket calculator)
$P(X=14)>0.05$ (14 is not good)
$P(X=15)=0.035$ (mmmh...let's see the next)
$P(X=16)=0.022$ (15 is not good)
The other values over $X=17$ have all a probability close to zero....Thus $C=16$
Verify with a Calculator but I'm sure it is correct!


text:
Q: How to generate the date Using SQL Server 2005
Tabl1
ID Date Intime Outtime

001 20101201 080000 180000
001 20101202 210000 060000
001 20101203 180000 090000
001 20101204 100000 170000
....

.
Date Datatype is nvarchar
Intime, Outtime datatype is nvarchar
Intime, Outtime Format: HHMMSS

From the table1, i want to make one more column name as NextDate.
The Next Date Column should display the next date of Date Column with the following condition
If Outtime is Greater than Intime then it should display the next date
If outtime is less than intime then it should display the same date

Expected Output
ID Date Intime Outtime NextDate
001 20101201 080000 180000 20101201 (Outtime is less than Intime)
001 20101202 210000 060000 20101203 (Outtime is greater than Intime)
001 20101203 180000 090000 20101204 (Outtime is greater than Intime)
001 20101204 100000 170000 20101204 (Outtime is less than Intime)
....

How to make a query for the above condition.
Need Query Help.

A: I agree with @marc_s, when you work with date and time best way is use datetime datatype.
But you can use this code temporary.
SELECT ID, [Date], Intime, Outtime,
            CASE
                WHEN Outtime > Intime THEN
                    [Date]
                WHEN Outtime < Intime THEN
                    CONVERT(
                            nvarchar,
                            DATEADD(
                                    dd,
                                    1,
                                    CONVERT(
                                            datetime,
                                            SUBSTRING([Date],1,4)+'-'+SUBSTRING([Date],5,2)+'-'+SUBSTRING([Date],7,2)
                                            )
                                    ),
                            112
                            )
                END AS NewDate

A: Use Select Case:
DECLARE @Dates  Datetime
DECLARE @Intime Datetime
DECLARE @Outtime Datetime

Set @Intime='1/21/2010'
Set @Outtime='1/20/2010'
Set @Dates=GETDATE()

Select @Dates,@Intime,@Outtime,
         cASE
     WHEN @Outtime > @Intime then  @Dates + 1
     WHEN @Outtime < @Intime then @Dates
     ELSE GETDATE()
     END as [NextDate]


text:
Q: OpenGL - Buffer, shader Every time I search on Google about OpenGL programming I found articles but it seems that all are mentioning shaders and buffers. What are those?
Can you explain some of them:

*

*Depth buffer

*Stencil buffer

*Pixel shader

*Frame buffer

*...?

I heard for few of them but couldn't find whole list. What are shaders in OpenGL, and what are buffers? Can somebody provide examples when we are using them?

A: A color buffer is some piece of internal memory with a specified memory layout, but otherwise more or less opaque to you that represents an image. It holds information about the color of each pixel in the image. You draw/render into color buffers. There can be more than a single color buffer with recent versions of OpenGL on recent hardware, which you can use to make some special rendering techniques more efficient.
Depth and stencil buffers are the same as color buffers, except they hold (as the name implies) depth and stencil information rather than color. Depth and stencil are often combined into one buffer (but need not be), and you can never have more than one depth/stencil buffer at a time.
The depth buffer is normally used to resolve overdrawing ambiguity when rendering several objects in no particular order. Only the one fragment closest to "your eye" survives. The stencil buffer can be used for special effects, e.g. to mask out regions of a buffer.
A framebuffer is something you attach color buffers to and draw/render into and which is optionally visible on the screen. There is always at least one framebuffer, this is what you see on your screen, but there may be any number of them. This is managed by the framebuffer extension which is core functionality since version 3.0. A framebuffer usually has separate "front" and "back" buffers too. One will be shown to you while you render to the other. At appropriate times, the buffers are flipped, so you do not see flickering.
A shader, most generally, is a "program" that OpenGL executes on your behalf inside its pipeline at well-defined times on well-defined data to generate some desired effect. It most often runs on the graphics card, but it may also be executed partially or wholly on the CPU.
Pixel shaders, the first shaders historically available (and namegivers) are run once for every fragment. They take some defined inputs (e.g. light position, normals) and produce a single output that later goes through the depth test, and is finally is written to or blended with the color buffer.
Vertex, geometry, or tesselation shaders do not really "shade" anything (they transform and/or generate vertices and primitives, which are later turned into fragments), but they inherit the name.

A: Type in opengl shaders in google and you get the answer for shaders actually.
The first search result:
http://en.wikipedia.org/wiki/GLSL
And for more direct listing of each shader, follow the link there too:
http://en.wikipedia.org/wiki/Shader#Types_of_shaders
For OpenGL you use GLSL for programming shaders and HLSL for Direct3D.
That should serve as a general introduction.
Some quick notes on the other (may be simplifications):
Depth buffer, also known as z-buffer, is used to solve the problem of what is behind what when rendering.
Frame buffer is simply the memory where the current frame (screen/pixels) is stored.
Stencil buffer is a bit more complicated and be used in a few different ways.
For introduction purposes, googles first hits on each (wikipedia) serves you quite well regarding these:
http://en.wikipedia.org/wiki/Framebuffer
http://en.wikipedia.org/wiki/Stencil_buffer
http://en.wikipedia.org/wiki/Z-buffering
etc


text:
Q: Test Driven Development for REST API I am writing a backend API in Django and using Tastypie, I am a beginner and want to clarify a basic question.
I want to use Test Driven Development approach. What I know of it is, that test cases are supposed to be written before production code.
How am I supposed to write a test case that would not have production code? Like am I just supposed to make a mock of every step?
Does this approach mean that I first write almost similar code (logic) for test cases and then implement the same for production?
For example, I have an Object book, I want to write an API that can put,get,post or delete. How do I write test case for this without writing any of the production code?
Any help would be great!
Thanks in advance.. :-)

A: The idea behind test driven development is that you write the tests first, but that they fail initially.  Then, as you actually write correct implementations, the tests start succeeding.
In this case, you'd write tests that would call put, get, post, and delete.  Obviously none of them would work at first.  Then, once you implemented, say, put correctly, that test would start succeeding, etc.
Now, depending on what level you are writing the tests at, you may need to write enough of your API to get the tests to compile.  However, it's okay if the API has no implementation and throws errors for everything at first.

A: You write specifications, that is, you write the method declarations first, and imagine what those APIs do, and don't implement it at the first place. Instead, you write down your imagination about how it should work from the view of the outside world.